* rename urlstring parser
[citadel.git] / webcit / html2html.c
1 /*
2  * $Id$
3  */
4 /**
5  * \defgroup HTML2HTML Output an HTML message, modifying it slightly to make sure it plays nice
6  * with the rest of our web framework.
7  * \ingroup WebcitHttpServer
8  */
9 /*@{*/
10 #include "webcit.h"
11 #include "webserver.h"
12
13
14 /**
15  * \brief       Strip surrounding single or double quotes from a string.
16  *
17  * \param s     String to be stripped.
18  */
19 void stripquotes(char *s)
20 {
21         int len;
22
23         if (!s) return;
24
25         len = strlen(s);
26         if (len < 2) return;
27
28         if ( ( (s[0] == '\"') && (s[len-1] == '\"') ) || ( (s[0] == '\'') && (s[len-1] == '\'') ) ) {
29                 s[len-1] = 0;
30                 strcpy(s, &s[1]);
31         }
32 }
33
34
35 /**
36  * \brief Check to see if a META tag has overridden the declared MIME character set.
37  *
38  * \param charset               Character set name (left unchanged if we don't do anything)
39  * \param meta_http_equiv       Content of the "http-equiv" portion of the META tag
40  * \param meta_content          Content of the "content" portion of the META tag
41  */
42 void extract_charset_from_meta(char *charset, char *meta_http_equiv, char *meta_content)
43 {
44         char *ptr;
45         char buf[64];
46
47         if (!charset) return;
48         if (!meta_http_equiv) return;
49         if (!meta_content) return;
50
51
52         if (strcasecmp(meta_http_equiv, "Content-type")) return;
53
54         ptr = strchr(meta_content, ';');
55         if (!ptr) return;
56
57         safestrncpy(buf, ++ptr, sizeof buf);
58         striplt(buf);
59         if (!strncasecmp(buf, "charset=", 8)) {
60                 strcpy(charset, &buf[8]);
61
62                 /*
63                  * The brain-damaged webmail program in Microsoft Exchange declares
64                  * a charset of "unicode" when they really mean "UTF-8".  GNU iconv
65                  * treats "unicode" as an alias for "UTF-16" so we have to manually
66                  * fix this here, otherwise messages generated in Exchange webmail
67                  * show up as a big pile of weird characters.
68                  */
69                 if (!strcasecmp(charset, "unicode")) {
70                         strcpy(charset, "UTF-8");
71                 }
72
73         }
74 }
75
76
77
78 /**
79  * \brief Sanitize and enhance an HTML message for display.
80  *        Also convert weird character sets to UTF-8 if necessary.
81  *        Also fixup img src="cid:..." type inline images to fetch the image
82  *
83  * \param supplied_charset the input charset as declared in the MIME headers
84  */
85 void output_html(char *supplied_charset, int treat_as_wiki, int msgnum) {
86         char buf[SIZ];
87         char *msg;
88         char *ptr;
89         char *msgstart;
90         char *msgend;
91         StrBuf *converted_msg;
92         int buffer_length = 1;
93         int line_length = 0;
94         int content_length = 0;
95         char new_window[SIZ];
96         int brak = 0;
97         int alevel = 0;
98         int scriptlevel = 0;
99         int script_start_pos = (-1);
100         int i;
101         int linklen;
102         char charset[128];
103 #ifdef HAVE_ICONV
104         iconv_t ic = (iconv_t)(-1) ;
105         char *ibuf;                   /**< Buffer of characters to be converted */
106         char *obuf;                   /**< Buffer for converted characters      */
107         size_t ibuflen;               /**< Length of input buffer               */
108         size_t obuflen;               /**< Length of output buffer              */
109         char *osav;                   /**< Saved pointer to output buffer       */
110 #endif
111
112         safestrncpy(charset, supplied_charset, sizeof charset);
113         msg = strdup("");
114         sprintf(new_window, "<a target=\"%s\" href=", TARGET);
115
116         while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
117                 line_length = strlen(buf);
118                 buffer_length = content_length + line_length + 2;
119                 ptr = realloc(msg, buffer_length);
120                 if (ptr == NULL) {
121                         wprintf("<b>");
122                         wprintf(_("realloc() error! couldn't get %d bytes: %s"),
123                                 buffer_length + 1,
124                                 strerror(errno));
125                         wprintf("</b><br /><br />\n");
126                         while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
127                                 /** flush */
128                         }
129                         free(msg);
130                         return;
131                 }
132                 msg = ptr;
133                 strcpy(&msg[content_length], buf);
134                 content_length += line_length;
135                 strcpy(&msg[content_length], "\n");
136                 content_length += 1;
137         }
138
139         /** Do a first pass to isolate the message body */
140         ptr = msg + 1;
141         msgstart = msg;
142         msgend = &msg[content_length];
143
144         while (ptr < msgend) {
145
146                 /** Advance to next tag */
147                 ptr = strchr(ptr, '<');
148                 if ((ptr == NULL) || (ptr >= msgend)) break;
149                 ++ptr;
150                 if ((ptr == NULL) || (ptr >= msgend)) break;
151
152                 /**
153                  *  Look for META tags.  Some messages (particularly in
154                  *  Asian locales) illegally declare a message's character
155                  *  set in the HTML instead of in the MIME headers.  This
156                  *  is wrong but we have to work around it anyway.
157                  */
158                 if (!strncasecmp(ptr, "META", 4)) {
159
160                         char *meta_start;
161                         char *meta_end;
162                         int meta_length;
163                         char *meta;
164                         char *meta_http_equiv;
165                         char *meta_content;
166                         char *spaceptr;
167
168                         meta_start = &ptr[4];
169                         meta_end = strchr(ptr, '>');
170                         if ((meta_end != NULL) && (meta_end <= msgend)) {
171                                 meta_length = meta_end - meta_start + 1;
172                                 meta = malloc(meta_length + 1);
173                                 safestrncpy(meta, meta_start, meta_length);
174                                 meta[meta_length] = 0;
175                                 striplt(meta);
176                                 if (!strncasecmp(meta, "HTTP-EQUIV=", 11)) {
177                                         meta_http_equiv = strdup(&meta[11]);
178                                         spaceptr = strchr(meta_http_equiv, ' ');
179                                         if (spaceptr != NULL) {
180                                                 *spaceptr = 0;
181                                                 meta_content = strdup(++spaceptr);
182                                                 if (!strncasecmp(meta_content, "content=", 8)) {
183                                                         strcpy(meta_content, &meta_content[8]);
184                                                         stripquotes(meta_http_equiv);
185                                                         stripquotes(meta_content);
186                                                         extract_charset_from_meta(charset,
187                                                                 meta_http_equiv, meta_content);
188                                                 }
189                                                 free(meta_content);
190                                         }
191                                         free(meta_http_equiv);
192                                 }
193                                 free(meta);
194                         }
195                 }
196
197                 /**
198                  * Any of these tags cause everything up to and including
199                  * the tag to be removed.
200                  */     
201                 if ( (!strncasecmp(ptr, "HTML", 4))
202                    ||(!strncasecmp(ptr, "HEAD", 4))
203                    ||(!strncasecmp(ptr, "/HEAD", 5))
204                    ||(!strncasecmp(ptr, "BODY", 4)) ) {
205                         ptr = strchr(ptr, '>');
206                         if ((ptr == NULL) || (ptr >= msgend)) break;
207                         ++ptr;
208                         if ((ptr == NULL) || (ptr >= msgend)) break;
209                         msgstart = ptr;
210                 }
211
212                 /**
213                  * Any of these tags cause everything including and following
214                  * the tag to be removed.
215                  */
216                 if ( (!strncasecmp(ptr, "/HTML", 5))
217                    ||(!strncasecmp(ptr, "/BODY", 5)) ) {
218                         --ptr;
219                         msgend = ptr;
220                         strcpy(ptr, "");
221                         
222                 }
223
224                 ++ptr;
225         }
226         if (msgstart > msg) {
227                 strcpy(msg, msgstart);
228         }
229
230         /** Convert foreign character sets to UTF-8 if necessary. */
231 #ifdef HAVE_ICONV
232         if ( (strcasecmp(charset, "us-ascii"))
233            && (strcasecmp(charset, "UTF-8"))
234            && (strcasecmp(charset, ""))
235         ) {
236                 lprintf(9, "Converting %s to UTF-8\n", charset);
237                 ic = ctdl_iconv_open("UTF-8", charset);
238                 if (ic == (iconv_t)(-1) ) {
239                         lprintf(5, "%s:%d iconv_open() failed: %s\n",
240                                 __FILE__, __LINE__, strerror(errno));
241                 }
242         }
243         if (ic != (iconv_t)(-1) ) {
244                 ibuf = msg;
245                 ibuflen = content_length;
246                 obuflen = content_length + (content_length / 2) ;
247                 obuf = (char *) malloc(obuflen);
248                 osav = obuf;
249                 iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
250                 content_length = content_length + (content_length / 2) - obuflen;
251                 osav[content_length] = 0;
252                 free(msg);
253                 msg = osav;
254                 iconv_close(ic);
255         }
256 #endif
257
258         /**
259          *      At this point, the message has been stripped down to
260          *      only the content inside the <BODY></BODY> tags, and has
261          *      been converted to UTF-8 if it was originally in a foreign
262          *      character set.  The text is also guaranteed to be null
263          *      terminated now.
264          */
265
266         /** Now go through the message, parsing tags as necessary. */
267         converted_msg = NewStrBufPlain(NULL, content_length + 8192);
268         if (converted_msg == NULL) {
269                 wprintf("Error %d: %s<br />%s:%d", errno, strerror(errno), __FILE__, __LINE__);
270                 goto BAIL;
271         }
272
273         ptr = msg;
274         msgend = strchr(msg, 0);
275         while (ptr < msgend) {
276
277                 /** Try to sanitize the html of any rogue scripts */
278                 if (!strncasecmp(ptr, "<script", 7)) {
279                         if (scriptlevel == 0) {
280                                 script_start_pos = StrLength(converted_msg);
281                         }
282                         ++scriptlevel;
283                 }
284                 if (!strncasecmp(ptr, "</script", 8)) {
285                         --scriptlevel;
286                 }
287
288                 /**
289                  * Change mailto: links to WebCit mail, by replacing the
290                  * link with one that points back to our mail room.  Due to
291                  * the way we parse URL's, it'll even handle mailto: links
292                  * that have "?subject=" in them.
293                  */
294                 if (!strncasecmp(ptr, "<a href=\"mailto:", 16)) {
295                         content_length += 64;
296                         StrBufAppendPrintf(converted_msg,
297                                 "<a href=\"display_enter?force_room=_MAIL_&recp=");
298                         ptr = &ptr[16];
299                         ++alevel;
300                         ++brak;
301                 }
302                 /** Make external links open in a separate window */
303                 else if (!strncasecmp(ptr, "<a href=\"", 9)) {
304                         ++alevel;
305                         ++brak;
306                         if ( ((strchr(ptr, ':') < strchr(ptr, '/')))
307                              &&  ((strchr(ptr, '/') < strchr(ptr, '>'))) 
308                              ) {
309                                 /* open external links to new window */
310                                 StrBufAppendPrintf(converted_msg, new_window);
311                                 ptr = &ptr[8];
312                         }
313                         else if ( (treat_as_wiki) && (strncasecmp(ptr, "<a href=\"wiki?", 14)) ) {
314                                 content_length += 64;
315                                 StrBufAppendPrintf(converted_msg, "<a href=\"wiki?page=");
316                                 ptr = &ptr[9];
317                         }
318                         else {
319                                 StrBufAppendPrintf(converted_msg, "<a href=\"");
320                                 ptr = &ptr[9];
321                         }
322                 }
323                 /** Fixup <img src="cid:... ...> to fetch the mime part */
324                 else if (!strncasecmp(ptr, "<img ", 5)) {
325                         char* tag_end=strchr(ptr,'>');
326                         char* src=strstr(ptr, " src=\"cid:");
327                         char *cid_start, *cid_end;
328                         ++brak;
329
330                         if (src && 
331                                 (cid_start=strchr(src,':')) && 
332                                 (cid_end=strchr(cid_start,'"')) &&
333                                 (cid_end < tag_end)) {
334
335                                 /* copy tag and attributes up to src="cid: */
336                                 StrBufAppendBufPlain(converted_msg, ptr, src - ptr, 0);
337                                 cid_start++;
338
339                                 /* add in /webcit/mimepart/<msgno>/CID/ 
340                                    trailing / stops dumb URL filters getting excited */
341                                 StrBufAppendPrintf(converted_msg,
342                                         "src=\"/webcit/mimepart/%d/",msgnum);
343                                 StrBufAppendBufPlain(converted_msg, cid_start, cid_end - cid_start, 0);
344                                 StrBufAppendBufPlain(converted_msg, "/\"", -1, 0);
345                                 
346                                 ptr = cid_end+1;
347                         }
348                         StrBufAppendBufPlain(converted_msg, ptr, tag_end - ptr, 0);
349                         ptr = tag_end;
350                 }
351
352                 /**
353                  * Turn anything that looks like a URL into a real link, as long
354                  * as it's not inside a tag already
355                  */
356                 else if ( (brak == 0) && (alevel == 0)
357                      && (!strncasecmp(ptr, "http://", 7))) {
358                                 /** Find the end of the link */
359                                 int strlenptr;
360                                 linklen = 0;
361                                 
362                                 strlenptr = strlen(ptr);
363                                 for (i=0; i<=strlenptr; ++i) {
364                                         if ((ptr[i]==0)
365                                            ||(isspace(ptr[i]))
366                                            ||(ptr[i]==10)
367                                            ||(ptr[i]==13)
368                                            ||(ptr[i]=='(')
369                                            ||(ptr[i]==')')
370                                            ||(ptr[i]=='<')
371                                            ||(ptr[i]=='>')
372                                            ||(ptr[i]=='[')
373                                            ||(ptr[i]==']')
374                                            ||(ptr[i]=='"')
375                                            ||(ptr[i]=='\'')
376                                         ) linklen = i;
377                                         /* did s.b. send us an entity? */
378                                         if (ptr[i] == '&') {
379                                                 if ((ptr[i+2] ==';') ||
380                                                     (ptr[i+3] ==';') ||
381                                                     (ptr[i+5] ==';') ||
382                                                     (ptr[i+6] ==';') ||
383                                                     (ptr[i+7] ==';'))
384                                                         linklen = i;
385                                         }
386                                         if (linklen > 0) break;
387                                 }
388                                 if (linklen > 0) {
389                                         char *ltreviewptr;
390                                         char *nbspreviewptr;
391                                         char linkedchar;
392                                         int len = linklen;
393                                         
394                                         len = linklen;
395                                         linkedchar = ptr[len];
396                                         ptr[len] = '\0';
397                                         /* spot for some subject strings tinymce tends to give us. */
398                                         ltreviewptr = strchr(ptr, '<');
399                                         if (ltreviewptr != NULL) {
400                                                 *ltreviewptr = '\0';
401                                                 linklen = ltreviewptr - ptr;
402                                         }
403
404                                         nbspreviewptr = strstr(ptr, "&nbsp;");
405                                         if (nbspreviewptr != NULL) {
406                                                 ///*nbspreviewptr = '\0';
407                                                 linklen = nbspreviewptr - ptr;
408                                         }
409                                         if (ltreviewptr != 0)
410                                                 *ltreviewptr = '<';
411
412                                         ptr[len] = linkedchar;
413
414                                         content_length += (32 + linklen);
415                                         StrBufAppendPrintf(converted_msg, "%s\"", new_window);
416                                         StrBufAppendBufPlain(converted_msg, ptr, linklen, 0);
417                                         StrBufAppendPrintf(converted_msg, "\">");
418                                         StrBufAppendBufPlain(converted_msg, ptr, linklen, 0);
419                                         ptr += linklen;
420                                         StrBufAppendPrintf(converted_msg, "</A>");
421                                 }
422                 }
423                 else {
424                         StrBufAppendBufPlain(converted_msg, ptr, 1, 0);
425                         ptr++;
426                 }
427
428                 /**
429                  * We need to know when we're inside a tag,
430                  * so we don't turn things that look like URL's into
431                  * links, when they're already links - or image sources.
432                  */
433                 if (*(ptr-1) == '<') {
434                         ++brak;
435                 }
436                 if (*(ptr-1) == '>') {
437                         --brak;
438                         if ((scriptlevel == 0) && (script_start_pos >= 0)) {
439                                 StrBufCutRight(converted_msg, StrLength(converted_msg) - script_start_pos);
440                                 script_start_pos = (-1);
441                         }
442                 }
443                 if (!strncasecmp(ptr, "</A>", 3)) --alevel;
444         }
445
446         /**     uncomment these two lines to override conversion        */
447         /**     memcpy(converted_msg, msg, content_length);             */
448         /**     output_length = content_length;                         */
449
450         /** Output our big pile of markup */
451         StrBufAppendBuf(WC->WBuf, converted_msg, 0);
452
453 BAIL:   /** A little trailing vertical whitespace... */
454         wprintf("<br /><br />\n");
455
456         /** Now give back the memory */
457         if (converted_msg != NULL) free(converted_msg);
458         if (msg != NULL) free(msg);
459 }
460
461 /*@}*/