File: buffer.c

package info (click to toggle)
lowdown 3.0.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,864 kB
  • sloc: ansic: 23,199; sh: 1,976; xml: 861; makefile: 568
file content (630 lines) | stat: -rw-r--r-- 13,699 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
/*
 * Copyright (c) 2008, Natacha Porté
 * Copyright (c) 2011, Vicent Martí
 * Copyright (c) 2014, Xavier Mendez, Devin Torres and the Hoedown authors
 * Copyright (c) Kristaps Dzonsons <kristaps@bsd.lv>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */
#include "config.h"

#if HAVE_SYS_QUEUE
# include <sys/queue.h>
#endif

#include <assert.h>
#include <ctype.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "lowdown.h"
#include "extern.h"

static void
hbuf_init(struct lowdown_buf *buf, size_t unit, int buffer_free)
{

	assert(buf != NULL);
	buf->data = NULL;
	buf->size = buf->maxsize = 0;
	buf->unit = unit;
	buf->buffer_free = buffer_free;
}

/*
 * Return a buffer that deep-copies "buf".  Returns the pointer of NULL
 * on memory allocation failure.
 */
struct lowdown_buf *
hbuf_dup(const struct lowdown_buf *buf)
{
	struct lowdown_buf	*v;

	v = calloc(1, sizeof(struct lowdown_buf));
	if (v != NULL && hbuf_clone(buf, v))
		return v;
	free(v);
	return NULL;
}

/*
 * Deep-copies "buf" into "v", wiping its contents.  Returns TRUE on
 * success or FALSE on memory allocation failure.
 */
int
hbuf_clone(const struct lowdown_buf *buf, struct lowdown_buf *v)
{

	*v = *buf;
	if (buf->size) {
		if ((v->data = malloc(buf->size)) == NULL)
			return 0;
		memcpy(v->data, buf->data, buf->size);
	} else
		v->data = NULL;

	return 1;
}

void
hbuf_truncate(struct lowdown_buf *buf)
{

	buf->size = 0;
}

int
hbuf_streq(const struct lowdown_buf *buf1, const char *buf2)
{
	size_t	 sz;

	sz = strlen(buf2);
	return buf1->size == sz &&
	       memcmp(buf1->data, buf2, sz) == 0;
}

int
hbuf_strprefix(const struct lowdown_buf *buf1, const char *buf2)
{
	size_t	 sz;

	sz = strlen(buf2);
	return buf1->size >= sz &&
	       memcmp(buf1->data, buf2, sz) == 0;
}

int
hbuf_eq(const struct lowdown_buf *buf1, const struct lowdown_buf *buf2)
{

	return buf1->size == buf2->size &&
	       memcmp(buf1->data, buf2->data, buf1->size) == 0;
}

struct lowdown_buf *
hbuf_new(size_t unit)
{
	struct lowdown_buf	*ret;

	if ((ret = malloc(sizeof(struct lowdown_buf))) == NULL)
		return NULL;
	hbuf_init(ret, unit, 1);
	return ret;
}

struct lowdown_buf *
lowdown_buf_new(size_t unit)
{

	return hbuf_new(unit);
}

void
hbuf_free(struct lowdown_buf *buf)
{

	if (buf == NULL) 
		return;
	free(buf->data);
	if (buf->buffer_free)
		free(buf);
}

void
lowdown_buf_free(struct lowdown_buf *buf)
{

	hbuf_free(buf);
}

int
hbuf_grow(struct lowdown_buf *buf, size_t neosz)
{
	size_t	 neoasz;
	void	*pp;

	if (buf->maxsize >= neosz)
		return 1;

	neoasz = (neosz/buf->unit + (neosz%buf->unit > 0)) * buf->unit;

	if ((pp = realloc(buf->data, neoasz)) == NULL)
		return 0;
	buf->data = pp;
	buf->maxsize = neoasz;
	return 1;
}

int
hbuf_putb(struct lowdown_buf *buf, const struct lowdown_buf *b)
{

	assert(buf != NULL && b != NULL);
	return hbuf_put(buf, b->data, b->size);
}

