Adjust OpenCSW & pkgsrc paths, drop CONFIG=MEDIUM (Alexander Harm)..
[s-mailx.git] / filter.c
blobd07ed69ee156e46ef26fdd23d0baab08ac7a3a2d
1 /*@ S-nail - a mail user agent derived from Berkeley Mail.
2 *@ Filter objects.
4 * Copyright (c) 2013 - 2017 Steffen (Daode) Nurpmeso <steffen@sdaoden.eu>.
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 n_CTAV(n_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 + n_QUOTE_TAB_SPACES) & ~(n_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 && n_QUOTE_IS_A(wc)) {
216 self->qf_wscnt = 0;
217 if (self->qf_currq.l >= n_QUOTE_MAX - 3) {
218 self->qf_currq.s[n_QUOTE_MAX - 3] = '.';
219 self->qf_currq.s[n_QUOTE_MAX - 2] = '.';
220 self->qf_currq.s[n_QUOTE_MAX - 1] = '.';
221 self->qf_currq.l = n_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 < n_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 const *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 whether the user wants the more fancy quoting algorithm */
320 /* TODO *quote-fold*: n_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;
325 /* These magic values ensure we don't bail */
326 n_idec_ui32_cp(&qmax, cp, 10, &xcp);
327 if (qmax < self->qf_pfix_len + 6)
328 qmax = self->qf_pfix_len + 6;
329 --qmax; /* The newline escape */
330 if (cp == xcp || *xcp == '\0')
331 qmin = (qmax >> 1) + (qmax >> 2) + (qmax >> 5);
332 else {
333 n_idec_ui32_cp(&qmin, &xcp[1], 10, NULL);
334 if (qmin < qmax >> 1)
335 qmin = qmax >> 1;
336 else if (qmin > qmax - 2)
337 qmin = qmax - 2;
339 self->qf_qfold_min = qmin;
340 self->qf_qfold_max = qmax;
342 /* Add pad for takeover copies, reverse solidus and newline */
343 self->qf_dat.s = salloc((qmax + 3) * n_mb_cur_max);
344 self->qf_currq.s = salloc((n_QUOTE_MAX + 1) * n_mb_cur_max);
346 #endif
347 NYD_LEAVE;
350 FL void
351 quoteflt_destroy(struct quoteflt *self) /* xxx inline */
353 NYD_ENTER;
354 n_UNUSED(self);
355 NYD_LEAVE;
358 FL void
359 quoteflt_reset(struct quoteflt *self, FILE *f) /* xxx inline */
361 NYD_ENTER;
362 self->qf_os = f;
363 #ifdef HAVE_QUOTE_FOLD
364 self->qf_state = _QF_CLEAN;
365 self->qf_dat.l =
366 self->qf_currq.l = 0;
367 memset(self->qf_mbps, 0, sizeof self->qf_mbps);
368 #endif
369 NYD_LEAVE;
372 FL ssize_t
373 quoteflt_push(struct quoteflt *self, char const *dat, size_t len)
375 /* (xxx Ideally the actual push() [and flush()] would be functions on their
376 * xxx own, via indirect vtbl call ..) */
377 ssize_t rv = 0;
378 NYD_ENTER;
380 self->qf_nl_last = (len > 0 && dat[len - 1] == '\n'); /* TODO HACK */
382 if (len == 0)
383 goto jleave;
385 /* Bypass? TODO Finally, this filter simply should not be used, then
386 * (TODO It supercedes prefix_write() or something) */
387 if (self->qf_pfix_len == 0) {
388 if (len != fwrite(dat, 1, len, self->qf_os))
389 goto jerr;
390 rv = len;
392 /* Normal: place *indentprefix* at every BOL */
393 else
394 #ifdef HAVE_QUOTE_FOLD
395 if (self->qf_qfold_max == 0)
396 #endif
398 void *vp;
399 size_t ll;
400 bool_t pxok = (self->qf_qfold_min != 0);
402 for (;;) {
403 if (!pxok) {
404 ll = self->qf_pfix_len;
405 if (ll != fwrite(self->qf_pfix, 1, ll, self->qf_os))
406 goto jerr;
407 rv += ll;
408 pxok = TRU1;
411 /* xxx Strictly speaking this is invalid, because only `/' and `.' are
412 * xxx mandated by POSIX.1-2008 as "invariant across all locales
413 * xxx supported"; though there is no charset known which uses this
414 * xxx control char as part of a multibyte character; note that S-nail
415 * XXX (and the Mail codebase as such) do not support EBCDIC */
416 if ((vp = memchr(dat, '\n', len)) == NULL)
417 ll = len;
418 else {
419 pxok = FAL0;
420 ll = PTR2SIZE((char*)vp - dat) + 1;
423 if (ll != fwrite(dat, sizeof *dat, ll, self->qf_os))
424 goto jerr;
425 rv += ll;
426 if ((len -= ll) == 0)
427 break;
428 dat += ll;
431 self->qf_qfold_min = pxok;
433 /* Overly complicated, though still only line-per-line: *quote-fold*.
434 * - If .qf_currq.l is 0, then we are in a clean state. Reset .qf_mbps;
435 * TODO note this means we assume that lines start with reset escape seq,
436 * TODO but i don't think this is any worse than what we currently do;
437 * TODO in 15.0, with the value carrier, we should carry conversion states
438 * TODO all along, only resetting on error (or at words for header =???=);
439 * TODO this still is weird for error handling, but we need to act more
440 * TODO stream-alike (though in practice i don't think cross-line states
441 * TODO can be found, because of compatibility reasons; however, being
442 * TODO a problem rather than a solution is not a good thing (tm))
443 * - Lookout for a newline */
444 #ifdef HAVE_QUOTE_FOLD
445 else {
446 struct qf_vc vc;
447 ssize_t i;
449 vc.self = self;
450 vc.buf = dat;
451 vc.len = len;
452 while (vc.len > 0) {
453 switch (self->qf_state) {
454 case _QF_CLEAN:
455 case _QF_PREFIX:
456 i = _qf_state_prefix(&vc);
457 break;
458 default: /* silence cc (`i' unused) */
459 case _QF_DATA:
460 i = _qf_state_data(&vc);
461 break;
463 if (i < 0)
464 goto jerr;
465 rv += i;
468 #endif /* HAVE_QUOTE_FOLD */
470 jleave:
471 NYD_LEAVE;
472 return rv;
473 jerr:
474 rv = -1;
475 goto jleave;
478 FL ssize_t
479 quoteflt_flush(struct quoteflt *self)
481 ssize_t rv = 0;
482 NYD_ENTER;
483 n_UNUSED(self);
485 #ifdef HAVE_QUOTE_FOLD
486 if (self->qf_dat.l > 0) {
487 rv = _qf_dump_prefix(self);
488 if (rv >= 0) {
489 size_t i = self->qf_dat.l;
490 if (i == fwrite(self->qf_dat.s, 1, i, self->qf_os))
491 rv += i;
492 else
493 rv = -1;
494 self->qf_dat.l = 0;
495 self->qf_brk_isws = FAL0;
496 self->qf_wscnt = self->qf_brkl = self->qf_brkw = 0;
497 self->qf_datw = self->qf_pfix_len + self->qf_currq.l;
500 #endif
501 NYD_LEAVE;
502 return rv;
506 * HTML tagsoup filter TODO rewrite wchar_t based (require HAVE_C90AMEND1)
507 * TODO . Numeric &#NO; entities should also be treated by struct hf_ent
508 * TODO . Yes, we COULD support CSS based quoting when we'd check type="quote"
509 * TODO (nonstandard) and watch out for style="gmail_quote" (or so, VERY
510 * TODO nonstandard) and tracking a stack of such elements (to be popped
511 * TODO once the closing element is seen). Then, after writing a newline,
512 * TODO place sizeof(stack) ">"s first. But aren't these HTML mails rude?
513 * TODO Interlocking and non-well-formed data will break us down
515 #ifdef HAVE_FILTER_HTML_TAGSOUP
517 enum hf_limits {
518 _HF_MINLEN = 10, /* Minimum line length (can't really be smaller) */
519 _HF_BRKSUB = 8 /* Start considering line break MAX - BRKSUB */
522 enum hf_flags {
523 _HF_UTF8 = 1<<0, /* Data is in UTF-8 */
524 _HF_ERROR = 1<<1, /* A hard error occurred, bail as soon as possible */
525 _HF_NOPUT = 1<<2, /* (In a tag,) Don't generate output */
526 _HF_IGN = 1<<3, /* Ignore mode on */
527 _HF_ANY = 1<<4, /* Yet seen just any output */
528 _HF_PRE = 1<<5, /* In <pre>formatted mode */
529 _HF_ENT = 1<<6, /* Currently parsing an entity */
530 _HF_BLANK = 1<<7, /* Whitespace last */
531 _HF_HREF = 1<<8, /* External <a href=> was the last href seen */
533 _HF_NL_1 = 1<<9, /* One \n seen */
534 _HF_NL_2 = 2<<9, /* We have produced an all empty line */
535 _HF_NL_MASK = _HF_NL_1 | _HF_NL_2
538 enum hf_special_actions {
539 _HFSA_NEEDSEP = -1, /* Need an empty line (paragraph separator) */
540 _HFSA_NEEDNL = -2, /* Need a new line start (table row) */
541 _HFSA_IGN = -3, /* Things like <style>..</style>, <script>.. */
542 _HFSA_PRE = -4, /* <pre>.. */
543 _HFSA_PRE_END = -5,
544 _HFSA_IMG = -6, /* <img> */
545 _HFSA_HREF = -7, /* <a>.. */
546 _HFSA_HREF_END = -8
549 enum hf_entity_flags {
550 _HFE_HAVE_UNI = 1<<6, /* Have a Unicode replacement character */
551 _HFE_HAVE_CSTR = 1<<7, /* Have a string replacement */
552 /* We store the length of the entity name in the flags, too */
553 _HFE_LENGTH_MASK = (1<<6) - 1
556 struct htmlflt_href {
557 struct htmlflt_href *hfh_next;
558 ui32_t hfh_no; /* Running sequence */
559 ui32_t hfh_len; /* of .hfh_dat */
560 char hfh_dat[n_VFIELD_SIZE(0)];
563 struct htmlflt_tag {
564 si32_t hft_act; /* char or hf_special_actions */
565 /* Not NUL: character to inject, with high bit set: place a space
566 * afterwards. Note: only recognized with _HFSA_NEEDSEP or _HFSA_NEEDNL */
567 char hft_injc;
568 ui8_t hft_len; /* Useful bytes in (NUL terminated) .hft_tag */
569 char const hft_tag[10]; /* Tag less < and > surroundings (TR, /TR, ..) */
571 n_CTA(n_SIZEOF_FIELD(struct htmlflt_tag, hft_tag) < LINESIZE,
572 "Structure field too large a size"); /* .hf_ign_tag */
574 struct hf_ent {
575 ui8_t hfe_flags; /* enum hf_entity_flags plus length of .hfe_ent */
576 char hfe_c; /* Plain replacement character */
577 ui16_t hfe_uni; /* Unicode codepoint if _HFE_HAVE_UNI */
578 char hfe_cstr[5]; /* _HFE_HAVE_CSTR (e.g., &hellip; -> ...) */
579 char const hfe_ent[7]; /* Entity less & and ; surroundings */
582 /* Tag list; not binary searched :(, so try to take care a bit */
583 static struct htmlflt_tag const _hf_tags[] = {
584 # undef _X
585 # undef _XC
586 # define _X(S,A) {A, '\0', sizeof(S) -1, S "\0"}
587 # define _XC(S,C,A) {A, C, sizeof(S) -1, S "\0"}
589 _X("P", _HFSA_NEEDSEP), _X("/P", _HFSA_NEEDNL),
590 _X("DIV", _HFSA_NEEDSEP), _X("/DIV", _HFSA_NEEDNL),
591 _X("TR", _HFSA_NEEDNL),
592 _X("/TH", '\t'),
593 _X("/TD", '\t'),
594 /* Let it stand out; also since we don't support implicit paragraphs after
595 * block elements, plain running text after a list (seen in Unicode
596 * announcement via Firefox) */
597 _X("UL", _HFSA_NEEDSEP), _X("/UL", _HFSA_NEEDSEP),
598 _XC("LI", (char)0x80 | '*', _HFSA_NEEDSEP),
599 _X("DL", _HFSA_NEEDSEP),
600 _X("DT", _HFSA_NEEDNL),
602 _X("A", _HFSA_HREF), _X("/A", _HFSA_HREF_END),
603 _X("IMG", _HFSA_IMG),
604 _X("BR", '\n'),
605 _X("PRE", _HFSA_PRE), _X("/PRE", _HFSA_PRE_END),
606 _X("TITLE", _HFSA_NEEDSEP), /*_X("/TITLE", '\n'),*/
607 _X("H1", _HFSA_NEEDSEP), /*_X("/H1", '\n'),*/
608 _X("H2", _HFSA_NEEDSEP), /*_X("/H2", '\n'),*/
609 _X("H3", _HFSA_NEEDSEP), /*_X("/H3", '\n'),*/
610 _X("H4", _HFSA_NEEDSEP), /*_X("/H4", '\n'),*/
611 _X("H5", _HFSA_NEEDSEP), /*_X("/H5", '\n'),*/
612 _X("H6", _HFSA_NEEDSEP), /*_X("/H6", '\n'),*/
614 _X("STYLE", _HFSA_IGN),
615 _X("SCRIPT", _HFSA_IGN),
617 # undef _X
620 /* Entity list; not binary searched.. */
621 static struct hf_ent const _hf_ents[] = {
622 # undef _X
623 # undef _XU
624 # undef _XS
625 # undef _XUS
626 # define _X(E,C) {(sizeof(E) -1), C, 0x0u, "", E "\0"}
627 # define _XU(E,C,U) {(sizeof(E) -1) | _HFE_HAVE_UNI, C, U, "", E "\0"}
628 # define _XS(E,S) {(sizeof(E) -1) | _HFE_HAVE_CSTR, '\0', 0x0u,S "\0",E "\0"}
629 # define _XSU(E,S,U) \
630 {(sizeof(E) -1) | _HFE_HAVE_UNI | _HFE_HAVE_CSTR, '\0', U, S "\0", E "\0"}
632 _X("quot", '"'),
633 _X("amp", '&'),
634 _X("lt", '<'), _X("gt", '>'),
636 _XU("nbsp", ' ', 0x0020 /* Note: not 0x00A0 seems to be better for us */),
637 _XU("middot", '.', 0x00B7),
638 _XSU("hellip", "...", 0x2026),
639 _XSU("mdash", "---", 0x2014), _XSU("ndash", "--", 0x2013),
640 _XSU("laquo", "<<", 0x00AB), _XSU("raquo", ">>", 0x00BB),
641 _XSU("lsaquo", "<", 0x2039), _XSU("rsaquo", ">", 0x203A),
642 _XSU("lsquo", "'", 0x2018), _XSU("rsquo", "'", 0x2019),
643 _XSU("ldquo", "\"", 0x201C), _XSU("rdquo", "\"", 0x201D),
644 _XSU("uarr", "^|", 0x2191), _XSU("darr", "|v", 0x2193),
646 _XSU("cent", "CENT", 0x00A2),
647 _XSU("copy", "(C)", 0x00A9),
648 _XSU("euro", "EUR", 0x20AC),
649 _XSU("infin", "INFY", 0x221E),
650 _XSU("pound", "GBP", 0x00A3),
651 _XSU("reg", "(R)", 0x00AE),
652 _XSU("sect", "S:", 0x00A7),
653 _XSU("yen", "JPY", 0x00A5),
655 /* German umlauts */
656 _XSU("Auml", "Ae", 0x00C4), _XSU("auml", "ae", 0x00E4),
657 _XSU("Ouml", "Oe", 0x00D6), _XSU("ouml", "oe", 0x00F6),
658 _XSU("Uuml", "Ue", 0x00DC), _XSU("uuml", "ue", 0x00FC),
659 _XSU("szlig", "ss", 0x00DF)
661 # undef _X
662 # undef _XU
663 # undef _XS
664 # undef _XSU
667 /* Real output */
668 static struct htmlflt * _hf_dump_hrefs(struct htmlflt *self);
669 static struct htmlflt * _hf_dump(struct htmlflt *self);
670 static struct htmlflt * _hf_store(struct htmlflt *self, char c);
671 # ifdef HAVE_NATCH_CHAR
672 static struct htmlflt * __hf_sync_mbstuff(struct htmlflt *self);
673 # endif
675 /* Virtual output */
676 static struct htmlflt * _hf_nl(struct htmlflt *self);
677 static struct htmlflt * _hf_nl_force(struct htmlflt *self);
678 static struct htmlflt * _hf_putc(struct htmlflt *self, char c);
679 static struct htmlflt * _hf_putc_premode(struct htmlflt *self, char c);
680 static struct htmlflt * _hf_puts(struct htmlflt *self, char const *cp);
681 static struct htmlflt * _hf_putbuf(struct htmlflt *self,
682 char const *cp, size_t len);
684 /* Try to locate a param'eter in >hf_bdat, store it (non-terminated!) or NULL */
685 static struct htmlflt * _hf_param(struct htmlflt *self, struct str *store,
686 char const *param);
688 /* Expand all entities in the given parameter */
689 static struct htmlflt * _hf_expand_all_ents(struct htmlflt *self,
690 struct str const *param);
692 /* Completely parsed over a tag / an entity, interpret that */
693 static struct htmlflt * _hf_check_tag(struct htmlflt *self, char const *s);
694 static struct htmlflt * _hf_check_ent(struct htmlflt *self, char const *s,
695 size_t l);
697 /* Input handler */
698 static ssize_t _hf_add_data(struct htmlflt *self,
699 char const *dat, size_t len);
701 static struct htmlflt *
702 _hf_dump_hrefs(struct htmlflt *self)
704 struct htmlflt_href *hhp;
705 NYD2_ENTER;
707 if (!(self->hf_flags & _HF_NL_2) && putc('\n', self->hf_os) == EOF) {
708 self->hf_flags |= _HF_ERROR;
709 goto jleave;
712 /* Reverse the list */
713 for (hhp = self->hf_hrefs, self->hf_hrefs = NULL; hhp != NULL;) {
714 struct htmlflt_href *tmp = hhp->hfh_next;
715 hhp->hfh_next = self->hf_hrefs;
716 self->hf_hrefs = hhp;
717 hhp = tmp;
720 /* Then dump it */
721 while ((hhp = self->hf_hrefs) != NULL) {
722 self->hf_hrefs = hhp->hfh_next;
724 if (!(self->hf_flags & _HF_ERROR)) {
725 int w = fprintf(self->hf_os, " [%u] %.*s\n",
726 hhp->hfh_no, (int)hhp->hfh_len, hhp->hfh_dat);
727 if (w < 0)
728 self->hf_flags |= _HF_ERROR;
730 free(hhp);
733 self->hf_flags |= (putc('\n', self->hf_os) == EOF)
734 ? _HF_ERROR : _HF_NL_1 | _HF_NL_2;
735 self->hf_href_dist = (ui32_t)n_realscreenheight >> 1;
736 jleave:
737 NYD2_LEAVE;
738 return self;
741 static struct htmlflt *
742 _hf_dump(struct htmlflt *self)
744 ui32_t f, l;
745 char c, *cp;
746 NYD2_ENTER;
748 f = self->hf_flags & ~_HF_BLANK;
749 l = self->hf_len;
750 cp = self->hf_line;
751 self->hf_mbwidth = self->hf_mboff = self->hf_last_ws = self->hf_len = 0;
753 for (c = '\0'; l > 0; --l) {
754 c = *cp++;
755 jput:
756 if (putc(c, self->hf_os) == EOF) {
757 self->hf_flags = (f |= _HF_ERROR);
758 goto jleave;
762 if (c != '\n') {
763 f |= (f & _HF_NL_1) ? _HF_NL_2 : _HF_NL_1;
764 l = 1;
765 c = '\n';
766 goto jput;
768 self->hf_flags = f;
770 /* Check whether there are HREFs to dump; there is so much messy tagsoup out
771 * there that it seems best not to simply dump HREFs in each _dump(), but
772 * only with some gap, let's say half the real screen height */
773 if (--self->hf_href_dist < 0 && (f & _HF_NL_2) && self->hf_hrefs != NULL)
774 self = _hf_dump_hrefs(self);
775 jleave:
776 NYD2_LEAVE;
777 return self;
780 static struct htmlflt *
781 _hf_store(struct htmlflt *self, char c)
783 ui32_t f, l, i;
784 NYD2_ENTER;
786 assert(c != '\n');
788 f = self->hf_flags;
789 l = self->hf_len;
790 self->hf_line[l] = (c == '\t' ? ' ' : c);
791 self->hf_len = ++l;
792 if (blankspacechar(c)) {
793 if (c == '\t') {
794 i = 8 - ((l - 1) & 7); /* xxx magic tab width of 8 */
795 if (i > 0) {
797 self = _hf_store(self, ' ');
798 while (--i > 0);
799 goto jleave;
802 self->hf_last_ws = l;
803 } else if (/*c == '.' ||*/ c == ',' || c == ';' || c == '-')
804 self->hf_last_ws = l;
806 i = l;
807 # ifdef HAVE_NATCH_CHAR /* XXX This code is really ridiculous! */
808 if (n_mb_cur_max > 1) { /* XXX should mbrtowc() and THEN store, at least.. */
809 wchar_t wc;
810 int w, x = mbtowc(&wc, self->hf_line + self->hf_mboff, l - self->hf_mboff);
812 if (x > 0) {
813 if ((w = wcwidth(wc)) == -1 ||
814 /* Actively filter out L-TO-R and R-TO-R marks TODO ctext */
815 (wc == 0x200E || wc == 0x200F ||
816 (wc >= 0x202A && wc <= 0x202E)) ||
817 /* And some zero-width messes */
818 wc == 0x00AD || (wc >= 0x200B && wc <= 0x200D) ||
819 /* Oh about the ISO C wide character interfaces, baby! */
820 (wc == 0xFEFF)){
821 self->hf_len -= x;
822 goto jleave;
823 } else if (iswspace(wc))
824 self->hf_last_ws = l;
825 self->hf_mboff += x;
826 i = (self->hf_mbwidth += w);
827 } else {
828 if (x < 0) {
829 (void)mbtowc(&wc, NULL, n_mb_cur_max);
830 if (UICMP(32, l - self->hf_mboff, >=, n_mb_cur_max)) { /* XXX */
831 ++self->hf_mboff;
832 ++self->hf_mbwidth;
835 i = self->hf_mbwidth;
838 # endif
840 /* Do we need to break the line? */
841 if (i >= self->hf_lmax - _HF_BRKSUB) {
842 ui32_t lim = self->hf_lmax >> 1;
844 /* Let's hope we saw a sane place to break this line! */
845 if (self->hf_last_ws >= lim) {
846 jput:
847 i = self->hf_len = self->hf_last_ws;
848 self = _hf_dump(self);
849 if ((self->hf_len = (l -= i)) > 0) {
850 self->hf_flags &= ~_HF_NL_MASK;
851 memmove(self->hf_line, self->hf_line + i, l);
852 # ifdef HAVE_NATCH_CHAR
853 __hf_sync_mbstuff(self);
854 # endif
856 goto jleave;
859 /* Any 7-bit characters? */
860 for (i = l; i-- >= lim;)
861 if (asciichar((c = self->hf_line[i]))) {
862 self->hf_last_ws = ++i;
863 goto jput;
864 } else if ((f & _HF_UTF8) && ((ui8_t)c & 0xC0) != 0x80) {
865 self->hf_last_ws = i;
866 goto jput;
869 /* Hard break necessary! xxx really badly done */
870 if (l >= self->hf_lmax - 1)
871 self = _hf_dump(self);
873 jleave:
874 NYD2_LEAVE;
875 return self;
878 # ifdef HAVE_NATCH_CHAR
879 static struct htmlflt *
880 __hf_sync_mbstuff(struct htmlflt *self)
882 wchar_t wc;
883 char const *b;
884 ui32_t o, w, l;
885 NYD2_ENTER;
887 b = self->hf_line;
888 o = w = 0;
889 l = self->hf_len;
890 goto jumpin;
892 while (l > 0) {
893 int x = mbtowc(&wc, b, l);
895 if (x == 0)
896 break;
898 if (x > 0) {
899 b += x;
900 l -= x;
901 o += x;
902 if ((x = wcwidth(wc)) == -1)
903 x = 1;
904 w += x;
905 continue;
908 /* Bad, skip over a single character.. XXX very bad indeed */
909 ++b;
910 ++o;
911 ++w;
912 --l;
913 jumpin:
914 (void)mbtowc(&wc, NULL, n_mb_cur_max);
917 self->hf_mboff = o;
918 self->hf_mbwidth = w;
920 NYD2_LEAVE;
921 return self;
923 # endif /* HAVE_NATCH_CHAR */
925 static struct htmlflt *
926 _hf_nl(struct htmlflt *self)
928 ui32_t f;
929 NYD2_ENTER;
931 if (!((f = self->hf_flags) & _HF_ERROR)) {
932 if (f & _HF_ANY) {
933 if ((f & _HF_NL_MASK) != _HF_NL_MASK)
934 self = _hf_dump(self);
935 } else
936 self->hf_flags = (f |= _HF_NL_MASK);
938 NYD2_LEAVE;
939 return self;
942 static struct htmlflt *
943 _hf_nl_force(struct htmlflt *self)
945 NYD2_ENTER;
946 if (!(self->hf_flags & _HF_ERROR))
947 self = _hf_dump(self);
948 NYD2_LEAVE;
949 return self;
952 static struct htmlflt *
953 _hf_putc(struct htmlflt *self, char c)
955 ui32_t f;
956 NYD2_ENTER;
958 if ((f = self->hf_flags) & _HF_ERROR)
959 goto jleave;
961 if (c == '\n') {
962 self = _hf_nl(self);
963 goto jleave;
964 } else if (c == ' ' || c == '\t') {
965 if ((f & _HF_BLANK) || self->hf_len == 0)
966 goto jleave;
967 f |= _HF_BLANK;
968 } else
969 f &= ~_HF_BLANK;
970 f &= ~_HF_NL_MASK;
971 self->hf_flags = (f |= _HF_ANY);
972 self = _hf_store(self, c);
973 jleave:
974 NYD2_LEAVE;
975 return self;
978 static struct htmlflt *
979 _hf_putc_premode(struct htmlflt *self, char c)
981 ui32_t f;
982 NYD2_ENTER;
984 if ((f = self->hf_flags) & _HF_ERROR) {
986 } else if (c == '\n')
987 self = _hf_nl_force(self);
988 else {
989 f &= ~_HF_NL_MASK;
990 self->hf_flags = (f |= _HF_ANY);
991 self = _hf_store(self, c);
993 NYD2_LEAVE;
994 return self;
997 static struct htmlflt *
998 _hf_puts(struct htmlflt *self, char const *cp)
1000 char c;
1001 NYD2_ENTER;
1003 while ((c = *cp++) != '\0')
1004 self = _hf_putc(self, c);
1005 NYD2_LEAVE;
1006 return self;
1009 static struct htmlflt *
1010 _hf_putbuf(struct htmlflt *self, char const *cp, size_t len)
1012 NYD2_ENTER;
1014 while (len-- > 0)
1015 self = _hf_putc(self, *cp++);
1016 NYD2_LEAVE;
1017 return self;
1020 static struct htmlflt *
1021 _hf_param(struct htmlflt *self, struct str *store, char const *param)
1023 char const *cp;
1024 char c, x, quote;
1025 size_t i;
1026 bool_t hot;
1027 NYD2_ENTER;
1029 store->s = NULL;
1030 store->l = 0;
1031 cp = self->hf_bdat;
1033 /* Skip over any non-WS first; be aware of soup, if it slipped through */
1034 for(;;){
1035 if((c = *cp++) == '\0' || c == '>')
1036 goto jleave;
1037 if(whitechar(c))
1038 break;
1041 /* Search for the parameter, take care of other quoting along the way */
1042 x = *param++;
1043 x = upperconv(x);
1044 i = strlen(param);
1046 for(hot = TRU1;;){
1047 if((c = *cp++) == '\0' || c == '>')
1048 goto jleave;
1049 if(whitechar(c)){
1050 hot = TRU1;
1051 continue;
1054 /* Could it be a parameter? */
1055 if(hot){
1056 hot = FAL0;
1058 /* Is it the desired one? */
1059 if((c = upperconv(c)) == x && !ascncasecmp(param, cp, i)){
1060 char const *cp2 = cp + i;
1062 if((quote = *cp2++) != '='){
1063 if(quote == '\0' || quote == '>')
1064 goto jleave;
1065 while(whitechar(quote))
1066 quote = *cp2++;
1068 if(quote == '='){
1069 cp = cp2;
1070 break;
1072 continue; /* XXX Optimize: i bytes or even cp2 can't be it! */
1076 /* Not the desired one; but a parameter? */
1077 if(c != '=')
1078 continue;
1079 /* If so, properly skip over the value */
1080 if((c = *cp++) == '"' || c == '\''){
1081 /* TODO i have forgotten whether reverse solidus quoting is allowed
1082 * TODO quoted HTML parameter values? not supporting that for now.. */
1083 for(quote = c; (c = *cp++) != '\0' && c != quote;)
1085 }else
1086 while(c != '\0' && !whitechar(c) && c != '>')
1087 c = *++cp;
1088 if(c == '\0')
1089 goto jleave;
1092 /* Skip further whitespace */
1093 for(;;){
1094 if((c = *cp++) == '\0' || c == '>')
1095 goto jleave;
1096 if(!whitechar(c))
1097 break;
1100 if(c == '"' || c == '\''){
1101 /* TODO i have forgotten whether reverse solisud quoting is allowed in
1102 * TODO quoted HTML parameter values? not supporting that for now.. */
1103 store->s = n_UNCONST(cp);
1104 for(quote = c; (c = *cp) != '\0' && c != quote; ++cp)
1106 /* XXX ... and we simply ignore a missing trailing " :> */
1107 }else{
1108 store->s = n_UNCONST(cp - 1);
1109 if(!whitechar(c))
1110 while((c = *cp) != '\0' && !whitechar(c) && c != '>')
1111 ++cp;
1113 i = PTR2SIZE(cp - store->s);
1115 /* Terrible tagsoup out there, e.g., groups.google.com produces href=""
1116 * parameter values prefixed and suffixed by newlines! Therefore trim the
1117 * value content TODO join into the parse step above! */
1118 for (cp = store->s; i > 0 && spacechar(*cp); ++cp, --i)
1120 store->s = n_UNCONST(cp);
1121 for (cp += i - 1; i > 0 && spacechar(*cp); --cp, --i)
1123 if ((store->l = i) == 0)
1124 store->s = NULL;
1125 jleave:
1126 NYD2_LEAVE;
1127 return self;
1130 static struct htmlflt *
1131 _hf_expand_all_ents(struct htmlflt *self, struct str const *param)
1133 char const *cp, *maxcp, *ep;
1134 char c;
1135 size_t i;
1136 NYD2_ENTER;
1138 for (cp = param->s, maxcp = cp + param->l; cp < maxcp;)
1139 if ((c = *cp++) != '&')
1140 jputc:
1141 self = _hf_putc(self, c);
1142 else {
1143 for (ep = cp--;;) {
1144 if (ep == maxcp || (c = *ep++) == '\0') {
1145 for (; cp < ep; ++cp)
1146 self = _hf_putc(self, *cp);
1147 goto jleave;
1148 } else if (c == ';') {
1149 if ((i = PTR2SIZE(ep - cp)) > 1) {
1150 self = _hf_check_ent(self, cp, i);
1151 break;
1152 } else {
1153 c = *cp++;
1154 goto jputc;
1158 cp = ep;
1160 jleave:
1161 NYD2_LEAVE;
1162 return self;
1165 static struct htmlflt *
1166 _hf_check_tag(struct htmlflt *self, char const *s)
1168 char nobuf[32], c;
1169 struct str param;
1170 size_t i;
1171 struct htmlflt_tag const *hftp;
1172 ui32_t f;
1173 NYD2_ENTER;
1175 /* Extra check only */
1176 assert(s != NULL);
1177 if (*s != '<') {
1178 DBG( n_alert("HTML tagsoup filter _hf_check_tag() called on soup!"); )
1179 jput_as_is:
1180 self = _hf_puts(self, self->hf_bdat);
1181 goto jleave;
1184 for (++s, i = 0; (c = s[i]) != '\0' && c != '>' && !whitechar(c); ++i)
1185 /* Special massage for things like <br/>: after the slash only whitespace
1186 * may separate us from the closing right angle! */
1187 if (c == '/') {
1188 size_t j = i + 1;
1190 while ((c = s[j]) != '\0' && c != '>' && whitechar(c))
1191 ++j;
1192 if (c == '>')
1193 break;
1196 for (hftp = _hf_tags;;) {
1197 if (i == hftp->hft_len && !ascncasecmp(s, hftp->hft_tag, i)) {
1198 c = s[hftp->hft_len];
1199 if (c == '>' || c == '/' || whitechar(c))
1200 break;
1202 if (PTRCMP(++hftp, >=, _hf_tags + n_NELEM(_hf_tags)))
1203 goto jnotknown;
1206 f = self->hf_flags;
1207 switch (hftp->hft_act) {
1208 case _HFSA_PRE_END:
1209 f &= ~_HF_PRE;
1210 if (0) {
1211 /* FALLTHRU */
1212 case _HFSA_PRE:
1213 f |= _HF_PRE;
1215 self->hf_flags = f;
1216 /* FALLTHRU */
1218 case _HFSA_NEEDSEP:
1219 if (!(self->hf_flags & _HF_NL_2))
1220 self = _hf_nl(self);
1221 /* FALLTHRU */
1222 case _HFSA_NEEDNL:
1223 if (!(f & _HF_NL_1))
1224 self = _hf_nl(self);
1225 if (hftp->hft_injc != '\0') {
1226 self = _hf_putc(self, hftp->hft_injc & 0x7F);
1227 if ((uc_i)hftp->hft_injc & 0x80)
1228 self = _hf_putc(self, ' ');
1230 break;
1232 case _HFSA_IGN:
1233 self->hf_ign_tag = hftp;
1234 self->hf_flags = (f |= _HF_IGN | _HF_NOPUT);
1235 break;
1237 case _HFSA_IMG:
1238 self = _hf_param(self, &param, "alt");
1239 self = _hf_putc(self, '[');
1240 if (param.s == NULL) {
1241 param.s = n_UNCONST("IMG");
1242 param.l = 3;
1243 goto jimg_put;
1244 } /* else */ if (memchr(param.s, '&', param.l) != NULL)
1245 self = _hf_expand_all_ents(self, &param);
1246 else
1247 jimg_put:
1248 self = _hf_putbuf(self, param.s, param.l);
1249 self = _hf_putc(self, ']');
1250 break;
1252 case _HFSA_HREF:
1253 self = _hf_param(self, &param, "href");
1254 /* Ignore non-external links */
1255 if (param.s != NULL && *param.s != '#') {
1256 struct htmlflt_href *hhp = smalloc(
1257 n_VSTRUCT_SIZEOF(struct htmlflt_href, hfh_dat) + param.l +1);
1259 hhp->hfh_next = self->hf_hrefs;
1260 hhp->hfh_no = ++self->hf_href_no;
1261 hhp->hfh_len = (ui32_t)param.l;
1262 memcpy(hhp->hfh_dat, param.s, param.l);
1264 snprintf(nobuf, sizeof nobuf, "[%u]", hhp->hfh_no);
1265 self->hf_flags = (f |= _HF_HREF);
1266 self->hf_hrefs = hhp;
1267 self = _hf_puts(self, nobuf);
1268 } else
1269 self->hf_flags = (f &= ~_HF_HREF);
1270 break;
1271 case _HFSA_HREF_END:
1272 if (f & _HF_HREF) {
1273 snprintf(nobuf, sizeof nobuf, "[/%u]", self->hf_href_no);
1274 self = _hf_puts(self, nobuf);
1276 break;
1278 default:
1279 c = (char)(hftp->hft_act & 0xFF);
1280 self = _hf_putc(self, c);
1281 break;
1282 case '\0':
1283 break;
1285 jleave:
1286 NYD2_LEAVE;
1287 return self;
1289 /* The problem is that even invalid tagsoup is widely used, without real
1290 * searching i have seen e-mail address in <N@H.D> notation, and more.
1291 * To protect us a bit look around and possibly write the content as such */
1292 jnotknown:
1293 switch (*s) {
1294 case '!':
1295 case '?':
1296 /* Ignore <!DOCTYPE, <!-- comments, <? PIs.. */
1297 goto jleave;
1298 case '>':
1299 /* Print out an empty tag as such */
1300 if (s[1] == '\0') {
1301 --s;
1302 goto jput_as_is;
1304 break;
1305 case '/':
1306 ++s;
1307 break;
1308 default:
1309 break;
1312 /* Also skip over : in order to suppress v:roundrect, w:anchorlock.. */
1313 while ((c = *s++) != '\0' && c != '>' && !whitechar(c) && c != ':')
1314 if (!asciichar(c) || punctchar(c)) {
1315 self = _hf_puts(self, self->hf_bdat);
1316 break;
1318 goto jleave;
1321 static struct htmlflt *
1322 _hf_check_ent(struct htmlflt *self, char const *s, size_t l)
1324 char nobuf[32];
1325 char const *s_save;
1326 size_t l_save;
1327 struct hf_ent const *hfep;
1328 size_t i;
1329 NYD2_ENTER;
1331 s_save = s;
1332 l_save = l;
1333 assert(*s == '&');
1334 assert(l > 0);
1335 /* False entities seen in the wild assert(s[l - 1] == ';'); */
1336 ++s;
1337 l -= 2;
1339 /* Numeric entity, or try named search */
1340 if (*s == '#') {
1341 i = (*++s == 'x' ? 16 : 10);
1343 if ((i != 16 || (++s, --l) > 0) && l < sizeof(nobuf)) {
1344 memcpy(nobuf, s, l);
1345 nobuf[l] = '\0';
1346 n_idec_uiz_cp(&i, nobuf, i, NULL);
1347 if (i <= 0x7F)
1348 self = _hf_putc(self, (char)i);
1349 else if (self->hf_flags & _HF_UTF8) {
1350 jputuni:
1351 l = n_utf32_to_utf8((ui32_t)i, nobuf);
1352 self = _hf_putbuf(self, nobuf, l);
1353 } else
1354 goto jeent;
1355 } else
1356 goto jeent;
1357 } else {
1358 ui32_t f = self->hf_flags, hf;
1360 for (hfep = _hf_ents; PTRCMP(hfep, <, _hf_ents + n_NELEM(_hf_ents));
1361 ++hfep)
1362 if (l == ((hf = hfep->hfe_flags) & _HFE_LENGTH_MASK) &&
1363 !strncmp(s, hfep->hfe_ent, l)) {
1364 if ((hf & _HFE_HAVE_UNI) && (f & _HF_UTF8)) {
1365 i = hfep->hfe_uni;
1366 goto jputuni;
1367 } else if (hf & _HFE_HAVE_CSTR)
1368 self = _hf_puts(self, hfep->hfe_cstr);
1369 else
1370 self = _hf_putc(self, hfep->hfe_c);
1371 goto jleave;
1373 jeent:
1374 self = _hf_putbuf(self, s_save, l_save);
1376 jleave:
1377 NYD2_LEAVE;
1378 return self;
1381 static ssize_t
1382 _hf_add_data(struct htmlflt *self, char const *dat, size_t len)
1384 char c, *cp, *cp_max;
1385 bool_t hot;
1386 ssize_t rv = 0;
1387 NYD_ENTER;
1389 /* Final put request? */
1390 if (dat == NULL) {
1391 if (self->hf_len > 0 || self->hf_hrefs != NULL) {
1392 self = _hf_dump(self);
1393 if (self->hf_hrefs != NULL)
1394 self = _hf_dump_hrefs(self);
1395 rv = 1;
1397 goto jleave;
1400 /* Always ensure some initial buffer */
1401 if ((cp = self->hf_curr) != NULL)
1402 cp_max = self->hf_bmax;
1403 else {
1404 cp = self->hf_curr = self->hf_bdat = smalloc(LINESIZE);
1405 cp_max = self->hf_bmax = cp + LINESIZE -1; /* (Always room for NUL!) */
1407 hot = (cp != self->hf_bdat);
1409 for (rv = (ssize_t)len; len > 0; --len) {
1410 ui32_t f = self->hf_flags;
1412 if (f & _HF_ERROR)
1413 break;
1414 c = *dat++;
1416 /* Soup is really weird, and scripts may contain almost anything (and
1417 * newer CSS standards are also cryptic): therefore prefix the _HF_IGN
1418 * test and walk until we see the required end tag */
1419 /* TODO For real safety _HF_IGN soup condome would also need to know
1420 * TODO about quoted strings so that 'var i = "</script>";' couldn't
1421 * TODO fool it! We really want this mode also for _HF_NOPUT to be
1422 * TODO able to *gracefully* detect the tag-closing '>', but then if
1423 * TODO that is a single mechanism we should have made it! */
1424 if (f & _HF_IGN) {
1425 struct htmlflt_tag const *hftp = self->hf_ign_tag;
1426 size_t i;
1428 if (c == '<') {
1429 hot = TRU1;
1430 jcp_reset:
1431 cp = self->hf_bdat;
1432 } else if (c == '>') {
1433 if (hot) {
1434 if ((i = PTR2SIZE(cp - self->hf_bdat)) > 1 &&
1435 --i == hftp->hft_len &&
1436 !ascncasecmp(self->hf_bdat + 1, hftp->hft_tag, i))
1437 self->hf_flags = (f &= ~(_HF_IGN | _HF_NOPUT));
1438 hot = FAL0;
1439 goto jcp_reset;
1441 } else if (hot) {
1442 *cp++ = c;
1443 i = PTR2SIZE(cp - self->hf_bdat);
1444 if ((i == 1 && c != '/') || --i > hftp->hft_len) {
1445 hot = FAL0;
1446 goto jcp_reset;
1449 } else switch (c) {
1450 case '<':
1451 /* People are using & without &amp;ing it, ditto <; be aware */
1452 if (f & (_HF_NOPUT | _HF_ENT)) {
1453 f &= ~_HF_ENT;
1454 /* Special case "<!--" buffer content to deal with really weird
1455 * things that can be done with "<!--[if gte mso 9]>" syntax */
1456 if (PTR2SIZE(cp - self->hf_bdat) != 4 ||
1457 memcmp(self->hf_bdat, "<!--", 4)) {
1458 self->hf_flags = f;
1459 *cp = '\0';
1460 self = _hf_puts(self, self->hf_bdat);
1461 f = self->hf_flags;
1464 cp = self->hf_bdat;
1465 *cp++ = c;
1466 self->hf_flags = (f |= _HF_NOPUT);
1467 break;
1468 case '>':
1469 /* Weird tagsoup around, do we actually parse a tag? */
1470 if (!(f & _HF_NOPUT))
1471 goto jdo_c;
1472 cp[0] = c;
1473 cp[1] = '\0';
1474 f &= ~(_HF_NOPUT | _HF_ENT);
1475 self->hf_flags = f;
1476 self = _hf_check_tag(self, self->hf_bdat);
1477 *(cp = self->hf_bdat) = '\0'; /* xxx extra safety */
1478 /* Quick hack to get rid of redundant newline after <pre> XXX */
1479 if (!(f & _HF_PRE) && (self->hf_flags & _HF_PRE) &&
1480 len > 1 && *dat == '\n')
1481 ++dat, --len;
1482 break;
1484 case '\r': /* TODO CR should be stripped in lower level!! (Only B64!?!) */
1485 break;
1486 case '\n':
1487 /* End of line is not considered unless we are in PRE section.
1488 * However, in _HF_NOPUT mode we must be aware of tagsoup which uses
1489 * newlines for separating parameters */
1490 if (f & _HF_NOPUT)
1491 goto jdo_c;
1492 self = (f & _HF_PRE) ? _hf_nl_force(self) : _hf_putc(self, ' ');
1493 break;
1495 case '\t':
1496 if (!(f & _HF_PRE))
1497 c = ' ';
1498 /* FALLTHRU */
1499 default:
1500 jdo_c:
1501 /* If not currently parsing a tag and bypassing normal output.. */
1502 if (!(f & _HF_NOPUT)) {
1503 if (cntrlchar(c))
1504 break;
1505 if (c == '&') {
1506 cp = self->hf_bdat;
1507 *cp++ = c;
1508 self->hf_flags = (f |= _HF_NOPUT | _HF_ENT);
1509 } else if (f & _HF_PRE) {
1510 self = _hf_putc_premode(self, c);
1511 self->hf_flags &= ~_HF_BLANK;
1512 } else
1513 self = _hf_putc(self, c);
1514 } else if ((f & _HF_ENT) && c == ';') {
1515 cp[0] = c;
1516 cp[1] = '\0';
1517 f &= ~(_HF_NOPUT | _HF_ENT);
1518 self->hf_flags = f;
1519 self = _hf_check_ent(self, self->hf_bdat,
1520 PTR2SIZE(cp + 1 - self->hf_bdat));
1521 } else {
1522 /* We may need to grow the buffer */
1523 if (PTRCMP(cp + 42/2, >=, cp_max)) {
1524 size_t i = PTR2SIZE(cp - self->hf_bdat),
1525 m = PTR2SIZE(self->hf_bmax - self->hf_bdat) + LINESIZE;
1527 cp = self->hf_bdat = srealloc(self->hf_bdat, m);
1528 self->hf_bmax = cp + m -1;
1529 self->hf_curr = (cp += i);
1531 *cp++ = c;
1535 self->hf_curr = cp;
1536 jleave:
1537 NYD_LEAVE;
1538 return (self->hf_flags & _HF_ERROR) ? -1 : rv;
1542 * TODO Because we don't support filter chains yet this filter will be run
1543 * TODO in a dedicated subprocess, driven via a special Popen() mode
1545 static bool_t __hf_hadpipesig;
1546 static void
1547 __hf_onpipe(int signo)
1549 NYD_X; /* Signal handler */
1550 n_UNUSED(signo);
1551 __hf_hadpipesig = TRU1;
1554 FL int
1555 htmlflt_process_main(void)
1557 char buf[BUFFER_SIZE];
1558 struct htmlflt hf;
1559 size_t i;
1560 int rv;
1561 NYD_ENTER;
1563 __hf_hadpipesig = FAL0;
1564 safe_signal(SIGPIPE, &__hf_onpipe);
1566 htmlflt_init(&hf);
1567 htmlflt_reset(&hf, n_stdout);
1569 for (;;) {
1570 if ((i = fread(buf, sizeof(buf[0]), n_NELEM(buf), n_stdin)) == 0) {
1571 rv = !feof(n_stdin);
1572 break;
1575 if ((rv = __hf_hadpipesig))
1576 break;
1577 /* Just use this directly.. */
1578 if (htmlflt_push(&hf, buf, i) < 0) {
1579 rv = 1;
1580 break;
1583 if (rv == 0 && htmlflt_flush(&hf) < 0)
1584 rv = 1;
1586 htmlflt_destroy(&hf);
1588 rv |= __hf_hadpipesig;
1589 NYD_LEAVE;
1590 return rv;
1593 FL void
1594 htmlflt_init(struct htmlflt *self)
1596 NYD_ENTER;
1597 /* (Rather redundant though) */
1598 memset(self, 0, sizeof *self);
1599 NYD_LEAVE;
1602 FL void
1603 htmlflt_destroy(struct htmlflt *self)
1605 NYD_ENTER;
1606 htmlflt_reset(self, NULL);
1607 NYD_LEAVE;
1610 FL void
1611 htmlflt_reset(struct htmlflt *self, FILE *f)
1613 struct htmlflt_href *hfhp;
1614 NYD_ENTER;
1616 while ((hfhp = self->hf_hrefs) != NULL) {
1617 self->hf_hrefs = hfhp->hfh_next;
1618 free(hfhp);
1621 if (self->hf_bdat != NULL)
1622 free(self->hf_bdat);
1623 if (self->hf_line != NULL)
1624 free(self->hf_line);
1626 memset(self, 0, sizeof *self);
1628 if (f != NULL) {
1629 ui32_t sw = n_MAX(_HF_MINLEN, (ui32_t)n_scrnwidth);
1631 self->hf_line = smalloc((size_t)sw * n_mb_cur_max +1);
1632 self->hf_lmax = sw;
1634 if (n_psonce & n_PSO_UNICODE) /* TODO not truly generic */
1635 self->hf_flags = _HF_UTF8;
1636 self->hf_os = f;
1638 NYD_LEAVE;
1641 FL ssize_t
1642 htmlflt_push(struct htmlflt *self, char const *dat, size_t len)
1644 ssize_t rv;
1645 NYD_ENTER;
1647 rv = _hf_add_data(self, dat, len);
1648 NYD_LEAVE;
1649 return rv;
1652 FL ssize_t
1653 htmlflt_flush(struct htmlflt *self)
1655 ssize_t rv;
1656 NYD_ENTER;
1658 rv = _hf_add_data(self, NULL, 0);
1659 rv |= !fflush(self->hf_os) ? 0 : -1;
1660 NYD_LEAVE;
1661 return rv;
1663 #endif /* HAVE_FILTER_HTML_TAGSOUP */
1665 /* s-it-mode */