various clean-ups and optimisations by Olaf Hering
[claws.git] / src / procheader.c
blob30c262d7c1821e0658c530340a0f339936008366
1 /*
2 * Claws Mail -- a GTK based, lightweight, and fast e-mail client
3 * Copyright (C) 1999-2024 the Claws Mail team and Hiroyuki Yamamoto
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 3 of the License, or
8 * (at your option) any later version.
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.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 #ifdef HAVE_CONFIG_H
21 # include "config.h"
22 #include "claws-features.h"
23 #endif
25 #include <glib.h>
26 #include <glib/gi18n.h>
27 #include <stdio.h>
28 #include <string.h>
29 #include <stdlib.h>
30 #include <time.h>
31 #include <sys/stat.h>
33 #include "procheader.h"
34 #include "procmsg.h"
35 #include "codeconv.h"
36 #include "prefs_common.h"
37 #include "hooks.h"
38 #include "utils.h"
39 #include "defs.h"
40 #include "file-utils.h"
42 #define BUFFSIZE 8192
44 static gchar monthstr[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
46 typedef char *(*getlinefunc) (char *, size_t, void *);
47 typedef int (*peekcharfunc) (void *);
48 typedef int (*getcharfunc) (void *);
49 typedef gint (*get_one_field_func) (gchar **, void *, HeaderEntry[]);
51 static gint string_get_one_field(gchar **buf, char **str,
52 HeaderEntry hentry[]);
54 static char *string_getline(char *buf, size_t len, char **str);
55 static int string_peekchar(char **str);
56 static int file_peekchar(FILE *fp);
57 static gint generic_get_one_field(gchar **bufptr, void *data,
58 HeaderEntry hentry[],
59 getlinefunc getline,
60 peekcharfunc peekchar,
61 gboolean unfold);
62 static MsgInfo *parse_stream(void *data, gboolean isstring, MsgFlags flags,
63 gboolean full, gboolean decrypted);
66 gint procheader_get_one_field(gchar **buf, FILE *fp,
67 HeaderEntry hentry[])
69 return generic_get_one_field(buf, fp, hentry,
70 (getlinefunc)fgets_crlf, (peekcharfunc)file_peekchar,
71 TRUE);
74 static gint string_get_one_field(gchar **buf, char **str,
75 HeaderEntry hentry[])
77 return generic_get_one_field(buf, str, hentry,
78 (getlinefunc)string_getline,
79 (peekcharfunc)string_peekchar,
80 TRUE);
83 gboolean procheader_skip_headers(FILE *fp)
85 gchar *buf = g_malloc(BUFFSIZE);
86 do {
87 if (fgets_crlf(buf, BUFFSIZE - 1, fp) == NULL) {
88 g_free(buf);
89 return FALSE;
91 if (buf[0] == '\r' || buf[0] == '\n') {
92 break;
94 } while (TRUE);
95 g_free(buf);
97 return TRUE;
101 static char *string_getline(char *buf, size_t len, char **str)
103 gboolean is_cr = FALSE;
104 gboolean last_was_cr = FALSE;
106 if (!*str || !**str)
107 return NULL;
109 for (; **str && len > 1; --len) {
110 is_cr = (**str == '\r');
111 if ((*buf++ = *(*str)++) == '\n') {
112 break;
114 if (last_was_cr) {
115 *(--buf) = '\n';
116 buf++;
117 break;
119 last_was_cr = is_cr;
122 *buf = '\0';
124 return buf;
127 static int string_peekchar(char **str)
129 return **str;
132 static int file_peekchar(FILE *fp)
134 return ungetc(getc(fp), fp);
137 static gint generic_get_one_field(gchar **bufptr, void *data,
138 HeaderEntry *hentry,
139 getlinefunc getline, peekcharfunc peekchar,
140 gboolean unfold)
142 /* returns -1 in case of failure of any kind, whatever it's a parsing error
143 or an allocation error. if returns -1, *bufptr is always NULL, and vice-versa,
144 and if returning 0 (OK), *bufptr is always non-NULL, so callers just have to
145 test the return value
147 gint nexthead;
148 gint hnum = 0;
149 HeaderEntry *hp = NULL;
150 size_t len;
151 gchar *buf;
153 cm_return_val_if_fail(bufptr != NULL, -1);
155 len = BUFFSIZE;
156 buf = g_malloc(len);
158 if (hentry != NULL) {
159 /* skip non-required headers */
160 /* and get hentry header line */
161 do {
162 do {
163 if (getline(buf, len, data) == NULL) {
164 debug_print("generic_get_one_field: getline\n");
165 g_free(buf);
166 *bufptr = NULL;
167 return -1;
169 if (buf[0] == '\r' || buf[0] == '\n') {
170 debug_print("generic_get_one_field: empty line\n");
171 g_free(buf);
172 *bufptr = NULL;
173 return -1;
175 } while (buf[0] == ' ' || buf[0] == '\t');
177 for (hp = hentry, hnum = 0; hp->name != NULL;
178 hp++, hnum++) {
179 if (!g_ascii_strncasecmp(hp->name, buf,
180 strlen(hp->name)))
181 break;
183 } while (hp->name == NULL);
184 } else {
185 /* read first line */
186 if (getline(buf, len, data) == NULL) {
187 debug_print("generic_get_one_field: getline\n");
188 g_free(buf);
189 *bufptr = NULL;
190 return -1;
192 if (buf[0] == '\r' || buf[0] == '\n') {
193 debug_print("generic_get_one_field: empty line\n");
194 g_free(buf);
195 *bufptr = NULL;
196 return -1;
199 /* reduce initial buffer to its useful part */
200 len = strlen(buf)+1;
201 buf = g_realloc(buf, len);
202 if (buf == NULL) {
203 debug_print("generic_get_one_field: reallocation error\n");
204 *bufptr = NULL;
205 return -1;
208 /* unfold line */
209 while (1) {
210 nexthead = peekchar(data);
211 /* ([*WSP CRLF] 1*WSP) */
212 if (nexthead == ' ' || nexthead == '\t') {
213 size_t buflen;
214 gchar *tmpbuf;
215 size_t tmplen;
217 gboolean skiptab = (nexthead == '\t');
218 /* trim previous trailing \n if requesting one header or
219 * unfolding was requested */
220 if ((!hentry && unfold) || (hp && hp->unfold))
221 strretchomp(buf);
223 buflen = strlen(buf);
225 /* read next line */
226 tmpbuf = g_malloc(BUFFSIZE);
228 if (getline(tmpbuf, BUFFSIZE, data) == NULL) {
229 g_free(tmpbuf);
230 break;
232 tmplen = strlen(tmpbuf)+1;
234 /* extend initial buffer and concatenate next line */
235 len += tmplen;
236 buf = g_realloc(buf, len);
237 if (buf == NULL) {
238 debug_print("generic_get_one_field: reallocation error\n");
239 g_free(buf);
240 *bufptr = NULL;
241 return -1;
243 memcpy(buf+buflen, tmpbuf, tmplen);
244 g_free(tmpbuf);
245 if (skiptab) { /* replace tab with space */
246 *(buf + buflen) = ' ';
248 } else {
249 /* remove trailing new line */
250 strretchomp(buf);
251 break;
255 *bufptr = buf;
257 return hnum;
260 gint procheader_get_one_field_asis(gchar **buf, FILE *fp)
262 return generic_get_one_field(buf, fp, NULL,
263 (getlinefunc)fgets_crlf,
264 (peekcharfunc)file_peekchar,
265 FALSE);
268 GPtrArray *procheader_get_header_array(FILE *fp)
270 gchar *buf = NULL;
271 GPtrArray *headers;
272 Header *header;
274 cm_return_val_if_fail(fp != NULL, NULL);
276 headers = g_ptr_array_new();
278 while (procheader_get_one_field_asis(&buf, fp) != -1) {
279 if ((header = procheader_parse_header(buf)) != NULL)
280 g_ptr_array_add(headers, header);
281 g_free(buf);
282 buf = NULL;
285 return headers;
288 void procheader_header_array_destroy(GPtrArray *harray)
290 gint i;
291 Header *header;
293 cm_return_if_fail(harray != NULL);
295 for (i = 0; i < harray->len; i++) {
296 header = g_ptr_array_index(harray, i);
297 procheader_header_free(header);
300 g_ptr_array_free(harray, TRUE);
303 void procheader_header_free(Header *header)
305 if (!header) return;
307 g_free(header->name);
308 g_free(header->body);
309 g_free(header);
313 tests whether two headers' names are equal
314 remove the trailing ':' or ' ' before comparing
317 gboolean procheader_headername_equal(char * hdr1, char * hdr2)
319 int len1;
320 int len2;
322 len1 = strlen(hdr1);
323 len2 = strlen(hdr2);
324 if (hdr1[len1 - 1] == ':')
325 len1--;
326 if (hdr2[len2 - 1] == ':')
327 len2--;
328 if (len1 != len2)
329 return 0;
331 return (g_ascii_strncasecmp(hdr1, hdr2, len1) == 0);
335 parse headers, for example :
336 From: dinh@enseirb.fr becomes :
337 header->name = "From:"
338 header->body = "dinh@enseirb.fr"
340 static gboolean header_is_addr_field(const gchar *hdr)
342 static char *addr_headers[] = {
343 "To:",
344 "Cc:",
345 "Bcc:",
346 "From:",
347 "Reply-To:",
348 "Followup-To:",
349 "Followup-and-Reply-To:",
350 "Disposition-Notification-To:",
351 "Return-Receipt-To:",
352 NULL};
353 int i;
355 if (!hdr)
356 return FALSE;
358 for (i = 0; addr_headers[i] != NULL; i++)
359 if (!strcasecmp(hdr, addr_headers[i]))
360 return FALSE;
362 return FALSE;
365 Header * procheader_parse_header(gchar * buf)
367 gchar *p;
368 Header * header;
369 gboolean addr_field = FALSE;
371 cm_return_val_if_fail(buf != NULL, NULL);
373 if ((*buf == ':') || (*buf == ' '))
374 return NULL;
376 for (p = buf; *p ; p++) {
377 if ((*p == ':') || (*p == ' ')) {
378 header = g_new(Header, 1);
379 header->name = g_strndup(buf, p - buf + 1);
380 addr_field = header_is_addr_field(header->name);
381 p++;
382 while (*p == ' ' || *p == '\t') p++;
383 header->body = conv_unmime_header(p, NULL, addr_field);
384 return header;
387 return NULL;
390 void procheader_get_header_fields(FILE *fp, HeaderEntry hentry[])
392 gchar *buf = NULL;
393 HeaderEntry *hp;
394 gint hnum;
395 gchar *p;
397 if (hentry == NULL) return;
399 while ((hnum = procheader_get_one_field(&buf, fp, hentry)) != -1) {
400 hp = hentry + hnum;
402 p = buf + strlen(hp->name);
403 while (*p == ' ' || *p == '\t') p++;
405 if (hp->body == NULL)
406 hp->body = g_strdup(p);
407 else if (procheader_headername_equal(hp->name, "To") ||
408 procheader_headername_equal(hp->name, "Cc")) {
409 gchar *tp = hp->body;
410 hp->body = g_strconcat(tp, ", ", p, NULL);
411 g_free(tp);
413 g_free(buf);
414 buf = NULL;
418 MsgInfo *procheader_parse_file(const gchar *file, MsgFlags flags,
419 gboolean full, gboolean decrypted)
421 #ifdef G_OS_WIN32
422 GFile *f;
423 GFileInfo *fi;
424 GTimeVal tv;
425 GError *error = NULL;
426 #else
427 GStatBuf s;
428 #endif
429 FILE *fp;
430 MsgInfo *msginfo;
432 #ifdef G_OS_WIN32
433 f = g_file_new_for_path(file);
434 fi = g_file_query_info(f, "standard::size,standard::type,time::modified",
435 G_FILE_QUERY_INFO_NONE, NULL, &error);
436 if (error != NULL) {
437 g_warning(error->message);
438 g_error_free(error);
439 g_object_unref(f);
441 #else
442 if (g_stat(file, &s) < 0) {
443 FILE_OP_ERROR(file, "stat");
444 return NULL;
446 #endif
448 #ifdef G_OS_WIN32
449 if (g_file_info_get_file_type(fi) != G_FILE_TYPE_REGULAR) {
450 g_object_unref(fi);
451 g_object_unref(f);
452 return NULL;
454 #else
455 if (!S_ISREG(s.st_mode))
456 return NULL;
457 #endif
459 if ((fp = claws_fopen(file, "rb")) == NULL) {
460 FILE_OP_ERROR(file, "claws_fopen");
461 return NULL;
464 msginfo = procheader_parse_stream(fp, flags, full, decrypted);
465 claws_fclose(fp);
467 if (msginfo) {
468 #ifdef G_OS_WIN32
469 msginfo->size = g_file_info_get_size(fi);
470 g_file_info_get_modification_time(fi, &tv);
471 msginfo->mtime = tv.tv_sec;
472 #else
473 msginfo->size = s.st_size;
474 msginfo->mtime = s.st_mtime;
475 #endif
478 #ifdef G_OS_WIN32
479 g_object_unref(fi);
480 g_object_unref(f);
481 #endif
483 return msginfo;
486 MsgInfo *procheader_parse_str(const gchar *str, MsgFlags flags, gboolean full,
487 gboolean decrypted)
489 return parse_stream(&str, TRUE, flags, full, decrypted);
492 enum
494 H_DATE = 0,
495 H_FROM,
496 H_TO,
497 H_CC,
498 H_NEWSGROUPS,
499 H_SUBJECT,
500 H_MSG_ID,
501 H_REFERENCES,
502 H_IN_REPLY_TO,
503 H_CONTENT_TYPE,
504 H_SEEN,
505 H_STATUS,
506 H_FROM_SPACE,
507 H_SC_PLANNED_DOWNLOAD,
508 H_SC_MESSAGE_SIZE,
509 H_FACE,
510 H_X_FACE,
511 H_DISPOSITION_NOTIFICATION_TO,
512 H_RETURN_RECEIPT_TO,
513 H_SC_PARTIALLY_RETRIEVED,
514 H_SC_ACCOUNT_SERVER,
515 H_SC_ACCOUNT_LOGIN,
516 H_LIST_POST,
517 H_LIST_SUBSCRIBE,
518 H_LIST_UNSUBSCRIBE,
519 H_LIST_HELP,
520 H_LIST_ARCHIVE,
521 H_LIST_OWNER,
522 H_RESENT_FROM,
525 static HeaderEntry hentry_full[] = {
526 {"Date:", NULL, FALSE},
527 {"From:", NULL, TRUE},
528 {"To:", NULL, TRUE},
529 {"Cc:", NULL, TRUE},
530 {"Newsgroups:", NULL, TRUE},
531 {"Subject:", NULL, TRUE},
532 {"Message-ID:", NULL, FALSE},
533 {"References:", NULL, FALSE},
534 {"In-Reply-To:", NULL, FALSE},
535 {"Content-Type:", NULL, FALSE},
536 {"Seen:", NULL, FALSE},
537 {"Status:", NULL, FALSE},
538 {"From ", NULL, FALSE},
539 {"SC-Marked-For-Download:", NULL, FALSE},
540 {"SC-Message-Size:", NULL, FALSE},
541 {"Face:", NULL, FALSE},
542 {"X-Face:", NULL, FALSE},
543 {"Disposition-Notification-To:", NULL, FALSE},
544 {"Return-Receipt-To:", NULL, FALSE},
545 {"SC-Partially-Retrieved:", NULL, FALSE},
546 {"SC-Account-Server:", NULL, FALSE},
547 {"SC-Account-Login:",NULL, FALSE},
548 {"List-Post:", NULL, TRUE},
549 {"List-Subscribe:", NULL, TRUE},
550 {"List-Unsubscribe:",NULL, TRUE},
551 {"List-Help:", NULL, TRUE},
552 {"List-Archive:", NULL, TRUE},
553 {"List-Owner:", NULL, TRUE},
554 {"Resent-From:", NULL, TRUE},
555 {NULL, NULL, FALSE}};
557 static HeaderEntry hentry_short[] = {
558 {"Date:", NULL, FALSE},
559 {"From:", NULL, TRUE},
560 {"To:", NULL, TRUE},
561 {"Cc:", NULL, TRUE},
562 {"Newsgroups:", NULL, TRUE},
563 {"Subject:", NULL, TRUE},
564 {"Message-ID:", NULL, FALSE},
565 {"References:", NULL, FALSE},
566 {"In-Reply-To:", NULL, FALSE},
567 {"Content-Type:", NULL, FALSE},
568 {"Seen:", NULL, FALSE},
569 {"Status:", NULL, FALSE},
570 {"From ", NULL, FALSE},
571 {"SC-Marked-For-Download:", NULL, FALSE},
572 {"SC-Message-Size:",NULL, FALSE},
573 {NULL, NULL, FALSE}};
575 static HeaderEntry* procheader_get_headernames(gboolean full)
577 return full ? hentry_full : hentry_short;
580 MsgInfo *procheader_parse_stream(FILE *fp, MsgFlags flags, gboolean full,
581 gboolean decrypted)
583 return parse_stream(fp, FALSE, flags, full, decrypted);
586 static gboolean avatar_from_some_face(gpointer source, gpointer userdata)
588 AvatarCaptureData *acd = (AvatarCaptureData *)source;
590 if (*(acd->content) == '\0') /* won't be null, but may be empty */
591 return FALSE;
593 if (!strcmp(acd->header, hentry_full[H_FACE].name)) {
594 debug_print("avatar_from_some_face: found 'Face' header\n");
595 procmsg_msginfo_add_avatar(acd->msginfo, AVATAR_FACE, acd->content);
597 #if HAVE_LIBCOMPFACE
598 else if (!strcmp(acd->header, hentry_full[H_X_FACE].name)) {
599 debug_print("avatar_from_some_face: found 'X-Face' header\n");
600 procmsg_msginfo_add_avatar(acd->msginfo, AVATAR_XFACE, acd->content);
602 #endif
603 return FALSE;
606 static gulong avatar_hook_id = HOOK_NONE;
608 static MsgInfo *parse_stream(void *data, gboolean isstring, MsgFlags flags,
609 gboolean full, gboolean decrypted)
611 MsgInfo *msginfo;
612 gchar *buf = NULL;
613 gchar *p, *tmp;
614 gchar *hp;
615 HeaderEntry *hentry;
616 gint hnum;
617 void *orig_data = data;
619 get_one_field_func get_one_field =
620 isstring ? (get_one_field_func)string_get_one_field
621 : (get_one_field_func)procheader_get_one_field;
623 hentry = procheader_get_headernames(full);
625 if (MSG_IS_QUEUED(flags) || MSG_IS_DRAFT(flags)) {
626 while (get_one_field(&buf, data, NULL) != -1) {
627 if ((!strncmp(buf, "X-Claws-End-Special-Headers: 1",
628 strlen("X-Claws-End-Special-Headers:"))) ||
629 (!strncmp(buf, "X-Sylpheed-End-Special-Headers: 1",
630 strlen("X-Sylpheed-End-Special-Headers:")))) {
631 g_free(buf);
632 buf = NULL;
633 break;
635 /* from other mailers */
636 if (!strncmp(buf, "Date: ", 6)
637 || !strncmp(buf, "To: ", 4)
638 || !strncmp(buf, "From: ", 6)
639 || !strncmp(buf, "Subject: ", 9)) {
640 if (isstring)
641 data = orig_data;
642 else
643 rewind((FILE *)data);
644 g_free(buf);
645 buf = NULL;
646 break;
648 g_free(buf);
649 buf = NULL;
653 msginfo = procmsg_msginfo_new();
655 if (flags.tmp_flags || flags.perm_flags)
656 msginfo->flags = flags;
657 else
658 MSG_SET_PERM_FLAGS(msginfo->flags, MSG_NEW | MSG_UNREAD);
660 msginfo->inreplyto = NULL;
662 if (avatar_hook_id == HOOK_NONE &&
663 (prefs_common.enable_avatars & (AVATARS_ENABLE_CAPTURE | AVATARS_ENABLE_RENDER))) {
664 avatar_hook_id = hooks_register_hook(AVATAR_HEADER_UPDATE_HOOKLIST,
665 avatar_from_some_face, NULL);
666 } else if (avatar_hook_id != HOOK_NONE &&
667 !(prefs_common.enable_avatars & AVATARS_ENABLE_CAPTURE)) {
668 hooks_unregister_hook(AVATAR_HEADER_UPDATE_HOOKLIST, avatar_hook_id);
669 avatar_hook_id = HOOK_NONE;
672 while ((hnum = get_one_field(&buf, data, hentry)) != -1) {
673 hp = buf + strlen(hentry[hnum].name);
674 while (*hp == ' ' || *hp == '\t') hp++;
676 switch (hnum) {
677 case H_DATE:
678 if (msginfo->date) break;
679 msginfo->date_t =
680 procheader_date_parse(NULL, hp, 0);
681 if (g_utf8_validate(hp, -1, NULL)) {
682 msginfo->date = g_strdup(hp);
683 } else {
684 gchar *utf = conv_codeset_strdup(
685 hp,
686 conv_get_locale_charset_str_no_utf8(),
687 CS_INTERNAL);
688 if (utf == NULL ||
689 !g_utf8_validate(utf, -1, NULL)) {
690 g_free(utf);
691 utf = g_malloc(strlen(buf)*2+1);
692 conv_localetodisp(utf,
693 strlen(hp)*2+1, hp);
695 msginfo->date = utf;
697 break;
698 case H_FROM:
699 if (msginfo->from) break;
700 msginfo->from = conv_unmime_header(hp, NULL, TRUE);
701 msginfo->fromname = procheader_get_fromname(msginfo->from);
702 remove_return(msginfo->from);
703 remove_return(msginfo->fromname);
704 break;
705 case H_TO:
706 tmp = conv_unmime_header(hp, NULL, TRUE);
707 remove_return(tmp);
708 if (msginfo->to) {
709 p = msginfo->to;
710 msginfo->to =
711 g_strconcat(p, ", ", tmp, NULL);
712 g_free(p);
713 } else
714 msginfo->to = g_strdup(tmp);
715 g_free(tmp);
716 break;
717 case H_CC:
718 tmp = conv_unmime_header(hp, NULL, TRUE);
719 remove_return(tmp);
720 if (msginfo->cc) {
721 p = msginfo->cc;
722 msginfo->cc =
723 g_strconcat(p, ", ", tmp, NULL);
724 g_free(p);
725 } else
726 msginfo->cc = g_strdup(tmp);
727 g_free(tmp);
728 break;
729 case H_NEWSGROUPS:
730 if (msginfo->newsgroups) {
731 p = msginfo->newsgroups;
732 msginfo->newsgroups =
733 g_strconcat(p, ",", hp, NULL);
734 g_free(p);
735 } else
736 msginfo->newsgroups = g_strdup(hp);
737 break;
738 case H_SUBJECT:
739 if (msginfo->subject) break;
740 msginfo->subject = conv_unmime_header(hp, NULL, FALSE);
741 unfold_line(msginfo->subject);
742 break;
743 case H_MSG_ID:
744 if (msginfo->msgid) break;
746 extract_parenthesis(hp, '<', '>');
747 remove_space(hp);
748 msginfo->msgid = g_strdup(hp);
749 break;
750 case H_REFERENCES:
751 msginfo->references =
752 references_list_prepend(msginfo->references,
753 hp);
754 break;
755 case H_IN_REPLY_TO:
756 if (msginfo->inreplyto) break;
758 eliminate_parenthesis(hp, '(', ')');
759 if ((p = strrchr(hp, '<')) != NULL &&
760 strchr(p + 1, '>') != NULL) {
761 extract_parenthesis(p, '<', '>');
762 remove_space(p);
763 if (*p != '\0')
764 msginfo->inreplyto = g_strdup(p);
766 break;
767 case H_CONTENT_TYPE:
768 if (!g_ascii_strncasecmp(hp, "multipart/", 10))
769 MSG_SET_TMP_FLAGS(msginfo->flags, MSG_MULTIPART);
770 break;
771 case H_DISPOSITION_NOTIFICATION_TO:
772 if (!msginfo->extradata)
773 msginfo->extradata = g_new0(MsgInfoExtraData, 1);
774 if (msginfo->extradata->dispositionnotificationto) break;
775 msginfo->extradata->dispositionnotificationto = g_strdup(hp);
776 break;
777 case H_RETURN_RECEIPT_TO:
778 if (!msginfo->extradata)
779 msginfo->extradata = g_new0(MsgInfoExtraData, 1);
780 if (msginfo->extradata->returnreceiptto) break;
781 msginfo->extradata->returnreceiptto = g_strdup(hp);
782 break;
783 /* partial download infos */
784 case H_SC_PARTIALLY_RETRIEVED:
785 if (!msginfo->extradata)
786 msginfo->extradata = g_new0(MsgInfoExtraData, 1);
787 if (msginfo->extradata->partial_recv) break;
788 msginfo->extradata->partial_recv = g_strdup(hp);
789 break;
790 case H_SC_ACCOUNT_SERVER:
791 if (!msginfo->extradata)
792 msginfo->extradata = g_new0(MsgInfoExtraData, 1);
793 if (msginfo->extradata->account_server) break;
794 msginfo->extradata->account_server = g_strdup(hp);
795 break;
796 case H_SC_ACCOUNT_LOGIN:
797 if (!msginfo->extradata)
798 msginfo->extradata = g_new0(MsgInfoExtraData, 1);
799 if (msginfo->extradata->account_login) break;
800 msginfo->extradata->account_login = g_strdup(hp);
801 break;
802 case H_SC_MESSAGE_SIZE:
803 if (msginfo->total_size) break;
804 msginfo->total_size = atoi(hp);
805 break;
806 case H_SC_PLANNED_DOWNLOAD:
807 msginfo->planned_download = atoi(hp);
808 break;
809 /* end partial download infos */
810 case H_FROM_SPACE:
811 if (msginfo->fromspace) break;
812 msginfo->fromspace = g_strdup(hp);
813 remove_return(msginfo->fromspace);
814 break;
815 /* list infos */
816 case H_LIST_POST:
817 if (!msginfo->extradata)
818 msginfo->extradata = g_new0(MsgInfoExtraData, 1);
819 if (msginfo->extradata->list_post) break;
820 msginfo->extradata->list_post = g_strdup(hp);
821 break;
822 case H_LIST_SUBSCRIBE:
823 if (!msginfo->extradata)
824 msginfo->extradata = g_new0(MsgInfoExtraData, 1);
825 if (msginfo->extradata->list_subscribe) break;
826 msginfo->extradata->list_subscribe = g_strdup(hp);
827 break;
828 case H_LIST_UNSUBSCRIBE:
829 if (!msginfo->extradata)
830 msginfo->extradata = g_new0(MsgInfoExtraData, 1);
831 if (msginfo->extradata->list_unsubscribe) break;
832 msginfo->extradata->list_unsubscribe = g_strdup(hp);
833 break;
834 case H_LIST_HELP:
835 if (!msginfo->extradata)
836 msginfo->extradata = g_new0(MsgInfoExtraData, 1);
837 if (msginfo->extradata->list_help) break;
838 msginfo->extradata->list_help = g_strdup(hp);
839 break;
840 case H_LIST_ARCHIVE:
841 if (!msginfo->extradata)
842 msginfo->extradata = g_new0(MsgInfoExtraData, 1);
843 if (msginfo->extradata->list_archive) break;
844 msginfo->extradata->list_archive = g_strdup(hp);
845 break;
846 case H_LIST_OWNER:
847 if (!msginfo->extradata)
848 msginfo->extradata = g_new0(MsgInfoExtraData, 1);
849 if (msginfo->extradata->list_owner) break;
850 msginfo->extradata->list_owner = g_strdup(hp);
851 break;
852 case H_RESENT_FROM:
853 if (!msginfo->extradata)
854 msginfo->extradata = g_new0(MsgInfoExtraData, 1);
855 if (msginfo->extradata->resent_from) break;
856 msginfo->extradata->resent_from = g_strdup(hp);
857 break;
858 /* end list infos */
859 default:
860 break;
862 /* to avoid performance penalty hooklist is invoked only for
863 headers known to be able to generate avatars */
864 if (hnum == H_FROM || hnum == H_X_FACE || hnum == H_FACE) {
865 AvatarCaptureData *acd = g_new0(AvatarCaptureData, 1);
866 /* no extra memory is wasted, hooks are expected to
867 take care of copying members when needed */
868 acd->msginfo = msginfo;
869 acd->header = hentry_full[hnum].name;
870 acd->content = hp;
871 hooks_invoke(AVATAR_HEADER_UPDATE_HOOKLIST, (gpointer)acd);
872 g_free(acd);
874 g_free(buf);
875 buf = NULL;
878 if (!msginfo->inreplyto && msginfo->references)
879 msginfo->inreplyto =
880 g_strdup((gchar *)msginfo->references->data);
882 return msginfo;
885 gchar *procheader_get_fromname(const gchar *str)
887 gchar *tmp, *name;
889 Xstrdup_a(tmp, str, return NULL);
891 if (*tmp == '\"') {
892 extract_quote(tmp, '\"');
893 g_strstrip(tmp);
894 } else if (strchr(tmp, '<')) {
895 eliminate_parenthesis(tmp, '<', '>');
896 g_strstrip(tmp);
897 if (*tmp == '\0') {
898 strcpy(tmp, str);
899 extract_parenthesis(tmp, '<', '>');
900 g_strstrip(tmp);
902 } else if (strchr(tmp, '(')) {
903 extract_parenthesis(tmp, '(', ')');
904 g_strstrip(tmp);
907 if (*tmp == '\0')
908 name = g_strdup(str);
909 else
910 name = g_strdup(tmp);
912 return name;
915 static gint procheader_remove_comment_in_date_string(gchar *o_str)
917 gchar str[strlen(o_str)+1];
918 int i, j = 0;
919 int in_comment_nest_level = 0;
920 gboolean flag_escape_backslash = FALSE;
922 for (i=0; i < strlen(o_str); i++) {
923 switch (o_str[i]) {
924 case '(':
925 in_comment_nest_level++;
926 if (in_comment_nest_level > 16) {
927 str[j] = '\0';
928 return TRUE;
930 continue;
931 case '\\':
932 if (in_comment_nest_level > 0) {
933 flag_escape_backslash = TRUE;
934 continue;
936 break;
937 case ')':
938 if (flag_escape_backslash == TRUE) {
939 flag_escape_backslash = FALSE;
940 continue;
942 in_comment_nest_level--;
943 if (in_comment_nest_level < 0) {
944 str[j] = '\0';
945 return TRUE;
947 continue;
948 default:
949 if (in_comment_nest_level > 0) {
950 if (flag_escape_backslash == TRUE)
951 flag_escape_backslash = FALSE;
952 continue;
954 break;
956 str[j++] = o_str[i];
958 str[j] = '\0';
959 strcpy(o_str, str);
960 return TRUE;
964 static gint procheader_scan_date_string(const gchar *o_str,
965 gchar *weekday, gint *day,
966 gchar *month, gint *year,
967 gint *hh, gint *mm, gint *ss,
968 gchar *zone)
970 gint result;
971 gint month_n;
972 gint secfract;
973 gint zone1 = 0, zone2 = 0;
974 gchar offset_sign, zonestr[7];
975 gchar sep1;
977 if (o_str == NULL)
978 return -1;
980 gchar str[strlen(o_str)+1];
982 strcpy(str, o_str);
983 if (strchr(str, '(') != NULL)
984 procheader_remove_comment_in_date_string(str);
986 result = sscanf(str, "%10s %d %9s %d %2d:%2d:%2d %6s",
987 weekday, day, month, year, hh, mm, ss, zone);
988 if (result == 8) return 0;
990 /* RFC2822 */
991 result = sscanf(str, "%3s,%d %9s %d %2d:%2d:%2d %6s",
992 weekday, day, month, year, hh, mm, ss, zone);
993 if (result == 8) return 0;
995 result = sscanf(str, "%3s %3s %d %2d:%2d:%2d %d %6s",
996 weekday, month, day, hh, mm, ss, year, zone);
997 if (result == 8) return 0;
999 result = sscanf(str, "%d %9s %d %2d:%2d:%2d %6s",
1000 day, month, year, hh, mm, ss, zone);
1001 if (result == 7) return 0;
1003 *zone = '\0';
1004 result = sscanf(str, "%10s %d %9s %d %2d:%2d:%2d",
1005 weekday, day, month, year, hh, mm, ss);
1006 if (result == 7) return 0;
1008 result = sscanf(str, "%3s %3s %d %2d:%2d:%2d %d",
1009 weekday, month, day, hh, mm, ss, year);
1010 if (result == 7) return 0;
1012 result = sscanf(str, "%d %9s %d %2d:%2d:%2d",
1013 day, month, year, hh, mm, ss);
1014 if (result == 6) return 0;
1016 *ss = 0;
1017 result = sscanf(str, "%10s %d %9s %d %2d:%2d %6s",
1018 weekday, day, month, year, hh, mm, zone);
1019 if (result == 7) return 0;
1021 result = sscanf(str, "%d %9s %d %2d:%2d %5s",
1022 day, month, year, hh, mm, zone);
1023 if (result == 6) return 0;
1025 *zone = '\0';
1026 result = sscanf(str, "%10s %d %9s %d %2d:%2d",
1027 weekday, day, month, year, hh, mm);
1028 if (result == 6) return 0;
1030 result = sscanf(str, "%d %9s %d %2d:%2d",
1031 day, month, year, hh, mm);
1032 if (result == 5) return 0;
1034 *weekday = '\0';
1036 /* RFC3339 subset, with fraction of second */
1037 result = sscanf(str, "%4d-%2d-%2d%c%2d:%2d:%2d.%d%6s",
1038 year, &month_n, day, &sep1, hh, mm, ss, &secfract, zonestr);
1039 if (result == 9
1040 && (sep1 == 'T' || sep1 == 't' || sep1 == ' ')) {
1041 if (month_n >= 1 && month_n <= 12) {
1042 strncpy2(month, monthstr+((month_n-1)*3), 4);
1043 if (zonestr[0] == 'z' || zonestr[0] == 'Z') {
1044 strcat(zone, "+00:00");
1045 } else if (sscanf(zonestr, "%c%2d:%2d",
1046 &offset_sign, &zone1, &zone2) == 3) {
1047 strcat(zone, zonestr);
1049 return 0;
1053 /* RFC3339 subset, no fraction of second */
1054 result = sscanf(str, "%4d-%2d-%2d%c%2d:%2d:%2d%6s",
1055 year, &month_n, day, &sep1, hh, mm, ss, zonestr);
1056 if (result == 8
1057 && (sep1 == 'T' || sep1 == 't' || sep1 == ' ')) {
1058 if (month_n >= 1 && month_n <= 12) {
1059 strncpy2(month, monthstr+((month_n-1)*3), 4);
1060 if (zonestr[0] == 'z' || zonestr[0] == 'Z') {
1061 strcat(zone, "+00:00");
1062 } else if (sscanf(zonestr, "%c%2d:%2d",
1063 &offset_sign, &zone1, &zone2) == 3) {
1064 strcat(zone, zonestr);
1066 return 0;
1070 *zone = '\0';
1072 /* RFC3339 subset, no fraction of second, and no timezone offset */
1073 /* This particular "subset" is invalid, RFC requires the offset */
1074 result = sscanf(str, "%4d-%2d-%2d %2d:%2d:%2d",
1075 year, &month_n, day, hh, mm, ss);
1076 if (result == 6) {
1077 if (1 <= month_n && month_n <= 12) {
1078 strncpy2(month, monthstr+((month_n-1)*3), 4);
1079 return 0;
1083 /* ISO8601 format with just date (YYYY-MM-DD) */
1084 result = sscanf(str, "%4d-%2d-%2d",
1085 year, &month_n, day);
1086 if (result == 3) {
1087 *hh = *mm = *ss = 0;
1088 if (1 <= month_n && month_n <= 12) {
1089 strncpy2(month, monthstr+((month_n-1)*3), 4);
1090 return 0;
1094 return -1;
1098 * Hiro, most UNIXen support this function:
1099 * http://www.mcsr.olemiss.edu/cgi-bin/man-cgi?getdate
1101 gboolean procheader_date_parse_to_tm(const gchar *src, struct tm *t, char *zone)
1103 gchar weekday[11];
1104 gint day;
1105 gchar month[10];
1106 gint year;
1107 gint hh, mm, ss;
1108 GDateMonth dmonth;
1109 gchar *p;
1111 if (!t)
1112 return FALSE;
1114 memset(t, 0, sizeof *t);
1116 if (procheader_scan_date_string(src, weekday, &day, month, &year,
1117 &hh, &mm, &ss, zone) < 0) {
1118 g_warning("invalid date: %s", src);
1119 return FALSE;
1122 /* Y2K compliant :) */
1123 if (year < 100) {
1124 if (year < 70)
1125 year += 2000;
1126 else
1127 year += 1900;
1130 month[3] = '\0';
1131 if ((p = strstr(monthstr, month)) != NULL)
1132 dmonth = (gint)(p - monthstr) / 3 + 1;
1133 else {
1134 g_warning("invalid month: %s", month);
1135 dmonth = G_DATE_BAD_MONTH;
1138 t->tm_sec = ss;
1139 t->tm_min = mm;
1140 t->tm_hour = hh;
1141 t->tm_mday = day;
1142 t->tm_mon = dmonth - 1;
1143 t->tm_year = year - 1900;
1144 t->tm_wday = 0;
1145 t->tm_yday = 0;
1146 t->tm_isdst = -1;
1148 mktime(t);
1150 return TRUE;
1153 time_t procheader_date_parse(gchar *dest, const gchar *src, gint len)
1155 gchar weekday[11];
1156 gint day;
1157 gchar month[10];
1158 gint year;
1159 gint hh, mm, ss;
1160 gchar zone[7];
1161 GDateMonth dmonth = G_DATE_BAD_MONTH;
1162 gchar *p;
1163 time_t timer;
1165 if (procheader_scan_date_string(src, weekday, &day, month, &year,
1166 &hh, &mm, &ss, zone) < 0) {
1167 if (dest && len > 0)
1168 strncpy2(dest, src, len);
1169 return 0;
1172 month[3] = '\0';
1173 for (p = monthstr; *p != '\0'; p += 3) {
1174 if (!g_ascii_strncasecmp(p, month, 3)) {
1175 dmonth = (gint)(p - monthstr) / 3 + 1;
1176 break;
1180 #ifdef G_OS_WIN32
1181 GTimeZone *tz;
1182 GDateTime *dt, *dt2;
1184 #if GLIB_CHECK_VERSION(2,68,0)
1185 tz = g_time_zone_new_identifier(zone);
1186 if (tz == NULL)
1187 tz = g_time_zone_new_utc();
1188 #else
1189 tz = g_time_zone_new(zone); // can't return NULL no need to check for it
1190 #endif
1191 dt = g_date_time_new(tz, 1, 1, 1, 0, 0, 0);
1192 g_time_zone_unref(tz);
1193 dt2 = g_date_time_add_full(dt, year-1, dmonth-1, day-1, hh, mm, ss);
1194 g_date_time_unref(dt);
1196 timer = g_date_time_to_unix(dt2);
1197 g_date_time_unref(dt2);
1199 #else
1200 struct tm t;
1201 time_t tz_offset;
1203 /* Y2K compliant :) */
1204 if (year < 1000) {
1205 if (year < 50)
1206 year += 2000;
1207 else
1208 year += 1900;
1211 t.tm_sec = ss;
1212 t.tm_min = mm;
1213 t.tm_hour = hh;
1214 t.tm_mday = day;
1215 t.tm_mon = dmonth - 1;
1216 t.tm_year = year - 1900;
1217 t.tm_wday = 0;
1218 t.tm_yday = 0;
1219 t.tm_isdst = -1;
1221 timer = mktime(&t);
1222 tz_offset = remote_tzoffset_sec(zone);
1223 if (tz_offset != -1)
1224 timer += tzoffset_sec(&timer) - tz_offset;
1226 #endif
1227 if (dest)
1228 procheader_date_get_localtime(dest, len, timer);
1230 return timer;
1233 void procheader_date_get_localtime(gchar *dest, gint len, const time_t timer)
1235 struct tm *lt;
1236 gchar *default_format = "%y/%m/%d(%a) %H:%M";
1237 gchar *str;
1238 const gchar *src_codeset, *dest_codeset;
1239 struct tm buf;
1241 if (timer > 0)
1242 lt = localtime_r(&timer, &buf);
1243 else {
1244 time_t dummy = 1;
1245 lt = localtime_r(&dummy, &buf);
1248 if (prefs_common.date_format)
1249 fast_strftime(dest, len, prefs_common.date_format, lt);
1250 else
1251 fast_strftime(dest, len, default_format, lt);
1253 if (!g_utf8_validate(dest, -1, NULL)) {
1254 src_codeset = conv_get_locale_charset_str_no_utf8();
1255 dest_codeset = CS_UTF_8;
1256 str = conv_codeset_strdup(dest, src_codeset, dest_codeset);
1257 if (str) {
1258 strncpy2(dest, str, len);
1259 g_free(str);
1264 /* Added by Mel Hadasht on 27 Aug 2001 */
1265 /* Get a header from msginfo */
1266 gint procheader_get_header_from_msginfo(MsgInfo *msginfo, gchar **buf, gchar *header)
1268 gchar *file;
1269 FILE *fp;
1270 HeaderEntry hentry[]={ { NULL, NULL, TRUE },
1271 { NULL, NULL, FALSE } };
1272 gint val;
1274 cm_return_val_if_fail(msginfo != NULL, -1);
1275 cm_return_val_if_fail(buf != NULL, -1);
1276 cm_return_val_if_fail(header != NULL, -1);
1278 hentry[0].name = header;
1280 file = procmsg_get_message_file_path(msginfo);
1281 if ((fp = claws_fopen(file, "rb")) == NULL) {
1282 FILE_OP_ERROR(file, "claws_fopen");
1283 g_free(file);
1284 g_free(*buf);
1285 *buf = NULL;
1286 return -1;
1288 val = procheader_get_one_field(buf, fp, hentry);
1290 if (claws_fclose(fp) == EOF) {
1291 FILE_OP_ERROR(file, "claws_fclose");
1292 claws_unlink(file);
1293 g_free(file);
1294 g_free(*buf);
1295 *buf = NULL;
1296 return -1;
1299 g_free(file);
1300 if (val == -1) {
1301 /* *buf is already NULL in that case, see procheader_get_one_field() */
1302 return -1;
1305 return 0;
1308 HeaderEntry *procheader_entries_from_str(const gchar *str)
1310 HeaderEntry *entries = NULL, *he;
1311 int numh = 0, i = 0;
1312 gchar **names = NULL;
1313 const gchar *s = str;
1315 if (s == NULL) {
1316 return NULL;
1318 while (*s != '\0') {
1319 if (*s == ' ') ++numh;
1320 ++s;
1322 if (numh == 0) {
1323 return NULL;
1325 entries = g_new0(HeaderEntry, numh + 1); /* room for last NULL */
1326 s = str;
1327 ++s; /* skip first space */
1328 names = g_strsplit(s, " ", numh);
1329 he = entries;
1330 while (names[i]) {
1331 he->name = g_strdup_printf("%s:", names[i]);
1332 he->body = NULL;
1333 he->unfold = FALSE;
1334 ++i, ++he;
1336 he->name = NULL;
1337 g_strfreev(names);
1338 return entries;
1341 void procheader_entries_free (HeaderEntry *entries)
1343 if (entries != NULL) {
1344 HeaderEntry *he = entries;
1345 while (he->name != NULL) {
1346 g_free(he->name);
1347 if (he->body != NULL)
1348 g_free(he->body);
1349 ++he;
1351 g_free(entries);
1355 gboolean procheader_header_is_internal(const gchar *hdr_name)
1357 const gchar *internal_hdrs[] = {
1358 "AF:", "NF:", "PS:", "SRH:", "SFN:", "DSR:", "MID:", "CFG:",
1359 "PT:", "S:", "RQ:", "SSV:", "NSV:", "SSH:", "R:", "MAID:",
1360 "SCF:", "RMID:", "FMID:", "NAID:",
1361 "X-Claws-Account-Id:",
1362 "X-Claws-Sign:",
1363 "X-Claws-Encrypt:",
1364 "X-Claws-Privacy-System:",
1365 "X-Claws-Auto-Wrapping:",
1366 "X-Claws-Auto-Indent:",
1367 "X-Claws-End-Special-Headers:",
1368 "X-Sylpheed-Account-Id:",
1369 "X-Sylpheed-Sign:",
1370 "X-Sylpheed-Encrypt:",
1371 "X-Sylpheed-Privacy-System:",
1372 "X-Sylpheed-End-Special-Headers:",
1373 NULL
1375 int i;
1377 for (i = 0; internal_hdrs[i]; i++) {
1378 if (!strcmp(hdr_name, internal_hdrs[i]))
1379 return TRUE;
1381 return FALSE;