76ba1409d42f5b2bdbc004f3bb7d1098d58ae4ec
[claws.git] / src / procheader.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2001 Hiroyuki Yamamoto
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include <glib.h>
25 #include <stdio.h>
26 #include <string.h>
27 #include <stdlib.h>
28 #include <time.h>
29
30 #include "intl.h"
31 #include "procheader.h"
32 #include "procmsg.h"
33 #include "codeconv.h"
34 #include "prefs_common.h"
35 #include "utils.h"
36
37 #define BUFFSIZE        8192
38
39 /*
40   procheader_get_one_field
41   - reads fp and puts the header and the corresponding content into buf
42     if one of these is one of hentry table.
43   - if hentry is NULL, ignores no headers
44  */
45
46 gint procheader_get_one_field(gchar *buf, gint len, FILE *fp,
47                               HeaderEntry hentry[])
48 {
49         gint nexthead;
50         gint hnum = 0;
51         HeaderEntry *hp = NULL;
52
53         if (hentry != NULL) {
54                 /* skip non-required headers */
55                 do {
56                         do {
57                                 if (fgets(buf, len, fp) == NULL)
58                                         return -1;
59                                 if (buf[0] == '\r' || buf[0] == '\n')
60                                         return -1;
61                         } while (buf[0] == ' ' || buf[0] == '\t');
62
63                         for (hp = hentry, hnum = 0; hp->name != NULL;
64                              hp++, hnum++) {
65                                 if (!strncasecmp(hp->name, buf,
66                                                  strlen(hp->name)))
67                                         break;
68                         }
69                 } while (hp->name == NULL);
70         } else {
71                 if (fgets(buf, len, fp) == NULL) return -1;
72                 if (buf[0] == '\r' || buf[0] == '\n') return -1;
73         }
74
75         /* unfold the specified folded line */
76         if (hp && hp->unfold) {
77                 gboolean folded = FALSE;
78                 gchar *bufp = buf + strlen(buf);
79
80                 while (1) {
81                         nexthead = fgetc(fp);
82
83                         /* folded */
84                         if (nexthead == ' ' || nexthead == '\t')
85                                 folded = TRUE;
86                         else if (nexthead == EOF)
87                                 break;
88                         else if (folded == TRUE) {
89                                 /* concatenate next line */
90                                 if ((len - (bufp - buf)) <= 2) break;
91
92                                 /* replace return code on the tail end
93                                    with space */
94                                 *(bufp - 1) = ' ';
95                                 *bufp++ = nexthead;
96                                 *bufp = '\0';
97                                 if (nexthead == '\r' || nexthead == '\n') {
98                                         folded = FALSE;
99                                         continue;
100                                 }
101                                 if (fgets(bufp, len - (bufp - buf), fp)
102                                     == NULL) break;
103                                 bufp += strlen(bufp);
104
105                                 folded = FALSE;
106                         } else {
107                                 ungetc(nexthead, fp);
108                                 break;
109                         }
110                 }
111
112                 /* remove trailing return code */
113                 strretchomp(buf);
114
115                 return hnum;
116         }
117
118         while (1) {
119                 nexthead = fgetc(fp);
120                 if (nexthead == ' ' || nexthead == '\t') {
121                         size_t buflen = strlen(buf);
122
123                         /* concatenate next line */
124                         if ((len - buflen) > 2) {
125                                 gchar *p = buf + buflen;
126
127                                 *p++ = nexthead;
128                                 *p = '\0';
129                                 buflen++;
130                                 if (fgets(p, len - buflen, fp) == NULL)
131                                         break;
132                         } else
133                                 break;
134                 } else {
135                         if (nexthead != EOF)
136                                 ungetc(nexthead, fp);
137                         break;
138                 }
139         }
140
141         /* remove trailing return code */
142         strretchomp(buf);
143
144         return hnum;
145 }
146
147 gchar *procheader_get_unfolded_line(gchar *buf, gint len, FILE *fp)
148 {
149         gboolean folded = FALSE;
150         gint nexthead;
151         gchar *bufp;
152
153         if (fgets(buf, len, fp) == NULL) return NULL;
154         if (buf[0] == '\r' || buf[0] == '\n') return NULL;
155         bufp = buf + strlen(buf);
156
157         while (1) {
158                 nexthead = fgetc(fp);
159
160                 /* folded */
161                 if (nexthead == ' ' || nexthead == '\t')
162                         folded = TRUE;
163                 else if (nexthead == EOF)
164                         break;
165                 else if (folded == TRUE) {
166                         /* concatenate next line */
167                         if ((len - (bufp - buf)) <= 2) break;
168
169                         /* replace return code on the tail end
170                            with space */
171                         *(bufp - 1) = ' ';
172                         *bufp++ = nexthead;
173                         *bufp = '\0';
174                         if (nexthead == '\r' || nexthead == '\n') {
175                                 folded = FALSE;
176                                 continue;
177                         }
178                         if (fgets(bufp, len - (bufp - buf), fp)
179                             == NULL) break;
180                         bufp += strlen(bufp);
181
182                         folded = FALSE;
183                 } else {
184                         ungetc(nexthead, fp);
185                         break;
186                 }
187         }
188
189         /* remove trailing return code */
190         strretchomp(buf);
191
192         return buf;
193 }
194
195 GSList *procheader_get_header_list(const gchar *file)
196 {
197         FILE *fp;
198         gchar buf[BUFFSIZE], tmp[BUFFSIZE];
199         gchar *p;
200         GSList *hlist = NULL;
201         Header *header;
202
203         if ((fp = fopen(file, "r")) == NULL) {
204                 FILE_OP_ERROR(file, "fopen");
205                 return NULL;
206         }
207
208         while (procheader_get_unfolded_line(buf, sizeof(buf), fp) != NULL) {
209                 if (*buf == ':') continue;
210                 for (p = buf; *p && *p != ' '; p++) {
211                         if (*p == ':') {
212                                 header = g_new(Header, 1);
213                                 header->name = g_strndup(buf, p - buf);
214                                 p++;
215                                 while (*p == ' ' || *p == '\t') p++;
216                                 conv_unmime_header(tmp, sizeof(tmp), p, NULL);
217                                 header->body = g_strdup(tmp);
218
219                                 hlist = g_slist_append(hlist, header);
220                                 break;
221                         }
222                 }
223         }
224
225         fclose(fp);
226         return hlist;
227 }
228
229 void procheader_header_list_destroy(GSList *hlist)
230 {
231         Header *header;
232
233         while (hlist != NULL) {
234                 header = hlist->data;
235
236                 g_free(header->name);
237                 g_free(header->body);
238                 g_free(header);
239                 hlist = g_slist_remove(hlist, header);
240         }
241 }
242
243 void procheader_get_header_fields(FILE *fp, HeaderEntry hentry[])
244 {
245         gchar buf[BUFFSIZE];
246         HeaderEntry *hp;
247         gint hnum;
248         gchar *p;
249
250         if (hentry == NULL) return;
251
252         while ((hnum = procheader_get_one_field(buf, sizeof(buf), fp, hentry))
253                != -1) {
254                 hp = hentry + hnum;
255
256                 p = buf + strlen(hp->name);
257                 while (*p == ' ' || *p == '\t') p++;
258
259                 if (hp->body == NULL)
260                         hp->body = g_strdup(p);
261                 else if (!strcasecmp(hp->name, "To:") ||
262                          !strcasecmp(hp->name, "Cc:")) {
263                         gchar *tp = hp->body;
264                         hp->body = g_strconcat(tp, ", ", p, NULL);
265                         g_free(tp);
266                 }
267         }
268 }
269
270 enum
271 {
272         H_DATE          = 0,
273         H_FROM          = 1,
274         H_TO            = 2,
275         H_CC            = 3,
276         H_NEWSGROUPS    = 4,
277         H_SUBJECT       = 5,
278         H_MSG_ID        = 6,
279         H_REFERENCES    = 7,
280         H_IN_REPLY_TO   = 8,
281         H_CONTENT_TYPE  = 9,
282         H_SEEN          = 10,
283         H_X_FACE        = 11,
284         H_DISPOSITION_NOTIFICATION_TO = 12
285 };
286
287 MsgInfo *procheader_parse(const gchar *file, MsgFlags flags, gboolean full)
288 {
289         static HeaderEntry hentry_full[] = {{"Date:",           NULL, FALSE},
290                                            {"From:",            NULL, TRUE},
291                                            {"To:",              NULL, TRUE},
292                                            {"Cc:",              NULL, TRUE},
293                                            {"Newsgroups:",      NULL, TRUE},
294                                            {"Subject:",         NULL, TRUE},
295                                            {"Message-Id:",      NULL, FALSE},
296                                            {"References:",      NULL, FALSE},
297                                            {"In-Reply-To:",     NULL, FALSE},
298                                            {"Content-Type:",    NULL, FALSE},
299                                            {"Seen:",            NULL, FALSE},
300                                            {"X-Face:",          NULL, FALSE},
301                                            {"Disposition-Notification-To:",NULL, FALSE},
302                                            {NULL,               NULL, FALSE}};
303
304         static HeaderEntry hentry_short[] = {{"Date:",          NULL, FALSE},
305                                             {"From:",           NULL, TRUE},
306                                             {"To:",             NULL, TRUE},
307                                             {"Cc:",             NULL, TRUE},
308                                             {"Newsgroups:",     NULL, TRUE},
309                                             {"Subject:",        NULL, TRUE},
310                                             {"Message-Id:",     NULL, FALSE},
311                                             {"References:",     NULL, FALSE},
312                                             {"In-Reply-To:",    NULL, FALSE},
313                                             {"Content-Type:",   NULL, FALSE},
314                                             {"Seen:",           NULL, FALSE},
315                                             {NULL,              NULL, FALSE}};
316
317         FILE *fp;
318         MsgInfo *msginfo;
319         gchar buf[BUFFSIZE], tmp[BUFFSIZE];
320         gchar *reference = NULL;
321         gchar *p;
322         gchar *hp;
323         HeaderEntry *hentry;
324         gint hnum;
325
326         hentry = full ? hentry_full : hentry_short;
327
328         if ((fp = fopen(file, "r")) == NULL) {
329                 FILE_OP_ERROR(file, "fopen");
330                 return NULL;
331         }
332         if (MSG_IS_QUEUED(flags)) {
333                 while (fgets(buf, sizeof(buf), fp) != NULL)
334                         if (buf[0] == '\r' || buf[0] == '\n') break;
335         }
336
337         msginfo = g_new0(MsgInfo, 1);
338         msginfo->flags = flags != 0 ? flags : MSG_NEW|MSG_UNREAD;
339         msginfo->inreplyto = NULL;
340
341         while ((hnum = procheader_get_one_field(buf, sizeof(buf), fp, hentry))
342                != -1) {
343                 hp = buf + strlen(hentry[hnum].name);
344                 while (*hp == ' ' || *hp == '\t') hp++;
345
346                 switch (hnum) {
347                 case H_DATE:
348                         if (msginfo->date) break;
349                         msginfo->date_t =
350                                 procheader_date_parse(NULL, hp, 0);
351                         msginfo->date = g_strdup(hp);
352                         break;
353                 case H_FROM:
354                         if (msginfo->from) break;
355                         conv_unmime_header(tmp, sizeof(tmp), hp, NULL);
356                         msginfo->from = g_strdup(tmp);
357                         msginfo->fromname = procheader_get_fromname(tmp);
358                         break;
359                 case H_TO:
360                         conv_unmime_header(tmp, sizeof(tmp), hp, NULL);
361                         if (msginfo->to) {
362                                 p = msginfo->to;
363                                 msginfo->to =
364                                         g_strconcat(p, ", ", tmp, NULL);
365                                 g_free(p);
366                         } else
367                                 msginfo->to = g_strdup(tmp);
368                         break;
369                 case H_CC:
370                         conv_unmime_header(tmp, sizeof(tmp), hp, NULL);
371                         if (msginfo->cc) {
372                                 p = msginfo->cc;
373                                 msginfo->cc =
374                                         g_strconcat(p, ", ", tmp, NULL);
375                                 g_free(p);
376                         } else
377                                 msginfo->cc = g_strdup(tmp);
378                         break;
379                 case H_NEWSGROUPS:
380                         if (msginfo->newsgroups) {
381                                 p = msginfo->newsgroups;
382                                 msginfo->newsgroups =
383                                         g_strconcat(p, ",", hp, NULL);
384                                 g_free(p);
385                         } else
386                                 msginfo->newsgroups = g_strdup(buf + 12);
387                         break;
388                 case H_SUBJECT:
389                         if (msginfo->subject) break;
390                         conv_unmime_header(tmp, sizeof(tmp), hp, NULL);
391                         msginfo->subject = g_strdup(tmp);
392                         break;
393                 case H_MSG_ID:
394                         if (msginfo->msgid) break;
395
396                         extract_parenthesis(hp, '<', '>');
397                         remove_space(hp);
398                         msginfo->msgid = g_strdup(hp);
399                         break;
400                 case H_REFERENCES:
401                         if (!reference) {
402                                 eliminate_parenthesis(hp, '(', ')');
403                                 if ((p = strrchr(hp, '<')) != NULL &&
404                                     strchr(p + 1, '>') != NULL) {
405                                         extract_parenthesis(p, '<', '>');
406                                         remove_space(p);
407                                         if (*p != '\0')
408                                                 reference = g_strdup(p);
409                                 }
410                         }
411                         break;
412                 case H_IN_REPLY_TO:
413                         if (!reference) {
414                                 eliminate_parenthesis(hp, '(', ')');
415                                 extract_parenthesis(hp, '<', '>');
416                                 remove_space(hp);
417                                 if (*hp != '\0')
418                                         reference = g_strdup(hp);
419                         }
420                         break;
421                 case H_CONTENT_TYPE:
422                         if (!strncasecmp(hp, "multipart", 9))
423                                 msginfo->flags |= MSG_MIME;
424                         break;
425                 case H_SEEN:
426                         /* mnews Seen header */
427                         MSG_UNSET_FLAGS(msginfo->flags, MSG_NEW|MSG_UNREAD);
428                         break;
429                 case H_X_FACE:
430                         if (msginfo->xface) break;
431                         msginfo->xface = g_strdup(hp);
432                         break;
433                 case H_DISPOSITION_NOTIFICATION_TO:
434                         if (msginfo->dispositionnotificationto) break;
435                         msginfo->dispositionnotificationto = g_strdup(hp);
436                         break;
437                 default:
438                 }
439         }
440         msginfo->inreplyto = reference;
441
442         fclose(fp);
443
444         return msginfo;
445 }
446
447 gchar *procheader_get_fromname(const gchar *str)
448 {
449         gchar *tmp, *name;
450
451         Xalloca(tmp, strlen(str) + 1, return NULL);
452         strcpy(tmp, str);
453
454         if (*tmp == '\"') {
455                 extract_quote(tmp, '\"');
456                 g_strstrip(tmp);
457         } else if (strchr(tmp, '<')) {
458                 eliminate_parenthesis(tmp, '<', '>');
459                 g_strstrip(tmp);
460                 if (*tmp == '\0') {
461                         strcpy(tmp, str);
462                         extract_parenthesis(tmp, '<', '>');
463                         g_strstrip(tmp);
464                 }
465         } else if (strchr(tmp, '(')) {
466                 extract_parenthesis(tmp, '(', ')');
467                 g_strstrip(tmp);
468         }
469
470         if (*tmp == '\0')
471                 name = g_strdup(str);
472         else
473                 name = g_strdup(tmp);
474
475         return name;
476 }
477
478 time_t procheader_date_parse(gchar *dest, const gchar *src, gint len)
479 {
480         static gchar monthstr[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
481         gchar weekday[4];
482         gint day;
483         gchar month[4];
484         gint year;
485         gint hh, mm, ss;
486         gchar zone[6];
487         gint result;
488         GDateMonth dmonth;
489         struct tm t;
490         gchar *p;
491         time_t timer;
492
493         /* parsing date field... */
494         result = sscanf(src, "%3s, %d %3s %d %2d:%2d:%2d %5s",
495                         weekday, &day, month, &year, &hh, &mm, &ss, zone);
496         if (result != 8) {
497                 result = sscanf(src, "%d %3s %d %2d:%2d:%2d %5s",
498                                 &day, month, &year, &hh, &mm, &ss, zone);
499                 if (result != 7) {
500                         ss = 0;
501                         result = sscanf(src, "%3s, %d %3s %d %2d:%2d %5s",
502                                         weekday, &day, month, &year, &hh, &mm, zone);
503                         if (result != 7) {
504                                 result = sscanf(src, "%d %3s %d %2d:%2d %5s",
505                                                 &day, month, &year, &hh, &mm,
506                                                 zone);
507                                 if (result != 6) {
508                                         g_warning("Invalid date: %s\n", src);
509                                         if (dest && len > 0)
510                                                 strncpy2(dest, src, len);
511                                         return 0;
512                                 }
513                         }
514                 }
515         }
516
517         /* Y2K compliant :) */
518         if (year < 100) {
519                 if (year < 70)
520                         year += 2000;
521                 else
522                         year += 1900;
523         }
524
525         if ((p = strstr(monthstr, month)) != NULL)
526                 dmonth = (gint)(p - monthstr) / 3 + 1;
527         else {
528                 g_warning("Invalid month: %s\n", month);
529                 dmonth = G_DATE_BAD_MONTH;
530         }
531
532         t.tm_sec = ss;
533         t.tm_min = mm;
534         t.tm_hour = hh;
535         t.tm_mday = day;
536         t.tm_mon = dmonth - 1;
537         t.tm_year = year - 1900;
538         t.tm_wday = 0;
539         t.tm_yday = 0;
540         t.tm_isdst = -1;
541
542         timer = mktime(&t);
543         timer += tzoffset_sec(&timer) - remote_tzoffset_sec(zone);
544
545         if (dest)
546                 procheader_date_get_localtime(dest, len, timer);
547
548         return timer;
549 }
550
551 void procheader_date_get_localtime(gchar *dest, gint len, const time_t timer)
552 {
553         struct tm *lt;
554         gchar *default_format = "%y/%m/%d(%a) %H:%M";
555
556         lt = localtime(&timer);
557
558         if (prefs_common.date_format)
559                 strftime(dest, len, prefs_common.date_format, lt);
560         else
561                 strftime(dest, len, default_format, lt);
562 }