int
hbuf_put(struct lowdown_buf *buf, const char *data, size_t size)
{
	assert(buf != NULL && buf->unit);

	if (data == NULL || size == 0)
		return 1;

	if (buf->size + size > buf->maxsize &&
	    !hbuf_grow(buf, buf->size + size))
		return 0;

	memcpy(buf->data + buf->size, data, size);
	buf->size += size;
	return 1;
}

int
hbuf_puts(struct lowdown_buf *buf, const char *str)
{

	assert(buf != NULL && str != NULL);
	return hbuf_put(buf, str, strlen(str));
}

int
hbuf_putc(struct lowdown_buf *buf, char c)
{
	assert(buf && buf->unit);

	if (buf->size >= buf->maxsize &&
	    !hbuf_grow(buf, buf->size + 1))
		return 0;

	buf->data[buf->size] = c;
	buf->size += 1;
	return 1;
}

int
hbuf_putf(struct lowdown_buf *buf, FILE *file)
{

	assert(buf != NULL && buf->unit);
	while (!(feof(file) || ferror(file))) {
		if (!hbuf_grow(buf, buf->size + buf->unit))
			return 0;
		buf->size += fread(buf->data + buf->size, 
			1, buf->unit, file);
	}

	return ferror(file) == 0;
}

int
hbuf_printf(struct lowdown_buf *buf, const char *fmt, ...)
{
	va_list	 ap;
	int	 n;

	assert(buf != NULL && buf->unit);

	if (buf->size >= buf->maxsize &&
	    !hbuf_grow(buf, buf->size + 1))
		return 0;

	va_start(ap, fmt);
	n = vsnprintf(buf->data + buf->size,
		buf->maxsize - buf->size, fmt, ap);
	va_end(ap);

	if (n < 0)
		return 0;

	if ((size_t)n >= buf->maxsize - buf->size) {
		if (!hbuf_grow(buf, buf->size + n + 1))
			return 0;
		va_start(ap, fmt);
		n = vsnprintf(buf->data + buf->size,
			buf->maxsize - buf->size, fmt, ap);
		va_end(ap);
	}

	if (n < 0)
		return 0;

	buf->size += n;
	return 1;
}

/*
 * Link shortener.
 * This only shows the domain name and last path/filename.
 * It uses the following algorithm:
 *   (1) strip schema (if none, print in full)
 *   (2) print domain following
 *   (3) if no path, return
 *   (4) if path, look for final path component
 *   (5) print final path component with /.../ if shortened
 * Return zero on failure (memory), non-zero on success.
 */
int
hbuf_shortlink(struct lowdown_buf *out, const struct lowdown_buf *link)
{
	size_t		 start = 0, sz;
	const char	*cp, *rcp;

	/* 
	 * Skip the leading protocol.
	 * If we don't find a protocol, leave it be.
	 */

	if (link->size > 7 && strncmp(link->data, "http://", 7) == 0)
		start = 7;
	else if (link->size > 8 && strncmp(link->data, "https://", 8) == 0)
		start = 8;
	else if (link->size > 7 && strncmp(link->data, "file://", 7) == 0)
		start = 7;
	else if (link->size > 7 && strncmp(link->data, "mailto:", 7) == 0)
		start = 7;
	else if (link->size > 6 && strncmp(link->data, "ftp://", 6) == 0)
		start = 6;

	if (start == 0)
		return hbuf_putb(out, link);

	sz = link->size;
	if (link->data[link->size - 1] == '/')
		sz--;

	/* 
	 * Look for the end of the domain name. 
	 * If we don't have an end, then print the whole thing.
	 */

	cp = memchr(link->data + start, '/', sz - start);
	if (cp == NULL)
		return hbuf_put(out, link->data + start, sz - start);

	if (!hbuf_put(out, 
	    link->data + start, cp - (link->data + start)))
		return 0;

	/* 
	 * Look for the filename.
	 * If it's the same as the end of the domain, then print the
	 * whole thing.
	 * Otherwise, use a "..." between.
	 */

	rcp = memrchr(link->data + start, '/', sz - start);

	if (rcp == cp)
		return hbuf_put(out, cp, sz - (cp - link->data));

	return HBUF_PUTSL(out, "/...") &&
		hbuf_put(out, rcp, sz - (rcp - link->data));
}

