Move string dope from strings.c to the new memory.c..
[s-mailx.git] / filter.c
blobc4c6613d1e9a9dff34c561694c1a06b5d157e2e8
1 /*@ S-nail - a mail user agent derived from Berkeley Mail.
2 *@ Filter objects.
4 * Copyright (c) 2013 - 2015 Steffen (Daode) Nurpmeso <sdaoden@users.sf.net>.
6 * Permission to use, copy, modify, and/or distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 #undef n_FILE
19 #define n_FILE filter
21 #ifndef HAVE_AMALGAMATION
22 # include "nail.h"
23 #endif
26 * Quotation filter
30 * TODO quotation filter: anticipate in future data: don't break if only WS
31 * TODO or a LF escaping \ follows on the line (simply reuse the latter).
34 #ifdef HAVE_QUOTE_FOLD
35 CTA(QUOTE_MAX > 3);
37 enum qf_state {
38 _QF_CLEAN,
39 _QF_PREFIX,
40 _QF_DATA
43 struct qf_vc {
44 struct quoteflt *self;
45 char const *buf;
46 size_t len;
49 /* Print out prefix and current quote */
50 static ssize_t _qf_dump_prefix(struct quoteflt *self);
52 /* Add one data character */
53 static ssize_t _qf_add_data(struct quoteflt *self, wchar_t wc);
55 /* State machine handlers */
56 static ssize_t _qf_state_prefix(struct qf_vc *vc);
57 static ssize_t _qf_state_data(struct qf_vc *vc);
59 static ssize_t
60 _qf_dump_prefix(struct quoteflt *self)
62 ssize_t rv;
63 size_t i;
64 NYD_ENTER;
66 if ((i = self->qf_pfix_len) > 0 && i != fwrite(self->qf_pfix, 1, i,
67 self->qf_os))
68 goto jerr;
69 rv = i;
71 if ((i = self->qf_currq.l) > 0 && i != fwrite(self->qf_currq.s, 1, i,
72 self->qf_os))
73 goto jerr;
74 rv += i;
75 jleave:
76 NYD_LEAVE;
77 return rv;
78 jerr:
79 rv = -1;
80 goto jleave;
83 static ssize_t
84 _qf_add_data(struct quoteflt *self, wchar_t wc)
86 char *save_b;
87 ui32_t save_l, save_w;
88 ssize_t rv = 0;
89 int w, l;
90 NYD_ENTER;
92 save_l = save_w = 0; /* silence cc */
93 save_b = NULL;
94 /* <newline> ends state */
95 if (wc == L'\n')
96 goto jflush;
97 if (wc == L'\r') /* TODO CR should be stripped in lower level!! */
98 goto jleave;
100 /* Unroll <tab> to spaces */
101 if (wc == L'\t') {
102 save_l = self->qf_datw;
103 save_w = (save_l + QUOTE_TAB_SPACES) & ~(QUOTE_TAB_SPACES - 1);
104 save_w -= save_l;
105 while (save_w-- > 0) {
106 ssize_t j = _qf_add_data(self, L' ');
107 if (j < 0) {
108 rv = j;
109 break;
111 rv += j;
113 goto jleave;
116 w = wcwidth(wc);
117 if (w == -1) {
118 jbad:
119 ++self->qf_datw;
120 self->qf_dat.s[self->qf_dat.l++] = '?';
121 } else {
122 l = wctomb(self->qf_dat.s + self->qf_dat.l, wc);
123 if (l < 0)
124 goto jbad;
125 self->qf_datw += (ui32_t)w;
126 self->qf_dat.l += (size_t)l;
129 /* TODO The last visual may excess (adjusted!) *qfold-max* if it's a wide;
130 * TODO place it on the next line, break before */
131 if (self->qf_datw >= self->qf_qfold_max) {
132 /* If we have seen a nice breakpoint during traversal, shuffle data
133 * around a bit so as to restore the trailing part after flushing */
134 if (self->qf_brkl > 0) {
135 save_w = self->qf_datw - self->qf_brkw;
136 save_l = self->qf_dat.l - self->qf_brkl;
137 save_b = self->qf_dat.s + self->qf_brkl + 2;
138 memmove(save_b, save_b - 2, save_l);
139 self->qf_dat.l = self->qf_brkl;
142 self->qf_dat.s[self->qf_dat.l++] = '\\';
143 jflush:
144 self->qf_dat.s[self->qf_dat.l++] = '\n';
145 rv = quoteflt_flush(self);
147 /* Restore takeovers, if any */
148 if (save_b != NULL) {
149 self->qf_brk_isws = FAL0;
150 self->qf_datw += save_w;
151 self->qf_dat.l = save_l;
152 memmove(self->qf_dat.s, save_b, save_l);
154 } else if (self->qf_datw >= self->qf_qfold_min && !self->qf_brk_isws) {
155 bool_t isws = (iswspace(wc) != 0);
157 if (isws || !self->qf_brk_isws || self->qf_brkl == 0) {
158 self->qf_brkl = self->qf_dat.l;
159 self->qf_brkw = self->qf_datw;
160 self->qf_brk_isws = isws;
164 /* If state changed to prefix, perform full reset (note this implies that
165 * quoteflt_flush() performs too much work..) */
166 if (wc == '\n') {
167 self->qf_state = _QF_PREFIX;
168 self->qf_wscnt = self->qf_datw = 0;
169 self->qf_currq.l = 0;
171 jleave:
172 NYD_LEAVE;
173 return rv;
176 static ssize_t
177 _qf_state_prefix(struct qf_vc *vc)
179 struct quoteflt *self;
180 ssize_t rv;
181 char const *buf;
182 size_t len, i;
183 wchar_t wc;
184 NYD_ENTER;
186 self = vc->self;
187 rv = 0;
189 for (buf = vc->buf, len = vc->len; len > 0;) {
190 /* xxx NULL BYTE! */
191 i = mbrtowc(&wc, buf, len, self->qf_mbps);
192 if (i == (size_t)-1) {
193 /* On hard error, don't modify mbstate_t and step one byte */
194 self->qf_mbps[0] = self->qf_mbps[1];
195 ++buf;
196 --len;
197 self->qf_wscnt = 0;
198 continue;
200 self->qf_mbps[1] = self->qf_mbps[0];
201 if (i == (size_t)-2) {
202 /* Redundant shift sequence, out of buffer */
203 len = 0;
204 break;
206 buf += i;
207 len -= i;
209 if (wc == L'\n')
210 goto jfin;
211 if (iswspace(wc)) {
212 ++self->qf_wscnt;
213 continue;
215 if (i == 1 && ISQUOTE(wc)) {
216 self->qf_wscnt = 0;
217 if (self->qf_currq.l >= QUOTE_MAX - 3) {
218 self->qf_currq.s[QUOTE_MAX - 3] = '.';
219 self->qf_currq.s[QUOTE_MAX - 2] = '.';
220 self->qf_currq.s[QUOTE_MAX - 1] = '.';
221 self->qf_currq.l = QUOTE_MAX;
222 } else
223 self->qf_currq.s[self->qf_currq.l++] = buf[-1];
224 continue;
227 /* The quote is parsed and compressed; dump it */
228 jfin:
229 self->qf_state = _QF_DATA;
230 /* Overtake WS to the current quote in order to preserve it for eventual
231 * necessary follow lines, too */
232 /* TODO we de-facto "normalize" to ASCII SP here which MESSES tabs!! */
233 while (self->qf_wscnt-- > 0 && self->qf_currq.l < QUOTE_MAX)
234 self->qf_currq.s[self->qf_currq.l++] = ' ';
235 self->qf_datw = self->qf_pfix_len + self->qf_currq.l;
236 self->qf_wscnt = 0;
237 rv = _qf_add_data(self, wc);
238 break;
241 vc->buf = buf;
242 vc->len = len;
243 NYD_LEAVE;
244 return rv;
247 static ssize_t
248 _qf_state_data(struct qf_vc *vc)
250 struct quoteflt *self;
251 ssize_t rv;
252 char const *buf;
253 size_t len, i;
254 wchar_t wc;
255 NYD_ENTER;
257 self = vc->self;
258 rv = 0;
260 for (buf = vc->buf, len = vc->len; len > 0;) {
261 /* xxx NULL BYTE! */
262 i = mbrtowc(&wc, buf, len, self->qf_mbps);
263 if (i == (size_t)-1) {
264 /* On hard error, don't modify mbstate_t and step one byte */
265 self->qf_mbps[0] = self->qf_mbps[1];
266 ++buf;
267 --len;
268 continue;
270 self->qf_mbps[1] = self->qf_mbps[0];
271 if (i == (size_t)-2) {
272 /* Redundant shift sequence, out of buffer */
273 len = 0;
274 break;
276 buf += i;
277 len -= i;
279 { ssize_t j = _qf_add_data(self, wc);
280 if (j < 0) {
281 rv = j;
282 break;
284 rv += j;
287 if (self->qf_state != _QF_DATA)
288 break;
291 vc->buf = buf;
292 vc->len = len;
293 NYD_LEAVE;
294 return rv;
296 #endif /* HAVE_QUOTE_FOLD */
298 FL struct quoteflt *
299 quoteflt_dummy(void) /* TODO LEGACY (until filters are plugged when needed) */
301 static struct quoteflt qf_i;
303 return &qf_i;
306 FL void
307 quoteflt_init(struct quoteflt *self, char const *prefix)
309 #ifdef HAVE_QUOTE_FOLD
310 char *xcp, *cp;
311 #endif
312 NYD_ENTER;
314 memset(self, 0, sizeof *self);
316 if ((self->qf_pfix = prefix) != NULL)
317 self->qf_pfix_len = (ui32_t)strlen(prefix);
319 /* Check wether the user wants the more fancy quoting algorithm */
320 /* TODO *quote-fold*: QUOTE_MAX may excess it! */
321 #ifdef HAVE_QUOTE_FOLD
322 if (self->qf_pfix_len > 0 && (cp = ok_vlook(quote_fold)) != NULL) {
323 ui32_t qmin, qmax = (ui32_t)strtol(cp, &xcp, 10);
324 /* These magic values ensure we don't bail :) */
325 if (qmax < self->qf_pfix_len + 6)
326 qmax = self->qf_pfix_len + 6;
327 --qmax; /* The newline escape */
328 if (cp == xcp || *xcp == '\0')
329 qmin = (qmax >> 1) + (qmax >> 2) + (qmax >> 5);
330 else {
331 qmin = (ui32_t)strtol(xcp + 1, NULL, 10);
332 if (qmin < qmax >> 1)
333 qmin = qmax >> 1;
334 else if (qmin > qmax - 2)
335 qmin = qmax - 2;
337 self->qf_qfold_min = qmin;
338 self->qf_qfold_max = qmax;
340 /* Add pad for takeover copies, backslash and newline */
341 self->qf_dat.s = salloc((qmax + 3) * mb_cur_max);
342 self->qf_currq.s = salloc((QUOTE_MAX + 1) * mb_cur_max);
344 #endif
345 NYD_LEAVE;
348 FL void
349 quoteflt_destroy(struct quoteflt *self) /* xxx inline */
351 NYD_ENTER;
352 UNUSED(self);
353 NYD_LEAVE;
356 FL void
357 quoteflt_reset(struct quoteflt *self, FILE *f) /* xxx inline */
359 NYD_ENTER;
360 self->qf_os = f;
361 #ifdef HAVE_QUOTE_FOLD
362 self->qf_state = _QF_CLEAN;
363 self->qf_dat.l =
364 self->qf_currq.l = 0;
365 memset(self->qf_mbps, 0, sizeof self->qf_mbps);
366 #endif
367 NYD_LEAVE;
370 FL ssize_t
371 quoteflt_push(struct quoteflt *self, char const *dat, size_t len)
373 /* (xxx Ideally the actual push() [and flush()] would be functions on their
374 * xxx own, via indirect vtbl call ..) */
375 ssize_t rv = 0;
376 NYD_ENTER;
378 if (len == 0)
379 goto jleave;
381 /* Bypass? XXX Finally, this filter simply should not be used, then */
382 if (self->qf_pfix_len == 0) {
383 if (len != fwrite(dat, 1, len, self->qf_os))
384 goto jerr;
385 rv = len;
387 /* Normal: place *indentprefix* at every BOL */
388 else
389 #ifdef HAVE_QUOTE_FOLD
390 if (self->qf_qfold_max == 0)
391 #endif
393 void *vp;
394 size_t ll;
395 bool_t pxok = (self->qf_qfold_min != 0);
397 for (;;) {
398 if (!pxok) {
399 ll = self->qf_pfix_len;
400 if (ll != fwrite(self->qf_pfix, 1, ll, self->qf_os))
401 goto jerr;
402 rv += ll;
403 pxok = TRU1;
406 /* xxx Strictly speaking this is invalid, because only `/' and `.' are
407 * xxx mandated by POSIX.1-2008 as "invariant across all locales
408 * xxx supported"; though there is no charset known which uses this
409 * xxx control char as part of a multibyte character; note that S-nail
410 * XXX (and the Mail codebase as such) do not support EBCDIC */
411 if ((vp = memchr(dat, '\n', len)) == NULL)
412 ll = len;
413 else {
414 pxok = FAL0;
415 ll = PTR2SIZE((char*)vp - dat) + 1;
418 if (ll != fwrite(dat, sizeof *dat, ll, self->qf_os))
419 goto jerr;
420 rv += ll;
421 if ((len -= ll) == 0)
422 break;
423 dat += ll;
426 self->qf_qfold_min = pxok;
428 /* Overly complicated, though still only line-per-line: *quote-fold*.
429 * - If .qf_currq.l is 0, then we are in a clean state. Reset .qf_mbps;
430 * TODO note this means we assume that lines start with reset escape seq,
431 * TODO but i don't think this is any worse than what we currently do;
432 * TODO in 15.0, with the value carrier, we should carry conversion states
433 * TODO all along, only resetting on error (or at words for header =???=);
434 * TODO this still is weird for error handling, but we need to act more
435 * TODO stream-alike (though in practice i don't think cross-line states
436 * TODO can be found, because of compatibility reasons; however, being
437 * TODO a problem rather than a solution is not a good thing (tm))
438 * - Lookout for a newline */
439 #ifdef HAVE_QUOTE_FOLD
440 else {
441 struct qf_vc vc;
442 ssize_t i;
444 vc.self = self;
445 vc.buf = dat;
446 vc.len = len;
447 while (vc.len > 0) {
448 switch (self->qf_state) {
449 case _QF_CLEAN:
450 case _QF_PREFIX:
451 i = _qf_state_prefix(&vc);
452 break;
453 default: /* silence cc (`i' unused) */
454 case _QF_DATA:
455 i = _qf_state_data(&vc);
456 break;
458 if (i < 0)
459 goto jerr;
460 rv += i;
463 #endif /* HAVE_QUOTE_FOLD */
465 jleave:
466 NYD_LEAVE;
467 return rv;
468 jerr:
469 rv = -1;
470 goto jleave;
473 FL ssize_t
474 quoteflt_flush(struct quoteflt *self)
476 ssize_t rv = 0;
477 NYD_ENTER;
478 UNUSED(self);
480 #ifdef HAVE_QUOTE_FOLD
481 if (self->qf_dat.l > 0) {
482 rv = _qf_dump_prefix(self);
483 if (rv >= 0) {
484 size_t i = self->qf_dat.l;
485 if (i == fwrite(self->qf_dat.s, 1, i, self->qf_os))
486 rv += i;
487 else
488 rv = -1;
489 self->qf_dat.l = 0;
490 self->qf_brk_isws = FAL0;
491 self->qf_wscnt = self->qf_brkl = self->qf_brkw = 0;
492 self->qf_datw = self->qf_pfix_len + self->qf_currq.l;
495 #endif
496 NYD_LEAVE;
497 return rv;
501 * HTML tagsoup filter TODO rewrite wchar_t based (require HAVE_C90AMEND1)
502 * TODO . Numeric &#NO; entities should also be treated by struct hf_ent
503 * TODO . Yes, we COULD support CSS based quoting when we'd check type="quote"
504 * TODO (nonstandard) and watch out for style="gmail_quote" (or so, VERY
505 * TODO nonstandard) and tracking a stack of such elements (to be popped
506 * TODO once the closing element is seen). Then, after writing a newline,
507 * TODO place sizeof(stack) ">"s first. But aren't these HTML mails rude?
508 * TODO Interlocking and non-well-formed data will break us down
510 #ifdef HAVE_FILTER_HTML_TAGSOUP
512 enum hf_limits {
513 _HF_MINLEN = 10, /* Minimum line length (can't really be smaller) */
514 _HF_BRKSUB = 8 /* Start considering line break MAX - BRKSUB */
517 enum hf_flags {
518 _HF_UTF8 = 1<<0, /* Data is in UTF-8 */
519 _HF_ERROR = 1<<1, /* A hard error occurred, bail as soon as possible */
520 _HF_NOPUT = 1<<2, /* (In a tag,) Don't generate output */
521 _HF_IGN = 1<<3, /* Ignore mode on */
522 _HF_ANY = 1<<4, /* Yet seen just any output */
523 _HF_PRE = 1<<5, /* In <pre>formatted mode */
524 _HF_ENT = 1<<6, /* Currently parsing an entity */
525 _HF_BLANK = 1<<7, /* Whitespace last */
526 _HF_HREF = 1<<8, /* External <a href=> was the last href seen */
528 _HF_NL_1 = 1<<9, /* One \n seen */
529 _HF_NL_2 = 2<<9, /* We have produced an all empty line */
530 _HF_NL_MASK = _HF_NL_1 | _HF_NL_2
533 enum hf_special_actions {
534 _HFSA_NEEDSEP = -1, /* Need an empty line (paragraph separator) */
535 _HFSA_NEEDNL = -2, /* Need a new line start (table row) */
536 _HFSA_IGN = -3, /* Things like <style>..</style>, <script>.. */
537 _HFSA_PRE = -4, /* <pre>.. */
538 _HFSA_PRE_END = -5,
539 _HFSA_IMG = -6, /* <img> */
540 _HFSA_HREF = -7, /* <a>.. */
541 _HFSA_HREF_END = -8
544 enum hf_entity_flags {
545 _HFE_HAVE_UNI = 1<<6, /* Have a Unicode replacement character */
546 _HFE_HAVE_CSTR = 1<<7, /* Have a string replacement */
547 /* We store the length of the entity name in the flags, too */
548 _HFE_LENGTH_MASK = (1<<6) - 1
551 struct htmlflt_href {
552 struct htmlflt_href *hfh_next;
553 ui32_t hfh_no; /* Running sequence */
554 ui32_t hfh_len; /* of .hfh_dat */
555 char hfh_dat[VFIELD_SIZE(0)];
558 struct htmlflt_tag {
559 si32_t hft_act; /* char or hf_special_actions */
560 /* Not NUL: character to inject, with high bit set: place a space
561 * afterwards. Note: only recognized with _HFSA_NEEDSEP or _HFSA_NEEDNL */
562 char hft_injc;
563 ui8_t hft_len; /* Useful bytes in (NUL terminated) .hft_tag */
564 char const hft_tag[10]; /* Tag less < and > surroundings (TR, /TR, ..) */
566 CTA(SIZEOF_FIELD(struct htmlflt_tag, hft_tag) < LINESIZE); /* .hf_ign_tag */
568 struct hf_ent {
569 ui8_t hfe_flags; /* enum hf_entity_flags plus length of .hfe_ent */
570 char hfe_c; /* Plain replacement character */
571 ui16_t hfe_uni; /* Unicode codepoint if _HFE_HAVE_UNI */
572 char hfe_cstr[5]; /* _HFE_HAVE_CSTR (e.g., &hellip; -> ...) */
573 char const hfe_ent[7]; /* Entity less & and ; surroundings */
576 /* Tag list; not binary searched :(, so try to take care a bit */
577 static struct htmlflt_tag const _hf_tags[] = {
578 # undef _X
579 # undef _XC
580 # define _X(S,A) {A, '\0', sizeof(S) -1, S "\0"}
581 # define _XC(S,C,A) {A, C, sizeof(S) -1, S "\0"}
583 _X("P", _HFSA_NEEDSEP), _X("/P", _HFSA_NEEDNL),
584 _X("DIV", _HFSA_NEEDSEP), _X("/DIV", _HFSA_NEEDNL),
585 _X("TR", _HFSA_NEEDNL),
586 _X("/TH", '\t'),
587 _X("/TD", '\t'),
588 /* Let it stand out; also since we don't support implicit paragraphs after
589 * block elements, plain running text after a list (seen in Unicode
590 * announcement via Firefox) */
591 _X("UL", _HFSA_NEEDSEP), _X("/UL", _HFSA_NEEDSEP),
592 _XC("LI", (char)0x80 | '*', _HFSA_NEEDSEP),
593 _X("DL", _HFSA_NEEDSEP),
594 _X("DT", _HFSA_NEEDNL),
596 _X("A", _HFSA_HREF), _X("/A", _HFSA_HREF_END),
597 _X("IMG", _HFSA_IMG),
598 _X("BR", '\n'),
599 _X("PRE", _HFSA_PRE), _X("/PRE", _HFSA_PRE_END),
600 _X("TITLE", _HFSA_NEEDSEP), /*_X("/TITLE", '\n'),*/
601 _X("H1", _HFSA_NEEDSEP), /*_X("/H1", '\n'),*/
602 _X("H2", _HFSA_NEEDSEP), /*_X("/H2", '\n'),*/
603 _X("H3", _HFSA_NEEDSEP), /*_X("/H3", '\n'),*/
604 _X("H4", _HFSA_NEEDSEP), /*_X("/H4", '\n'),*/
605 _X("H5", _HFSA_NEEDSEP), /*_X("/H5", '\n'),*/
606 _X("H6", _HFSA_NEEDSEP), /*_X("/H6", '\n'),*/
608 _X("STYLE", _HFSA_IGN),
609 _X("SCRIPT", _HFSA_IGN),
611 # undef _X
614 /* Entity list; not binary searched.. */
615 static struct hf_ent const _hf_ents[] = {
616 # undef _X
617 # undef _XU
618 # undef _XS
619 # undef _XUS
620 # define _X(E,C) {(sizeof(E) -1), C, 0x0u, "", E "\0"}
621 # define _XU(E,C,U) {(sizeof(E) -1) | _HFE_HAVE_UNI, C, U, "", E "\0"}
622 # define _XS(E,S) {(sizeof(E) -1) | _HFE_HAVE_CSTR, '\0', 0x0u,S "\0",E "\0"}
623 # define _XSU(E,S,U) \
624 {(sizeof(E) -1) | _HFE_HAVE_UNI | _HFE_HAVE_CSTR, '\0', U, S "\0", E "\0"}
626 _X("quot", '"'),
627 _X("amp", '&'),
628 _X("lt", '<'), _X("gt", '>'),
630 _XU("nbsp", ' ', 0x0020 /* Note: not 0x00A0 seems to be better for us */),
631 _XU("middot", '.', 0x00B7),
632 _XSU("hellip", "...", 0x2026),
633 _XSU("mdash", "---", 0x2014), _XSU("ndash", "--", 0x2013),
634 _XSU("laquo", "<<", 0x00AB), _XSU("raquo", ">>", 0x00BB),
635 _XSU("lsaquo", "<", 0x2039), _XSU("rsaquo", ">", 0x203A),
636 _XSU("lsquo", "'", 0x2018), _XSU("rsquo", "'", 0x2019),
637 _XSU("ldquo", "\"", 0x201C), _XSU("rdquo", "\"", 0x201D),
638 _XSU("uarr", "^|", 0x2191), _XSU("darr", "|v", 0x2193),
640 _XSU("cent", "CENT", 0x00A2),
641 _XSU("copy", "(C)", 0x00A9),
642 _XSU("euro", "EUR", 0x20AC),
643 _XSU("infin", "INFY", 0x221E),
644 _XSU("pound", "GBP", 0x00A3),
645 _XSU("reg", "(R)", 0x00AE),
646 _XSU("sect", "S:", 0x00A7),
647 _XSU("yen", "JPY", 0x00A5),
649 /* German umlauts */
650 _XSU("Auml", "Ae", 0x00C4), _XSU("auml", "ae", 0x00E4),
651 _XSU("Ouml", "Oe", 0x00D6), _XSU("ouml", "oe", 0x00F6),
652 _XSU("Uuml", "Ue", 0x00DC), _XSU("uuml", "ue", 0x00FC),
653 _XSU("szlig", "ss", 0x00DF)
655 # undef _X
656 # undef _XU
657 # undef _XS
658 # undef _XSU
661 /* Real output */
662 static struct htmlflt * _hf_dump_hrefs(struct htmlflt *self);
663 static struct htmlflt * _hf_dump(struct htmlflt *self);
664 static struct htmlflt * _hf_store(struct htmlflt *self, char c);
665 # ifdef HAVE_NATCH_CHAR
666 static struct htmlflt * __hf_sync_mbstuff(struct htmlflt *self);
667 # endif
669 /* Virtual output */
670 static struct htmlflt * _hf_nl(struct htmlflt *self);
671 static struct htmlflt * _hf_nl_force(struct htmlflt *self);
672 static struct htmlflt * _hf_putc(struct htmlflt *self, char c);
673 static struct htmlflt * _hf_putc_premode(struct htmlflt *self, char c);
674 static struct htmlflt * _hf_puts(struct htmlflt *self, char const *cp);
675 static struct htmlflt * _hf_putbuf(struct htmlflt *self,
676 char const *cp, size_t len);
678 /* Try to locate a param'eter in >hf_bdat, store it (non-terminated!) or NULL */
679 static struct htmlflt * _hf_param(struct htmlflt *self, struct str *store,
680 char const *param);
682 /* Expand all entities in the given parameter */
683 static struct htmlflt * _hf_expand_all_ents(struct htmlflt *self,
684 struct str const *param);
686 /* Completely parsed over a tag / an entity, interpret that */
687 static struct htmlflt * _hf_check_tag(struct htmlflt *self, char const *s);
688 static struct htmlflt * _hf_check_ent(struct htmlflt *self, char const *s,
689 size_t l);
691 /* Input handler */
692 static ssize_t _hf_add_data(struct htmlflt *self,
693 char const *dat, size_t len);
695 static struct htmlflt *
696 _hf_dump_hrefs(struct htmlflt *self)
698 struct htmlflt_href *hhp;
699 NYD2_ENTER;
701 if (!(self->hf_flags & _HF_NL_2) && putc('\n', self->hf_os) == EOF) {
702 self->hf_flags |= _HF_ERROR;
703 goto jleave;
706 /* Reverse the list */
707 for (hhp = self->hf_hrefs, self->hf_hrefs = NULL; hhp != NULL;) {
708 struct htmlflt_href *tmp = hhp->hfh_next;
709 hhp->hfh_next = self->hf_hrefs;
710 self->hf_hrefs = hhp;
711 hhp = tmp;
714 /* Then dump it */
715 while ((hhp = self->hf_hrefs) != NULL) {
716 self->hf_hrefs = hhp->hfh_next;
718 if (!(self->hf_flags & _HF_ERROR)) {
719 int w = fprintf(self->hf_os, " [%u] %.*s\n",
720 hhp->hfh_no, (int)hhp->hfh_len, hhp->hfh_dat);
721 if (w < 0)
722 self->hf_flags |= _HF_ERROR;
724 free(hhp);
727 self->hf_flags |= (putc('\n', self->hf_os) == EOF)
728 ? _HF_ERROR : _HF_NL_1 | _HF_NL_2;
729 self->hf_href_dist = (ui32_t)realscreenheight >> 1;
730 jleave:
731 NYD2_LEAVE;
732 return self;
735 static struct htmlflt *
736 _hf_dump(struct htmlflt *self)
738 ui32_t f, l;
739 char c, *cp;
740 NYD2_ENTER;
742 f = self->hf_flags & ~_HF_BLANK;
743 l = self->hf_len;
744 cp = self->hf_line;
745 self->hf_mbwidth = self->hf_mboff = self->hf_last_ws = self->hf_len = 0;
747 for (c = '\0'; l > 0; --l) {
748 c = *cp++;
749 jput:
750 if (putc(c, self->hf_os) == EOF) {
751 self->hf_flags = (f |= _HF_ERROR);
752 goto jleave;
756 if (c != '\n') {
757 f |= (f & _HF_NL_1) ? _HF_NL_2 : _HF_NL_1;
758 l = 1;
759 c = '\n';
760 goto jput;
762 self->hf_flags = f;
764 /* Check wether there are HREFs to dump; there is so much messy tagsoup out
765 * there that it seems best not to simply dump HREFs in each _dump(), but
766 * only with some gap, let's say half the real screen height */
767 if (--self->hf_href_dist < 0 && (f & _HF_NL_2) && self->hf_hrefs != NULL)
768 self = _hf_dump_hrefs(self);
769 jleave:
770 NYD2_LEAVE;
771 return self;
774 static struct htmlflt *
775 _hf_store(struct htmlflt *self, char c)
777 ui32_t f, l, i;
778 NYD2_ENTER;
780 assert(c != '\n');
782 f = self->hf_flags;
783 l = self->hf_len;
784 self->hf_line[l] = (c == '\t' ? ' ' : c);
785 self->hf_len = ++l;
786 if (blankspacechar(c)) {
787 if (c == '\t') {
788 i = 8 - ((l - 1) & 7); /* xxx magic tab width of 8 */
789 if (i > 0) {
791 self = _hf_store(self, ' ');
792 while (--i > 0);
793 goto jleave;
796 self->hf_last_ws = l;
797 } else if (/*c == '.' ||*/ c == ',' || c == ';' || c == '-')
798 self->hf_last_ws = l;
800 i = l;
801 # ifdef HAVE_NATCH_CHAR /* XXX This code is really ridiculous! */
802 if (mb_cur_max > 1) { /* XXX should mbrtowc() and THEN store, at least.. */
803 wchar_t wc;
804 int w, x = mbtowc(&wc, self->hf_line + self->hf_mboff, l - self->hf_mboff);
806 if (x > 0) {
807 if ((w = wcwidth(wc)) == -1 ||
808 /* Actively filter out L-TO-R and R-TO-R marks TODO ctext */
809 (wc == 0x200E || wc == 0x200F ||
810 (wc >= 0x202A && wc <= 0x202E)) ||
811 /* And some zero-width messes */
812 wc == 0x00AD || (wc >= 0x200B && wc <= 0x200D) ||
813 /* Oh about the ISO C wide character interfaces, baby! */
814 (wc == 0xFEFF)){
815 self->hf_len -= x;
816 goto jleave;
817 } else if (iswspace(wc))
818 self->hf_last_ws = l;
819 self->hf_mboff += x;
820 i = (self->hf_mbwidth += w);
821 } else {
822 if (x < 0) {
823 mbtowc(&wc, NULL, mb_cur_max);
824 if (UICMP(32, l - self->hf_mboff, >=, mb_cur_max)) { /* XXX */
825 ++self->hf_mboff;
826 ++self->hf_mbwidth;
829 i = self->hf_mbwidth;
832 # endif
834 /* Do we need to break the line? */
835 if (i >= self->hf_lmax - _HF_BRKSUB) {
836 ui32_t lim = self->hf_lmax >> 1;
838 /* Let's hope we saw a sane place to break this line! */
839 if (self->hf_last_ws >= lim) {
840 jput:
841 i = self->hf_len = self->hf_last_ws;
842 self = _hf_dump(self);
843 if ((self->hf_len = (l -= i)) > 0) {
844 self->hf_flags &= ~_HF_NL_MASK;
845 memmove(self->hf_line, self->hf_line + i, l);
846 # ifdef HAVE_NATCH_CHAR
847 __hf_sync_mbstuff(self);
848 # endif
850 goto jleave;
853 /* Any 7-bit characters? */
854 for (i = l; i-- >= lim;)
855 if (asciichar((c = self->hf_line[i]))) {
856 self->hf_last_ws = ++i;
857 goto jput;
858 } else if ((f & _HF_UTF8) && ((ui8_t)c & 0xC0) != 0x80) {
859 self->hf_last_ws = i;
860 goto jput;
863 /* Hard break necessary! xxx really badly done */
864 if (l >= self->hf_lmax - 1)
865 self = _hf_dump(self);
867 jleave:
868 NYD2_LEAVE;
869 return self;
872 # ifdef HAVE_NATCH_CHAR
873 static struct htmlflt *
874 __hf_sync_mbstuff(struct htmlflt *self)
876 wchar_t wc;
877 char const *b;
878 ui32_t o, w, l;
879 NYD2_ENTER;
881 b = self->hf_line;
882 o = w = 0;
883 l = self->hf_len;
884 goto jumpin;
886 while (l > 0) {
887 int x = mbtowc(&wc, b, l);
889 if (x == 0)
890 break;
892 if (x > 0) {
893 b += x;
894 l -= x;
895 o += x;
896 if ((x = wcwidth(wc)) == -1)
897 x = 1;
898 w += x;
899 continue;
902 /* Bad, skip over a single character.. XXX very bad indeed */
903 ++b;
904 ++o;
905 ++w;
906 --l;
907 jumpin:
908 mbtowc(&wc, NULL, mb_cur_max);
911 self->hf_mboff = o;
912 self->hf_mbwidth = w;
914 NYD2_LEAVE;
915 return self;
917 # endif /* HAVE_NATCH_CHAR */
919 static struct htmlflt *
920 _hf_nl(struct htmlflt *self)
922 ui32_t f;
923 NYD2_ENTER;
925 if (!((f = self->hf_flags) & _HF_ERROR)) {
926 if (f & _HF_ANY) {
927 if ((f & _HF_NL_MASK) != _HF_NL_MASK)
928 self = _hf_dump(self);
929 } else
930 self->hf_flags = (f |= _HF_NL_MASK);
932 NYD2_LEAVE;
933 return self;
936 static struct htmlflt *
937 _hf_nl_force(struct htmlflt *self)
939 NYD2_ENTER;
940 if (!(self->hf_flags & _HF_ERROR))
941 self = _hf_dump(self);
942 NYD2_LEAVE;
943 return self;
946 static struct htmlflt *
947 _hf_putc(struct htmlflt *self, char c)
949 ui32_t f;
950 NYD2_ENTER;
952 if ((f = self->hf_flags) & _HF_ERROR)
953 goto jleave;
955 if (c == '\n') {
956 self = _hf_nl(self);
957 goto jleave;
958 } else if (c == ' ' || c == '\t') {
959 if ((f & _HF_BLANK) || self->hf_len == 0)
960 goto jleave;
961 f |= _HF_BLANK;
962 } else
963 f &= ~_HF_BLANK;
964 f &= ~_HF_NL_MASK;
965 self->hf_flags = (f |= _HF_ANY);
966 self = _hf_store(self, c);
967 jleave:
968 NYD2_LEAVE;
969 return self;
972 static struct htmlflt *
973 _hf_putc_premode(struct htmlflt *self, char c)
975 ui32_t f;
976 NYD2_ENTER;
978 if ((f = self->hf_flags) & _HF_ERROR) {
980 } else if (c == '\n')
981 self = _hf_nl_force(self);
982 else {
983 f &= ~_HF_NL_MASK;
984 self->hf_flags = (f |= _HF_ANY);
985 self = _hf_store(self, c);
987 NYD2_LEAVE;
988 return self;
991 static struct htmlflt *
992 _hf_puts(struct htmlflt *self, char const *cp)
994 char c;
995 NYD2_ENTER;
997 while ((c = *cp++) != '\0')
998 self = _hf_putc(self, c);
999 NYD2_LEAVE;
1000 return self;
1003 static struct htmlflt *
1004 _hf_putbuf(struct htmlflt *self, char const *cp, size_t len)
1006 NYD2_ENTER;
1008 while (len-- > 0)
1009 self = _hf_putc(self, *cp++);
1010 NYD2_LEAVE;
1011 return self;
1014 static struct htmlflt *
1015 _hf_param(struct htmlflt *self, struct str *store, char const *param)
1017 char const *cp;
1018 char c, x, quote;
1019 size_t i;
1020 bool_t hot;
1021 NYD2_ENTER;
1023 store->s = NULL;
1024 store->l = 0;
1025 cp = self->hf_bdat;
1027 /* Skip over any non-WS first; be aware of soup, if it slipped through */
1028 for(;;){
1029 if((c = *cp++) == '\0' || c == '>')
1030 goto jleave;
1031 if(whitechar(c))
1032 break;
1035 /* Search for the parameter, take care of other quoting along the way */
1036 x = *param++;
1037 x = upperconv(x);
1038 quote = '\0';
1039 i = strlen(param);
1041 for(hot = TRU1;;){
1042 if((c = *cp++) == '\0' || c == '>')
1043 goto jleave;
1044 if(whitechar(c)){
1045 hot = TRU1;
1046 continue;
1049 /* Could it be a parameter? */
1050 if(hot){
1051 hot = FAL0;
1053 /* Is it the desired one? */
1054 if((c = upperconv(c)) == x && !ascncasecmp(param, cp, i)){
1055 char const *cp2 = cp + i;
1057 if((quote = *cp2++) != '='){
1058 if(quote == '\0' || quote == '>')
1059 goto jleave;
1060 while(whitechar(quote))
1061 quote = *cp2++;
1063 if(quote == '='){
1064 cp = cp2;
1065 break;
1067 continue; /* XXX Optimize: i bytes or even cp2 can't be it! */
1071 /* Not the desired one; but a parameter? */
1072 if(c != '=')
1073 continue;
1074 /* If so, properly skip over the value */
1075 if(c == '"' || c == '\''){
1076 /* TODO oops i have forgotten wether backslash quoting is allowed in
1077 * TODO quoted HTML parameter values? not supporting that for now.. */
1078 for(quote = c; (c = *cp) != '\0' && c != quote; ++cp)
1080 }else
1081 while((c = *cp) != '\0' && !whitechar(c) && c != '>')
1082 ++cp;
1083 if(c == '\0')
1084 goto jleave;
1087 /* Skip further whitespace */
1088 for(;;){
1089 if((c = *cp++) == '\0' || c == '>')
1090 goto jleave;
1091 if(!whitechar(c))
1092 break;
1095 if(c == '"' || c == '\''){
1096 /* TODO oops i have forgotten wether backslash quoting is allowed in
1097 * TODO quoted HTML parameter values? not supporting that for now.. */
1098 store->s = UNCONST(cp);
1099 for(quote = c; (c = *cp) != '\0' && c != quote; ++cp)
1101 /* XXX ... and we simply ignore a missing trailing " :> */
1102 }else{
1103 store->s = UNCONST(cp - 1);
1104 if(!whitechar(c))
1105 while((c = *cp) != '\0' && !whitechar(c) && c != '>')
1106 ++cp;
1108 i = PTR2SIZE(cp - store->s);
1110 /* Terrible tagsoup out there, e.g., groups.google.com produces href=""
1111 * parameter values prefixed and suffixed by newlines! Therefore trim the
1112 * value content TODO join into the parse step above! */
1113 for (cp = store->s; i > 0 && spacechar(*cp); ++cp, --i)
1115 store->s = UNCONST(cp);
1116 for (cp += i - 1; i > 0 && spacechar(*cp); --cp, --i)
1118 if ((store->l = i) == 0)
1119 store->s = NULL;
1120 jleave:
1121 NYD2_LEAVE;
1122 return self;
1125 static struct htmlflt *
1126 _hf_expand_all_ents(struct htmlflt *self, struct str const *param)
1128 char const *cp, *maxcp, *ep;
1129 char c;
1130 size_t i;
1131 NYD2_ENTER;
1133 for (cp = param->s, maxcp = cp + param->l; cp < maxcp;)
1134 if ((c = *cp++) != '&')
1135 jputc:
1136 self = _hf_putc(self, c);
1137 else {
1138 for (ep = cp--;;) {
1139 if (ep == maxcp || (c = *ep++) == '\0') {
1140 for (; cp < ep; ++cp)
1141 self = _hf_putc(self, *cp);
1142 goto jleave;
1143 } else if (c == ';') {
1144 if ((i = PTR2SIZE(ep - cp)) > 1) {
1145 self = _hf_check_ent(self, cp, i);
1146 break;
1147 } else {
1148 c = *cp++;
1149 goto jputc;
1153 cp = ep;
1155 jleave:
1156 NYD2_LEAVE;
1157 return self;
1160 static struct htmlflt *
1161 _hf_check_tag(struct htmlflt *self, char const *s)
1163 char nobuf[32], c;
1164 struct str param;
1165 size_t i;
1166 struct htmlflt_tag const *hftp;
1167 ui32_t f;
1168 NYD2_ENTER;
1170 /* Extra check only */
1171 assert(s != NULL);
1172 if (*s != '<') {
1173 DBG( n_alert("HTML tagsoup filter _hf_check_tag() called on soup!"); )
1174 jput_as_is:
1175 self = _hf_puts(self, self->hf_bdat);
1176 goto jleave;
1179 for (++s, i = 0; (c = s[i]) != '\0' && c != '>' && !whitechar(c); ++i)
1180 /* Special massage for things like <br/>: after the slash only whitespace
1181 * may separate us from the closing right angle! */
1182 if (c == '/') {
1183 size_t j = i + 1;
1185 while ((c = s[j]) != '\0' && c != '>' && whitechar(c))
1186 ++j;
1187 if (c == '>')
1188 break;
1191 for (hftp = _hf_tags;;) {
1192 if (i == hftp->hft_len && !ascncasecmp(s, hftp->hft_tag, i)) {
1193 c = s[hftp->hft_len];
1194 if (c == '>' || c == '/' || whitechar(c))
1195 break;
1197 if (PTRCMP(++hftp, >=, _hf_tags + NELEM(_hf_tags)))
1198 goto jnotknown;
1201 f = self->hf_flags;
1202 switch (hftp->hft_act) {
1203 case _HFSA_PRE_END:
1204 f &= ~_HF_PRE;
1205 if (0) {
1206 /* FALLTHRU */
1207 case _HFSA_PRE:
1208 f |= _HF_PRE;
1210 self->hf_flags = f;
1211 /* FALLTHRU */
1213 case _HFSA_NEEDSEP:
1214 if (!(self->hf_flags & _HF_NL_2))
1215 self = _hf_nl(self);
1216 /* FALLTHRU */
1217 case _HFSA_NEEDNL:
1218 if (!(f & _HF_NL_1))
1219 self = _hf_nl(self);
1220 if (hftp->hft_injc != '\0') {
1221 self = _hf_putc(self, hftp->hft_injc & 0x7F);
1222 if ((uc_i)hftp->hft_injc & 0x80)
1223 self = _hf_putc(self, ' ');
1225 break;
1227 case _HFSA_IGN:
1228 self->hf_ign_tag = hftp;
1229 self->hf_flags = (f |= _HF_IGN | _HF_NOPUT);
1230 break;
1232 case _HFSA_IMG:
1233 self = _hf_param(self, &param, "alt");
1234 self = _hf_putc(self, '[');
1235 if (param.s == NULL) {
1236 param.s = UNCONST("IMG");
1237 param.l = 3;
1238 goto jimg_put;
1239 } /* else */ if (memchr(param.s, '&', param.l) != NULL)
1240 self = _hf_expand_all_ents(self, &param);
1241 else
1242 jimg_put:
1243 self = _hf_putbuf(self, param.s, param.l);
1244 self = _hf_putc(self, ']');
1245 break;
1247 case _HFSA_HREF:
1248 self = _hf_param(self, &param, "href");
1249 /* Ignore non-external links */
1250 if (param.s != NULL && *param.s != '#') {
1251 struct htmlflt_href *hhp = smalloc(sizeof(*hhp) -
1252 VFIELD_SIZEOF(struct htmlflt_href, hfh_dat) + param.l +1);
1254 hhp->hfh_next = self->hf_hrefs;
1255 hhp->hfh_no = ++self->hf_href_no;
1256 hhp->hfh_len = (ui32_t)param.l;
1257 memcpy(hhp->hfh_dat, param.s, param.l);
1259 snprintf(nobuf, sizeof nobuf, "[%u]", hhp->hfh_no);
1260 self->hf_flags = (f |= _HF_HREF);
1261 self->hf_hrefs = hhp;
1262 self = _hf_puts(self, nobuf);
1263 } else
1264 self->hf_flags = (f &= ~_HF_HREF);
1265 break;
1266 case _HFSA_HREF_END:
1267 if (f & _HF_HREF) {
1268 snprintf(nobuf, sizeof nobuf, "[/%u]", self->hf_href_no);
1269 self = _hf_puts(self, nobuf);
1271 break;
1273 default:
1274 c = (char)(hftp->hft_act & 0xFF);
1275 self = _hf_putc(self, c);
1276 break;
1277 case '\0':
1278 break;
1280 jleave:
1281 NYD2_LEAVE;
1282 return self;
1284 /* The problem is that even invalid tagsoup is widely used, without real
1285 * searching i have seen e-mail address in <N@H.D> notation, and more.
1286 * To protect us a bit look around and possibly write the content as such */
1287 jnotknown:
1288 switch (*s) {
1289 case '!':
1290 case '?':
1291 /* Ignore <!DOCTYPE, <!-- comments, <? PIs.. */
1292 goto jleave;
1293 case '>':
1294 /* Print out an empty tag as such */
1295 if (s[1] == '\0') {
1296 --s;
1297 goto jput_as_is;
1299 break;
1300 case '/':
1301 ++s;
1302 break;
1303 default:
1304 break;
1307 /* Also skip over : in order to suppress v:roundrect, w:anchorlock.. */
1308 while ((c = *s++) != '\0' && c != '>' && !whitechar(c) && c != ':')
1309 if (!asciichar(c) || punctchar(c)) {
1310 self = _hf_puts(self, self->hf_bdat);
1311 break;
1313 goto jleave;
1316 static struct htmlflt *
1317 _hf_check_ent(struct htmlflt *self, char const *s, size_t l)
1319 char nobuf[32];
1320 char const *s_save;
1321 size_t l_save;
1322 struct hf_ent const *hfep;
1323 long i;
1324 NYD2_ENTER;
1326 s_save = s;
1327 l_save = l;
1328 assert(*s == '&');
1329 assert(l > 0);
1330 /* False entities seen in the wild assert(s[l - 1] == ';'); */
1331 ++s;
1332 l -= 2;
1334 /* Numeric entity, or try named search */
1335 if (*s == '#') {
1336 i = (*++s == 'x' ? 16 : 10);
1338 if ((i != 16 || (++s, --l) > 0) && l < sizeof(nobuf)) {
1339 memcpy(nobuf, s, l);
1340 nobuf[l] = '\0';
1341 i = strtol(nobuf, NULL, i);
1342 if (i <= 0x7F)
1343 self = _hf_putc(self, (char)i);
1344 else if (self->hf_flags & _HF_UTF8) {
1345 jputuni:
1346 l = n_utf32_to_utf8((ui32_t)i, nobuf);
1347 self = _hf_putbuf(self, nobuf, l);
1348 } else
1349 goto jeent;
1350 } else
1351 goto jeent;
1352 } else {
1353 ui32_t f = self->hf_flags, hf;
1355 for (hfep = _hf_ents; PTRCMP(hfep, <, _hf_ents + NELEM(_hf_ents)); ++hfep)
1356 if (l == ((hf = hfep->hfe_flags) & _HFE_LENGTH_MASK) &&
1357 !strncmp(s, hfep->hfe_ent, l)) {
1358 if ((hf & _HFE_HAVE_UNI) && (f & _HF_UTF8)) {
1359 i = hfep->hfe_uni;
1360 goto jputuni;
1361 } else if (hf & _HFE_HAVE_CSTR)
1362 self = _hf_puts(self, hfep->hfe_cstr);
1363 else
1364 self = _hf_putc(self, hfep->hfe_c);
1365 goto jleave;
1367 jeent:
1368 self = _hf_putbuf(self, s_save, l_save);
1370 jleave:
1371 NYD2_LEAVE;
1372 return self;
1375 static ssize_t
1376 _hf_add_data(struct htmlflt *self, char const *dat, size_t len)
1378 char c, *cp, *cp_max;
1379 bool_t hot;
1380 ssize_t rv = 0;
1381 NYD_ENTER;
1383 /* Final put request? */
1384 if (dat == NULL) {
1385 if (self->hf_len > 0 || self->hf_hrefs != NULL) {
1386 self = _hf_dump(self);
1387 if (self->hf_hrefs != NULL)
1388 self = _hf_dump_hrefs(self);
1389 rv = 1;
1391 goto jleave;
1394 /* Always ensure some initial buffer */
1395 if ((cp = self->hf_curr) != NULL)
1396 cp_max = self->hf_bmax;
1397 else {
1398 cp = self->hf_curr = self->hf_bdat = smalloc(LINESIZE);
1399 cp_max = self->hf_bmax = cp + LINESIZE -1; /* (Always room for NUL!) */
1401 hot = (cp != self->hf_bdat);
1403 for (rv = (ssize_t)len; len > 0; --len) {
1404 ui32_t f = self->hf_flags;
1406 if (f & _HF_ERROR)
1407 break;
1408 c = *dat++;
1410 /* Soup is really weird, and scripts may contain almost anything (and
1411 * newer CSS standards are also cryptic): therefore prefix the _HF_IGN
1412 * test and walk until we see the required end tag */
1413 /* TODO For real safety _HF_IGN soup condome would also need to know
1414 * TODO about quoted strings so that 'var i = "</script>";' couldn't
1415 * TODO fool it! We really want this mode also for _HF_NOPUT to be
1416 * TODO able to *gracefully* detect the tag-closing '>', but then if
1417 * TODO that is a single mechanism we should have made it! */
1418 if (f & _HF_IGN) {
1419 struct htmlflt_tag const *hftp = self->hf_ign_tag;
1420 size_t i;
1422 if (c == '<') {
1423 hot = TRU1;
1424 jcp_reset:
1425 cp = self->hf_bdat;
1426 } else if (c == '>') {
1427 if (hot) {
1428 if ((i = PTR2SIZE(cp - self->hf_bdat)) > 1 &&
1429 --i == hftp->hft_len &&
1430 !ascncasecmp(self->hf_bdat + 1, hftp->hft_tag, i))
1431 self->hf_flags = (f &= ~(_HF_IGN | _HF_NOPUT));
1432 hot = FAL0;
1433 goto jcp_reset;
1435 } else if (hot) {
1436 *cp++ = c;
1437 i = PTR2SIZE(cp - self->hf_bdat);
1438 if ((i == 1 && c != '/') || --i > hftp->hft_len) {
1439 hot = FAL0;
1440 goto jcp_reset;
1443 } else switch (c) {
1444 case '<':
1445 /* People are using & without &amp;ing it, ditto <; be aware */
1446 if (f & (_HF_NOPUT | _HF_ENT)) {
1447 f &= ~_HF_ENT;
1448 /* Special case "<!--" buffer content to deal with really weird
1449 * things that can be done with "<!--[if gte mso 9]>" syntax */
1450 if (PTR2SIZE(cp - self->hf_bdat) != 4 ||
1451 memcmp(self->hf_bdat, "<!--", 4)) {
1452 self->hf_flags = f;
1453 *cp = '\0';
1454 self = _hf_puts(self, self->hf_bdat);
1455 f = self->hf_flags;
1458 cp = self->hf_bdat;
1459 *cp++ = c;
1460 self->hf_flags = (f |= _HF_NOPUT);
1461 break;
1462 case '>':
1463 /* Weird tagsoup around, do we actually parse a tag? */
1464 if (!(f & _HF_NOPUT))
1465 goto jdo_c;
1466 cp[0] = c;
1467 cp[1] = '\0';
1468 f &= ~(_HF_NOPUT | _HF_ENT);
1469 self->hf_flags = f;
1470 self = _hf_check_tag(self, self->hf_bdat);
1471 *(cp = self->hf_bdat) = '\0'; /* xxx extra safety */
1472 /* Quick hack to get rid of redundant newline after <pre> XXX */
1473 if (!(f & _HF_PRE) && (self->hf_flags & _HF_PRE) &&
1474 len > 1 && *dat == '\n')
1475 ++dat, --len;
1476 break;
1478 case '\r': /* TODO CR should be stripped in lower level!! (Only B64!?!) */
1479 break;
1480 case '\n':
1481 /* End of line is not considered unless we are in PRE section.
1482 * However, in _HF_NOPUT mode we must be aware of tagsoup which uses
1483 * newlines for separating parameters */
1484 if (f & _HF_NOPUT)
1485 goto jdo_c;
1486 self = (f & _HF_PRE) ? _hf_nl_force(self) : _hf_putc(self, ' ');
1487 break;
1489 case '\t':
1490 if (!(f & _HF_PRE))
1491 c = ' ';
1492 /* FALLTHRU */
1493 default:
1494 jdo_c:
1495 /* If not currently parsing a tag and bypassing normal output.. */
1496 if (!(f & _HF_NOPUT)) {
1497 if (cntrlchar(c))
1498 break;
1499 if (c == '&') {
1500 cp = self->hf_bdat;
1501 *cp++ = c;
1502 self->hf_flags = (f |= _HF_NOPUT | _HF_ENT);
1503 } else if (f & _HF_PRE) {
1504 self = _hf_putc_premode(self, c);
1505 self->hf_flags &= ~_HF_BLANK;
1506 } else
1507 self = _hf_putc(self, c);
1508 } else if ((f & _HF_ENT) && c == ';') {
1509 cp[0] = c;
1510 cp[1] = '\0';
1511 f &= ~(_HF_NOPUT | _HF_ENT);
1512 self->hf_flags = f;
1513 self = _hf_check_ent(self, self->hf_bdat,
1514 PTR2SIZE(cp + 1 - self->hf_bdat));
1515 } else {
1516 /* We may need to grow the buffer */
1517 if (PTRCMP(cp + 42/2, >=, cp_max)) {
1518 size_t i = PTR2SIZE(cp - self->hf_bdat),
1519 m = PTR2SIZE(self->hf_bmax - self->hf_bdat) + LINESIZE;
1521 cp = self->hf_bdat = srealloc(self->hf_bdat, m);
1522 self->hf_bmax = cp + m -1;
1523 self->hf_curr = (cp += i);
1525 *cp++ = c;
1529 self->hf_curr = cp;
1530 jleave:
1531 NYD_LEAVE;
1532 return (self->hf_flags & _HF_ERROR) ? -1 : rv;
1536 * TODO Because we don't support filter chains yet this filter will be run
1537 * TODO in a dedicated subprocess, driven via a special Popen() mode
1539 static bool_t __hf_hadpipesig;
1540 static void
1541 __hf_onpipe(int signo)
1543 NYD_X; /* Signal handler */
1544 UNUSED(signo);
1545 __hf_hadpipesig = TRU1;
1548 FL int
1549 htmlflt_process_main(void)
1551 char buf[BUFFER_SIZE];
1552 struct htmlflt hf;
1553 size_t i;
1554 int rv;
1555 NYD_ENTER;
1557 __hf_hadpipesig = FAL0;
1558 safe_signal(SIGPIPE, &__hf_onpipe);
1560 htmlflt_init(&hf);
1561 htmlflt_reset(&hf, stdout);
1563 for (;;) {
1564 if ((i = fread(buf, sizeof(buf[0]), NELEM(buf), stdin)) == 0) {
1565 rv = !feof(stdin);
1566 break;
1569 if ((rv = __hf_hadpipesig))
1570 break;
1571 /* Just use this directly.. */
1572 if (htmlflt_push(&hf, buf, i) < 0) {
1573 rv = 1;
1574 break;
1577 if (rv == 0 && htmlflt_flush(&hf) < 0)
1578 rv = 1;
1580 htmlflt_destroy(&hf);
1582 rv |= __hf_hadpipesig;
1583 NYD_LEAVE;
1584 return rv;
1587 FL void
1588 htmlflt_init(struct htmlflt *self)
1590 NYD_ENTER;
1591 /* (Rather redundant though) */
1592 memset(self, 0, sizeof *self);
1593 NYD_LEAVE;
1596 FL void
1597 htmlflt_destroy(struct htmlflt *self)
1599 NYD_ENTER;
1600 htmlflt_reset(self, NULL);
1601 NYD_LEAVE;
1604 FL void
1605 htmlflt_reset(struct htmlflt *self, FILE *f)
1607 struct htmlflt_href *hfhp;
1608 NYD_ENTER;
1610 while ((hfhp = self->hf_hrefs) != NULL) {
1611 self->hf_hrefs = hfhp->hfh_next;
1612 free(hfhp);
1615 if (self->hf_bdat != NULL)
1616 free(self->hf_bdat);
1617 if (self->hf_line != NULL)
1618 free(self->hf_line);
1620 memset(self, 0, sizeof *self);
1622 if (f != NULL) {
1623 ui32_t sw = MAX(_HF_MINLEN, (ui32_t)scrnwidth);
1625 self->hf_line = smalloc((size_t)sw * mb_cur_max +1);
1626 self->hf_lmax = sw;
1628 if (options & OPT_UNICODE) /* TODO not truly generic */
1629 self->hf_flags = _HF_UTF8;
1630 self->hf_os = f;
1632 NYD_LEAVE;
1635 FL ssize_t
1636 htmlflt_push(struct htmlflt *self, char const *dat, size_t len)
1638 ssize_t rv;
1639 NYD_ENTER;
1641 rv = _hf_add_data(self, dat, len);
1642 NYD_LEAVE;
1643 return rv;
1646 FL ssize_t
1647 htmlflt_flush(struct htmlflt *self)
1649 ssize_t rv;
1650 NYD_ENTER;
1652 rv = _hf_add_data(self, NULL, 0);
1653 rv |= !fflush(self->hf_os) ? 0 : -1;
1654 NYD_LEAVE;
1655 return rv;
1657 #endif /* HAVE_FILTER_HTML_TAGSOUP */
1659 /* s-it-mode */