Simplify ccred_lookup()..
[s-mailx.git] / imap.c
blob16383ca4f0fea9d7f318026ba4e2871e44ec35ca
1 /*@ S-nail - a mail user agent derived from Berkeley Mail.
2 *@ IMAP v4r1 client following RFC 2060.
3 *@ CRAM-MD5 as of RFC 2195.
5 * Copyright (c) 2000-2004 Gunnar Ritter, Freiburg i. Br., Germany.
6 * Copyright (c) 2012 - 2014 Steffen (Daode) Nurpmeso <sdaoden@users.sf.net>.
7 */
8 /*
9 * Copyright (c) 2004
10 * Gunnar Ritter. All rights reserved.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. All advertising materials mentioning features or use of this software
21 * must display the following acknowledgement:
22 * This product includes software developed by Gunnar Ritter
23 * and his contributors.
24 * 4. Neither the name of Gunnar Ritter nor the names of his contributors
25 * may be used to endorse or promote products derived from this software
26 * without specific prior written permission.
28 * THIS SOFTWARE IS PROVIDED BY GUNNAR RITTER AND CONTRIBUTORS ``AS IS'' AND
29 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31 * ARE DISCLAIMED. IN NO EVENT SHALL GUNNAR RITTER OR CONTRIBUTORS BE LIABLE
32 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 * SUCH DAMAGE.
41 #ifndef HAVE_AMALGAMATION
42 # include "nail.h"
43 #endif
45 #ifdef HAVE_IMAP
46 # include <sys/socket.h>
48 # include <netdb.h>
50 # include <netinet/in.h>
52 # ifdef HAVE_ARPA_INET_H
53 # include <arpa/inet.h>
54 # endif
55 #endif
57 #ifdef HAVE_IMAP
58 #define IMAP_ANSWER() \
60 if (mp->mb_type != MB_CACHE) {\
61 enum okay ok = OKAY;\
62 while (mp->mb_active & MB_COMD)\
63 ok = imap_answer(mp, 1);\
64 if (ok == STOP)\
65 return STOP;\
69 /* TODO IMAP_OUT() simply returns instead of doing "actioN" if imap_finish()
70 * TODO fails, which leaves behind leaks in, e.g., imap_append1()!
71 * TODO IMAP_XOUT() was added due to this, but (1) needs to be used everywhere
72 * TODO and (2) doesn't handle all I/O errors itself, yet, too.
73 * TODO I.e., that should be a function, not a macro ... or so.
74 * TODO This entire module needs MASSIVE work! */
75 #define IMAP_OUT(X,Y,ACTION) IMAP_XOUT(X, Y, ACTION, return STOP)
76 #define IMAP_XOUT(X,Y,ACTIONERR,ACTIONBAIL) \
77 do {\
78 if (mp->mb_type != MB_CACHE) {\
79 if (imap_finish(mp) == STOP) {\
80 ACTIONBAIL;\
82 if (options & OPT_VERBVERB)\
83 fprintf(stderr, ">>> %s", X);\
84 mp->mb_active |= Y;\
85 if (swrite(&mp->mb_sock, X) == STOP) {\
86 ACTIONERR;\
88 } else {\
89 if (queuefp != NULL)\
90 fputs(X, queuefp);\
92 } while (0);
94 static struct record {
95 struct record *rec_next;
96 unsigned long rec_count;
97 enum rec_type {
98 REC_EXISTS,
99 REC_EXPUNGE
100 } rec_type;
101 } *record, *recend;
103 static enum {
104 RESPONSE_TAGGED,
105 RESPONSE_DATA,
106 RESPONSE_FATAL,
107 RESPONSE_CONT,
108 RESPONSE_ILLEGAL
109 } response_type;
111 static enum {
112 RESPONSE_OK,
113 RESPONSE_NO,
114 RESPONSE_BAD,
115 RESPONSE_PREAUTH,
116 RESPONSE_BYE,
117 RESPONSE_OTHER,
118 RESPONSE_UNKNOWN
119 } response_status;
121 static char *responded_tag;
122 static char *responded_text;
123 static char *responded_other_text;
124 static long responded_other_number;
126 static enum {
127 MAILBOX_DATA_FLAGS,
128 MAILBOX_DATA_LIST,
129 MAILBOX_DATA_LSUB,
130 MAILBOX_DATA_MAILBOX,
131 MAILBOX_DATA_SEARCH,
132 MAILBOX_DATA_STATUS,
133 MAILBOX_DATA_EXISTS,
134 MAILBOX_DATA_RECENT,
135 MESSAGE_DATA_EXPUNGE,
136 MESSAGE_DATA_FETCH,
137 CAPABILITY_DATA,
138 RESPONSE_OTHER_UNKNOWN
139 } response_other;
141 static enum list_attributes {
142 LIST_NONE = 000,
143 LIST_NOINFERIORS = 001,
144 LIST_NOSELECT = 002,
145 LIST_MARKED = 004,
146 LIST_UNMARKED = 010
147 } list_attributes;
149 static int list_hierarchy_delimiter;
150 static char *list_name;
152 struct list_item {
153 struct list_item *l_next;
154 char *l_name;
155 char *l_base;
156 enum list_attributes l_attr;
157 int l_delim;
158 int l_level;
159 int l_has_children;
162 static char *imapbuf; /* TODO not static, use pool */
163 static size_t imapbufsize;
164 static sigjmp_buf imapjmp;
165 static sighandler_type savealrm;
166 static int imapkeepalive;
167 static long had_exists = -1;
168 static long had_expunge = -1;
169 static long expunged_messages;
170 static int volatile imaplock;
171 static int same_imap_account;
172 static bool_t _imap_rdonly;
174 static void imap_other_get(char *pp);
175 static void imap_response_get(const char **cp);
176 static void imap_response_parse(void);
177 static enum okay imap_answer(struct mailbox *mp, int errprnt);
178 static enum okay imap_parse_list(void);
179 static enum okay imap_finish(struct mailbox *mp);
180 static void imap_timer_off(void);
181 static void imapcatch(int s);
182 static void _imap_maincatch(int s);
183 static enum okay imap_noop1(struct mailbox *mp);
184 static void rec_queue(enum rec_type type, unsigned long cnt);
185 static enum okay rec_dequeue(void);
186 static void rec_rmqueue(void);
187 static void imapalarm(int s);
188 static int imap_use_starttls(const char *uhp);
189 static enum okay imap_preauth(struct mailbox *mp, const char *xserver,
190 const char *uhp);
191 static enum okay imap_capability(struct mailbox *mp);
192 static enum okay imap_auth(struct mailbox *mp, struct ccred *ccred);
193 #ifdef HAVE_MD5
194 static enum okay imap_cram_md5(struct mailbox *mp, struct ccred *ccred);
195 #endif
196 static enum okay imap_login(struct mailbox *mp, struct ccred *ccred);
197 #ifdef HAVE_GSSAPI
198 static enum okay _imap_gssapi(struct mailbox *mp, struct ccred *ccred);
199 #endif
200 static enum okay imap_flags(struct mailbox *mp, unsigned X, unsigned Y);
201 static void imap_init(struct mailbox *mp, int n);
202 static void imap_setptr(struct mailbox *mp, int nmail, int transparent,
203 int *prevcount);
204 static bool_t _imap_getcred(struct mailbox *mbp, struct ccred *ccredp,
205 struct url *urlp);
206 static int _imap_setfile1(struct url *urlp, enum fedit_mode fm,
207 int transparent);
208 static int imap_fetchdata(struct mailbox *mp, struct message *m,
209 size_t expected, int need, const char *head,
210 size_t headsize, long headlines);
211 static void imap_putstr(struct mailbox *mp, struct message *m,
212 const char *str, const char *head, size_t headsize,
213 long headlines);
214 static enum okay imap_get(struct mailbox *mp, struct message *m,
215 enum needspec need);
216 static void commitmsg(struct mailbox *mp, struct message *to,
217 struct message *from, enum havespec have);
218 static enum okay imap_fetchheaders(struct mailbox *mp, struct message *m,
219 int bot, int top);
220 static enum okay imap_exit(struct mailbox *mp);
221 static enum okay imap_delete(struct mailbox *mp, int n, struct message *m,
222 int needstat);
223 static enum okay imap_close(struct mailbox *mp);
224 static enum okay imap_update(struct mailbox *mp);
225 static enum okay imap_store(struct mailbox *mp, struct message *m, int n,
226 int c, const char *sp, int needstat);
227 static enum okay imap_unstore(struct message *m, int n, const char *flag);
228 static const char *tag(int new);
229 static char * imap_putflags(int f);
230 static void imap_getflags(const char *cp, char const **xp, enum mflag *f);
231 static enum okay imap_append1(struct mailbox *mp, const char *name, FILE *fp,
232 off_t off1, long xsize, enum mflag flag, time_t t);
233 static enum okay imap_append0(struct mailbox *mp, const char *name, FILE *fp);
234 static enum okay imap_list1(struct mailbox *mp, const char *base,
235 struct list_item **list, struct list_item **lend,
236 int level);
237 static enum okay imap_list(struct mailbox *mp, const char *base, int strip,
238 FILE *fp);
239 static void dopr(FILE *fp);
240 static enum okay imap_copy1(struct mailbox *mp, struct message *m, int n,
241 const char *name);
242 static enum okay imap_copyuid_parse(const char *cp,
243 unsigned long *uidvalidity, unsigned long *olduid,
244 unsigned long *newuid);
245 static enum okay imap_appenduid_parse(const char *cp,
246 unsigned long *uidvalidity, unsigned long *uid);
247 static enum okay imap_copyuid(struct mailbox *mp, struct message *m,
248 const char *name);
249 static enum okay imap_appenduid(struct mailbox *mp, FILE *fp, time_t t,
250 long off1, long xsize, long size, long lines, int flag,
251 const char *name);
252 static enum okay imap_appenduid_cached(struct mailbox *mp, FILE *fp);
253 #ifdef HAVE_IMAP_SEARCH
254 static enum okay imap_search2(struct mailbox *mp, struct message *m, int cnt,
255 const char *spec, int f);
256 #endif
257 static enum okay imap_remove1(struct mailbox *mp, const char *name);
258 static enum okay imap_rename1(struct mailbox *mp, const char *old,
259 const char *new);
260 static char * imap_strex(char const *cp, char const **xp);
261 static enum okay check_expunged(void);
263 static void
264 imap_other_get(char *pp)
266 char *xp;
267 NYD2_ENTER;
269 if (ascncasecmp(pp, "FLAGS ", 6) == 0) {
270 pp += 6;
271 response_other = MAILBOX_DATA_FLAGS;
272 } else if (ascncasecmp(pp, "LIST ", 5) == 0) {
273 pp += 5;
274 response_other = MAILBOX_DATA_LIST;
275 } else if (ascncasecmp(pp, "LSUB ", 5) == 0) {
276 pp += 5;
277 response_other = MAILBOX_DATA_LSUB;
278 } else if (ascncasecmp(pp, "MAILBOX ", 8) == 0) {
279 pp += 8;
280 response_other = MAILBOX_DATA_MAILBOX;
281 } else if (ascncasecmp(pp, "SEARCH ", 7) == 0) {
282 pp += 7;
283 response_other = MAILBOX_DATA_SEARCH;
284 } else if (ascncasecmp(pp, "STATUS ", 7) == 0) {
285 pp += 7;
286 response_other = MAILBOX_DATA_STATUS;
287 } else if (ascncasecmp(pp, "CAPABILITY ", 11) == 0) {
288 pp += 11;
289 response_other = CAPABILITY_DATA;
290 } else {
291 responded_other_number = strtol(pp, &xp, 10);
292 while (*xp == ' ')
293 ++xp;
294 if (ascncasecmp(xp, "EXISTS\r\n", 8) == 0) {
295 response_other = MAILBOX_DATA_EXISTS;
296 } else if (ascncasecmp(xp, "RECENT\r\n", 8) == 0) {
297 response_other = MAILBOX_DATA_RECENT;
298 } else if (ascncasecmp(xp, "EXPUNGE\r\n", 9) == 0) {
299 response_other = MESSAGE_DATA_EXPUNGE;
300 } else if (ascncasecmp(xp, "FETCH ", 6) == 0) {
301 pp = &xp[6];
302 response_other = MESSAGE_DATA_FETCH;
303 } else
304 response_other = RESPONSE_OTHER_UNKNOWN;
306 responded_other_text = pp;
307 NYD2_LEAVE;
310 static void
311 imap_response_get(const char **cp)
313 NYD2_ENTER;
314 if (ascncasecmp(*cp, "OK ", 3) == 0) {
315 *cp += 3;
316 response_status = RESPONSE_OK;
317 } else if (ascncasecmp(*cp, "NO ", 3) == 0) {
318 *cp += 3;
319 response_status = RESPONSE_NO;
320 } else if (ascncasecmp(*cp, "BAD ", 4) == 0) {
321 *cp += 4;
322 response_status = RESPONSE_BAD;
323 } else if (ascncasecmp(*cp, "PREAUTH ", 8) == 0) {
324 *cp += 8;
325 response_status = RESPONSE_PREAUTH;
326 } else if (ascncasecmp(*cp, "BYE ", 4) == 0) {
327 *cp += 4;
328 response_status = RESPONSE_BYE;
329 } else
330 response_status = RESPONSE_OTHER;
331 NYD2_LEAVE;
334 static void
335 imap_response_parse(void)
337 static char *parsebuf; /* TODO Use pool */
338 static size_t parsebufsize;
340 const char *ip = imapbuf;
341 char *pp;
342 NYD2_ENTER;
344 if (parsebufsize < imapbufsize)
345 parsebuf = srealloc(parsebuf, parsebufsize = imapbufsize);
346 memcpy(parsebuf, imapbuf, strlen(imapbuf) + 1);
347 pp = parsebuf;
348 switch (*ip) {
349 case '+':
350 response_type = RESPONSE_CONT;
351 ip++;
352 pp++;
353 while (*ip == ' ') {
354 ip++;
355 pp++;
357 break;
358 case '*':
359 ip++;
360 pp++;
361 while (*ip == ' ') {
362 ip++;
363 pp++;
365 imap_response_get(&ip);
366 pp = &parsebuf[ip - imapbuf];
367 switch (response_status) {
368 case RESPONSE_BYE:
369 response_type = RESPONSE_FATAL;
370 break;
371 default:
372 response_type = RESPONSE_DATA;
374 break;
375 default:
376 responded_tag = parsebuf;
377 while (*pp && *pp != ' ')
378 pp++;
379 if (*pp == '\0') {
380 response_type = RESPONSE_ILLEGAL;
381 break;
383 *pp++ = '\0';
384 while (*pp && *pp == ' ')
385 pp++;
386 if (*pp == '\0') {
387 response_type = RESPONSE_ILLEGAL;
388 break;
390 ip = &imapbuf[pp - parsebuf];
391 response_type = RESPONSE_TAGGED;
392 imap_response_get(&ip);
393 pp = &parsebuf[ip - imapbuf];
395 responded_text = pp;
396 if (response_type != RESPONSE_CONT && response_type != RESPONSE_ILLEGAL &&
397 response_status == RESPONSE_OTHER)
398 imap_other_get(pp);
399 NYD2_LEAVE;
402 static enum okay
403 imap_answer(struct mailbox *mp, int errprnt)
405 int i, complete;
406 enum okay rv;
407 NYD2_ENTER;
409 rv = OKAY;
410 if (mp->mb_type == MB_CACHE)
411 goto jleave;
412 rv = STOP;
413 jagain:
414 if (sgetline(&imapbuf, &imapbufsize, NULL, &mp->mb_sock) > 0) {
415 if (options & OPT_VERBVERB)
416 fputs(imapbuf, stderr);
417 imap_response_parse();
418 if (response_type == RESPONSE_ILLEGAL)
419 goto jagain;
420 if (response_type == RESPONSE_CONT) {
421 rv = OKAY;
422 goto jleave;
424 if (response_status == RESPONSE_OTHER) {
425 if (response_other == MAILBOX_DATA_EXISTS) {
426 had_exists = responded_other_number;
427 rec_queue(REC_EXISTS, responded_other_number);
428 if (had_expunge > 0)
429 had_expunge = 0;
430 } else if (response_other == MESSAGE_DATA_EXPUNGE) {
431 rec_queue(REC_EXPUNGE, responded_other_number);
432 if (had_expunge < 0)
433 had_expunge = 0;
434 had_expunge++;
435 expunged_messages++;
438 complete = 0;
439 if (response_type == RESPONSE_TAGGED) {
440 if (asccasecmp(responded_tag, tag(0)) == 0)
441 complete |= 1;
442 else
443 goto jagain;
445 switch (response_status) {
446 case RESPONSE_PREAUTH:
447 mp->mb_active &= ~MB_PREAUTH;
448 /*FALLTHRU*/
449 case RESPONSE_OK:
450 jokay:
451 rv = OKAY;
452 complete |= 2;
453 break;
454 case RESPONSE_NO:
455 case RESPONSE_BAD:
456 jstop:
457 rv = STOP;
458 complete |= 2;
459 if (errprnt)
460 fprintf(stderr, _("IMAP error: %s"), responded_text);
461 break;
462 case RESPONSE_UNKNOWN: /* does not happen */
463 case RESPONSE_BYE:
464 i = mp->mb_active;
465 mp->mb_active = MB_NONE;
466 if (i & MB_BYE)
467 goto jokay;
468 goto jstop;
469 case RESPONSE_OTHER:
470 rv = OKAY;
471 break;
473 if (response_status != RESPONSE_OTHER &&
474 ascncasecmp(responded_text, "[ALERT] ", 8) == 0)
475 fprintf(stderr, "IMAP alert: %s", &responded_text[8]);
476 if (complete == 3)
477 mp->mb_active &= ~MB_COMD;
478 } else {
479 rv = STOP;
480 mp->mb_active = MB_NONE;
482 jleave:
483 NYD2_LEAVE;
484 return rv;
487 static enum okay
488 imap_parse_list(void)
490 char *cp;
491 enum okay rv;
492 NYD2_ENTER;
494 rv = STOP;
496 cp = responded_other_text;
497 list_attributes = LIST_NONE;
498 if (*cp == '(') {
499 while (*cp && *cp != ')') {
500 if (*cp == '\\') {
501 if (ascncasecmp(&cp[1], "Noinferiors ", 12) == 0) {
502 list_attributes |= LIST_NOINFERIORS;
503 cp += 12;
504 } else if (ascncasecmp(&cp[1], "Noselect ", 9) == 0) {
505 list_attributes |= LIST_NOSELECT;
506 cp += 9;
507 } else if (ascncasecmp(&cp[1], "Marked ", 7) == 0) {
508 list_attributes |= LIST_MARKED;
509 cp += 7;
510 } else if (ascncasecmp(&cp[1], "Unmarked ", 9) == 0) {
511 list_attributes |= LIST_UNMARKED;
512 cp += 9;
515 cp++;
517 if (*++cp != ' ')
518 goto jleave;
519 while (*cp == ' ')
520 cp++;
523 list_hierarchy_delimiter = EOF;
524 if (*cp == '"') {
525 if (*++cp == '\\')
526 cp++;
527 list_hierarchy_delimiter = *cp++ & 0377;
528 if (cp[0] != '"' || cp[1] != ' ')
529 goto jleave;
530 cp++;
531 } else if (cp[0] == 'N' && cp[1] == 'I' && cp[2] == 'L' && cp[3] == ' ') {
532 list_hierarchy_delimiter = EOF;
533 cp += 3;
536 while (*cp == ' ')
537 cp++;
538 list_name = cp;
539 while (*cp && *cp != '\r')
540 cp++;
541 *cp = '\0';
542 rv = OKAY;
543 jleave:
544 NYD2_LEAVE;
545 return rv;
548 static enum okay
549 imap_finish(struct mailbox *mp)
551 NYD_ENTER;
552 while (mp->mb_sock.s_fd > 0 && mp->mb_active & MB_COMD)
553 imap_answer(mp, 1);
554 NYD_LEAVE;
555 return OKAY;
558 static void
559 imap_timer_off(void)
561 NYD_ENTER;
562 if (imapkeepalive > 0) {
563 alarm(0);
564 safe_signal(SIGALRM, savealrm);
566 NYD_LEAVE;
569 static void
570 imapcatch(int s)
572 NYD_X; /* Signal handler */
573 switch (s) {
574 case SIGINT:
575 fprintf(stderr, _("Interrupt\n"));
576 siglongjmp(imapjmp, 1);
577 /*NOTREACHED*/
578 case SIGPIPE:
579 fprintf(stderr, _("Received SIGPIPE during IMAP operation\n"));
580 break;
584 static void
585 _imap_maincatch(int s)
587 NYD_X; /* Signal handler */
588 UNUSED(s);
589 if (interrupts++ == 0) {
590 fprintf(stderr, _("Interrupt\n"));
591 return;
593 onintr(0);
596 static enum okay
597 imap_noop1(struct mailbox *mp)
599 char o[LINESIZE];
600 FILE *queuefp = NULL;
601 NYD_X;
603 snprintf(o, sizeof o, "%s NOOP\r\n", tag(1));
604 IMAP_OUT(o, MB_COMD, return STOP)
605 IMAP_ANSWER()
606 return OKAY;
609 FL char const *
610 imap_fileof(char const *xcp)
612 char const *cp = xcp;
613 int state = 0;
614 NYD_ENTER;
616 while (*cp) {
617 if (cp[0] == ':' && cp[1] == '/' && cp[2] == '/') {
618 cp += 3;
619 state = 1;
621 if (cp[0] == '/' && state == 1) {
622 ++cp;
623 goto jleave;
625 if (cp[0] == '/') {
626 cp = xcp;
627 goto jleave;
629 ++cp;
631 jleave:
632 NYD_LEAVE;
633 return cp;
636 FL enum okay
637 imap_noop(void)
639 sighandler_type volatile oldint, oldpipe;
640 enum okay rv = STOP;
641 NYD_ENTER;
643 if (mb.mb_type != MB_IMAP)
644 goto jleave;
646 imaplock = 1;
647 if ((oldint = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN)
648 safe_signal(SIGINT, &_imap_maincatch);
649 oldpipe = safe_signal(SIGPIPE, SIG_IGN);
650 if (sigsetjmp(imapjmp, 1) == 0) {
651 if (oldpipe != SIG_IGN)
652 safe_signal(SIGPIPE, imapcatch);
654 rv = imap_noop1(&mb);
656 safe_signal(SIGINT, oldint);
657 safe_signal(SIGPIPE, oldpipe);
658 imaplock = 0;
659 jleave:
660 NYD_LEAVE;
661 if (interrupts)
662 onintr(0);
663 return rv;
666 static void
667 rec_queue(enum rec_type rt, unsigned long cnt)
669 struct record *rp;
670 NYD_ENTER;
672 rp = scalloc(1, sizeof *rp);
673 rp->rec_type = rt;
674 rp->rec_count = cnt;
675 if (record && recend) {
676 recend->rec_next = rp;
677 recend = rp;
678 } else
679 record = recend = rp;
680 NYD_LEAVE;
683 static enum okay
684 rec_dequeue(void)
686 struct message *omessage;
687 struct record *rp, *rq;
688 uiz_t exists = 0, i;
689 enum okay rv = STOP;
690 NYD_ENTER;
692 if (record == NULL)
693 goto jleave;
695 omessage = message;
696 message = smalloc((msgCount+1) * sizeof *message);
697 if (msgCount)
698 memcpy(message, omessage, msgCount * sizeof *message);
699 memset(&message[msgCount], 0, sizeof *message);
701 rp = record, rq = NULL;
702 rv = OKAY;
703 while (rp != NULL) {
704 switch (rp->rec_type) {
705 case REC_EXISTS:
706 exists = rp->rec_count;
707 break;
708 case REC_EXPUNGE:
709 if (rp->rec_count == 0) {
710 rv = STOP;
711 break;
713 if (rp->rec_count > (unsigned long)msgCount) {
714 if (exists == 0 || rp->rec_count > exists--)
715 rv = STOP;
716 break;
718 if (exists > 0)
719 exists--;
720 delcache(&mb, &message[rp->rec_count-1]);
721 memmove(&message[rp->rec_count-1], &message[rp->rec_count],
722 ((msgCount - rp->rec_count + 1) * sizeof *message));
723 --msgCount;
724 /* If the message was part of a collapsed thread,
725 * the m_collapsed field of one of its ancestors
726 * should be incremented. It seems hardly possible
727 * to do this with the current message structure,
728 * though. The result is that a '+' may be shown
729 * in the header summary even if no collapsed
730 * children exists */
731 break;
733 if (rq != NULL)
734 free(rq);
735 rq = rp;
736 rp = rp->rec_next;
738 if (rq != NULL)
739 free(rq);
741 record = recend = NULL;
742 if (rv == OKAY && UICMP(z, exists, >, msgCount)) {
743 message = srealloc(message, (exists + 1) * sizeof *message);
744 memset(&message[msgCount], 0, (exists - msgCount + 1) * sizeof *message);
745 for (i = msgCount; i < exists; ++i)
746 imap_init(&mb, i);
747 imap_flags(&mb, msgCount+1, exists);
748 msgCount = exists;
751 if (rv == STOP) {
752 free(message);
753 message = omessage;
755 jleave:
756 NYD_LEAVE;
757 return rv;
760 static void
761 rec_rmqueue(void)
763 struct record *rp;
764 NYD_ENTER;
766 for (rp = record; rp != NULL;) {
767 struct record *tmp = rp;
768 rp = rp->rec_next;
769 free(tmp);
771 record = recend = NULL;
772 NYD_LEAVE;
775 /*ARGSUSED*/
776 static void
777 imapalarm(int s)
779 sighandler_type volatile saveint, savepipe;
780 NYD_X; /* Signal handler */
781 UNUSED(s);
783 if (imaplock++ == 0) {
784 if ((saveint = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN)
785 safe_signal(SIGINT, &_imap_maincatch);
786 savepipe = safe_signal(SIGPIPE, SIG_IGN);
787 if (sigsetjmp(imapjmp, 1)) {
788 safe_signal(SIGINT, saveint);
789 safe_signal(SIGPIPE, savepipe);
790 goto jbrk;
792 if (savepipe != SIG_IGN)
793 safe_signal(SIGPIPE, imapcatch);
794 if (imap_noop1(&mb) != OKAY) {
795 safe_signal(SIGINT, saveint);
796 safe_signal(SIGPIPE, savepipe);
797 goto jleave;
799 safe_signal(SIGINT, saveint);
800 safe_signal(SIGPIPE, savepipe);
802 jbrk:
803 alarm(imapkeepalive);
804 jleave:
805 --imaplock;
808 static int
809 imap_use_starttls(const char *uhp)
811 int rv;
812 NYD_ENTER;
814 if (ok_blook(imap_use_starttls))
815 rv = 1;
816 else {
817 char *var = savecat("imap-use-starttls-", uhp);
818 rv = vok_blook(var);
820 NYD_LEAVE;
821 return rv;
824 static enum okay
825 imap_preauth(struct mailbox *mp, const char *xserver, const char *uhp)
827 char *cp;
828 NYD_X;
830 mp->mb_active |= MB_PREAUTH;
831 imap_answer(mp, 1);
832 if ((cp = strchr(xserver, ':')) != NULL) {
833 char *x = salloc(cp - xserver + 1);
834 memcpy(x, xserver, cp - xserver);
835 x[cp - xserver] = '\0';
836 xserver = x;
838 #ifdef HAVE_SSL
839 if (mp->mb_sock.s_use_ssl == 0 && imap_use_starttls(uhp)) {
840 FILE *queuefp = NULL;
841 char o[LINESIZE];
843 snprintf(o, sizeof o, "%s STARTTLS\r\n", tag(1));
844 IMAP_OUT(o, MB_COMD, return STOP)
845 IMAP_ANSWER()
846 if (ssl_open(xserver, &mp->mb_sock, uhp) != OKAY)
847 return STOP;
849 #else
850 if (imap_use_starttls(uhp)) {
851 fprintf(stderr, "No SSL support compiled in.\n");
852 return STOP;
854 #endif
855 imap_capability(mp);
856 return OKAY;
859 static enum okay
860 imap_capability(struct mailbox *mp)
862 char o[LINESIZE];
863 FILE *queuefp = NULL;
864 enum okay ok = STOP;
865 const char *cp;
866 NYD_X;
868 snprintf(o, sizeof o, "%s CAPABILITY\r\n", tag(1));
869 IMAP_OUT(o, MB_COMD, return STOP)
870 while (mp->mb_active & MB_COMD) {
871 ok = imap_answer(mp, 0);
872 if (response_status == RESPONSE_OTHER &&
873 response_other == CAPABILITY_DATA) {
874 cp = responded_other_text;
875 while (*cp) {
876 while (spacechar(*cp))
877 ++cp;
878 if (strncmp(cp, "UIDPLUS", 7) == 0 && spacechar(cp[7]))
879 /* RFC 2359 */
880 mp->mb_flags |= MB_UIDPLUS;
881 while (*cp && !spacechar(*cp))
882 ++cp;
886 return ok;
889 static enum okay
890 imap_auth(struct mailbox *mp, struct ccred *ccred)
892 enum okay rv;
893 NYD_ENTER;
895 if (!(mp->mb_active & MB_PREAUTH)) {
896 rv = OKAY;
897 goto jleave;
900 switch (ccred->cc_authtype) {
901 case AUTHTYPE_LOGIN:
902 rv = imap_login(mp, ccred);
903 break;
904 #ifdef HAVE_MD5
905 case AUTHTYPE_CRAM_MD5:
906 rv = imap_cram_md5(mp, ccred);
907 break;
908 #endif
909 #ifdef HAVE_GSSAPI
910 case AUTHTYPE_GSSAPI:
911 rv = _imap_gssapi(mp, ccred);
912 break;
913 #endif
914 default:
915 rv = STOP;
916 break;
918 jleave:
919 NYD_LEAVE;
920 return rv;
923 #ifdef HAVE_MD5
924 static enum okay
925 imap_cram_md5(struct mailbox *mp, struct ccred *ccred)
927 char o[LINESIZE], *cp;
928 FILE *queuefp = NULL;
929 enum okay rv = STOP;
930 NYD_ENTER;
932 snprintf(o, sizeof o, "%s AUTHENTICATE CRAM-MD5\r\n", tag(1));
933 IMAP_XOUT(o, 0, goto jleave, goto jleave);
934 imap_answer(mp, 1);
935 if (response_type != RESPONSE_CONT)
936 goto jleave;
938 cp = cram_md5_string(&ccred->cc_user, &ccred->cc_pass, responded_text);
939 IMAP_XOUT(cp, MB_COMD, goto jleave, goto jleave);
940 while (mp->mb_active & MB_COMD)
941 rv = imap_answer(mp, 1);
942 jleave:
943 NYD_LEAVE;
944 return rv;
946 #endif /* HAVE_MD5 */
948 static enum okay
949 imap_login(struct mailbox *mp, struct ccred *ccred)
951 char o[LINESIZE];
952 FILE *queuefp = NULL;
953 enum okay rv = STOP;
954 NYD_ENTER;
956 snprintf(o, sizeof o, "%s LOGIN %s %s\r\n",
957 tag(1), imap_quotestr(ccred->cc_user.s), imap_quotestr(ccred->cc_pass.s));
958 IMAP_XOUT(o, MB_COMD, goto jleave, goto jleave);
959 while (mp->mb_active & MB_COMD)
960 rv = imap_answer(mp, 1);
961 jleave:
962 NYD_LEAVE;
963 return rv;
966 #ifdef HAVE_GSSAPI
967 # include "imap_gssapi.h"
968 #endif
970 FL enum okay
971 imap_select(struct mailbox *mp, off_t *size, int *cnt, const char *mbx)
973 enum okay ok = OKAY;
974 char const *cp;
975 char o[LINESIZE];
976 FILE *queuefp = NULL;
977 NYD_X;
978 UNUSED(size);
980 mp->mb_uidvalidity = 0;
981 snprintf(o, sizeof o, "%s SELECT %s\r\n", tag(1), imap_quotestr(mbx));
982 IMAP_OUT(o, MB_COMD, return STOP)
983 while (mp->mb_active & MB_COMD) {
984 ok = imap_answer(mp, 1);
985 if (response_status != RESPONSE_OTHER &&
986 (cp = asccasestr(responded_text, "[UIDVALIDITY ")) != NULL)
987 mp->mb_uidvalidity = atol(&cp[13]);
989 *cnt = (had_exists > 0) ? had_exists : 0;
990 if (response_status != RESPONSE_OTHER &&
991 ascncasecmp(responded_text, "[READ-ONLY] ", 12) == 0)
992 mp->mb_perm = 0;
993 return ok;
996 static enum okay
997 imap_flags(struct mailbox *mp, unsigned X, unsigned Y)
999 char o[LINESIZE];
1000 FILE *queuefp = NULL;
1001 char const *cp;
1002 struct message *m;
1003 unsigned x = X, y = Y, n;
1004 NYD_X;
1006 snprintf(o, sizeof o, "%s FETCH %u:%u (FLAGS UID)\r\n", tag(1), x, y);
1007 IMAP_OUT(o, MB_COMD, return STOP)
1008 while (mp->mb_active & MB_COMD) {
1009 imap_answer(mp, 1);
1010 if (response_status == RESPONSE_OTHER &&
1011 response_other == MESSAGE_DATA_FETCH) {
1012 n = responded_other_number;
1013 if (n < x || n > y)
1014 continue;
1015 m = &message[n-1];
1016 m->m_xsize = 0;
1017 } else
1018 continue;
1020 if ((cp = asccasestr(responded_other_text, "FLAGS ")) != NULL) {
1021 cp += 5;
1022 while (*cp == ' ')
1023 cp++;
1024 if (*cp == '(')
1025 imap_getflags(cp, &cp, &m->m_flag);
1028 if ((cp = asccasestr(responded_other_text, "UID ")) != NULL)
1029 m->m_uid = strtoul(&cp[4], NULL, 10);
1030 getcache1(mp, m, NEED_UNSPEC, 1);
1031 m->m_flag &= ~MHIDDEN;
1034 while (x <= y && message[x-1].m_xsize && message[x-1].m_time)
1035 x++;
1036 while (y > x && message[y-1].m_xsize && message[y-1].m_time)
1037 y--;
1038 if (x <= y) {
1039 snprintf(o, sizeof o, "%s FETCH %u:%u (RFC822.SIZE INTERNALDATE)\r\n",
1040 tag(1), x, y);
1041 IMAP_OUT(o, MB_COMD, return STOP)
1042 while (mp->mb_active & MB_COMD) {
1043 imap_answer(mp, 1);
1044 if (response_status == RESPONSE_OTHER &&
1045 response_other == MESSAGE_DATA_FETCH) {
1046 n = responded_other_number;
1047 if (n < x || n > y)
1048 continue;
1049 m = &message[n-1];
1050 } else
1051 continue;
1052 if ((cp = asccasestr(responded_other_text, "RFC822.SIZE ")) != NULL)
1053 m->m_xsize = strtol(&cp[12], NULL, 10);
1054 if ((cp = asccasestr(responded_other_text, "INTERNALDATE ")) != NULL)
1055 m->m_time = imap_read_date_time(&cp[13]);
1059 for (n = X; n <= Y; n++)
1060 putcache(mp, &message[n-1]);
1061 return OKAY;
1064 static void
1065 imap_init(struct mailbox *mp, int n)
1067 struct message *m;
1068 NYD_ENTER;
1069 UNUSED(mp);
1071 m = message + n;
1072 m->m_flag = MUSED | MNOFROM;
1073 m->m_block = 0;
1074 m->m_offset = 0;
1075 NYD_LEAVE;
1078 static void
1079 imap_setptr(struct mailbox *mp, int nmail, int transparent, int *prevcount)
1081 struct message *omessage = 0;
1082 int i, omsgCount = 0;
1083 enum okay dequeued = STOP;
1084 NYD_ENTER;
1086 if (nmail || transparent) {
1087 omessage = message;
1088 omsgCount = msgCount;
1090 if (nmail)
1091 dequeued = rec_dequeue();
1093 if (had_exists >= 0) {
1094 if (dequeued != OKAY)
1095 msgCount = had_exists;
1096 had_exists = -1;
1098 if (had_expunge >= 0) {
1099 if (dequeued != OKAY)
1100 msgCount -= had_expunge;
1101 had_expunge = -1;
1104 if (nmail && expunged_messages)
1105 printf("Expunged %ld message%s.\n", expunged_messages,
1106 (expunged_messages != 1 ? "s" : ""));
1107 *prevcount = omsgCount - expunged_messages;
1108 expunged_messages = 0;
1109 if (msgCount < 0) {
1110 fputs("IMAP error: Negative message count\n", stderr);
1111 msgCount = 0;
1114 if (dequeued != OKAY) {
1115 message = scalloc(msgCount + 1, sizeof *message);
1116 for (i = 0; i < msgCount; i++)
1117 imap_init(mp, i);
1118 if (!nmail && mp->mb_type == MB_IMAP)
1119 initcache(mp);
1120 if (msgCount > 0)
1121 imap_flags(mp, 1, msgCount);
1122 message[msgCount].m_size = 0;
1123 message[msgCount].m_lines = 0;
1124 rec_rmqueue();
1126 if (nmail || transparent)
1127 transflags(omessage, omsgCount, transparent);
1128 else
1129 setdot(message);
1130 NYD_LEAVE;
1133 FL int
1134 imap_setfile(const char *xserver, enum fedit_mode fm)
1136 struct url url;
1137 int rv;
1138 NYD_ENTER;
1140 if (!url_parse(&url, CPROTO_IMAP, xserver)) {
1141 rv = 1;
1142 goto jleave;
1144 if (!ok_blook(v15_compat) &&
1145 (!url.url_had_user || url.url_pass.s != NULL))
1146 fprintf(stderr, "New-style URL used without *v15-compat* being set!\n");
1148 _imap_rdonly = ((fm & FEDIT_RDONLY) != 0);
1149 rv = _imap_setfile1(&url, fm, 0);
1150 jleave:
1151 NYD_LEAVE;
1152 return rv;
1155 static bool_t
1156 _imap_getcred(struct mailbox *mbp, struct ccred *ccredp, struct url *urlp)
1158 bool_t rv = FAL0;
1159 NYD_ENTER;
1161 if (ok_blook(v15_compat))
1162 rv = ccred_lookup(ccredp, urlp);
1163 else {
1164 char *var, *old;
1166 if ((var = mbp->mb_imap_pass) != NULL) {
1167 var = savecat("password-", urlp->url_u_h_p.s);
1168 old = vok_vlook(var);
1169 vok_vset(var, mbp->mb_imap_pass);
1171 rv = ccred_lookup_old(ccredp, CPROTO_IMAP, urlp->url_u_h_p.s);
1172 if (var != NULL) {
1173 if (old != NULL)
1174 vok_vset(var, old);
1175 else
1176 vok_vclear(var);
1180 NYD_LEAVE;
1181 return rv;
1184 static int
1185 _imap_setfile1(struct url *urlp, enum fedit_mode fm, int volatile transparent)
1187 struct sock so;
1188 struct ccred ccred;
1189 sighandler_type volatile saveint, savepipe;
1190 char const *cp;
1191 int rv;
1192 int volatile prevcount = 0;
1193 enum mbflags same_flags;
1194 NYD_ENTER;
1196 if (fm & FEDIT_NEWMAIL) {
1197 saveint = safe_signal(SIGINT, SIG_IGN);
1198 savepipe = safe_signal(SIGPIPE, SIG_IGN);
1199 if (saveint != SIG_IGN)
1200 safe_signal(SIGINT, imapcatch);
1201 if (savepipe != SIG_IGN)
1202 safe_signal(SIGPIPE, imapcatch);
1203 imaplock = 1;
1204 goto jnmail;
1207 same_flags = mb.mb_flags;
1208 same_imap_account = 0;
1209 if (mb.mb_imap_account != NULL &&
1210 (mb.mb_type == MB_IMAP || mb.mb_type == MB_CACHE)) {
1211 if (mb.mb_sock.s_fd > 0 && mb.mb_sock.s_rsz >= 0 &&
1212 !strcmp(mb.mb_imap_account, urlp->url_p_eu_h_p) &&
1213 disconnected(mb.mb_imap_account) == 0) {
1214 same_imap_account = 1;
1215 if (urlp->url_pass.s == NULL && mb.mb_imap_pass != NULL)
1216 goto jduppass;
1217 } else if ((transparent || mb.mb_type == MB_CACHE) &&
1218 !strcmp(mb.mb_imap_account, urlp->url_p_eu_h_p) &&
1219 urlp->url_pass.s == NULL && mb.mb_imap_pass != NULL)
1220 jduppass:
1221 urlp->url_pass.l = strlen(urlp->url_pass.s = savestr(mb.mb_imap_pass));
1224 if (!_imap_getcred(&mb, &ccred, urlp)) {
1225 rv = -1;
1226 goto jleave;
1229 so.s_fd = -1;
1230 if (!same_imap_account) {
1231 if (!disconnected(urlp->url_p_eu_h_p) && !sopen(&so, urlp)) {
1232 rv = -1;
1233 goto jleave;
1235 } else
1236 so = mb.mb_sock;
1237 if (!transparent)
1238 quit();
1240 edit = !(fm & FEDIT_SYSBOX);
1241 if (mb.mb_imap_account != NULL)
1242 free(mb.mb_imap_account);
1243 if (mb.mb_imap_pass != NULL)
1244 free(mb.mb_imap_pass);
1245 mb.mb_imap_account = sstrdup(urlp->url_p_eu_h_p);
1246 /* TODO This is a hack to allow '@boxname'; in the end everything will be an
1247 * TODO object, and mailbox will naturally have an URL and credentials */
1248 mb.mb_imap_pass = sbufdup(ccred.cc_pass.s, ccred.cc_pass.l);
1250 if (!same_imap_account) {
1251 if (mb.mb_sock.s_fd >= 0)
1252 sclose(&mb.mb_sock);
1254 same_imap_account = 0;
1256 if (!transparent) {
1257 if (mb.mb_itf) {
1258 fclose(mb.mb_itf);
1259 mb.mb_itf = NULL;
1261 if (mb.mb_otf) {
1262 fclose(mb.mb_otf);
1263 mb.mb_otf = NULL;
1265 if (mb.mb_imap_mailbox != NULL)
1266 free(mb.mb_imap_mailbox);
1267 mb.mb_imap_mailbox = sstrdup((urlp->url_path.s != NULL)
1268 ? urlp->url_path.s : "INBOX");
1269 initbox(urlp->url_p_eu_h_p_p);
1271 mb.mb_type = MB_VOID;
1272 mb.mb_active = MB_NONE;
1274 imaplock = 1;
1275 saveint = safe_signal(SIGINT, SIG_IGN);
1276 savepipe = safe_signal(SIGPIPE, SIG_IGN);
1277 if (sigsetjmp(imapjmp, 1)) {
1278 /* Not safe to use &so; save to use mb.mb_sock?? :-( TODO */
1279 sclose(&mb.mb_sock);
1280 safe_signal(SIGINT, saveint);
1281 safe_signal(SIGPIPE, savepipe);
1282 imaplock = 0;
1284 mb.mb_type = MB_VOID;
1285 mb.mb_active = MB_NONE;
1286 rv = -1;
1287 goto jleave;
1289 if (saveint != SIG_IGN)
1290 safe_signal(SIGINT, imapcatch);
1291 if (savepipe != SIG_IGN)
1292 safe_signal(SIGPIPE, imapcatch);
1294 if (mb.mb_sock.s_fd < 0) {
1295 if (disconnected(mb.mb_imap_account)) {
1296 if (cache_setptr(fm, transparent) == STOP)
1297 fprintf(stderr, "Mailbox \"%s\" is not cached.\n",
1298 urlp->url_p_eu_h_p_p);
1299 goto jdone;
1301 if ((cp = ok_vlook(imap_keepalive)) != NULL) {
1302 if ((imapkeepalive = strtol(cp, NULL, 10)) > 0) {
1303 savealrm = safe_signal(SIGALRM, imapalarm);
1304 alarm(imapkeepalive);
1308 mb.mb_sock = so;
1309 mb.mb_sock.s_desc = "IMAP";
1310 mb.mb_sock.s_onclose = imap_timer_off;
1311 if (imap_preauth(&mb, urlp->url_h_p.s, urlp->url_u_h_p.s) != OKAY ||
1312 imap_auth(&mb, &ccred) != OKAY) {
1313 sclose(&mb.mb_sock);
1314 imap_timer_off();
1315 safe_signal(SIGINT, saveint);
1316 safe_signal(SIGPIPE, savepipe);
1317 imaplock = 0;
1318 rv = -1;
1319 goto jleave;
1321 } else /* same account */
1322 mb.mb_flags |= same_flags;
1324 mb.mb_perm = ((options & OPT_R_FLAG) || (fm & FEDIT_RDONLY)) ? 0 : MB_DELE;
1325 mb.mb_type = MB_IMAP;
1326 cache_dequeue(&mb);
1327 if (imap_select(&mb, &mailsize, &msgCount,
1328 (urlp->url_path.s != NULL ? urlp->url_path.s : "INBOX")) != OKAY) {
1329 /*sclose(&mb.mb_sock);
1330 imap_timer_off();*/
1331 safe_signal(SIGINT, saveint);
1332 safe_signal(SIGPIPE, savepipe);
1333 imaplock = 0;
1334 mb.mb_type = MB_VOID;
1335 rv = -1;
1336 goto jleave;
1339 jnmail:
1340 imap_setptr(&mb, ((fm & FEDIT_NEWMAIL) != 0), transparent,
1341 UNVOLATILE(&prevcount));
1342 jdone:
1343 setmsize(msgCount);
1344 if (!(fm & FEDIT_NEWMAIL) && !transparent)
1345 sawcom = FAL0;
1346 safe_signal(SIGINT, saveint);
1347 safe_signal(SIGPIPE, savepipe);
1348 imaplock = 0;
1350 if (!(fm & FEDIT_NEWMAIL) && mb.mb_type == MB_IMAP)
1351 purgecache(&mb, message, msgCount);
1352 if (((fm & FEDIT_NEWMAIL) || transparent) && mb.mb_sorted) {
1353 mb.mb_threaded = 0;
1354 c_sort((void*)-1);
1357 if (!(fm & FEDIT_NEWMAIL) && !edit && msgCount == 0) {
1358 if ((mb.mb_type == MB_IMAP || mb.mb_type == MB_CACHE) &&
1359 !ok_blook(emptystart))
1360 fprintf(stderr, _("No mail at %s\n"), urlp->url_p_eu_h_p_p);
1361 rv = 1;
1362 goto jleave;
1364 if (fm & FEDIT_NEWMAIL)
1365 newmailinfo(prevcount);
1366 rv = 0;
1367 jleave:
1368 NYD_LEAVE;
1369 return rv;
1372 static int
1373 imap_fetchdata(struct mailbox *mp, struct message *m, size_t expected,
1374 int need, const char *head, size_t headsize, long headlines)
1376 char *line = NULL, *lp;
1377 size_t linesize = 0, linelen, size = 0;
1378 int emptyline = 0, lines = 0, excess = 0;
1379 off_t offset;
1380 NYD_ENTER;
1382 fseek(mp->mb_otf, 0L, SEEK_END);
1383 offset = ftell(mp->mb_otf);
1385 if (head)
1386 fwrite(head, 1, headsize, mp->mb_otf);
1388 while (sgetline(&line, &linesize, &linelen, &mp->mb_sock) > 0) {
1389 lp = line;
1390 if (linelen > expected) {
1391 excess = linelen - expected;
1392 linelen = expected;
1394 /* TODO >>
1395 * Need to mask 'From ' lines. This cannot be done properly
1396 * since some servers pass them as 'From ' and others as
1397 * '>From '. Although one could identify the first kind of
1398 * server in principle, it is not possible to identify the
1399 * second as '>From ' may also come from a server of the
1400 * first type as actual data. So do what is absolutely
1401 * necessary only - mask 'From '.
1403 * If the line is the first line of the message header, it
1404 * is likely a real 'From ' line. In this case, it is just
1405 * ignored since it violates all standards.
1406 * TODO can the latter *really* happen??
1407 * TODO <<
1409 /* Since we simply copy over data without doing any transfer
1410 * encoding reclassification/adjustment we *have* to perform
1411 * RFC 4155 compliant From_ quoting here */
1412 if (is_head(lp, linelen)) {
1413 if (lines + headlines == 0)
1414 goto jskip;
1415 fputc('>', mp->mb_otf);
1416 ++size;
1418 if (lp[linelen-1] == '\n' && (linelen == 1 || lp[linelen-2] == '\r')) {
1419 emptyline = linelen <= 2;
1420 if (linelen > 2) {
1421 fwrite(lp, 1, linelen - 2, mp->mb_otf);
1422 size += linelen - 1;
1423 } else
1424 ++size;
1425 fputc('\n', mp->mb_otf);
1426 } else {
1427 emptyline = 0;
1428 fwrite(lp, 1, linelen, mp->mb_otf);
1429 size += linelen;
1431 ++lines;
1432 jskip:
1433 if ((expected -= linelen) <= 0)
1434 break;
1436 if (!emptyline) {
1437 /* This is very ugly; but some IMAP daemons don't end a
1438 * message with \r\n\r\n, and we need \n\n for mbox format */
1439 fputc('\n', mp->mb_otf);
1440 ++lines;
1441 ++size;
1443 fflush(mp->mb_otf);
1445 if (m != NULL) {
1446 m->m_size = size + headsize;
1447 m->m_lines = lines + headlines;
1448 m->m_block = mailx_blockof(offset);
1449 m->m_offset = mailx_offsetof(offset);
1450 switch (need) {
1451 case NEED_HEADER:
1452 m->m_have |= HAVE_HEADER;
1453 break;
1454 case NEED_BODY:
1455 m->m_have |= HAVE_HEADER | HAVE_BODY;
1456 m->m_xlines = m->m_lines;
1457 m->m_xsize = m->m_size;
1458 break;
1461 free(line);
1462 NYD_LEAVE;
1463 return excess;
1466 static void
1467 imap_putstr(struct mailbox *mp, struct message *m, const char *str,
1468 const char *head, size_t headsize, long headlines)
1470 off_t offset;
1471 size_t len;
1472 NYD_ENTER;
1474 len = strlen(str);
1475 fseek(mp->mb_otf, 0L, SEEK_END);
1476 offset = ftell(mp->mb_otf);
1477 if (head)
1478 fwrite(head, 1, headsize, mp->mb_otf);
1479 if (len > 0) {
1480 fwrite(str, 1, len, mp->mb_otf);
1481 fputc('\n', mp->mb_otf);
1482 ++len;
1484 fflush(mp->mb_otf);
1486 if (m != NULL) {
1487 m->m_size = headsize + len;
1488 m->m_lines = headlines + 1;
1489 m->m_block = mailx_blockof(offset);
1490 m->m_offset = mailx_offsetof(offset);
1491 m->m_have |= HAVE_HEADER | HAVE_BODY;
1492 m->m_xlines = m->m_lines;
1493 m->m_xsize = m->m_size;
1495 NYD_LEAVE;
1498 static enum okay
1499 imap_get(struct mailbox *mp, struct message *m, enum needspec need)
1501 char o[LINESIZE];
1502 struct message mt;
1503 sighandler_type volatile saveint, savepipe;
1504 char * volatile head;
1505 char const *cp, *loc, * volatile item, * volatile resp;
1506 size_t expected;
1507 size_t volatile headsize;
1508 int number;
1509 FILE *queuefp;
1510 long volatile headlines;
1511 long n;
1512 ul_it volatile u;
1513 enum okay ok;
1514 NYD_X;
1516 saveint = savepipe = SIG_IGN;
1517 head = NULL;
1518 cp = loc = item = resp = NULL;
1519 headsize = 0;
1520 number = (int)PTR2SIZE(m - message + 1);
1521 queuefp = NULL;
1522 headlines = 0;
1523 n = -1;
1524 u = 0;
1525 ok = STOP;
1527 if (getcache(mp, m, need) == OKAY)
1528 return OKAY;
1529 if (mp->mb_type == MB_CACHE) {
1530 fprintf(stderr, "Message %u not available.\n", number);
1531 return STOP;
1534 if (mp->mb_sock.s_fd < 0) {
1535 fprintf(stderr, "IMAP connection closed.\n");
1536 return STOP;
1539 switch (need) {
1540 case NEED_HEADER:
1541 resp = item = "RFC822.HEADER";
1542 break;
1543 case NEED_BODY:
1544 item = "BODY.PEEK[]";
1545 resp = "BODY[]";
1546 if (m->m_flag & HAVE_HEADER && m->m_size) {
1547 char *hdr = smalloc(m->m_size);
1548 fflush(mp->mb_otf);
1549 if (fseek(mp->mb_itf, (long)mailx_positionof(m->m_block, m->m_offset),
1550 SEEK_SET) < 0 ||
1551 fread(hdr, 1, m->m_size, mp->mb_itf) != m->m_size) {
1552 free(hdr);
1553 break;
1555 head = hdr;
1556 headsize = m->m_size;
1557 headlines = m->m_lines;
1558 item = "BODY.PEEK[TEXT]";
1559 resp = "BODY[TEXT]";
1561 break;
1562 case NEED_UNSPEC:
1563 return STOP;
1566 imaplock = 1;
1567 savepipe = safe_signal(SIGPIPE, SIG_IGN);
1568 if (sigsetjmp(imapjmp, 1)) {
1569 safe_signal(SIGINT, saveint);
1570 safe_signal(SIGPIPE, savepipe);
1571 imaplock = 0;
1572 return STOP;
1574 if ((saveint = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN)
1575 safe_signal(SIGINT, &_imap_maincatch);
1576 if (savepipe != SIG_IGN)
1577 safe_signal(SIGPIPE, imapcatch);
1579 if (m->m_uid)
1580 snprintf(o, sizeof o, "%s UID FETCH %lu (%s)\r\n",
1581 tag(1), m->m_uid, item);
1582 else {
1583 if (check_expunged() == STOP)
1584 goto out;
1585 snprintf(o, sizeof o, "%s FETCH %u (%s)\r\n", tag(1), number, item);
1587 IMAP_OUT(o, MB_COMD, goto out)
1588 for (;;) {
1589 ok = imap_answer(mp, 1);
1590 if (ok == STOP)
1591 break;
1592 if (response_status != RESPONSE_OTHER ||
1593 response_other != MESSAGE_DATA_FETCH)
1594 continue;
1595 if ((loc = asccasestr(responded_other_text, resp)) == NULL)
1596 continue;
1597 if (m->m_uid) {
1598 if ((cp = asccasestr(responded_other_text, "UID "))) {
1599 u = atol(&cp[4]);
1600 n = 0;
1601 } else {
1602 n = -1;
1603 u = 0;
1605 } else
1606 n = responded_other_number;
1607 if ((cp = strrchr(responded_other_text, '{')) == NULL) {
1608 if (m->m_uid ? m->m_uid != u : n != number)
1609 continue;
1610 if ((cp = strchr(loc, '"')) != NULL) {
1611 cp = imap_unquotestr(cp);
1612 imap_putstr(mp, m, cp, head, headsize, headlines);
1613 } else {
1614 m->m_have |= HAVE_HEADER|HAVE_BODY;
1615 m->m_xlines = m->m_lines;
1616 m->m_xsize = m->m_size;
1618 goto out;
1620 expected = atol(&cp[1]);
1621 if (m->m_uid ? n == 0 && m->m_uid != u : n != number) {
1622 imap_fetchdata(mp, NULL, expected, need, NULL, 0, 0);
1623 continue;
1625 mt = *m;
1626 imap_fetchdata(mp, &mt, expected, need, head, headsize, headlines);
1627 if (n >= 0) {
1628 commitmsg(mp, m, &mt, mt.m_have);
1629 break;
1631 if (n == -1 && sgetline(&imapbuf, &imapbufsize, NULL, &mp->mb_sock) > 0) {
1632 if (options & OPT_VERBVERB)
1633 fputs(imapbuf, stderr);
1634 if ((cp = asccasestr(imapbuf, "UID ")) != NULL) {
1635 u = atol(&cp[4]);
1636 if (u == m->m_uid) {
1637 commitmsg(mp, m, &mt, mt.m_have);
1638 break;
1643 out:
1644 while (mp->mb_active & MB_COMD)
1645 ok = imap_answer(mp, 1);
1647 if (saveint != SIG_IGN)
1648 safe_signal(SIGINT, saveint);
1649 if (savepipe != SIG_IGN)
1650 safe_signal(SIGPIPE, savepipe);
1651 imaplock--;
1653 if (ok == OKAY)
1654 putcache(mp, m);
1655 if (head != NULL)
1656 free(head);
1657 if (interrupts)
1658 onintr(0);
1659 return ok;
1662 FL enum okay
1663 imap_header(struct message *m)
1665 enum okay rv;
1666 NYD_ENTER;
1668 rv = imap_get(&mb, m, NEED_HEADER);
1669 NYD_LEAVE;
1670 return rv;
1674 FL enum okay
1675 imap_body(struct message *m)
1677 enum okay rv;
1678 NYD_ENTER;
1680 rv = imap_get(&mb, m, NEED_BODY);
1681 NYD_LEAVE;
1682 return rv;
1685 static void
1686 commitmsg(struct mailbox *mp, struct message *tomp, struct message *frommp,
1687 enum havespec have)
1689 NYD_ENTER;
1690 tomp->m_size = frommp->m_size;
1691 tomp->m_lines = frommp->m_lines;
1692 tomp->m_block = frommp->m_block;
1693 tomp->m_offset = frommp->m_offset;
1694 tomp->m_have = have;
1695 if (have & HAVE_BODY) {
1696 tomp->m_xlines = frommp->m_lines;
1697 tomp->m_xsize = frommp->m_size;
1699 putcache(mp, tomp);
1700 NYD_LEAVE;
1703 static enum okay
1704 imap_fetchheaders(struct mailbox *mp, struct message *m, int bot, int topp)
1706 /* bot > topp */
1707 char o[LINESIZE];
1708 char const *cp;
1709 struct message mt;
1710 size_t expected;
1711 int n = 0, u;
1712 FILE *queuefp = NULL;
1713 enum okay ok;
1714 NYD_X;
1716 if (m[bot].m_uid)
1717 snprintf(o, sizeof o, "%s UID FETCH %lu:%lu (RFC822.HEADER)\r\n",
1718 tag(1), m[bot-1].m_uid, m[topp-1].m_uid);
1719 else {
1720 if (check_expunged() == STOP)
1721 return STOP;
1722 snprintf(o, sizeof o, "%s FETCH %u:%u (RFC822.HEADER)\r\n",
1723 tag(1), bot, topp);
1725 IMAP_OUT(o, MB_COMD, return STOP)
1726 for (;;) {
1727 ok = imap_answer(mp, 1);
1728 if (response_status != RESPONSE_OTHER)
1729 break;
1730 if (response_other != MESSAGE_DATA_FETCH)
1731 continue;
1732 if (ok == STOP || (cp=strrchr(responded_other_text, '{')) == 0)
1733 return STOP;
1734 if (asccasestr(responded_other_text, "RFC822.HEADER") == NULL)
1735 continue;
1736 expected = atol(&cp[1]);
1737 if (m[bot-1].m_uid) {
1738 if ((cp = asccasestr(responded_other_text, "UID ")) != NULL) {
1739 u = atoi(&cp[4]);
1740 for (n = bot; n <= topp; n++)
1741 if ((unsigned long)u == m[n-1].m_uid)
1742 break;
1743 if (n > topp) {
1744 imap_fetchdata(mp, NULL, expected, NEED_HEADER, NULL, 0, 0);
1745 continue;
1747 } else
1748 n = -1;
1749 } else {
1750 n = responded_other_number;
1751 if (n <= 0 || n > msgCount) {
1752 imap_fetchdata(mp, NULL, expected, NEED_HEADER, NULL, 0, 0);
1753 continue;
1756 imap_fetchdata(mp, &mt, expected, NEED_HEADER, NULL, 0, 0);
1757 if (n >= 0 && !(m[n-1].m_have & HAVE_HEADER))
1758 commitmsg(mp, &m[n-1], &mt, HAVE_HEADER);
1759 if (n == -1 && sgetline(&imapbuf, &imapbufsize, NULL, &mp->mb_sock) > 0) {
1760 if (options & OPT_VERBVERB)
1761 fputs(imapbuf, stderr);
1762 if ((cp = asccasestr(imapbuf, "UID ")) != NULL) {
1763 u = atoi(&cp[4]);
1764 for (n = bot; n <= topp; n++)
1765 if ((unsigned long)u == m[n-1].m_uid)
1766 break;
1767 if (n <= topp && !(m[n-1].m_have & HAVE_HEADER))
1768 commitmsg(mp, &m[n-1], &mt,HAVE_HEADER);
1769 n = 0;
1773 while (mp->mb_active & MB_COMD)
1774 ok = imap_answer(mp, 1);
1775 return ok;
1778 FL void
1779 imap_getheaders(int volatile bot, int volatile topp) /* TODO iterator!! */
1781 sighandler_type saveint, savepipe;
1782 /* enum okay ok = STOP;*/
1783 int i, chunk = 256;
1784 NYD_X;
1786 if (mb.mb_type == MB_CACHE)
1787 return;
1788 if (bot < 1)
1789 bot = 1;
1790 if (topp > msgCount)
1791 topp = msgCount;
1792 for (i = bot; i < topp; i++) {
1793 if (message[i-1].m_have & HAVE_HEADER ||
1794 getcache(&mb, &message[i-1], NEED_HEADER) == OKAY)
1795 bot = i+1;
1796 else
1797 break;
1799 for (i = topp; i > bot; i--) {
1800 if (message[i-1].m_have & HAVE_HEADER ||
1801 getcache(&mb, &message[i-1], NEED_HEADER) == OKAY)
1802 topp = i-1;
1803 else
1804 break;
1806 if (bot >= topp)
1807 return;
1809 imaplock = 1;
1810 if ((saveint = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN)
1811 safe_signal(SIGINT, &_imap_maincatch);
1812 savepipe = safe_signal(SIGPIPE, SIG_IGN);
1813 if (sigsetjmp(imapjmp, 1) == 0) {
1814 if (savepipe != SIG_IGN)
1815 safe_signal(SIGPIPE, imapcatch);
1817 for (i = bot; i <= topp; i += chunk) {
1818 int j = i + chunk - 1;
1819 j = MIN(j, topp);
1820 if (visible(message + j))
1821 /*ok = */imap_fetchheaders(&mb, message, i, j);
1822 if (interrupts)
1823 onintr(0); /* XXX imaplock? */
1826 safe_signal(SIGINT, saveint);
1827 safe_signal(SIGPIPE, savepipe);
1828 imaplock = 0;
1831 static enum okay
1832 __imap_exit(struct mailbox *mp)
1834 char o[LINESIZE];
1835 FILE *queuefp = NULL;
1836 NYD_X;
1838 mp->mb_active |= MB_BYE;
1839 snprintf(o, sizeof o, "%s LOGOUT\r\n", tag(1));
1840 IMAP_OUT(o, MB_COMD, return STOP)
1841 IMAP_ANSWER()
1842 return OKAY;
1845 static enum okay
1846 imap_exit(struct mailbox *mp)
1848 enum okay rv;
1849 NYD_ENTER;
1851 rv = __imap_exit(mp);
1852 #if 0 /* TODO the option today: memory leak(s) and halfway reuse or nottin */
1853 free(mp->mb_imap_pass);
1854 free(mp->mb_imap_account);
1855 free(mp->mb_imap_mailbox);
1856 if (mp->mb_cache_directory != NULL)
1857 free(mp->mb_cache_directory);
1858 #ifndef HAVE_DEBUG /* TODO ASSERT LEGACY */
1859 mp->mb_imap_account =
1860 mp->mb_imap_mailbox =
1861 mp->mb_cache_directory = "";
1862 #else
1863 mp->mb_imap_account = NULL; /* for assert legacy time.. */
1864 mp->mb_imap_mailbox = NULL;
1865 mp->mb_cache_directory = NULL;
1866 #endif
1867 #endif
1868 sclose(&mp->mb_sock);
1869 NYD_LEAVE;
1870 return rv;
1873 static enum okay
1874 imap_delete(struct mailbox *mp, int n, struct message *m, int needstat)
1876 NYD_ENTER;
1877 imap_store(mp, m, n, '+', "\\Deleted", needstat);
1878 if (mp->mb_type == MB_IMAP)
1879 delcache(mp, m);
1880 NYD_LEAVE;
1881 return OKAY;
1884 static enum okay
1885 imap_close(struct mailbox *mp)
1887 char o[LINESIZE];
1888 FILE *queuefp = NULL;
1889 NYD_X;
1891 snprintf(o, sizeof o, "%s CLOSE\r\n", tag(1));
1892 IMAP_OUT(o, MB_COMD, return STOP)
1893 IMAP_ANSWER()
1894 return OKAY;
1897 static enum okay
1898 imap_update(struct mailbox *mp)
1900 struct message *m;
1901 int dodel, c, gotcha = 0, held = 0, modflags = 0, needstat, stored = 0;
1902 NYD_ENTER;
1904 if (!edit && mp->mb_perm != 0) {
1905 holdbits();
1906 c = 0;
1907 for (m = message; PTRCMP(m, <, message + msgCount); ++m)
1908 if (m->m_flag & MBOX)
1909 ++c;
1910 if (c > 0)
1911 if (makembox() == STOP)
1912 goto jbypass;
1915 gotcha = held = 0;
1916 for (m = message; PTRCMP(m, <, message + msgCount); ++m) {
1917 if (mp->mb_perm == 0)
1918 dodel = 0;
1919 else if (edit)
1920 dodel = ((m->m_flag & MDELETED) != 0);
1921 else
1922 dodel = !((m->m_flag & MPRESERVE) || !(m->m_flag & MTOUCH));
1924 /* Fetch the result after around each 800 STORE commands
1925 * sent (approx. 32k data sent). Otherwise, servers will
1926 * try to flush the return queue at some point, leading
1927 * to a deadlock if we are still writing commands but not
1928 * reading their results */
1929 needstat = stored > 0 && stored % 800 == 0;
1930 /* Even if this message has been deleted, continue
1931 * to set further flags. This is necessary to support
1932 * Gmail semantics, where "delete" actually means
1933 * "archive", and the flags are applied to the copy
1934 * in "All Mail" */
1935 if ((m->m_flag & (MREAD | MSTATUS)) == (MREAD | MSTATUS)) {
1936 imap_store(mp, m, m-message+1, '+', "\\Seen", needstat);
1937 stored++;
1939 if (m->m_flag & MFLAG) {
1940 imap_store(mp, m, m-message+1, '+', "\\Flagged", needstat);
1941 stored++;
1943 if (m->m_flag & MUNFLAG) {
1944 imap_store(mp, m, m-message+1, '-', "\\Flagged", needstat);
1945 stored++;
1947 if (m->m_flag & MANSWER) {
1948 imap_store(mp, m, m-message+1, '+', "\\Answered", needstat);
1949 stored++;
1951 if (m->m_flag & MUNANSWER) {
1952 imap_store(mp, m, m-message+1, '-', "\\Answered", needstat);
1953 stored++;
1955 if (m->m_flag & MDRAFT) {
1956 imap_store(mp, m, m-message+1, '+', "\\Draft", needstat);
1957 stored++;
1959 if (m->m_flag & MUNDRAFT) {
1960 imap_store(mp, m, m-message+1, '-', "\\Draft", needstat);
1961 stored++;
1964 if (dodel) {
1965 imap_delete(mp, m-message+1, m, needstat);
1966 stored++;
1967 gotcha++;
1968 } else if (mp->mb_type != MB_CACHE ||
1969 (!edit && !(m->m_flag & (MBOXED | MSAVED | MDELETED))) ||
1970 (m->m_flag & (MBOXED | MPRESERVE | MTOUCH)) ==
1971 (MPRESERVE | MTOUCH) || (edit && !(m->m_flag & MDELETED)))
1972 held++;
1973 if (m->m_flag & MNEW) {
1974 m->m_flag &= ~MNEW;
1975 m->m_flag |= MSTATUS;
1978 jbypass:
1979 if (gotcha)
1980 imap_close(mp);
1982 for (m = &message[0]; PTRCMP(m, <, message + msgCount); ++m)
1983 if (!(m->m_flag & MUNLINKED) &&
1984 m->m_flag & (MBOXED | MDELETED | MSAVED | MSTATUS | MFLAG |
1985 MUNFLAG | MANSWER | MUNANSWER | MDRAFT | MUNDRAFT)) {
1986 putcache(mp, m);
1987 modflags++;
1989 if ((gotcha || modflags) && edit) {
1990 printf(_("\"%s\" "), displayname);
1991 printf((ok_blook(bsdcompat) || ok_blook(bsdmsgs))
1992 ? _("complete\n") : _("updated.\n"));
1993 } else if (held && !edit && mp->mb_perm != 0) {
1994 if (held == 1)
1995 printf(_("Held 1 message in %s\n"), displayname);
1996 else
1997 printf(_("Held %d messages in %s\n"), held, displayname);
1999 fflush(stdout);
2000 NYD_LEAVE;
2001 return OKAY;
2004 FL void
2005 imap_quit(void)
2007 sighandler_type volatile saveint, savepipe;
2008 NYD_ENTER;
2010 if (mb.mb_type == MB_CACHE) {
2011 imap_update(&mb);
2012 goto jleave;
2015 if (mb.mb_sock.s_fd < 0) {
2016 fprintf(stderr, "IMAP connection closed.\n");
2017 goto jleave;
2020 imaplock = 1;
2021 saveint = safe_signal(SIGINT, SIG_IGN);
2022 savepipe = safe_signal(SIGPIPE, SIG_IGN);
2023 if (sigsetjmp(imapjmp, 1)) {
2024 safe_signal(SIGINT, saveint);
2025 safe_signal(SIGPIPE, saveint);
2026 imaplock = 0;
2027 goto jleave;
2029 if (saveint != SIG_IGN)
2030 safe_signal(SIGINT, imapcatch);
2031 if (savepipe != SIG_IGN)
2032 safe_signal(SIGPIPE, imapcatch);
2034 imap_update(&mb);
2035 if (!same_imap_account)
2036 imap_exit(&mb);
2038 safe_signal(SIGINT, saveint);
2039 safe_signal(SIGPIPE, savepipe);
2040 imaplock = 0;
2041 jleave:
2042 NYD_LEAVE;
2045 static enum okay
2046 imap_store(struct mailbox *mp, struct message *m, int n, int c, const char *sp,
2047 int needstat)
2049 char o[LINESIZE];
2050 FILE *queuefp = NULL;
2051 NYD_X;
2053 if (mp->mb_type == MB_CACHE && (queuefp = cache_queue(mp)) == NULL)
2054 return STOP;
2055 if (m->m_uid)
2056 snprintf(o, sizeof o, "%s UID STORE %lu %cFLAGS (%s)\r\n",
2057 tag(1), m->m_uid, c, sp);
2058 else {
2059 if (check_expunged() == STOP)
2060 return STOP;
2061 snprintf(o, sizeof o, "%s STORE %u %cFLAGS (%s)\r\n", tag(1), n, c, sp);
2063 IMAP_OUT(o, MB_COMD, return STOP)
2064 if (needstat)
2065 IMAP_ANSWER()
2066 else
2067 mb.mb_active &= ~MB_COMD;
2068 if (queuefp != NULL)
2069 Fclose(queuefp);
2070 return OKAY;
2073 FL enum okay
2074 imap_undelete(struct message *m, int n)
2076 enum okay rv;
2077 NYD_ENTER;
2079 rv = imap_unstore(m, n, "\\Deleted");
2080 NYD_LEAVE;
2081 return rv;
2084 FL enum okay
2085 imap_unread(struct message *m, int n)
2087 enum okay rv;
2088 NYD_ENTER;
2090 rv = imap_unstore(m, n, "\\Seen");
2091 NYD_LEAVE;
2092 return rv;
2095 static enum okay
2096 imap_unstore(struct message *m, int n, const char *flag)
2098 sighandler_type saveint, savepipe;
2099 enum okay rv = STOP;
2100 NYD_ENTER;
2102 imaplock = 1;
2103 if ((saveint = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN)
2104 safe_signal(SIGINT, &_imap_maincatch);
2105 savepipe = safe_signal(SIGPIPE, SIG_IGN);
2106 if (sigsetjmp(imapjmp, 1) == 0) {
2107 if (savepipe != SIG_IGN)
2108 safe_signal(SIGPIPE, imapcatch);
2110 rv = imap_store(&mb, m, n, '-', flag, 1);
2112 safe_signal(SIGINT, saveint);
2113 safe_signal(SIGPIPE, savepipe);
2114 imaplock = 0;
2116 NYD_LEAVE;
2117 if (interrupts)
2118 onintr(0);
2119 return rv;
2122 static const char *
2123 tag(int new)
2125 static char ts[20];
2126 static long n;
2127 NYD2_ENTER;
2129 if (new)
2130 ++n;
2131 snprintf(ts, sizeof ts, "T%lu", n);
2132 NYD2_LEAVE;
2133 return ts;
2136 FL int
2137 c_imap_imap(void *vp)
2139 char o[LINESIZE];
2140 sighandler_type saveint, savepipe;
2141 struct mailbox *mp = &mb;
2142 FILE *queuefp = NULL;
2143 enum okay volatile ok = STOP;
2144 NYD_X;
2146 if (mp->mb_type != MB_IMAP) {
2147 printf("Not operating on an IMAP mailbox.\n");
2148 return 1;
2150 imaplock = 1;
2151 if ((saveint = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN)
2152 safe_signal(SIGINT, &_imap_maincatch);
2153 savepipe = safe_signal(SIGPIPE, SIG_IGN);
2154 if (sigsetjmp(imapjmp, 1) == 0) {
2155 if (savepipe != SIG_IGN)
2156 safe_signal(SIGPIPE, imapcatch);
2158 snprintf(o, sizeof o, "%s %s\r\n", tag(1), (char *)vp);
2159 IMAP_OUT(o, MB_COMD, goto out)
2160 while (mp->mb_active & MB_COMD) {
2161 ok = imap_answer(mp, 0);
2162 fputs(responded_text, stdout);
2165 out:
2166 safe_signal(SIGINT, saveint);
2167 safe_signal(SIGPIPE, savepipe);
2168 imaplock = 0;
2170 if (interrupts)
2171 onintr(0);
2172 return ok != OKAY;
2175 FL int
2176 imap_newmail(int nmail)
2178 NYD_ENTER;
2180 if (nmail && had_exists < 0 && had_expunge < 0) {
2181 imaplock = 1;
2182 imap_noop();
2183 imaplock = 0;
2186 if (had_exists == msgCount && had_expunge < 0)
2187 /* Some servers always respond with EXISTS to NOOP. If
2188 * the mailbox has been changed but the number of messages
2189 * has not, an EXPUNGE must also had been sent; otherwise,
2190 * nothing has changed */
2191 had_exists = -1;
2192 NYD_LEAVE;
2193 return (had_expunge >= 0 ? 2 : (had_exists >= 0 ? 1 : 0));
2196 static char *
2197 imap_putflags(int f)
2199 const char *cp;
2200 char *buf, *bp;
2201 NYD2_ENTER;
2203 bp = buf = salloc(100);
2204 if (f & (MREAD | MFLAGGED | MANSWERED | MDRAFTED)) {
2205 *bp++ = '(';
2206 if (f & MREAD) {
2207 if (bp[-1] != '(')
2208 *bp++ = ' ';
2209 for (cp = "\\Seen"; *cp; cp++)
2210 *bp++ = *cp;
2212 if (f & MFLAGGED) {
2213 if (bp[-1] != '(')
2214 *bp++ = ' ';
2215 for (cp = "\\Flagged"; *cp; cp++)
2216 *bp++ = *cp;
2218 if (f & MANSWERED) {
2219 if (bp[-1] != '(')
2220 *bp++ = ' ';
2221 for (cp = "\\Answered"; *cp; cp++)
2222 *bp++ = *cp;
2224 if (f & MDRAFT) {
2225 if (bp[-1] != '(')
2226 *bp++ = ' ';
2227 for (cp = "\\Draft"; *cp; cp++)
2228 *bp++ = *cp;
2230 *bp++ = ')';
2231 *bp++ = ' ';
2233 *bp = '\0';
2234 NYD2_LEAVE;
2235 return buf;
2238 static void
2239 imap_getflags(const char *cp, char const **xp, enum mflag *f)
2241 NYD2_ENTER;
2242 while (*cp != ')') {
2243 if (*cp == '\\') {
2244 if (ascncasecmp(cp, "\\Seen", 5) == 0)
2245 *f |= MREAD;
2246 else if (ascncasecmp(cp, "\\Recent", 7) == 0)
2247 *f |= MNEW;
2248 else if (ascncasecmp(cp, "\\Deleted", 8) == 0)
2249 *f |= MDELETED;
2250 else if (ascncasecmp(cp, "\\Flagged", 8) == 0)
2251 *f |= MFLAGGED;
2252 else if (ascncasecmp(cp, "\\Answered", 9) == 0)
2253 *f |= MANSWERED;
2254 else if (ascncasecmp(cp, "\\Draft", 6) == 0)
2255 *f |= MDRAFTED;
2257 cp++;
2260 if (xp != NULL)
2261 *xp = cp;
2262 NYD2_LEAVE;
2265 static enum okay
2266 imap_append1(struct mailbox *mp, const char *name, FILE *fp, off_t off1,
2267 long xsize, enum mflag flag, time_t t)
2269 char o[LINESIZE], *buf;
2270 size_t bufsize, buflen, cnt;
2271 long size, lines, ysize;
2272 int twice = 0;
2273 FILE *queuefp = NULL;
2274 enum okay rv;
2275 NYD_ENTER;
2277 if (mp->mb_type == MB_CACHE) {
2278 queuefp = cache_queue(mp);
2279 if (queuefp == NULL) {
2280 rv = STOP;
2281 buf = NULL;
2282 goto jleave;
2284 rv = OKAY;
2285 } else
2286 rv = STOP;
2288 buf = smalloc(bufsize = LINESIZE);
2289 buflen = 0;
2290 jagain:
2291 size = xsize;
2292 cnt = fsize(fp);
2293 if (fseek(fp, off1, SEEK_SET) < 0) {
2294 rv = STOP;
2295 goto jleave;
2298 snprintf(o, sizeof o, "%s APPEND %s %s%s {%ld}\r\n",
2299 tag(1), imap_quotestr(name), imap_putflags(flag),
2300 imap_make_date_time(t), size);
2301 IMAP_XOUT(o, MB_COMD, goto jleave, rv=STOP;goto jleave)
2302 while (mp->mb_active & MB_COMD) {
2303 rv = imap_answer(mp, twice);
2304 if (response_type == RESPONSE_CONT)
2305 break;
2308 if (mp->mb_type != MB_CACHE && rv == STOP) {
2309 if (twice == 0)
2310 goto jtrycreate;
2311 else
2312 goto jleave;
2315 lines = ysize = 0;
2316 while (size > 0) {
2317 fgetline(&buf, &bufsize, &cnt, &buflen, fp, 1);
2318 lines++;
2319 ysize += buflen;
2320 buf[buflen - 1] = '\r';
2321 buf[buflen] = '\n';
2322 if (mp->mb_type != MB_CACHE)
2323 swrite1(&mp->mb_sock, buf, buflen+1, 1);
2324 else if (queuefp)
2325 fwrite(buf, 1, buflen+1, queuefp);
2326 size -= buflen + 1;
2328 if (mp->mb_type != MB_CACHE)
2329 swrite(&mp->mb_sock, "\r\n");
2330 else if (queuefp)
2331 fputs("\r\n", queuefp);
2332 while (mp->mb_active & MB_COMD) {
2333 rv = imap_answer(mp, 0);
2334 if (response_status == RESPONSE_NO /*&&
2335 ascncasecmp(responded_text,
2336 "[TRYCREATE] ", 12) == 0*/) {
2337 jtrycreate:
2338 if (twice++) {
2339 rv = STOP;
2340 goto jleave;
2342 snprintf(o, sizeof o, "%s CREATE %s\r\n", tag(1), imap_quotestr(name));
2343 IMAP_XOUT(o, MB_COMD, goto jleave, rv=STOP;goto jleave)
2344 while (mp->mb_active & MB_COMD)
2345 rv = imap_answer(mp, 1);
2346 if (rv == STOP)
2347 goto jleave;
2348 imap_created_mailbox++;
2349 goto jagain;
2350 } else if (rv != OKAY)
2351 fprintf(stderr, _("IMAP error: %s"), responded_text);
2352 else if (response_status == RESPONSE_OK && (mp->mb_flags & MB_UIDPLUS))
2353 imap_appenduid(mp, fp, t, off1, xsize, ysize, lines, flag, name);
2355 jleave:
2356 if (queuefp != NULL)
2357 Fclose(queuefp);
2358 if (buf != NULL)
2359 free(buf);
2360 NYD_LEAVE;
2361 return rv;
2364 static enum okay
2365 imap_append0(struct mailbox *mp, const char *name, FILE *fp)
2367 char *buf, *bp, *lp;
2368 size_t bufsize, buflen, cnt;
2369 off_t off1 = -1, offs;
2370 int inhead = 1, flag = MNEW | MNEWEST;
2371 long size = 0;
2372 time_t tim;
2373 enum okay rv;
2374 NYD_ENTER;
2376 buf = smalloc(bufsize = LINESIZE);
2377 buflen = 0;
2378 cnt = fsize(fp);
2379 offs = ftell(fp);
2380 time(&tim);
2382 do {
2383 bp = fgetline(&buf, &bufsize, &cnt, &buflen, fp, 1);
2384 if (bp == NULL || strncmp(buf, "From ", 5) == 0) {
2385 if (off1 != (off_t)-1) {
2386 rv = imap_append1(mp, name, fp, off1, size, flag, tim);
2387 if (rv == STOP)
2388 goto jleave;
2389 fseek(fp, offs+buflen, SEEK_SET);
2391 off1 = offs + buflen;
2392 size = 0;
2393 inhead = 1;
2394 flag = MNEW;
2395 if (bp != NULL)
2396 tim = unixtime(buf);
2397 } else
2398 size += buflen+1;
2399 offs += buflen;
2401 if (bp && buf[0] == '\n')
2402 inhead = 0;
2403 else if (bp && inhead && ascncasecmp(buf, "status", 6) == 0) {
2404 lp = &buf[6];
2405 while (whitechar(*lp))
2406 lp++;
2407 if (*lp == ':')
2408 while (*++lp != '\0')
2409 switch (*lp) {
2410 case 'R':
2411 flag |= MREAD;
2412 break;
2413 case 'O':
2414 flag &= ~MNEW;
2415 break;
2417 } else if (bp && inhead && ascncasecmp(buf, "x-status", 8) == 0) {
2418 lp = &buf[8];
2419 while (whitechar(*lp))
2420 lp++;
2421 if (*lp == ':')
2422 while (*++lp != '\0')
2423 switch (*lp) {
2424 case 'F':
2425 flag |= MFLAGGED;
2426 break;
2427 case 'A':
2428 flag |= MANSWERED;
2429 break;
2430 case 'T':
2431 flag |= MDRAFTED;
2432 break;
2435 } while (bp != NULL);
2436 rv = OKAY;
2437 jleave:
2438 free(buf);
2439 NYD_LEAVE;
2440 return rv;
2443 FL enum okay
2444 imap_append(const char *xserver, FILE *fp)
2446 sighandler_type volatile saveint, savepipe;
2447 struct url url;
2448 struct ccred ccred;
2449 char const * volatile mbx;
2450 enum okay rv = STOP;
2451 NYD_ENTER;
2453 if (!url_parse(&url, CPROTO_IMAP, xserver))
2454 goto j_leave;
2455 if (!ok_blook(v15_compat) &&
2456 (!url.url_had_user || url.url_pass.s != NULL))
2457 fprintf(stderr, "New-style URL used without *v15-compat* being set!\n");
2458 mbx = (url.url_path.s != NULL) ? url.url_path.s : "INBOX";
2460 imaplock = 1;
2461 if ((saveint = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN)
2462 safe_signal(SIGINT, &_imap_maincatch);
2463 savepipe = safe_signal(SIGPIPE, SIG_IGN);
2464 if (sigsetjmp(imapjmp, 1))
2465 goto jleave;
2466 if (savepipe != SIG_IGN)
2467 safe_signal(SIGPIPE, imapcatch);
2469 if ((mb.mb_type == MB_CACHE || mb.mb_sock.s_fd > 0) && mb.mb_imap_account &&
2470 !strcmp(url.url_p_eu_h_p, mb.mb_imap_account)) {
2471 rv = imap_append0(&mb, mbx, fp);
2472 } else {
2473 struct mailbox mx;
2475 memset(&mx, 0, sizeof mx);
2477 if (!_imap_getcred(&mx, &ccred, &url))
2478 goto jleave;
2480 if (disconnected(url.url_p_eu_h_p) == 0) {
2481 if (!sopen(&mx.mb_sock, &url))
2482 goto jfail;
2483 mx.mb_sock.s_desc = "IMAP";
2484 mx.mb_type = MB_IMAP;
2485 mx.mb_imap_account = UNCONST(url.url_p_eu_h_p);
2486 /* TODO the code now did
2487 * TODO mx.mb_imap_mailbox = mbx;
2488 * TODO though imap_mailbox is sfree()d and mbx
2489 * TODO is possibly even a constant
2490 * TODO i changed this to sstrdup() sofar, as is used
2491 * TODO somewhere else in this file for this! */
2492 mx.mb_imap_mailbox = sstrdup(mbx);
2493 if (imap_preauth(&mx, url.url_h_p.s, url.url_u_h_p.s) != OKAY ||
2494 imap_auth(&mx, &ccred) != OKAY) {
2495 sclose(&mx.mb_sock);
2496 goto jfail;
2498 rv = imap_append0(&mx, mbx, fp);
2499 imap_exit(&mx);
2500 } else {
2501 mx.mb_imap_account = UNCONST(url.url_p_eu_h_p);
2502 mx.mb_imap_mailbox = sstrdup(mbx); /* TODO as above */
2503 mx.mb_type = MB_CACHE;
2504 rv = imap_append0(&mx, mbx, fp);
2506 jfail:
2510 jleave:
2511 safe_signal(SIGINT, saveint);
2512 safe_signal(SIGPIPE, savepipe);
2513 imaplock = 0;
2514 j_leave:
2515 NYD_LEAVE;
2516 if (interrupts)
2517 onintr(0);
2518 return rv;
2521 static enum okay
2522 imap_list1(struct mailbox *mp, const char *base, struct list_item **list,
2523 struct list_item **lend, int level)
2525 char o[LINESIZE], *cp;
2526 const char *bp;
2527 FILE *queuefp = NULL;
2528 struct list_item *lp;
2529 enum okay ok = STOP;
2530 NYD_X;
2532 *list = *lend = NULL;
2533 snprintf(o, sizeof o, "%s LIST %s %%\r\n", tag(1), imap_quotestr(base));
2534 IMAP_OUT(o, MB_COMD, return STOP)
2535 while (mp->mb_active & MB_COMD) {
2536 ok = imap_answer(mp, 1);
2537 if (response_status == RESPONSE_OTHER &&
2538 response_other == MAILBOX_DATA_LIST && imap_parse_list() == OKAY) {
2539 cp = imap_unquotestr(list_name);
2540 lp = csalloc(1, sizeof *lp);
2541 lp->l_name = cp;
2542 for (bp = base; *bp != '\0' && *bp == *cp; ++bp)
2543 ++cp;
2544 lp->l_base = *cp ? cp : savestr(base);
2545 lp->l_attr = list_attributes;
2546 lp->l_level = level+1;
2547 lp->l_delim = list_hierarchy_delimiter;
2548 if (*list && *lend) {
2549 (*lend)->l_next = lp;
2550 *lend = lp;
2551 } else
2552 *list = *lend = lp;
2555 return ok;
2558 static enum okay
2559 imap_list(struct mailbox *mp, const char *base, int strip, FILE *fp)
2561 struct list_item *list, *lend, *lp, *lx, *ly;
2562 int n, depth;
2563 const char *bp;
2564 char *cp;
2565 enum okay rv;
2566 NYD_ENTER;
2568 depth = (cp = ok_vlook(imap_list_depth)) != NULL ? atoi(cp) : 2;
2569 if ((rv = imap_list1(mp, base, &list, &lend, 0)) == STOP)
2570 goto jleave;
2571 rv = OKAY;
2572 if (list == NULL || lend == NULL)
2573 goto jleave;
2575 for (lp = list; lp; lp = lp->l_next)
2576 if (lp->l_delim != '/' && lp->l_delim != EOF && lp->l_level < depth &&
2577 !(lp->l_attr & LIST_NOINFERIORS)) {
2578 cp = salloc((n = strlen(lp->l_name)) + 2);
2579 memcpy(cp, lp->l_name, n);
2580 cp[n] = lp->l_delim;
2581 cp[n+1] = '\0';
2582 if (imap_list1(mp, cp, &lx, &ly, lp->l_level) == OKAY && lx && ly) {
2583 lp->l_has_children = 1;
2584 if (strcmp(cp, lx->l_name) == 0)
2585 lx = lx->l_next;
2586 if (lx) {
2587 lend->l_next = lx;
2588 lend = ly;
2593 for (lp = list; lp; lp = lp->l_next) {
2594 if (strip) {
2595 cp = lp->l_name;
2596 for (bp = base; *bp && *bp == *cp; bp++)
2597 cp++;
2598 } else
2599 cp = lp->l_name;
2600 if (!(lp->l_attr & LIST_NOSELECT))
2601 fprintf(fp, "%s\n", *cp ? cp : base);
2602 else if (lp->l_has_children == 0)
2603 fprintf(fp, "%s%c\n", *cp ? cp : base,
2604 (lp->l_delim != EOF ? lp->l_delim : '\n'));
2606 jleave:
2607 NYD_LEAVE;
2608 return rv;
2611 FL void
2612 imap_folders(const char * volatile name, int strip)
2614 sighandler_type saveint, savepipe;
2615 const char *fold, *cp, *sp;
2616 FILE * volatile fp;
2617 NYD_ENTER;
2619 cp = protbase(name);
2620 sp = mb.mb_imap_account;
2621 if (sp == NULL || strcmp(cp, sp)) {
2622 fprintf(stderr, _(
2623 "Cannot perform `folders' but when on the very IMAP "
2624 "account; the current one is\n `%s' -- "
2625 "try `folders @'.\n"),
2626 (sp != NULL ? sp : _("[NONE]")));
2627 goto jleave;
2630 fold = imap_fileof(name);
2631 if (options & OPT_TTYOUT) {
2632 if ((fp = Ftmp(NULL, "imapfold", OF_RDWR | OF_UNLINK | OF_REGISTER,
2633 0600)) == NULL) {
2634 perror("tmpfile");
2635 goto jleave;
2637 } else
2638 fp = stdout;
2640 imaplock = 1;
2641 if ((saveint = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN)
2642 safe_signal(SIGINT, &_imap_maincatch);
2643 savepipe = safe_signal(SIGPIPE, SIG_IGN);
2644 if (sigsetjmp(imapjmp, 1)) /* TODO imaplock? */
2645 goto junroll;
2646 if (savepipe != SIG_IGN)
2647 safe_signal(SIGPIPE, imapcatch);
2649 if (mb.mb_type == MB_CACHE)
2650 cache_list(&mb, fold, strip, fp);
2651 else
2652 imap_list(&mb, fold, strip, fp);
2654 imaplock = 0;
2655 if (interrupts) {
2656 if (options & OPT_TTYOUT)
2657 Fclose(fp);
2658 goto jleave;
2660 fflush(fp);
2662 if (options & OPT_TTYOUT) {
2663 rewind(fp);
2664 if (fsize(fp) > 0)
2665 dopr(fp);
2666 else
2667 fprintf(stderr, "Folder not found.\n");
2669 junroll:
2670 safe_signal(SIGINT, saveint);
2671 safe_signal(SIGPIPE, savepipe);
2672 if (options & OPT_TTYOUT)
2673 Fclose(fp);
2674 jleave:
2675 NYD_LEAVE;
2676 if (interrupts)
2677 onintr(0);
2680 static void
2681 dopr(FILE *fp)
2683 char o[LINESIZE];
2684 int c;
2685 long n = 0, mx = 0, columns, width;
2686 FILE *out;
2687 NYD_ENTER;
2689 if ((out = Ftmp(NULL, "imapdopr", OF_RDWR | OF_UNLINK | OF_REGISTER, 0600))
2690 == NULL) {
2691 perror("tmpfile");
2692 goto jleave;
2695 while ((c = getc(fp)) != EOF) {
2696 if (c == '\n') {
2697 if (n > mx)
2698 mx = n;
2699 n = 0;
2700 } else
2701 ++n;
2703 rewind(fp);
2705 width = scrnwidth;
2706 if (mx < width / 2) {
2707 columns = width / (mx+2);
2708 snprintf(o, sizeof o, "sort | pr -%lu -w%lu -t", columns, width);
2709 } else
2710 strncpy(o, "sort", sizeof o)[sizeof o - 1] = '\0';
2711 run_command(XSHELL, 0, fileno(fp), fileno(out), "-c", o, NULL);
2712 page_or_print(out, 0);
2713 Fclose(out);
2714 jleave:
2715 NYD_LEAVE;
2718 static enum okay
2719 imap_copy1(struct mailbox *mp, struct message *m, int n, const char *name)
2721 char o[LINESIZE];
2722 const char *qname;
2723 int twice = 0, stored = 0;
2724 FILE *queuefp = NULL;
2725 enum okay ok = STOP;
2726 NYD_X;
2728 if (mp->mb_type == MB_CACHE) {
2729 if ((queuefp = cache_queue(mp)) == NULL)
2730 return STOP;
2731 ok = OKAY;
2733 qname = imap_quotestr(name = imap_fileof(name));
2734 /* Since it is not possible to set flags on the copy, recently
2735 * set flags must be set on the original to include it in the copy */
2736 if ((m->m_flag & (MREAD | MSTATUS)) == (MREAD | MSTATUS))
2737 imap_store(mp, m, n, '+', "\\Seen", 0);
2738 if (m->m_flag&MFLAG)
2739 imap_store(mp, m, n, '+', "\\Flagged", 0);
2740 if (m->m_flag&MUNFLAG)
2741 imap_store(mp, m, n, '-', "\\Flagged", 0);
2742 if (m->m_flag&MANSWER)
2743 imap_store(mp, m, n, '+', "\\Answered", 0);
2744 if (m->m_flag&MUNANSWER)
2745 imap_store(mp, m, n, '-', "\\Flagged", 0);
2746 if (m->m_flag&MDRAFT)
2747 imap_store(mp, m, n, '+', "\\Draft", 0);
2748 if (m->m_flag&MUNDRAFT)
2749 imap_store(mp, m, n, '-', "\\Draft", 0);
2750 again:
2751 if (m->m_uid)
2752 snprintf(o, sizeof o, "%s UID COPY %lu %s\r\n", tag(1), m->m_uid, qname);
2753 else {
2754 if (check_expunged() == STOP)
2755 goto out;
2756 snprintf(o, sizeof o, "%s COPY %u %s\r\n", tag(1), n, qname);
2758 IMAP_OUT(o, MB_COMD, goto out)
2759 while (mp->mb_active & MB_COMD)
2760 ok = imap_answer(mp, twice);
2762 if (mp->mb_type == MB_IMAP && mp->mb_flags & MB_UIDPLUS &&
2763 response_status == RESPONSE_OK)
2764 imap_copyuid(mp, m, name);
2766 if (response_status == RESPONSE_NO && twice++ == 0) {
2767 snprintf(o, sizeof o, "%s CREATE %s\r\n", tag(1), qname);
2768 IMAP_OUT(o, MB_COMD, goto out)
2769 while (mp->mb_active & MB_COMD)
2770 ok = imap_answer(mp, 1);
2771 if (ok == OKAY) {
2772 imap_created_mailbox++;
2773 goto again;
2777 if (queuefp != NULL)
2778 Fclose(queuefp);
2780 /* ... and reset the flag to its initial value so that the 'exit'
2781 * command still leaves the message unread */
2782 out:
2783 if ((m->m_flag & (MREAD | MSTATUS)) == (MREAD | MSTATUS)) {
2784 imap_store(mp, m, n, '-', "\\Seen", 0);
2785 stored++;
2787 if (m->m_flag & MFLAG) {
2788 imap_store(mp, m, n, '-', "\\Flagged", 0);
2789 stored++;
2791 if (m->m_flag & MUNFLAG) {
2792 imap_store(mp, m, n, '+', "\\Flagged", 0);
2793 stored++;
2795 if (m->m_flag & MANSWER) {
2796 imap_store(mp, m, n, '-', "\\Answered", 0);
2797 stored++;
2799 if (m->m_flag & MUNANSWER) {
2800 imap_store(mp, m, n, '+', "\\Answered", 0);
2801 stored++;
2803 if (m->m_flag & MDRAFT) {
2804 imap_store(mp, m, n, '-', "\\Draft", 0);
2805 stored++;
2807 if (m->m_flag & MUNDRAFT) {
2808 imap_store(mp, m, n, '+', "\\Draft", 0);
2809 stored++;
2811 if (stored) {
2812 mp->mb_active |= MB_COMD;
2813 (void)imap_finish(mp);
2815 return ok;
2818 FL enum okay
2819 imap_copy(struct message *m, int n, const char *name)
2821 sighandler_type saveint, savepipe;
2822 enum okay rv = STOP;
2823 NYD_ENTER;
2825 imaplock = 1;
2826 if ((saveint = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN)
2827 safe_signal(SIGINT, &_imap_maincatch);
2828 savepipe = safe_signal(SIGPIPE, SIG_IGN);
2829 if (sigsetjmp(imapjmp, 1) == 0) {
2830 if (savepipe != SIG_IGN)
2831 safe_signal(SIGPIPE, imapcatch);
2833 rv = imap_copy1(&mb, m, n, name);
2835 safe_signal(SIGINT, saveint);
2836 safe_signal(SIGPIPE, savepipe);
2837 imaplock = 0;
2839 NYD_LEAVE;
2840 if (interrupts)
2841 onintr(0);
2842 return rv;
2845 static enum okay
2846 imap_copyuid_parse(const char *cp, unsigned long *uidvalidity,
2847 unsigned long *olduid, unsigned long *newuid)
2849 char *xp, *yp, *zp;
2850 enum okay rv;
2851 NYD_ENTER;
2853 *uidvalidity = strtoul(cp, &xp, 10);
2854 *olduid = strtoul(xp, &yp, 10);
2855 *newuid = strtoul(yp, &zp, 10);
2856 rv = (*uidvalidity && *olduid && *newuid && xp > cp && *xp == ' ' &&
2857 yp > xp && *yp == ' ' && zp > yp && *zp == ']');
2858 NYD_LEAVE;
2859 return rv;
2862 static enum okay
2863 imap_appenduid_parse(const char *cp, unsigned long *uidvalidity,
2864 unsigned long *uid)
2866 char *xp, *yp;
2867 enum okay rv;
2868 NYD_ENTER;
2870 *uidvalidity = strtoul(cp, &xp, 10);
2871 *uid = strtoul(xp, &yp, 10);
2872 rv = (*uidvalidity && *uid && xp > cp && *xp == ' ' && yp > xp &&
2873 *yp == ']');
2874 NYD_LEAVE;
2875 return rv;
2878 static enum okay
2879 imap_copyuid(struct mailbox *mp, struct message *m, const char *name)
2881 struct mailbox xmb;
2882 struct message xm;
2883 const char *cp;
2884 unsigned long uidvalidity, olduid, newuid;
2885 enum okay rv;
2886 NYD_ENTER;
2888 rv = STOP;
2889 if ((cp = asccasestr(responded_text, "[COPYUID ")) == NULL ||
2890 imap_copyuid_parse(&cp[9], &uidvalidity, &olduid, &newuid) == STOP)
2891 goto jleave;
2892 rv = OKAY;
2894 xmb = *mp;
2895 xmb.mb_cache_directory = NULL;
2896 xmb.mb_imap_mailbox = savestr(name);
2897 xmb.mb_uidvalidity = uidvalidity;
2898 initcache(&xmb);
2899 if (m == NULL) {
2900 memset(&xm, 0, sizeof xm);
2901 xm.m_uid = olduid;
2902 if ((rv = getcache1(mp, &xm, NEED_UNSPEC, 3)) != OKAY)
2903 goto jleave;
2904 getcache(mp, &xm, NEED_HEADER);
2905 getcache(mp, &xm, NEED_BODY);
2906 } else {
2907 if ((m->m_flag & HAVE_HEADER) == 0)
2908 getcache(mp, m, NEED_HEADER);
2909 if ((m->m_flag & HAVE_BODY) == 0)
2910 getcache(mp, m, NEED_BODY);
2911 xm = *m;
2913 xm.m_uid = newuid;
2914 xm.m_flag &= ~MFULLYCACHED;
2915 putcache(&xmb, &xm);
2916 jleave:
2917 NYD_LEAVE;
2918 return rv;
2921 static enum okay
2922 imap_appenduid(struct mailbox *mp, FILE *fp, time_t t, long off1, long xsize,
2923 long size, long lines, int flag, const char *name)
2925 struct mailbox xmb;
2926 struct message xm;
2927 const char *cp;
2928 unsigned long uidvalidity, uid;
2929 enum okay rv;
2930 NYD_ENTER;
2932 rv = STOP;
2933 if ((cp = asccasestr(responded_text, "[APPENDUID ")) == NULL ||
2934 imap_appenduid_parse(&cp[11], &uidvalidity, &uid) == STOP)
2935 goto jleave;
2936 rv = OKAY;
2938 xmb = *mp;
2939 xmb.mb_cache_directory = NULL;
2940 xmb.mb_imap_mailbox = savestr(name);
2941 xmb.mb_uidvalidity = uidvalidity;
2942 xmb.mb_otf = xmb.mb_itf = fp;
2943 initcache(&xmb);
2944 memset(&xm, 0, sizeof xm);
2945 xm.m_flag = (flag & MREAD) | MNEW;
2946 xm.m_time = t;
2947 xm.m_block = mailx_blockof(off1);
2948 xm.m_offset = mailx_offsetof(off1);
2949 xm.m_size = size;
2950 xm.m_xsize = xsize;
2951 xm.m_lines = xm.m_xlines = lines;
2952 xm.m_uid = uid;
2953 xm.m_have = HAVE_HEADER | HAVE_BODY;
2954 putcache(&xmb, &xm);
2955 jleave:
2956 NYD_LEAVE;
2957 return rv;
2960 static enum okay
2961 imap_appenduid_cached(struct mailbox *mp, FILE *fp)
2963 FILE *tp = NULL;
2964 time_t t;
2965 long size, xsize, ysize, lines;
2966 enum mflag flag = MNEW;
2967 char *name, *buf, *bp;
2968 char const *cp;
2969 size_t bufsize, buflen, cnt;
2970 enum okay rv = STOP;
2971 NYD_ENTER;
2973 buf = smalloc(bufsize = LINESIZE);
2974 buflen = 0;
2975 cnt = fsize(fp);
2976 if (fgetline(&buf, &bufsize, &cnt, &buflen, fp, 0) == NULL)
2977 goto jstop;
2979 for (bp = buf; *bp != ' '; ++bp) /* strip old tag */
2981 while (*bp == ' ')
2982 ++bp;
2984 if ((cp = strrchr(bp, '{')) == NULL)
2985 goto jstop;
2987 xsize = atol(&cp[1]) + 2;
2988 if ((name = imap_strex(&bp[7], &cp)) == NULL)
2989 goto jstop;
2990 while (*cp == ' ')
2991 cp++;
2993 if (*cp == '(') {
2994 imap_getflags(cp, &cp, &flag);
2995 while (*++cp == ' ')
2998 t = imap_read_date_time(cp);
3000 if ((tp = Ftmp(NULL, "imapapui", OF_RDWR | OF_UNLINK | OF_REGISTER, 0600)) ==
3001 NULL)
3002 goto jstop;
3004 size = xsize;
3005 ysize = lines = 0;
3006 while (size > 0) {
3007 if (fgetline(&buf, &bufsize, &cnt, &buflen, fp, 0) == NULL)
3008 goto jstop;
3009 size -= buflen;
3010 buf[--buflen] = '\0';
3011 buf[buflen-1] = '\n';
3012 fwrite(buf, 1, buflen, tp);
3013 ysize += buflen;
3014 ++lines;
3016 fflush(tp);
3017 rewind(tp);
3019 imap_appenduid(mp, tp, t, 0, xsize-2, ysize-1, lines-1, flag,
3020 imap_unquotestr(name));
3021 rv = OKAY;
3022 jstop:
3023 free(buf);
3024 if (tp)
3025 Fclose(tp);
3026 NYD_LEAVE;
3027 return rv;
3030 #ifdef HAVE_IMAP_SEARCH
3031 static enum okay
3032 imap_search2(struct mailbox *mp, struct message *m, int cnt, const char *spec,
3033 int f)
3035 char *o, *xp, *cs, c;
3036 size_t osize;
3037 FILE *queuefp = NULL;
3038 int i;
3039 unsigned long n;
3040 const char *cp;
3041 enum okay ok = STOP;
3042 NYD_X;
3044 c = 0;
3045 for (cp = spec; *cp; cp++)
3046 c |= *cp;
3047 if (c & 0200) {
3048 cp = charset_get_lc();
3049 # ifdef HAVE_ICONV
3050 if (asccasecmp(cp, "utf-8") && asccasecmp(cp, "utf8")) {
3051 iconv_t it;
3052 char *nsp, *nspec;
3053 size_t sz, nsz;
3055 if ((it = n_iconv_open("utf-8", cp)) != (iconv_t)-1) {
3056 sz = strlen(spec) + 1;
3057 nsp = nspec = salloc(nsz = 6*strlen(spec) + 1);
3058 if (n_iconv_buf(it, &spec, &sz, &nsp, &nsz, FAL0) == 0 &&
3059 sz == 0) {
3060 spec = nspec;
3061 cp = "utf-8";
3063 n_iconv_close(it);
3066 # endif
3067 cp = imap_quotestr(cp);
3068 cs = salloc(n = strlen(cp) + 10);
3069 snprintf(cs, n, "CHARSET %s ", cp);
3070 } else
3071 cs = UNCONST("");
3073 o = ac_alloc(osize = strlen(spec) + 60);
3074 snprintf(o, osize, "%s UID SEARCH %s%s\r\n", tag(1), cs, spec);
3075 IMAP_OUT(o, MB_COMD, goto out)
3076 while (mp->mb_active & MB_COMD) {
3077 ok = imap_answer(mp, 0);
3078 if (response_status == RESPONSE_OTHER &&
3079 response_other == MAILBOX_DATA_SEARCH) {
3080 xp = responded_other_text;
3081 while (*xp && *xp != '\r') {
3082 n = strtoul(xp, &xp, 10);
3083 for (i = 0; i < cnt; i++)
3084 if (m[i].m_uid == n && !(m[i].m_flag & MHIDDEN) &&
3085 (f == MDELETED || !(m[i].m_flag & MDELETED)))
3086 mark(i+1, f);
3090 out:
3091 ac_free(o);
3092 return ok;
3095 FL enum okay
3096 imap_search1(const char * volatile spec, int f)
3098 sighandler_type saveint, savepipe;
3099 enum okay volatile rv = STOP;
3100 NYD_ENTER;
3102 if (mb.mb_type != MB_IMAP)
3103 goto jleave;
3105 imaplock = 1;
3106 if ((saveint = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN)
3107 safe_signal(SIGINT, &_imap_maincatch);
3108 savepipe = safe_signal(SIGPIPE, SIG_IGN);
3109 if (sigsetjmp(imapjmp, 1) == 0) {
3110 if (savepipe != SIG_IGN)
3111 safe_signal(SIGPIPE, imapcatch);
3113 rv = imap_search2(&mb, message, msgCount, spec, f);
3115 safe_signal(SIGINT, saveint);
3116 safe_signal(SIGPIPE, savepipe);
3117 imaplock = 0;
3118 jleave:
3119 NYD_LEAVE;
3120 if (interrupts)
3121 onintr(0);
3122 return rv;
3124 #endif /* HAVE_IMAP_SEARCH */
3126 FL int
3127 imap_thisaccount(const char *cp)
3129 int rv;
3130 NYD_ENTER;
3132 if (mb.mb_type != MB_CACHE && mb.mb_type != MB_IMAP)
3133 rv = 0;
3134 else if ((mb.mb_type != MB_CACHE && mb.mb_sock.s_fd < 0) ||
3135 mb.mb_imap_account == NULL)
3136 rv = 0;
3137 else
3138 rv = !strcmp(protbase(cp), mb.mb_imap_account);
3139 NYD_LEAVE;
3140 return rv;
3143 FL enum okay
3144 imap_remove(const char * volatile name)
3146 sighandler_type volatile saveint, savepipe;
3147 enum okay rv = STOP;
3148 NYD_ENTER;
3150 if (mb.mb_type != MB_IMAP) {
3151 fprintf(stderr, "Refusing to remove \"%s\" in disconnected mode.\n",
3152 name);
3153 goto jleave;
3156 if (!imap_thisaccount(name)) {
3157 fprintf(stderr, "Can only remove mailboxes on current IMAP "
3158 "server: \"%s\" not removed.\n", name);
3159 goto jleave;
3162 imaplock = 1;
3163 if ((saveint = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN)
3164 safe_signal(SIGINT, &_imap_maincatch);
3165 savepipe = safe_signal(SIGPIPE, SIG_IGN);
3166 if (sigsetjmp(imapjmp, 1) == 0) {
3167 if (savepipe != SIG_IGN)
3168 safe_signal(SIGPIPE, imapcatch);
3170 rv = imap_remove1(&mb, imap_fileof(name));
3172 safe_signal(SIGINT, saveint);
3173 safe_signal(SIGPIPE, savepipe);
3174 imaplock = 0;
3176 if (rv == OKAY)
3177 rv = cache_remove(name);
3178 jleave:
3179 NYD_LEAVE;
3180 if (interrupts)
3181 onintr(0);
3182 return rv;
3185 static enum okay
3186 imap_remove1(struct mailbox *mp, const char *name)
3188 FILE *queuefp = NULL;
3189 char *o;
3190 int os;
3191 enum okay ok = STOP;
3192 NYD_X;
3194 o = ac_alloc(os = 2*strlen(name) + 100);
3195 snprintf(o, os, "%s DELETE %s\r\n", tag(1), imap_quotestr(name));
3196 IMAP_OUT(o, MB_COMD, goto out)
3197 while (mp->mb_active & MB_COMD)
3198 ok = imap_answer(mp, 1);
3199 out:
3200 ac_free(o);
3201 return ok;
3204 FL enum okay
3205 imap_rename(const char *old, const char *new)
3207 sighandler_type saveint, savepipe;
3208 enum okay rv = STOP;
3209 NYD_ENTER;
3211 if (mb.mb_type != MB_IMAP) {
3212 fprintf(stderr, "Refusing to rename mailboxes in disconnected mode.\n");
3213 goto jleave;
3216 if (!imap_thisaccount(old) || !imap_thisaccount(new)) {
3217 fprintf(stderr, "Can only rename mailboxes on current IMAP "
3218 "server: \"%s\" not renamed to \"%s\".\n", old, new);
3219 goto jleave;
3222 imaplock = 1;
3223 if ((saveint = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN)
3224 safe_signal(SIGINT, &_imap_maincatch);
3225 savepipe = safe_signal(SIGPIPE, SIG_IGN);
3226 if (sigsetjmp(imapjmp, 1) == 0) {
3227 if (savepipe != SIG_IGN)
3228 safe_signal(SIGPIPE, imapcatch);
3230 rv = imap_rename1(&mb, imap_fileof(old), imap_fileof(new));
3232 safe_signal(SIGINT, saveint);
3233 safe_signal(SIGPIPE, savepipe);
3234 imaplock = 0;
3236 if (rv == OKAY)
3237 rv = cache_rename(old, new);
3238 jleave:
3239 NYD_LEAVE;
3240 if (interrupts)
3241 onintr(0);
3242 return rv;
3245 static enum okay
3246 imap_rename1(struct mailbox *mp, const char *old, const char *new)
3248 FILE *queuefp = NULL;
3249 char *o;
3250 int os;
3251 enum okay ok = STOP;
3252 NYD_X;
3254 o = ac_alloc(os = 2*strlen(old) + 2*strlen(new) + 100);
3255 snprintf(o, os, "%s RENAME %s %s\r\n", tag(1), imap_quotestr(old),
3256 imap_quotestr(new));
3257 IMAP_OUT(o, MB_COMD, goto out)
3258 while (mp->mb_active & MB_COMD)
3259 ok = imap_answer(mp, 1);
3260 out:
3261 ac_free(o);
3262 return ok;
3265 FL enum okay
3266 imap_dequeue(struct mailbox *mp, FILE *fp)
3268 char o[LINESIZE], *newname, *buf, *bp, *cp, iob[4096];
3269 size_t bufsize, buflen, cnt;
3270 long offs, offs1, offs2, octets;
3271 int twice, gotcha = 0;
3272 FILE *queuefp = NULL;
3273 enum okay ok = OKAY, rok = OKAY;
3274 NYD_X;
3276 buf = smalloc(bufsize = LINESIZE);
3277 buflen = 0;
3278 cnt = fsize(fp);
3279 while ((offs1 = ftell(fp)) >= 0 &&
3280 fgetline(&buf, &bufsize, &cnt, &buflen, fp, 0) != NULL) {
3281 for (bp = buf; *bp != ' '; ++bp) /* strip old tag */
3283 while (*bp == ' ')
3284 ++bp;
3285 twice = 0;
3286 if ((offs = ftell(fp)) < 0)
3287 goto fail;
3288 again:
3289 snprintf(o, sizeof o, "%s %s", tag(1), bp);
3290 if (ascncasecmp(bp, "UID COPY ", 9) == 0) {
3291 cp = &bp[9];
3292 while (digitchar(*cp))
3293 cp++;
3294 if (*cp != ' ')
3295 goto fail;
3296 while (*cp == ' ')
3297 cp++;
3298 if ((newname = imap_strex(cp, NULL)) == NULL)
3299 goto fail;
3300 IMAP_OUT(o, MB_COMD, continue)
3301 while (mp->mb_active & MB_COMD)
3302 ok = imap_answer(mp, twice);
3303 if (response_status == RESPONSE_NO && twice++ == 0)
3304 goto trycreate;
3305 if (response_status == RESPONSE_OK && mp->mb_flags & MB_UIDPLUS) {
3306 imap_copyuid(mp, NULL, imap_unquotestr(newname));
3308 } else if (ascncasecmp(bp, "UID STORE ", 10) == 0) {
3309 IMAP_OUT(o, MB_COMD, continue)
3310 while (mp->mb_active & MB_COMD)
3311 ok = imap_answer(mp, 1);
3312 if (ok == OKAY)
3313 gotcha++;
3314 } else if (ascncasecmp(bp, "APPEND ", 7) == 0) {
3315 if ((cp = strrchr(bp, '{')) == NULL)
3316 goto fail;
3317 octets = atol(&cp[1]) + 2;
3318 if ((newname = imap_strex(&bp[7], NULL)) == NULL)
3319 goto fail;
3320 IMAP_OUT(o, MB_COMD, continue)
3321 while (mp->mb_active & MB_COMD) {
3322 ok = imap_answer(mp, twice);
3323 if (response_type == RESPONSE_CONT)
3324 break;
3326 if (ok == STOP) {
3327 if (twice++ == 0 && fseek(fp, offs, SEEK_SET) >= 0)
3328 goto trycreate;
3329 goto fail;
3331 while (octets > 0) {
3332 size_t n = (UICMP(z, octets, >, sizeof iob)
3333 ? sizeof iob : (size_t)octets);
3334 octets -= n;
3335 if (n != fread(iob, 1, n, fp))
3336 goto fail;
3337 swrite1(&mp->mb_sock, iob, n, 1);
3339 swrite(&mp->mb_sock, "");
3340 while (mp->mb_active & MB_COMD) {
3341 ok = imap_answer(mp, 0);
3342 if (response_status == RESPONSE_NO && twice++ == 0) {
3343 if (fseek(fp, offs, SEEK_SET) < 0)
3344 goto fail;
3345 goto trycreate;
3348 if (response_status == RESPONSE_OK && mp->mb_flags & MB_UIDPLUS) {
3349 if ((offs2 = ftell(fp)) < 0)
3350 goto fail;
3351 fseek(fp, offs1, SEEK_SET);
3352 if (imap_appenduid_cached(mp, fp) == STOP) {
3353 (void)fseek(fp, offs2, SEEK_SET);
3354 goto fail;
3357 } else {
3358 fail:
3359 fprintf(stderr, "Invalid command in IMAP cache queue: \"%s\"\n", bp);
3360 rok = STOP;
3362 continue;
3363 trycreate:
3364 snprintf(o, sizeof o, "%s CREATE %s\r\n", tag(1), newname);
3365 IMAP_OUT(o, MB_COMD, continue)
3366 while (mp->mb_active & MB_COMD)
3367 ok = imap_answer(mp, 1);
3368 if (ok == OKAY)
3369 goto again;
3371 fflush(fp);
3372 rewind(fp);
3373 ftruncate(fileno(fp), 0);
3374 if (gotcha)
3375 imap_close(mp);
3376 free(buf);
3377 return rok;
3380 static char *
3381 imap_strex(char const *cp, char const **xp)
3383 char const *cq;
3384 char *n = NULL;
3385 NYD_ENTER;
3387 if (*cp != '"')
3388 goto jleave;
3390 for (cq = cp + 1; *cq != '\0'; ++cq) {
3391 if (*cq == '\\')
3392 cq++;
3393 else if (*cq == '"')
3394 break;
3396 if (*cq != '"')
3397 goto jleave;
3399 n = salloc(cq - cp + 2);
3400 memcpy(n, cp, cq - cp +1);
3401 n[cq - cp + 1] = '\0';
3402 if (xp != NULL)
3403 *xp = cq + 1;
3404 jleave:
3405 NYD_LEAVE;
3406 return n;
3409 static enum okay
3410 check_expunged(void)
3412 enum okay rv;
3413 NYD_ENTER;
3415 if (expunged_messages > 0) {
3416 fprintf(stderr, "Command not executed - messages have been expunged\n");
3417 rv = STOP;
3418 } else
3419 rv = OKAY;
3420 NYD_LEAVE;
3421 return rv;
3424 FL int
3425 c_connect(void *vp) /* TODO v15-compat mailname<->URL (with password) */
3427 struct url url;
3428 int rv, omsgCount = msgCount;
3429 NYD_ENTER;
3430 UNUSED(vp);
3432 if (mb.mb_type == MB_IMAP && mb.mb_sock.s_fd > 0) {
3433 fprintf(stderr, "Already connected.\n");
3434 rv = 1;
3435 goto jleave;
3438 if (!url_parse(&url, CPROTO_IMAP, mailname)) {
3439 rv = 1;
3440 goto jleave;
3442 var_clear_allow_undefined = TRU1;
3443 ok_bclear(disconnected);
3444 vok_bclear(savecat("disconnected-", url.url_u_h_p.s));
3445 var_clear_allow_undefined = FAL0;
3447 if (mb.mb_type == MB_CACHE) {
3448 enum fedit_mode fm = FEDIT_NONE;
3449 if (_imap_rdonly)
3450 fm |= FEDIT_RDONLY;
3451 if (!edit)
3452 fm |= FEDIT_SYSBOX;
3453 _imap_setfile1(&url, fm, 1);
3454 if (msgCount > omsgCount)
3455 newmailinfo(omsgCount);
3457 rv = 0;
3458 jleave:
3459 NYD_LEAVE;
3460 return rv;
3463 FL int
3464 c_disconnect(void *vp) /* TODO v15-compat mailname<->URL (with password) */
3466 struct url url;
3467 int rv = 1, *msgvec = vp;
3468 NYD_ENTER;
3470 if (mb.mb_type == MB_CACHE) {
3471 fprintf(stderr, "Not connected.\n");
3472 goto jleave;
3474 if (mb.mb_type != MB_IMAP || cached_uidvalidity(&mb) == 0) {
3475 fprintf(stderr, "The current mailbox is not cached.\n");
3476 goto jleave;
3479 if (!url_parse(&url, CPROTO_IMAP, mailname))
3480 goto jleave;
3482 if (*msgvec)
3483 c_cache(vp);
3484 ok_bset(disconnected, TRU1);
3485 if (mb.mb_type == MB_IMAP) {
3486 enum fedit_mode fm = FEDIT_NONE;
3487 if (_imap_rdonly)
3488 fm |= FEDIT_RDONLY;
3489 if (!edit)
3490 fm |= FEDIT_SYSBOX;
3491 sclose(&mb.mb_sock);
3492 _imap_setfile1(&url, fm, 1);
3494 rv = 0;
3495 jleave:
3496 NYD_LEAVE;
3497 return rv;
3500 FL int
3501 c_cache(void *vp)
3503 int rv = 1, *msgvec = vp, *ip;
3504 struct message *mp;
3505 NYD_ENTER;
3507 if (mb.mb_type != MB_IMAP) {
3508 fprintf(stderr, "Not connected to an IMAP server.\n");
3509 goto jleave;
3511 if (cached_uidvalidity(&mb) == 0) {
3512 fprintf(stderr, "The current mailbox is not cached.\n");
3513 goto jleave;
3516 for (ip = msgvec; *ip; ++ip) {
3517 mp = &message[*ip - 1];
3518 if (!(mp->m_have & HAVE_BODY))
3519 get_body(mp);
3521 rv = 0;
3522 jleave:
3523 NYD_LEAVE;
3524 return rv;
3527 FL int
3528 disconnected(const char *file)
3530 struct url url;
3531 int rv = 1;
3532 NYD_ENTER;
3534 if (ok_blook(disconnected)) {
3535 rv = 1;
3536 goto jleave;
3539 if (!url_parse(&url, CPROTO_IMAP, file)) {
3540 rv = 0;
3541 goto jleave;
3543 rv = vok_blook(savecat("disconnected-", url.url_u_h_p.s));
3545 jleave:
3546 NYD_LEAVE;
3547 return rv;
3550 FL void
3551 transflags(struct message *omessage, long omsgCount, int transparent)
3553 struct message *omp, *nmp, *newdot, *newprevdot;
3554 int hf;
3555 NYD_ENTER;
3557 omp = omessage;
3558 nmp = message;
3559 newdot = message;
3560 newprevdot = NULL;
3561 while (PTRCMP(omp, <, omessage + omsgCount) &&
3562 PTRCMP(nmp, <, message + msgCount)) {
3563 if (dot && nmp->m_uid == dot->m_uid)
3564 newdot = nmp;
3565 if (prevdot && nmp->m_uid == prevdot->m_uid)
3566 newprevdot = nmp;
3567 if (omp->m_uid == nmp->m_uid) {
3568 hf = nmp->m_flag & MHIDDEN;
3569 if (transparent && mb.mb_type == MB_IMAP)
3570 omp->m_flag &= ~MHIDDEN;
3571 *nmp++ = *omp++;
3572 if (transparent && mb.mb_type == MB_CACHE)
3573 nmp[-1].m_flag |= hf;
3574 } else if (omp->m_uid < nmp->m_uid)
3575 ++omp;
3576 else
3577 ++nmp;
3579 dot = newdot;
3580 setdot(newdot);
3581 prevdot = newprevdot;
3582 free(omessage);
3583 NYD_LEAVE;
3586 FL time_t
3587 imap_read_date_time(const char *cp)
3589 char buf[3];
3590 time_t t;
3591 int i, year, month, day, hour, minute, second, sign = -1;
3592 NYD2_ENTER;
3594 /* "25-Jul-2004 15:33:44 +0200"
3595 * | | | | | |
3596 * 0 5 10 15 20 25 */
3597 if (cp[0] != '"' || strlen(cp) < 28 || cp[27] != '"')
3598 goto jinvalid;
3599 day = strtol(&cp[1], NULL, 10);
3600 for (i = 0;;) {
3601 if (ascncasecmp(&cp[4], month_names[i], 3) == 0)
3602 break;
3603 if (month_names[++i][0] == '\0')
3604 goto jinvalid;
3606 month = i + 1;
3607 year = strtol(&cp[8], NULL, 10);
3608 hour = strtol(&cp[13], NULL, 10);
3609 minute = strtol(&cp[16], NULL, 10);
3610 second = strtol(&cp[19], NULL, 10);
3611 if ((t = combinetime(year, month, day, hour, minute, second)) == (time_t)-1)
3612 goto jinvalid;
3613 switch (cp[22]) {
3614 case '-':
3615 sign = 1;
3616 break;
3617 case '+':
3618 break;
3619 default:
3620 goto jinvalid;
3622 buf[2] = '\0';
3623 buf[0] = cp[23];
3624 buf[1] = cp[24];
3625 t += strtol(buf, NULL, 10) * sign * 3600;
3626 buf[0] = cp[25];
3627 buf[1] = cp[26];
3628 t += strtol(buf, NULL, 10) * sign * 60;
3629 jleave:
3630 NYD2_LEAVE;
3631 return t;
3632 jinvalid:
3633 time(&t);
3634 goto jleave;
3637 FL const char *
3638 imap_make_date_time(time_t t)
3640 static char s[30];
3641 struct tm *tmptr;
3642 int tzdiff, tzdiff_hour, tzdiff_min;
3643 NYD2_ENTER;
3645 tzdiff = t - mktime(gmtime(&t));
3646 tzdiff_hour = (int)(tzdiff / 60);
3647 tzdiff_min = tzdiff_hour % 60;
3648 tzdiff_hour /= 60;
3649 tmptr = localtime(&t);
3650 if (tmptr->tm_isdst > 0)
3651 tzdiff_hour++;
3652 snprintf(s, sizeof s, "\"%02d-%s-%04d %02d:%02d:%02d %+03d%02d\"",
3653 tmptr->tm_mday, month_names[tmptr->tm_mon], tmptr->tm_year + 1900,
3654 tmptr->tm_hour, tmptr->tm_min, tmptr->tm_sec, tzdiff_hour, tzdiff_min);
3655 NYD2_LEAVE;
3656 return s;
3658 #endif /* HAVE_IMAP */
3660 #if defined HAVE_IMAP || defined HAVE_IMAP_SEARCH
3661 FL char *
3662 imap_quotestr(char const *s)
3664 char *n, *np;
3665 NYD2_ENTER;
3667 np = n = salloc(2 * strlen(s) + 3);
3668 *np++ = '"';
3669 while (*s) {
3670 if (*s == '"' || *s == '\\')
3671 *np++ = '\\';
3672 *np++ = *s++;
3674 *np++ = '"';
3675 *np = '\0';
3676 NYD2_LEAVE;
3677 return n;
3680 FL char *
3681 imap_unquotestr(char const *s)
3683 char *n, *np;
3684 NYD2_ENTER;
3686 if (*s != '"') {
3687 n = savestr(s);
3688 goto jleave;
3691 np = n = salloc(strlen(s) + 1);
3692 while (*++s) {
3693 if (*s == '\\')
3694 s++;
3695 else if (*s == '"')
3696 break;
3697 *np++ = *s;
3699 *np = '\0';
3700 jleave:
3701 NYD2_LEAVE;
3702 return n;
3704 #endif /* defined HAVE_IMAP || defined HAVE_IMAP_SEARCH */
3706 /* s-it-mode */