Updated the html2html filter. When we encounter a charset
[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 "vcard.h"
12 #include "webserver.h"
13
14
15 /**
16  * \brief       Strip surrounding single or double quotes from a string.
17  *
18  * \param s     String to be stripped.
19  */
20 void stripquotes(char *s)
21 {
22         int len;
23
24         if (!s) return;
25
26         len = strlen(s);
27         if (len < 2) return;
28
29         if ( ( (s[0] == '\"') && (s[len-1] == '\"') ) || ( (s[0] == '\'') && (s[len-1] == '\'') ) ) {
30                 s[len-1] = 0;
31                 strcpy(s, &s[1]);
32         }
33 }
34
35
36 /**
37  * \brief Check to see if a META tag has overridden the declared MIME character set.
38  *
39  * \param charset               Character set name (left unchanged if we don't do anything)
40  * \param meta_http_equiv       Content of the "http-equiv" portion of the META tag
41  * \param meta_content          Content of the "content" portion of the META tag
42  */
43 void extract_charset_from_meta(char *charset, char *meta_http_equiv, char *meta_content)
44 {
45         char *ptr;
46         char buf[64];
47
48         if (!charset) return;
49         if (!meta_http_equiv) return;
50         if (!meta_content) return;
51
52
53         if (strcasecmp(meta_http_equiv, "Content-type")) return;
54
55         ptr = strchr(meta_content, ';');
56         if (!ptr) return;
57
58         safestrncpy(buf, ++ptr, sizeof buf);
59         striplt(buf);
60         if (!strncasecmp(buf, "charset=", 8)) {
61                 strcpy(charset, &buf[8]);
62
63                 /*
64                  * The brain-damaged webmail program in Microsoft Exchange declares
65                  * a charset of "unicode" when they really mean "UTF-8".  GNU iconv
66                  * treats "unicode" as an alias for "UTF-16" so we have to manually
67                  * fix this here, otherwise messages generated in Exchange webmail
68                  * show up as a big pile of weird characters.
69                  */
70                 if (!strcasecmp(charset, "unicode")) {
71                         strcpy(charset, "UTF-8");
72                 }
73
74         }
75 }
76
77
78
79 /**
80  * \brief Sanitize and enhance an HTML message for display.
81  *        Also convert weird character sets to UTF-8 if necessary.
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) {
86         char buf[SIZ];
87         char *msg;
88         char *ptr;
89         char *msgstart;
90         char *msgend;
91         char *converted_msg;
92         size_t converted_alloc = 0;
93         int buffer_length = 1;
94         int line_length = 0;
95         int content_length = 0;
96         int output_length = 0;
97         char new_window[SIZ];
98         int brak = 0;
99         int alevel = 0;
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;
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_alloc = content_length + 8192;
268         converted_msg = malloc(converted_alloc);
269         if (converted_msg == NULL) {
270                 wprintf("Error %d: %s<br />%s:%s", errno, strerror(errno), __FILE__, __LINE__);
271                 goto BAIL;
272         }
273
274         strcpy(converted_msg, "");
275         ptr = msg;
276         msgend = strchr(msg, 0);
277         while (ptr < msgend) {
278
279                 /**
280                  * Change mailto: links to WebCit mail, by replacing the
281                  * link with one that points back to our mail room.  Due to
282                  * the way we parse URL's, it'll even handle mailto: links
283                  * that have "?subject=" in them.
284                  */
285                 if (!strncasecmp(ptr, "<a href=\"mailto:", 16)) {
286                         content_length += 64;
287                         if (content_length >= converted_alloc) {
288                                 converted_alloc += 8192;
289                                 converted_msg = realloc(converted_msg, converted_alloc);
290                                 if (converted_msg == NULL) {
291                                         abort();
292                                 }
293                         }
294                         sprintf(&converted_msg[output_length],
295                                 "<a href=\"display_enter"
296                                 "?force_room=_MAIL_&recp=");
297                         output_length += 47;
298                         ptr = &ptr[16];
299                         ++alevel;
300                 }
301                 /** Make external links open in a separate window */
302                 else if (!strncasecmp(ptr, "<a href=\"", 9)) {
303                         ++alevel;
304                         if ( ((strchr(ptr, ':') < strchr(ptr, '/')))
305                              &&  ((strchr(ptr, '/') < strchr(ptr, '>'))) 
306                              ) {
307                                 /* open external links to new window */
308                                 content_length += 64;
309                                 if (content_length >= converted_alloc) {
310                                         converted_alloc += 8192;
311                                         converted_msg = realloc(converted_msg, converted_alloc);
312                                         if (converted_msg == NULL) {
313                                                 abort();
314                                         }
315                                 }
316                                 sprintf(&converted_msg[output_length], new_window);
317                                 output_length += strlen(new_window);
318                                 ptr = &ptr[8];
319                         }
320                         else if ( (treat_as_wiki) && (strncasecmp(ptr, "<a href=\"wiki?", 14)) ) {
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], "<a href=\"wiki?page=");
330                                 output_length += 19;
331                                 ptr = &ptr[9];
332                         }
333                         else {
334                                 sprintf(&converted_msg[output_length], "<a href=\"");
335                                 output_length += 9;
336                                 ptr = &ptr[9];
337                         }
338                 }
339                 /**
340                  * Turn anything that looks like a URL into a real link, as long
341                  * as it's not inside a tag already
342                  */
343                 else if ( (brak == 0) && (alevel == 0)
344                      && (!strncasecmp(ptr, "http://", 7))) {
345                                 linklen = 0;
346                                 /** Find the end of the link */
347                                 for (i=0; i<=strlen(ptr); ++i) {
348                                         if ((ptr[i]==0)
349                                            ||(isspace(ptr[i]))
350                                            ||(ptr[i]==10)
351                                            ||(ptr[i]==13)
352                                            ||(ptr[i]=='(')
353                                            ||(ptr[i]==')')
354                                            ||(ptr[i]=='<')
355                                            ||(ptr[i]=='>')
356                                            ||(ptr[i]=='[')
357                                            ||(ptr[i]==']')
358                                         ) linklen = i;
359                                         if (linklen > 0) break;
360                                 }
361                                 if (linklen > 0) {
362                                         content_length += (32 + linklen);
363                                         if (content_length >= converted_alloc) {
364                                                 converted_alloc += 8192;
365                                                 converted_msg = realloc(converted_msg, converted_alloc);
366                                                 if (converted_msg == NULL) {
367                                                         abort();
368                                                 }
369                                         }
370                                         sprintf(&converted_msg[output_length], new_window);
371                                         output_length += strlen(new_window);
372                                         converted_msg[output_length] = '\"';
373                                         converted_msg[++output_length] = 0;
374                                         for (i=0; i<linklen; ++i) {
375                                                 converted_msg[output_length] = ptr[i];
376                                                 converted_msg[++output_length] = 0;
377                                         }
378                                         sprintf(&converted_msg[output_length], "\">");
379                                         output_length += 2;
380                                         for (i=0; i<linklen; ++i) {
381                                                 converted_msg[output_length] = *ptr++;
382                                                 converted_msg[++output_length] = 0;
383                                         }
384                                         sprintf(&converted_msg[output_length], "</A>");
385                                         output_length += 4;
386                                 }
387                 }
388                 else {
389                         /**
390                          * We need to know when we're inside a tag,
391                          * so we don't turn things that look like URL's into
392                          * links, when they're already links - or image sources.
393                          */
394                         if (*ptr == '<') ++brak;
395                         if (*ptr == '>') --brak;
396                         if (!strncasecmp(ptr, "</A>", 3)) --alevel;
397                         converted_msg[output_length] = *ptr++;
398                         converted_msg[++output_length] = 0;
399                 }
400         }
401
402         /**     uncomment these two lines to override conversion        */
403         /**     memcpy(converted_msg, msg, content_length);             */
404         /**     output_length = content_length;                         */
405
406         /** Output our big pile of markup */
407         client_write(converted_msg, output_length);
408
409 BAIL:   /** A little trailing vertical whitespace... */
410         wprintf("<br /><br />\n");
411
412         /** Now give back the memory */
413         if (converted_msg != NULL) free(converted_msg);
414         if (msg != NULL) free(msg);
415 }
416
417 /*@}*/