/**
 * Convert the buffer into an identifier.  These are used in various
 * front-ends for linking to a section identifier.  Use pandoc's format
 * for these identifiers: lowercase, no specials except some, and
 * collapsing whitespace into a dash.
 */
struct lowdown_buf *
hbuf_dupname(const struct lowdown_buf *buf)
{
	struct lowdown_buf	*nbuf;
	size_t			 i;
	int			 last_space = 1;
	char			 c;

	if ((nbuf = hbuf_new(32)) == NULL)
		goto err;

	for (i = 0; i < buf->size; i++) {
		if (isalnum((unsigned char)buf->data[i]) ||
		    buf->data[i] == '-' ||
		    buf->data[i] == '.' ||
		    buf->data[i] == '_') {
			c = tolower((unsigned char)buf->data[i]);
			if (!hbuf_putc(nbuf, c))
				goto err;
			last_space = 0;
		} else if (isspace((unsigned char)buf->data[i])) {
			if (!last_space) {
				if (!HBUF_PUTSL(nbuf, "-"))
					goto err;
				last_space = 1;
			}
		}
	}

	if (nbuf->size == 0 && !HBUF_PUTSL(nbuf, "section"))
		goto err;

	return nbuf;
err:
	hbuf_free(nbuf);
	return NULL;
}

/*
 * Format the raw string used for creating header identifiers.  This
 * recursively drops through the header contents extracting text along
 * the way.
 */
int
hbuf_extract_text(struct lowdown_buf *ob, const struct lowdown_node *n)
{
	const struct lowdown_node	*child;

	/* For footnotes, use nothing and don't descend to children. */

	if (n->type == LOWDOWN_FOOTNOTE)
		return 1;

	/* All non-footnotes are ok... */

	if (n->type == LOWDOWN_NORMAL_TEXT)
		if (!hbuf_putb(ob, &n->rndr_normal_text.text))
			return 0;
	if (n->type == LOWDOWN_IMAGE)
		if (!hbuf_putb(ob, &n->rndr_image.alt))
			return 0;
	if (n->type == LOWDOWN_LINK_AUTO)
		if (!hbuf_putb(ob, &n->rndr_autolink.link))
			return 0;
	if (n->type == LOWDOWN_CODESPAN)
		if (!hbuf_putb(ob, &n->rndr_codespan.text))
			return 0;
	TAILQ_FOREACH(child, &n->children, entries)
		if (!hbuf_extract_text(ob, child))
			return 0;

	return 1;
}

/*
 * Return a unique header identifier for "header".  Return zero on
 * failure (memory), non-zero on success.  The new value is appended to
 * the queue, which must be freed with hentryq_clear at some point.
 */
const struct lowdown_buf *
hbuf_id(const struct lowdown_buf *header, const struct lowdown_node *n,
	struct hentryq *q)
{
	struct lowdown_buf		*buf = NULL, *nbuf = NULL;
	const struct lowdown_node	*child;
	size_t				 count;
	struct hentry			*he = NULL, *entry;

	if (header == NULL) {
		if ((nbuf = hbuf_new(32)) == NULL)
			goto out;
		TAILQ_FOREACH(child, &n->children, entries)
			if (!hbuf_extract_text(nbuf, child))
				goto out;
		if ((buf = hbuf_dupname(nbuf)) == NULL)
			goto out;
		hbuf_free(nbuf);
		nbuf = NULL;
	} else
		if ((buf = hbuf_dupname(header)) == NULL)
			goto out;

	TAILQ_FOREACH(entry, q, entries)
		if (hbuf_eq(entry->buf, buf))
			break;

	if (entry == NULL) {
		he = calloc(1, sizeof(struct hentry));
		if (he == NULL)
			goto out;
		TAILQ_INSERT_TAIL(q, he, entries);
		he->buf = buf;
		return buf;
	}

	if ((nbuf = hbuf_new(32)) == NULL)
		goto out;

	for (count = 1;; count++) {
		hbuf_truncate(nbuf);
		if (!hbuf_putb(nbuf, buf))
			goto out;
		if (!hbuf_printf(nbuf, "-%zu", count))
			goto out;
		TAILQ_FOREACH(entry, q, entries)
			if (hbuf_eq(entry->buf, nbuf))
				break;
		if (entry == NULL) {
			he = calloc(1, sizeof(struct hentry));
			if (he == NULL)
				goto out;
			TAILQ_INSERT_TAIL(q, he, entries);
			he->buf = nbuf;
			hbuf_free(buf);
			return nbuf;
		}
	}
out:
	hbuf_free(buf);
	hbuf_free(nbuf);
	free(he);
	return NULL;
}

