659f454c33e409c6c0a5521bd68a70fca3a1ffcd
[citadel.git] / webcit / html2html.c
1 /*
2  * Output an HTML message, modifying it slightly to make sure it plays nice
3  * with the rest of our web framework.
4  *
5  * Copyright (c) 2005-2012 by the citadel.org team
6  *
7  * This program is open source software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License, version 3.
9  * 
10  * 
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * 
18  * 
19  */
20
21 #include "webcit.h"
22 #include "webserver.h"
23
24
25 /*
26  * Strip surrounding single or double quotes from a string.
27  */
28 void stripquotes(char *s)
29 {
30         int len;
31
32         if (!s) return;
33
34         len = strlen(s);
35         if (len < 2) return;
36
37         if ( ( (s[0] == '\"') && (s[len-1] == '\"') ) || ( (s[0] == '\'') && (s[len-1] == '\'') ) ) {
38                 s[len-1] = 0;
39                 strcpy(s, &s[1]);
40         }
41 }
42
43
44 /*
45  * Check to see if a META tag has overridden the declared MIME character set.
46  *
47  * charset              Character set name (left unchanged if we don't do anything)
48  * meta_http_equiv      Content of the "http-equiv" portion of the META tag
49  * meta_content         Content of the "content" portion of the META tag
50  */
51 void extract_charset_from_meta(char *charset, char *meta_http_equiv, char *meta_content)
52 {
53         char *ptr;
54         char buf[64];
55
56         if (!charset) return;
57         if (!meta_http_equiv) return;
58         if (!meta_content) return;
59
60
61         if (strcasecmp(meta_http_equiv, "Content-type")) return;
62
63         ptr = strchr(meta_content, ';');
64         if (!ptr) return;
65
66         safestrncpy(buf, ++ptr, sizeof buf);
67         striplt(buf);
68         if (!strncasecmp(buf, "charset=", 8)) {
69                 strcpy(charset, &buf[8]);
70
71                 /*
72                  * The brain-damaged webmail program in Microsoft Exchange declares
73                  * a charset of "unicode" when they really mean "UTF-8".  GNU iconv
74                  * treats "unicode" as an alias for "UTF-16" so we have to manually
75                  * fix this here, otherwise messages generated in Exchange webmail
76                  * show up as a big pile of weird characters.
77                  */
78                 if (!strcasecmp(charset, "unicode")) {
79                         strcpy(charset, "UTF-8");
80                 }
81
82                 /* Remove wandering punctuation */
83                 if ((ptr=strchr(charset, '\"'))) *ptr = 0;
84                 striplt(charset);
85         }
86 }
87
88
89
90 /*
91  * Sanitize and enhance an HTML message for display.
92  * Also convert weird character sets to UTF-8 if necessary.
93  * Also fixup img src="cid:..." type inline images to fetch the image
94  *
95  */
96 void output_html(const char *supplied_charset, int treat_as_wiki, int msgnum, StrBuf *Source, StrBuf *Target) {
97         char buf[SIZ];
98         char *msg;
99         char *ptr;
100         char *msgstart;
101         char *msgend;
102         StrBuf *converted_msg;
103         int buffer_length = 1;
104         int line_length = 0;
105         int content_length = 0;
106         char new_window[SIZ];
107         int brak = 0;
108         int alevel = 0;
109         int scriptlevel = 0;
110         int script_start_pos = (-1);
111         int i;
112         int linklen;
113         char charset[128];
114         StrBuf *BodyArea = NULL;
115 #ifdef HAVE_ICONV
116         iconv_t ic = (iconv_t)(-1) ;
117         char *ibuf;                   /* Buffer of characters to be converted */
118         char *obuf;                   /* Buffer for converted characters      */
119         size_t ibuflen;               /* Length of input buffer               */
120         size_t obuflen;               /* Length of output buffer              */
121         char *osav;                   /* Saved pointer to output buffer       */
122 #endif
123         if (Target == NULL)
124                 Target = WC->WBuf;
125
126         safestrncpy(charset, supplied_charset, sizeof charset);
127         msg = strdup("");
128         sprintf(new_window, "<a target=\"%s\" href=", TARGET);
129
130         if (Source == NULL) while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
131                 line_length = strlen(buf);
132                 buffer_length = content_length + line_length + 2;
133                 ptr = realloc(msg, buffer_length);
134                 if (ptr == NULL) {
135                         StrBufAppendPrintf(Target, "<b>");
136                         StrBufAppendPrintf(Target, _("realloc() error! couldn't get %d bytes: %s"),
137                                         buffer_length + 1,
138                                         strerror(errno));
139                         StrBufAppendPrintf(Target, "</b><br><br>\n");
140                         while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
141                                 /** flush */
142                         }
143                         free(msg);
144                         return;
145                 }
146                 msg = ptr;
147                 strcpy(&msg[content_length], buf);
148                 content_length += line_length;
149                 strcpy(&msg[content_length], "\n");
150                 content_length += 1;
151         }
152         else {
153                 content_length = StrLength(Source);
154                 free(msg);
155                 msg = (char*) ChrPtr(Source);/* TODO: remove cast */
156                 buffer_length = content_length;
157         }
158
159         /** Do a first pass to isolate the message body */
160         ptr = msg + 1;
161         msgstart = msg;
162         msgend = &msg[content_length];
163
164         while (ptr < msgend) {
165
166                 /** Advance to next tag */
167                 ptr = strchr(ptr, '<');
168                 if ((ptr == NULL) || (ptr >= msgend)) break;
169                 ++ptr;
170                 if ((ptr == NULL) || (ptr >= msgend)) break;
171
172                 /*
173                  *  Look for META tags.  Some messages (particularly in
174                  *  Asian locales) illegally declare a message's character
175                  *  set in the HTML instead of in the MIME headers.  This
176                  *  is wrong but we have to work around it anyway.
177                  */
178                 if (!strncasecmp(ptr, "META", 4)) {
179
180                         char *meta_start;
181                         char *meta_end;
182                         int meta_length;
183                         char *meta;
184                         char *meta_http_equiv;
185                         char *meta_content;
186                         char *spaceptr;
187
188                         meta_start = &ptr[4];
189                         meta_end = strchr(ptr, '>');
190                         if ((meta_end != NULL) && (meta_end <= msgend)) {
191                                 meta_length = meta_end - meta_start + 1;
192                                 meta = malloc(meta_length + 1);
193                                 safestrncpy(meta, meta_start, meta_length);
194                                 meta[meta_length] = 0;
195                                 striplt(meta);
196                                 if (!strncasecmp(meta, "HTTP-EQUIV=", 11)) {
197                                         meta_http_equiv = strdup(&meta[11]);
198                                         spaceptr = strchr(meta_http_equiv, ' ');
199                                         if (spaceptr != NULL) {
200                                                 *spaceptr = 0;
201                                                 meta_content = strdup(++spaceptr);
202                                                 if (!strncasecmp(meta_content, "content=", 8)) {
203                                                         strcpy(meta_content, &meta_content[8]);
204                                                         stripquotes(meta_http_equiv);
205                                                         stripquotes(meta_content);
206                                                         extract_charset_from_meta(charset,
207                                                                         meta_http_equiv, meta_content);
208                                                 }
209                                                 free(meta_content);
210                                         }
211                                         free(meta_http_equiv);
212                                 }
213                                 free(meta);
214                         }
215                 }
216
217                 /*
218                  * Any of these tags cause everything up to and including
219                  * the tag to be removed.
220                  */     
221                 if ( (!strncasecmp(ptr, "HTML", 4))
222                                 ||(!strncasecmp(ptr, "HEAD", 4))
223                                 ||(!strncasecmp(ptr, "/HEAD", 5))
224                                 ||(!strncasecmp(ptr, "BODY", 4)) ) {
225                         char *pBody = NULL;
226
227                         if (!strncasecmp(ptr, "BODY", 4)) {
228                                 pBody = ptr;
229                         }
230                         ptr = strchr(ptr, '>');
231                         if ((ptr == NULL) || (ptr >= msgend)) break;
232                         if ((pBody != NULL) && (ptr - pBody > 4)) {
233                                 char* src;
234                                 char *cid_start, *cid_end;
235
236                                 *ptr = '\0';
237                                 pBody += 4; 
238                                 while ((isspace(*pBody)) && (pBody < ptr))
239                                         pBody ++;
240                                 BodyArea = NewStrBufPlain(NULL,  ptr - pBody);
241
242                                 if (pBody < ptr) {
243                                         src = strstr(pBody, "cid:");
244                                         if (src) {
245                                                 cid_start = src + 4;
246                                                 cid_end = cid_start;
247                                                 while ((*cid_end != '"') && 
248                                                                 !isspace(*cid_end) &&
249                                                                 (cid_end < ptr))
250                                                         cid_end ++;
251
252                                                 /* copy tag and attributes up to src="cid: */
253                                                 StrBufAppendBufPlain(BodyArea, pBody, src - pBody, 0);
254
255                                                 /* add in /webcit/mimepart/<msgno>/CID/ 
256                                                    trailing / stops dumb URL filters getting excited */
257                                                 StrBufAppendPrintf(BodyArea,
258                                                                 "/webcit/mimepart/%d/",msgnum);
259                                                 StrBufAppendBufPlain(BodyArea, cid_start, cid_end - cid_start, 0);
260
261                                                 if (ptr - cid_end > 0)
262                                                         StrBufAppendBufPlain(BodyArea, 
263                                                                         cid_end + 1, 
264                                                                         ptr - cid_end, 0);
265                                         }
266                                         else 
267                                                 StrBufAppendBufPlain(BodyArea, pBody, ptr - pBody, 0);
268                                 }
269                                 *ptr = '>';
270                         }
271                         ++ptr;
272                         if ((ptr == NULL) || (ptr >= msgend)) break;
273                         msgstart = ptr;
274                 }
275
276                 /*
277                  * Any of these tags cause everything including and following
278                  * the tag to be removed.
279                  */
280                 if ( (!strncasecmp(ptr, "/HTML", 5))
281                                 ||(!strncasecmp(ptr, "/BODY", 5)) ) {
282                         --ptr;
283                         msgend = ptr;
284                         strcpy(ptr, "");
285
286                 }
287
288                 ++ptr;
289         }
290         if (msgstart > msg) {
291                 strcpy(msg, msgstart);
292         }
293
294         /* Now go through the message, parsing tags as necessary. */
295         converted_msg = NewStrBufPlain(NULL, content_length + 8192);
296
297
298         /** Convert foreign character sets to UTF-8 if necessary. */
299 #ifdef HAVE_ICONV
300         if ( (strcasecmp(charset, "us-ascii"))
301                         && (strcasecmp(charset, "UTF-8"))
302                         && (strcasecmp(charset, ""))
303            ) {
304                 syslog(9, "Converting %s to UTF-8\n", charset);
305                 ctdl_iconv_open("UTF-8", charset, &ic);
306                 if (ic == (iconv_t)(-1) ) {
307                         syslog(5, "%s:%d iconv_open() failed: %s\n",
308                                         __FILE__, __LINE__, strerror(errno));
309                 }
310         }
311         if  (Source == NULL) {
312                 if (ic != (iconv_t)(-1) ) {
313                         ibuf = msg;
314                         ibuflen = content_length;
315                         obuflen = content_length + (content_length / 2) ;
316                         obuf = (char *) malloc(obuflen);
317                         osav = obuf;
318                         iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
319                         content_length = content_length + (content_length / 2) - obuflen;
320                         osav[content_length] = 0;
321                         free(msg);
322                         msg = osav;
323                         iconv_close(ic);
324                 }
325         }
326         else {
327                 if (ic != (iconv_t)(-1) ) {
328                         StrBuf *Buf = NewStrBufPlain(NULL, StrLength(Source) + 8096);;
329                         StrBufConvert(Source, Buf, &ic);
330                         FreeStrBuf(&Buf);
331                         iconv_close(ic);
332                         msg = (char*)ChrPtr(Source); /* TODO: get rid of this. */
333                 }
334         }
335
336 #endif
337
338         /*
339          *      At this point, the message has been stripped down to
340          *      only the content inside the <BODY></BODY> tags, and has
341          *      been converted to UTF-8 if it was originally in a foreign
342          *      character set.  The text is also guaranteed to be null
343          *      terminated now.
344          */
345
346         if (converted_msg == NULL) {
347                 StrBufAppendPrintf(Target, "Error %d: %s<br>%s:%d", errno, strerror(errno), __FILE__, __LINE__);
348                 goto BAIL;
349         }
350
351         if (BodyArea != NULL) {
352                 StrBufAppendBufPlain(converted_msg, HKEY("<table "), 0);  
353                 StrBufAppendBuf(converted_msg, BodyArea, 0);
354                 StrBufAppendBufPlain(converted_msg, HKEY(" width=\"100%\"><tr><td>"), 0);
355         }
356         ptr = msg;
357         msgend = strchr(msg, 0);
358         while (ptr < msgend) {
359
360                 /** Try to sanitize the html of any rogue scripts */
361                 if (!strncasecmp(ptr, "<script", 7)) {
362                         if (scriptlevel == 0) {
363                                 script_start_pos = StrLength(converted_msg);
364                         }
365                         ++scriptlevel;
366                 }
367                 if (!strncasecmp(ptr, "</script", 8)) {
368                         --scriptlevel;
369                 }
370
371                 /**
372                  * Change mailto: links to WebCit mail, by replacing the
373                  * link with one that points back to our mail room.  Due to
374                  * the way we parse URL's, it'll even handle mailto: links
375                  * that have "?subject=" in them.
376                  */
377                 if (!strncasecmp(ptr, "<a href=\"mailto:", 16)) {
378                         content_length += 64;
379                         StrBufAppendPrintf(converted_msg,
380                                         "<a href=\"display_enter?force_room=_MAIL_?recp=");
381                         ptr = &ptr[16];
382                         ++alevel;
383                         ++brak;
384                 }
385                 /** Make external links open in a separate window */
386                 else if (!strncasecmp(ptr, "<a href=\"", 9)) {
387                         ++alevel;
388                         ++brak;
389                         if ( ((strchr(ptr, ':') < strchr(ptr, '/')))
390                                         &&  ((strchr(ptr, '/') < strchr(ptr, '>'))) 
391                            ) {
392                                 /* open external links to new window */
393                                 StrBufAppendPrintf(converted_msg, new_window);
394                                 ptr = &ptr[8];
395                         }
396                         else if (
397                                 (treat_as_wiki)
398                                 && (strncasecmp(ptr, "<a href=\"wiki?", 14))
399                                 && (strncasecmp(ptr, "<a href=\"dotgoto?", 17))
400                                 && (strncasecmp(ptr, "<a href=\"knrooms?", 17))
401                         ) {
402                                 content_length += 64;
403                                 StrBufAppendPrintf(converted_msg, "<a href=\"wiki?page=");
404                                 ptr = &ptr[9];
405                         }
406                         else {
407                                 StrBufAppendPrintf(converted_msg, "<a href=\"");
408                                 ptr = &ptr[9];
409                         }
410                 }
411                 /** Fixup <img src="cid:... ...> to fetch the mime part */
412                 else if (!strncasecmp(ptr, "<img ", 5)) {
413                         char *cid_start, *cid_end;
414                         char* tag_end=strchr(ptr,'>');
415                         char* src;
416                         /* FIXME - handle this situation (maybe someone opened an <img cid... 
417                          * and then ended the message)
418                          */
419                         if (!tag_end) {
420                                 syslog(9, "tag_end is null and ptr is:\n");
421                                 syslog(9, "%s\n", ptr);
422                                 syslog(9, "Theoretical bytes remaining: %d\n", (int)(msgend - ptr));
423                         }
424
425                         src=strstr(ptr, "src=\"cid:");
426                         ++brak;
427
428                         if (src
429                             && isspace(*(src-1))
430                                 && tag_end
431                                 && (cid_start=strchr(src,':'))
432                                 && (cid_end=strchr(cid_start,'"'))
433                                 && (cid_end < tag_end)
434                         ) {
435                                 /* copy tag and attributes up to src="cid: */
436                                 StrBufAppendBufPlain(converted_msg, ptr, src - ptr, 0);
437                                 cid_start++;
438
439                                 /* add in /webcit/mimepart/<msgno>/CID/ 
440                                    trailing / stops dumb URL filters getting excited */
441                                 StrBufAppendPrintf(converted_msg,
442                                                 " src=\"/webcit/mimepart/%d/",msgnum);
443                                 StrBufAppendBufPlain(converted_msg, cid_start, cid_end - cid_start, 0);
444                                 StrBufAppendBufPlain(converted_msg, "/\"", -1, 0);
445
446                                 ptr = cid_end+1;
447                         }
448                         StrBufAppendBufPlain(converted_msg, ptr, tag_end - ptr, 0);
449                         ptr = tag_end;
450                 }
451
452                 /**
453                  * Turn anything that looks like a URL into a real link, as long
454                  * as it's not inside a tag already
455                  */
456                 else if ( (brak == 0) && (alevel == 0)
457                      && (!strncasecmp(ptr, "http://", 7))) {
458                                 /** Find the end of the link */
459                                 int strlenptr;
460                                 linklen = 0;
461                                 
462                                 strlenptr = strlen(ptr);
463                                 for (i=0; i<=strlenptr; ++i) {
464                                         if ((ptr[i]==0)
465                                            ||(isspace(ptr[i]))
466                                            ||(ptr[i]==10)
467                                            ||(ptr[i]==13)
468                                            ||(ptr[i]=='(')
469                                            ||(ptr[i]==')')
470                                            ||(ptr[i]=='<')
471                                            ||(ptr[i]=='>')
472                                            ||(ptr[i]=='[')
473                                            ||(ptr[i]==']')
474                                            ||(ptr[i]=='"')
475                                            ||(ptr[i]=='\'')
476                                         ) linklen = i;
477                                         /* did s.b. send us an entity? */
478                                         if (ptr[i] == '&') {
479                                                 if ((ptr[i+2] ==';') ||
480                                                     (ptr[i+3] ==';') ||
481                                                     (ptr[i+5] ==';') ||
482                                                     (ptr[i+6] ==';') ||
483                                                     (ptr[i+7] ==';'))
484                                                         linklen = i;
485                                         }
486                                         if (linklen > 0) break;
487                                 }
488                                 if (linklen > 0) {
489                                         char *ltreviewptr;
490                                         char *nbspreviewptr;
491                                         char linkedchar;
492                                         int len;
493                                         
494                                         len = linklen;
495                                         linkedchar = ptr[len];
496                                         ptr[len] = '\0';
497                                         /* spot for some subject strings tinymce tends to give us. */
498                                         ltreviewptr = strchr(ptr, '<');
499                                         if (ltreviewptr != NULL) {
500                                                 *ltreviewptr = '\0';
501                                                 linklen = ltreviewptr - ptr;
502                                         }
503
504                                         nbspreviewptr = strstr(ptr, "&nbsp;");
505                                         if (nbspreviewptr != NULL) {
506                                                 /* nbspreviewptr = '\0'; */
507                                                 linklen = nbspreviewptr - ptr;
508                                         }
509                                         if (ltreviewptr != 0)
510                                                 *ltreviewptr = '<';
511
512                                         ptr[len] = linkedchar;
513
514                                         content_length += (32 + linklen);
515                                         StrBufAppendPrintf(converted_msg, "%s\"", new_window);
516                                         StrBufAppendBufPlain(converted_msg, ptr, linklen, 0);
517                                         StrBufAppendPrintf(converted_msg, "\">");
518                                         StrBufAppendBufPlain(converted_msg, ptr, linklen, 0);
519                                         ptr += linklen;
520                                         StrBufAppendPrintf(converted_msg, "</A>");
521                                 }
522                 }
523                 else {
524                         StrBufAppendBufPlain(converted_msg, ptr, 1, 0);
525                         ptr++;
526                 }
527
528
529                 if ((ptr >= msg) && (ptr <= msgend)) {
530                         /*
531                          * We need to know when we're inside a tag,
532                          * so we don't turn things that look like URL's into
533                          * links, when they're already links - or image sources.
534                          */
535                         if ((ptr > msg) && (*(ptr-1) == '<')) {
536                                 ++brak;
537                         }
538                         if ((ptr > msg) && (*(ptr-1) == '>')) {
539                                 --brak;
540                                 if ((scriptlevel == 0) && (script_start_pos >= 0)) {
541                                         StrBufCutRight(converted_msg, StrLength(converted_msg) - script_start_pos);
542                                         script_start_pos = (-1);
543                                 }
544                         }
545                         if (!strncasecmp(ptr, "</A>", 3)) --alevel;
546                 }
547         }
548
549         if (BodyArea != NULL) {
550                 StrBufAppendBufPlain(converted_msg, HKEY("</td></tr></table>"), 0);  
551                 FreeStrBuf(&BodyArea);
552         }
553
554         /**     uncomment these two lines to override conversion        */
555         /**     memcpy(converted_msg, msg, content_length);             */
556         /**     output_length = content_length;                         */
557
558         /** Output our big pile of markup */
559         StrBufAppendBuf(Target, converted_msg, 0);
560
561 BAIL:   /** A little trailing vertical whitespace... */
562         StrBufAppendPrintf(Target, "<br><br>\n");
563
564         /** Now give back the memory */
565         FreeStrBuf(&converted_msg);
566         if ((msg != NULL) && (Source == NULL)) free(msg);
567 }
568
569
570
571
572
573
574 /*
575  * Look for URL's embedded in a buffer and make them linkable.  We use a
576  * target window in order to keep the Citadel session in its own window.
577  */
578 void UrlizeText(StrBuf* Target, StrBuf *Source, StrBuf *WrkBuf)
579 {
580         int len, UrlLen, Offset, TrailerLen;
581         const char *start, *end, *pos;
582         
583         FlushStrBuf(Target);
584
585         start = NULL;
586         len = StrLength(Source);
587         end = ChrPtr(Source) + len;
588         for (pos = ChrPtr(Source); (pos < end) && (start == NULL); ++pos) {
589                 if (!strncasecmp(pos, "http://", 7))
590                         start = pos;
591                 else if (!strncasecmp(pos, "ftp://", 6))
592                         start = pos;
593         }
594
595         if (start == NULL) {
596                 StrBufAppendBuf(Target, Source, 0);
597                 return;
598         }
599         FlushStrBuf(WrkBuf);
600
601         for (pos = ChrPtr(Source) + len; pos > start; --pos) {
602                 if (  (!isprint(*pos))
603                    || (isspace(*pos))
604                    || (*pos == '{')
605                    || (*pos == '}')
606                    || (*pos == '|')
607                    || (*pos == '\\')
608                    || (*pos == '^')
609                    || (*pos == '[')
610                    || (*pos == ']')
611                    || (*pos == '`')
612                    || (*pos == '<')
613                    || (*pos == '>')
614                    || (*pos == '(')
615                    || (*pos == ')')
616                 ) {
617                         end = pos;
618                 }
619         }
620         
621         UrlLen = end - start;
622         StrBufAppendBufPlain(WrkBuf, start, UrlLen, 0);
623
624         Offset = start - ChrPtr(Source);
625         if (Offset != 0)
626                 StrBufAppendBufPlain(Target, ChrPtr(Source), Offset, 0);
627         StrBufAppendPrintf(Target, "%ca href=%c%s%c TARGET=%c%s%c%c%s%c/A%c",
628                            LB, QU, ChrPtr(WrkBuf), QU, QU, TARGET, 
629                            QU, RB, ChrPtr(WrkBuf), LB, RB);
630
631         TrailerLen = StrLength(Source) - (end - ChrPtr(Source));
632         if (TrailerLen > 0)
633                 StrBufAppendBufPlain(Target, end, TrailerLen, 0);
634 }
635
636
637 void url(char *buf, size_t bufsize)
638 {
639         int len, UrlLen, Offset, TrailerLen, outpos;
640         char *start, *end, *pos;
641         char urlbuf[SIZ];
642         char outbuf[SIZ];
643
644         start = NULL;
645         len = strlen(buf);
646         if (len > bufsize) {
647                 syslog(1, "URL: content longer than buffer!");
648                 return;
649         }
650         end = buf + len;
651         for (pos = buf; (pos < end) && (start == NULL); ++pos) {
652                 if (!strncasecmp(pos, "http://", 7))
653                         start = pos;
654                 if (!strncasecmp(pos, "ftp://", 6))
655                         start = pos;
656         }
657
658         if (start == NULL)
659                 return;
660
661         for (pos = buf+len; pos > start; --pos) {
662                 if (  (!isprint(*pos))
663                    || (isspace(*pos))
664                    || (*pos == '{')
665                    || (*pos == '}')
666                    || (*pos == '|')
667                    || (*pos == '\\')
668                    || (*pos == '^')
669                    || (*pos == '[')
670                    || (*pos == ']')
671                    || (*pos == '`')
672                    || (*pos == '<')
673                    || (*pos == '>')
674                    || (*pos == '(')
675                    || (*pos == ')')
676                 ) {
677                         end = pos;
678                 }
679         }
680         
681         UrlLen = end - start;
682         if (UrlLen > sizeof(urlbuf)){
683                 syslog(1, "URL: content longer than buffer!");
684                 return;
685         }
686         memcpy(urlbuf, start, UrlLen);
687         urlbuf[UrlLen] = '\0';
688
689         Offset = start - buf;
690         if ((Offset != 0) && (Offset < sizeof(outbuf)))
691                 memcpy(outbuf, buf, Offset);
692         outpos = snprintf(&outbuf[Offset], sizeof(outbuf) - Offset,  
693                           "%ca href=%c%s%c TARGET=%c%s%c%c%s%c/A%c",
694                           LB, QU, urlbuf, QU, QU, TARGET, QU, RB, urlbuf, LB, RB);
695         if (outpos >= sizeof(outbuf) - Offset) {
696                 syslog(1, "URL: content longer than buffer!");
697                 return;
698         }
699
700         TrailerLen = len - (end - start);
701         if (TrailerLen > 0)
702                 memcpy(outbuf + Offset + outpos, end, TrailerLen);
703         if (Offset + outpos + TrailerLen > bufsize) {
704                 syslog(1, "URL: content longer than buffer!");
705                 return;
706         }
707         memcpy (buf, outbuf, Offset + outpos + TrailerLen);
708         *(buf + Offset + outpos + TrailerLen) = '\0';
709 }
710