a695292fe869c349f13f3f20ccd68d76b8544c2d
[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  *
82  * \param supplied_charset the input charset as declared in the MIME headers
83  */
84 void output_html(char *supplied_charset, int treat_as_wiki) {
85         char buf[SIZ];
86         char *msg;
87         char *ptr;
88         char *msgstart;
89         char *msgend;
90         char *converted_msg;
91         size_t converted_alloc = 0;
92         int buffer_length = 1;
93         int line_length = 0;
94         int content_length = 0;
95         int output_length = 0;
96         char new_window[SIZ];
97         int brak = 0;
98         int alevel = 0;
99         int scriptlevel = 0;
100         int script_start_pos = (-1);
101         int i;
102         int linklen;
103         char charset[128];
104 #ifdef HAVE_ICONV
105         iconv_t ic = (iconv_t)(-1) ;
106         char *ibuf;                   /**< Buffer of characters to be converted */
107         char *obuf;                   /**< Buffer for converted characters      */
108         size_t ibuflen;               /**< Length of input buffer               */
109         size_t obuflen;               /**< Length of output buffer              */
110         char *osav;                   /**< Saved pointer to output buffer       */
111 #endif
112
113         safestrncpy(charset, supplied_charset, sizeof charset);
114         msg = strdup("");
115         sprintf(new_window, "<a target=\"%s\" href=", TARGET);
116
117         while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
118                 line_length = strlen(buf);
119                 buffer_length = content_length + line_length + 2;
120                 ptr = realloc(msg, buffer_length);
121                 if (ptr == NULL) {
122                         wprintf("<b>");
123                         wprintf(_("realloc() error! couldn't get %d bytes: %s"),
124                                 buffer_length + 1,
125                                 strerror(errno));
126                         wprintf("</b><br /><br />\n");
127                         while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
128                                 /** flush */
129                         }
130                         free(msg);
131                         return;
132                 }
133                 msg = ptr;
134                 strcpy(&msg[content_length], buf);
135                 content_length += line_length;
136                 strcpy(&msg[content_length], "\n");
137                 content_length += 1;
138         }
139
140         /** Do a first pass to isolate the message body */
141         ptr = msg + 1;
142         msgstart = msg;
143         msgend = &msg[content_length];
144
145         while (ptr < msgend) {
146
147                 /** Advance to next tag */
148                 ptr = strchr(ptr, '<');
149                 if ((ptr == NULL) || (ptr >= msgend)) break;
150                 ++ptr;
151                 if ((ptr == NULL) || (ptr >= msgend)) break;
152
153                 /**
154                  *  Look for META tags.  Some messages (particularly in
155                  *  Asian locales) illegally declare a message's character
156                  *  set in the HTML instead of in the MIME headers.  This
157                  *  is wrong but we have to work around it anyway.
158                  */
159                 if (!strncasecmp(ptr, "META", 4)) {
160
161                         char *meta_start;
162                         char *meta_end;
163                         int meta_length;
164                         char *meta;
165                         char *meta_http_equiv;
166                         char *meta_content;
167                         char *spaceptr;
168
169                         meta_start = &ptr[4];
170                         meta_end = strchr(ptr, '>');
171                         if ((meta_end != NULL) && (meta_end <= msgend)) {
172                                 meta_length = meta_end - meta_start + 1;
173                                 meta = malloc(meta_length + 1);
174                                 safestrncpy(meta, meta_start, meta_length);
175                                 meta[meta_length] = 0;
176                                 striplt(meta);
177                                 if (!strncasecmp(meta, "HTTP-EQUIV=", 11)) {
178                                         meta_http_equiv = strdup(&meta[11]);
179                                         spaceptr = strchr(meta_http_equiv, ' ');
180                                         if (spaceptr != NULL) {
181                                                 *spaceptr = 0;
182                                                 meta_content = strdup(++spaceptr);
183                                                 if (!strncasecmp(meta_content, "content=", 8)) {
184                                                         strcpy(meta_content, &meta_content[8]);
185                                                         stripquotes(meta_http_equiv);
186                                                         stripquotes(meta_content);
187                                                         extract_charset_from_meta(charset,
188                                                                 meta_http_equiv, meta_content);
189                                                 }
190                                                 free(meta_content);
191                                         }
192                                         free(meta_http_equiv);
193                                 }
194                                 free(meta);
195                         }
196                 }
197
198                 /**
199                  * Any of these tags cause everything up to and including
200                  * the tag to be removed.
201                  */     
202                 if ( (!strncasecmp(ptr, "HTML", 4))
203                    ||(!strncasecmp(ptr, "HEAD", 4))
204                    ||(!strncasecmp(ptr, "/HEAD", 5))
205                    ||(!strncasecmp(ptr, "BODY", 4)) ) {
206                         ptr = strchr(ptr, '>');
207                         if ((ptr == NULL) || (ptr >= msgend)) break;
208                         ++ptr;
209                         if ((ptr == NULL) || (ptr >= msgend)) break;
210                         msgstart = ptr;
211                 }
212
213                 /**
214                  * Any of these tags cause everything including and following
215                  * the tag to be removed.
216                  */
217                 if ( (!strncasecmp(ptr, "/HTML", 5))
218                    ||(!strncasecmp(ptr, "/BODY", 5)) ) {
219                         --ptr;
220                         msgend = ptr;
221                         strcpy(ptr, "");
222                         
223                 }
224
225                 ++ptr;
226         }
227         if (msgstart > msg) {
228                 strcpy(msg, msgstart);
229         }
230
231         /** Convert foreign character sets to UTF-8 if necessary. */
232 #ifdef HAVE_ICONV
233         if ( (strcasecmp(charset, "us-ascii"))
234            && (strcasecmp(charset, "UTF-8"))
235            && (strcasecmp(charset, ""))
236         ) {
237                 lprintf(9, "Converting %s to UTF-8\n", charset);
238                 ic = ctdl_iconv_open("UTF-8", charset);
239                 if (ic == (iconv_t)(-1) ) {
240                         lprintf(5, "%s:%d iconv_open() failed: %s\n",
241                                 __FILE__, __LINE__, strerror(errno));
242                 }
243         }
244         if (ic != (iconv_t)(-1) ) {
245                 ibuf = msg;
246                 ibuflen = content_length;
247                 obuflen = content_length + (content_length / 2) ;
248                 obuf = (char *) malloc(obuflen);
249                 osav = obuf;
250                 iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
251                 content_length = content_length + (content_length / 2) - obuflen;
252                 osav[content_length] = 0;
253                 free(msg);
254                 msg = osav;
255                 iconv_close(ic);
256         }
257 #endif
258
259         /**
260          *      At this point, the message has been stripped down to
261          *      only the content inside the <BODY></BODY> tags, and has
262          *      been converted to UTF-8 if it was originally in a foreign
263          *      character set.  The text is also guaranteed to be null
264          *      terminated now.
265          */
266
267         /** Now go through the message, parsing tags as necessary. */
268         converted_alloc = content_length + 8192;
269         converted_msg = malloc(converted_alloc);
270         if (converted_msg == NULL) {
271                 wprintf("Error %d: %s<br />%s:%s", errno, strerror(errno), __FILE__, __LINE__);
272                 goto BAIL;
273         }
274
275         strcpy(converted_msg, "");
276         ptr = msg;
277         msgend = strchr(msg, 0);
278         while (ptr < msgend) {
279
280                 /** Try to sanitize the html of any rogue scripts */
281                 if (!strncasecmp(ptr, "<script", 7)) {
282                         if (scriptlevel == 0) {
283                                 script_start_pos = output_length;
284                         }
285                         ++scriptlevel;
286                 }
287                 if (!strncasecmp(ptr, "</script", 8)) {
288                         --scriptlevel;
289                 }
290
291                 /**
292                  * Change mailto: links to WebCit mail, by replacing the
293                  * link with one that points back to our mail room.  Due to
294                  * the way we parse URL's, it'll even handle mailto: links
295                  * that have "?subject=" in them.
296                  */
297                 if (!strncasecmp(ptr, "<a href=\"mailto:", 16)) {
298                         content_length += 64;
299                         if (content_length >= converted_alloc) {
300                                 converted_alloc += 8192;
301                                 converted_msg = realloc(converted_msg, converted_alloc);
302                                 if (converted_msg == NULL) {
303                                         abort();
304                                 }
305                         }
306                         sprintf(&converted_msg[output_length],
307                                 "<a href=\"display_enter?force_room=_MAIL_&recp=");
308                         output_length += 46;
309                         ptr = &ptr[16];
310                         ++alevel;
311                         ++brak;
312                 }
313                 /** Make external links open in a separate window */
314                 else if (!strncasecmp(ptr, "<a href=\"", 9)) {
315                         ++alevel;
316                         ++brak;
317                         if ( ((strchr(ptr, ':') < strchr(ptr, '/')))
318                              &&  ((strchr(ptr, '/') < strchr(ptr, '>'))) 
319                              ) {
320                                 /* open external links to new window */
321                                 content_length += 64;
322                                 if (content_length >= converted_alloc) {
323                                         converted_alloc += 8192;
324                                         converted_msg = realloc(converted_msg, converted_alloc);
325                                         if (converted_msg == NULL) {
326                                                 abort();
327                                         }
328                                 }
329                                 sprintf(&converted_msg[output_length], new_window);
330                                 output_length += strlen(new_window);
331                                 ptr = &ptr[8];
332                         }
333                         else if ( (treat_as_wiki) && (strncasecmp(ptr, "<a href=\"wiki?", 14)) ) {
334                                 content_length += 64;
335                                 if (content_length >= converted_alloc) {
336                                         converted_alloc += 8192;
337                                         converted_msg = realloc(converted_msg, converted_alloc);
338                                         if (converted_msg == NULL) {
339                                                 abort();
340                                         }
341                                 }
342                                 sprintf(&converted_msg[output_length], "<a href=\"wiki?page=");
343                                 output_length += 19;
344                                 ptr = &ptr[9];
345                         }
346                         else {
347                                 sprintf(&converted_msg[output_length], "<a href=\"");
348                                 output_length += 9;
349                                 ptr = &ptr[9];
350                         }
351                 }
352
353                 /**
354                  * Turn anything that looks like a URL into a real link, as long
355                  * as it's not inside a tag already
356                  */
357                 else if ( (brak == 0) && (alevel == 0)
358                      && (!strncasecmp(ptr, "http://", 7))) {
359                                 /** Find the end of the link */
360                                 int strlenptr;
361                                 linklen = 0;
362                                 
363                                 strlenptr = strlen(ptr);
364                                 for (i=0; i<=strlenptr; ++i) {
365                                         if ((ptr[i]==0)
366                                            ||(isspace(ptr[i]))
367                                            ||(ptr[i]==10)
368                                            ||(ptr[i]==13)
369                                            ||(ptr[i]=='(')
370                                            ||(ptr[i]==')')
371                                            ||(ptr[i]=='<')
372                                            ||(ptr[i]=='>')
373                                            ||(ptr[i]=='[')
374                                            ||(ptr[i]==']')
375                                            ||(ptr[i]=='"')
376                                            ||(ptr[i]=='\'')
377                                         ) linklen = i;
378                                         /* did s.b. send us an entity? */
379                                         if (ptr[i] == '&') {
380                                                 if ((ptr[i+2] ==';') ||
381                                                     (ptr[i+3] ==';') ||
382                                                     (ptr[i+5] ==';') ||
383                                                     (ptr[i+6] ==';') ||
384                                                     (ptr[i+7] ==';'))
385                                                         linklen = i;
386                                         }
387                                         if (linklen > 0) break;
388                                 }
389                                 if (linklen > 0) {
390                                         char *ltreviewptr;
391                                         char *nbspreviewptr;
392                                         char linkedchar;
393                                         int len = linklen;
394                                         
395                                         len = linklen;
396                                         linkedchar = ptr[len];
397                                         ptr[len] = '\0';
398                                         /* spot for some subject strings tinymce tends to give us. */
399                                         ltreviewptr = strchr(ptr, '<');
400                                         if (ltreviewptr != NULL) {
401                                                 *ltreviewptr = '\0';
402                                                 linklen = ltreviewptr - ptr;
403                                         }
404
405                                         nbspreviewptr = strstr(ptr, "&nbsp;");
406                                         if (nbspreviewptr != NULL) {
407                                                 ///*nbspreviewptr = '\0';
408                                                 linklen = nbspreviewptr - ptr;
409                                         }
410                                         if (ltreviewptr != 0)
411                                                 *ltreviewptr = '<';
412
413                                         ptr[len] = linkedchar;
414
415                                         content_length += (32 + linklen);
416                                         if (content_length >= converted_alloc) {
417                                                 converted_alloc += 8192;
418                                                 converted_msg = realloc(converted_msg, converted_alloc);
419                                                 if (converted_msg == NULL) {
420                                                         abort();
421                                                 }
422                                         }
423                                         sprintf(&converted_msg[output_length], new_window);
424                                         output_length += strlen(new_window);
425                                         converted_msg[output_length] = '\"';
426                                         converted_msg[++output_length] = 0;
427                                         for (i=0; i<linklen; ++i) {
428                                                 converted_msg[output_length] = ptr[i];
429                                                 converted_msg[++output_length] = 0;
430                                         }
431                                         sprintf(&converted_msg[output_length], "\">");
432                                         output_length += 2;
433                                         for (i=0; i<linklen; ++i) {
434                                                 converted_msg[output_length] = *ptr++;
435                                                 converted_msg[++output_length] = 0;
436                                         }
437                                         sprintf(&converted_msg[output_length], "</A>");
438                                         output_length += 4;
439                                 }
440                 }
441                 else {
442                         converted_msg[output_length] = *ptr++;
443                         converted_msg[++output_length] = 0;
444                 }
445
446                 /**
447                  * We need to know when we're inside a tag,
448                  * so we don't turn things that look like URL's into
449                  * links, when they're already links - or image sources.
450                  */
451                 if (*(ptr-1) == '<') {
452                         ++brak;
453                 }
454                 if (*(ptr-1) == '>') {
455                         --brak;
456                         if ((scriptlevel == 0) && (script_start_pos >= 0)) {
457                                 output_length = script_start_pos;
458                                 converted_msg[output_length] = 0;
459                                 script_start_pos = (-1);
460                         }
461                 }
462                 if (!strncasecmp(ptr, "</A>", 3)) --alevel;
463         }
464
465         /**     uncomment these two lines to override conversion        */
466         /**     memcpy(converted_msg, msg, content_length);             */
467         /**     output_length = content_length;                         */
468
469         /** Output our big pile of markup */
470         client_write(converted_msg, output_length);
471
472 BAIL:   /** A little trailing vertical whitespace... */
473         wprintf("<br /><br />\n");
474
475         /** Now give back the memory */
476         if (converted_msg != NULL) free(converted_msg);
477         if (msg != NULL) free(msg);
478 }
479
480 /*@}*/