void
hentryq_clear(struct hentryq *q)
{
	struct hentry	*he;

	if (q == NULL)
		return;

	while ((he = TAILQ_FIRST(q)) != NULL) {
		TAILQ_REMOVE(q, he, entries);
		hbuf_free(he->buf);
		free(he);
	}
}

/*
 * Clone a (possibly binary) buffer as a NUL-terminated string.  Returns
 * NULL on memory failure.
 */
char *
hbuf_string(const struct lowdown_buf *buf)
{

	return hbuf_stringn(buf, 0, buf->size);
}

/*
 * Clone a slice from "start" to "end" of a (possibly binary) buffer as
 * a NUL-terminated string.  Returns NULL on memory failure.  The slice
 * must be within the buffer.
 */
char *
hbuf_stringn(const struct lowdown_buf *buf, size_t start, size_t end)
{

	assert(start <= end && end <= buf->size);
	return strndup(&buf->data[start], end - start);
}

/*
 * Clone a (possibly binary) buffer as a NUL-terminated string and trim
 * white-space.  Returns NULL on memory failure.
 */
char *
hbuf_string_trim(const struct lowdown_buf *buf)
{

	return hbuf_stringn_trim(buf, 0, buf->size);
}

/*
 * Clone a slice from "start" to "end" of a (possibly binary) buffer as
 * a NUL-terminated string.  Returns NULL on memory failure.  The slice
 * must be within the buffer.
 */
char *
hbuf_stringn_trim(const struct lowdown_buf *buf, size_t start, size_t end)
{

	assert(start <= end && end <= buf->size);

	for ( ; start < end; start++)
		if (!isspace((unsigned char)buf->data[start]))
			break;
	for ( ; end > start; end--)
		if (!isspace((unsigned char)buf->data[end - 1]))
			break;
	return strndup(&buf->data[start], end - start);
}

/*
 * Determine whether a link URL is relative.  Use a simple heuristic to
 * accomplish this: a relative URL is one without a schema.  Returns
 * zero if not a relative link, non-zero if it is.
 */
int
hbuf_isrellink(const struct lowdown_buf *link)
{
	const char	*colon;
	size_t	 	 rem;

	/* If there's no colon, it's a relative link (no schema) */

	if ((colon = memchr(link->data, ':', link->size)) == NULL)
		return 1;

	/* If there's a slash before the colon, it's a (rel) path. */

	assert(colon > link->data);
	rem = colon - link->data;
	return memchr(link->data, '/', rem) != NULL;
}

/*
 * Test if "buf" looks like a manpage, e.g., strlcpy(3), filefuncs(3am).
 * Really any word([0-9][a-z]{3}?).
 */
int
hbuf_ismanpage(const struct lowdown_buf *buf)
{
	const char	*paren, *sv;

	if (buf->size < 4)
		return 0;
	if (buf->data[buf->size - 1] != ')')
		return 0;
	if ((paren = memchr(buf->data, '(', buf->size)) == NULL)
		return 0;
	paren++;
	if (!isdigit((unsigned char)*paren))
		return 0;
	for (sv = ++paren; *paren != ')'; paren++)
		if (!isalpha((unsigned char)*paren))
			return 0;
	if ((ptrdiff_t)(paren - sv) > 3)
		return 0;
	return 1;
}

/*
 * Like hbuf_strncasecmpat, but starting at the beginning of the buffer.
 */
int
hbuf_strncasecmp(const struct lowdown_buf *buf, const char *val)
{
	return hbuf_strncasecmpat(buf, val, 0);
}

/*
 * Checks if the position at "pos" contains the full case-insensitive
 * text of "val".
 */
int
hbuf_strncasecmpat(const struct lowdown_buf *buf, const char *val,
    size_t pos)
{
	size_t	 sz;

	sz = strlen(val);
	return pos + sz <= buf->size &&
		strncasecmp(&buf->data[pos], val, sz) == 0;
}