acc78166114366c785a0f5bf0b2c375badad1b5e
[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?go=");
404                                 StrBufUrlescAppend(converted_msg, WC->CurRoom.name, NULL);
405                                 StrBufAppendPrintf(converted_msg, "?page=");
406                                 ptr = &ptr[9];
407                         }
408                         else {
409                                 StrBufAppendPrintf(converted_msg, "<a href=\"");
410                                 ptr = &ptr[9];
411                         }
412                 }
413                 /** Fixup <img src="cid:... ...> to fetch the mime part */
414                 else if (!strncasecmp(ptr, "<img ", 5)) {
415                         char *cid_start, *cid_end;
416                         char* tag_end=strchr(ptr,'>');
417                         char* src;
418                         /* FIXME - handle this situation (maybe someone opened an <img cid... 
419                          * and then ended the message)
420                          */
421                         if (!tag_end) {
422                                 syslog(9, "tag_end is null and ptr is:\n");
423                                 syslog(9, "%s\n", ptr);
424                                 syslog(9, "Theoretical bytes remaining: %d\n", (int)(msgend - ptr));
425                         }
426
427                         src=strstr(ptr, "src=\"cid:");
428                         ++brak;
429
430                         if (src
431                             && isspace(*(src-1))
432                                 && tag_end
433                                 && (cid_start=strchr(src,':'))
434                                 && (cid_end=strchr(cid_start,'"'))
435                                 && (cid_end < tag_end)
436                         ) {
437                                 /* copy tag and attributes up to src="cid: */
438                                 StrBufAppendBufPlain(converted_msg, ptr, src - ptr, 0);
439                                 cid_start++;
440
441                                 /* add in /webcit/mimepart/<msgno>/CID/ 
442                                    trailing / stops dumb URL filters getting excited */
443                                 StrBufAppendPrintf(converted_msg,
444                                                 " src=\"/webcit/mimepart/%d/",msgnum);
445                                 StrBufAppendBufPlain(converted_msg, cid_start, cid_end - cid_start, 0);
446                                 StrBufAppendBufPlain(converted_msg, "/\"", -1, 0);
447
448                                 ptr = cid_end+1;
449                         }
450                         StrBufAppendBufPlain(converted_msg, ptr, tag_end - ptr, 0);
451                         ptr = tag_end;
452                 }
453
454                 /**
455                  * Turn anything that looks like a URL into a real link, as long
456                  * as it's not inside a tag already
457                  */
458                 else if ( (brak == 0) && (alevel == 0)
459                      && (!strncasecmp(ptr, "http://", 7))) {
460                                 /** Find the end of the link */
461                                 int strlenptr;
462                                 linklen = 0;
463                                 
464                                 strlenptr = strlen(ptr);
465                                 for (i=0; i<=strlenptr; ++i) {
466                                         if ((ptr[i]==0)
467                                            ||(isspace(ptr[i]))
468                                            ||(ptr[i]==10)
469                                            ||(ptr[i]==13)
470                                            ||(ptr[i]=='(')
471                                            ||(ptr[i]==')')
472                                            ||(ptr[i]=='<')
473                                            ||(ptr[i]=='>')
474                                            ||(ptr[i]=='[')
475                                            ||(ptr[i]==']')
476                                            ||(ptr[i]=='"')
477                                            ||(ptr[i]=='\'')
478                                         ) linklen = i;
479                                         /* did s.b. send us an entity? */
480                                         if (ptr[i] == '&') {
481                                                 if ((ptr[i+2] ==';') ||
482                                                     (ptr[i+3] ==';') ||
483                                                     (ptr[i+5] ==';') ||
484                                                     (ptr[i+6] ==';') ||
485                                                     (ptr[i+7] ==';'))
486                                                         linklen = i;
487                                         }
488                                         if (linklen > 0) break;
489                                 }
490                                 if (linklen > 0) {
491                                         char *ltreviewptr;
492                                         char *nbspreviewptr;
493                                         char linkedchar;
494                                         int len;
495                                         
496                                         len = linklen;
497                                         linkedchar = ptr[len];
498                                         ptr[len] = '\0';
499                                         /* spot for some subject strings tinymce tends to give us. */
500                                         ltreviewptr = strchr(ptr, '<');
501                                         if (ltreviewptr != NULL) {
502                                                 *ltreviewptr = '\0';
503                                                 linklen = ltreviewptr - ptr;
504                                         }
505
506                                         nbspreviewptr = strstr(ptr, "&nbsp;");
507                                         if (nbspreviewptr != NULL) {
508                                                 /* nbspreviewptr = '\0'; */
509                                                 linklen = nbspreviewptr - ptr;
510                                         }
511                                         if (ltreviewptr != 0)
512                                                 *ltreviewptr = '<';
513
514                                         ptr[len] = linkedchar;
515
516                                         content_length += (32 + linklen);
517                                         StrBufAppendPrintf(converted_msg, "%s\"", new_window);
518                                         StrBufAppendBufPlain(converted_msg, ptr, linklen, 0);
519                                         StrBufAppendPrintf(converted_msg, "\">");
520                                         StrBufAppendBufPlain(converted_msg, ptr, linklen, 0);
521                                         ptr += linklen;
522                                         StrBufAppendPrintf(converted_msg, "</A>");
523                                 }
524                 }
525                 else {
526                         StrBufAppendBufPlain(converted_msg, ptr, 1, 0);
527                         ptr++;
528                 }
529
530
531                 if ((ptr >= msg) && (ptr <= msgend)) {
532                         /*
533                          * We need to know when we're inside a tag,
534                          * so we don't turn things that look like URL's into
535                          * links, when they're already links - or image sources.
536                          */
537                         if ((ptr > msg) && (*(ptr-1) == '<')) {
538                                 ++brak;
539                         }
540                         if ((ptr > msg) && (*(ptr-1) == '>')) {
541                                 --brak;
542                                 if ((scriptlevel == 0) && (script_start_pos >= 0)) {
543                                         StrBufCutRight(converted_msg, StrLength(converted_msg) - script_start_pos);
544                                         script_start_pos = (-1);
545                                 }
546                         }
547                         if (!strncasecmp(ptr, "</A>", 3)) --alevel;
548                 }
549         }
550
551         if (BodyArea != NULL) {
552                 StrBufAppendBufPlain(converted_msg, HKEY("</td></tr></table>"), 0);  
553                 FreeStrBuf(&BodyArea);
554         }
555
556         /**     uncomment these two lines to override conversion        */
557         /**     memcpy(converted_msg, msg, content_length);             */
558         /**     output_length = content_length;                         */
559
560         /** Output our big pile of markup */
561         StrBufAppendBuf(Target, converted_msg, 0);
562
563 BAIL:   /** A little trailing vertical whitespace... */
564         StrBufAppendPrintf(Target, "<br><br>\n");
565
566         /** Now give back the memory */
567         FreeStrBuf(&converted_msg);
568         if ((msg != NULL) && (Source == NULL)) free(msg);
569 }
570
571
572
573
574
575
576 /*
577  * Look for URL's embedded in a buffer and make them linkable.  We use a
578  * target window in order to keep the Citadel session in its own window.
579  */
580 void UrlizeText(StrBuf* Target, StrBuf *Source, StrBuf *WrkBuf)
581 {
582         int len, UrlLen, Offset, TrailerLen;
583         const char *start, *end, *pos;
584         
585         FlushStrBuf(Target);
586
587         start = NULL;
588         len = StrLength(Source);
589         end = ChrPtr(Source) + len;
590         for (pos = ChrPtr(Source); (pos < end) && (start == NULL); ++pos) {
591                 if (!strncasecmp(pos, "http://", 7))
592                         start = pos;
593                 else if (!strncasecmp(pos, "ftp://", 6))
594                         start = pos;
595         }
596
597         if (start == NULL) {
598                 StrBufAppendBuf(Target, Source, 0);
599                 return;
600         }
601         FlushStrBuf(WrkBuf);
602
603         for (pos = ChrPtr(Source) + len; pos > start; --pos) {
604                 if (  (!isprint(*pos))
605                    || (isspace(*pos))
606                    || (*pos == '{')
607                    || (*pos == '}')
608                    || (*pos == '|')
609                    || (*pos == '\\')
610                    || (*pos == '^')
611                    || (*pos == '[')
612                    || (*pos == ']')
613                    || (*pos == '`')
614                    || (*pos == '<')
615                    || (*pos == '>')
616                    || (*pos == '(')
617                    || (*pos == ')')
618                 ) {
619                         end = pos;
620                 }
621         }
622         
623         UrlLen = end - start;
624         StrBufAppendBufPlain(WrkBuf, start, UrlLen, 0);
625
626         Offset = start - ChrPtr(Source);
627         if (Offset != 0)
628                 StrBufAppendBufPlain(Target, ChrPtr(Source), Offset, 0);
629         StrBufAppendPrintf(Target, "%ca href=%c%s%c TARGET=%c%s%c%c%s%c/A%c",
630                            LB, QU, ChrPtr(WrkBuf), QU, QU, TARGET, 
631                            QU, RB, ChrPtr(WrkBuf), LB, RB);
632
633         TrailerLen = StrLength(Source) - (end - ChrPtr(Source));
634         if (TrailerLen > 0)
635                 StrBufAppendBufPlain(Target, end, TrailerLen, 0);
636 }
637
638
639 void url(char *buf, size_t bufsize)
640 {
641         int len, UrlLen, Offset, TrailerLen, outpos;
642         char *start, *end, *pos;
643         char urlbuf[SIZ];
644         char outbuf[SIZ];
645
646         start = NULL;
647         len = strlen(buf);
648         if (len > bufsize) {
649                 syslog(1, "URL: content longer than buffer!");
650                 return;
651         }
652         end = buf + len;
653         for (pos = buf; (pos < end) && (start == NULL); ++pos) {
654                 if (!strncasecmp(pos, "http://", 7))
655                         start = pos;
656                 if (!strncasecmp(pos, "ftp://", 6))
657                         start = pos;
658         }
659
660         if (start == NULL)
661                 return;
662
663         for (pos = buf+len; pos > start; --pos) {
664                 if (  (!isprint(*pos))
665                    || (isspace(*pos))
666                    || (*pos == '{')
667                    || (*pos == '}')
668                    || (*pos == '|')
669                    || (*pos == '\\')
670                    || (*pos == '^')
671                    || (*pos == '[')
672                    || (*pos == ']')
673                    || (*pos == '`')
674                    || (*pos == '<')
675                    || (*pos == '>')
676                    || (*pos == '(')
677                    || (*pos == ')')
678                 ) {
679                         end = pos;
680                 }
681         }
682         
683         UrlLen = end - start;
684         if (UrlLen > sizeof(urlbuf)){
685                 syslog(1, "URL: content longer than buffer!");
686                 return;
687         }
688         memcpy(urlbuf, start, UrlLen);
689         urlbuf[UrlLen] = '\0';
690
691         Offset = start - buf;
692         if ((Offset != 0) && (Offset < sizeof(outbuf)))
693                 memcpy(outbuf, buf, Offset);
694         outpos = snprintf(&outbuf[Offset], sizeof(outbuf) - Offset,  
695                           "%ca href=%c%s%c TARGET=%c%s%c%c%s%c/A%c",
696                           LB, QU, urlbuf, QU, QU, TARGET, QU, RB, urlbuf, LB, RB);
697         if (outpos >= sizeof(outbuf) - Offset) {
698                 syslog(1, "URL: content longer than buffer!");
699                 return;
700         }
701
702         TrailerLen = len - (end - start);
703         if (TrailerLen > 0)
704                 memcpy(outbuf + Offset + outpos, end, TrailerLen);
705         if (Offset + outpos + TrailerLen > bufsize) {
706                 syslog(1, "URL: content longer than buffer!");
707                 return;
708         }
709         memcpy (buf, outbuf, Offset + outpos + TrailerLen);
710         *(buf + Offset + outpos + TrailerLen) = '\0';
711 }
712