GSS-API: fix amalgamation compilation on old OpenBSD
[s-mailx.git] / imap.c
blob5772066bb20ced0ca42ecdc5d23bb07b738d804b
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 srelax_hold();
1060 for (n = X; n <= Y; ++n) {
1061 putcache(mp, &message[n-1]);
1062 srelax();
1064 srelax_rele();
1065 return OKAY;
1068 static void
1069 imap_init(struct mailbox *mp, int n)
1071 struct message *m;
1072 NYD_ENTER;
1073 UNUSED(mp);
1075 m = message + n;
1076 m->m_flag = MUSED | MNOFROM;
1077 m->m_block = 0;
1078 m->m_offset = 0;
1079 NYD_LEAVE;
1082 static void
1083 imap_setptr(struct mailbox *mp, int nmail, int transparent, int *prevcount)
1085 struct message *omessage = 0;
1086 int i, omsgCount = 0;
1087 enum okay dequeued = STOP;
1088 NYD_ENTER;
1090 if (nmail || transparent) {
1091 omessage = message;
1092 omsgCount = msgCount;
1094 if (nmail)
1095 dequeued = rec_dequeue();
1097 if (had_exists >= 0) {
1098 if (dequeued != OKAY)
1099 msgCount = had_exists;
1100 had_exists = -1;
1102 if (had_expunge >= 0) {
1103 if (dequeued != OKAY)
1104 msgCount -= had_expunge;
1105 had_expunge = -1;
1108 if (nmail && expunged_messages)
1109 printf("Expunged %ld message%s.\n", expunged_messages,
1110 (expunged_messages != 1 ? "s" : ""));
1111 *prevcount = omsgCount - expunged_messages;
1112 expunged_messages = 0;
1113 if (msgCount < 0) {
1114 fputs("IMAP error: Negative message count\n", stderr);
1115 msgCount = 0;
1118 if (dequeued != OKAY) {
1119 message = scalloc(msgCount + 1, sizeof *message);
1120 for (i = 0; i < msgCount; i++)
1121 imap_init(mp, i);
1122 if (!nmail && mp->mb_type == MB_IMAP)
1123 initcache(mp);
1124 if (msgCount > 0)
1125 imap_flags(mp, 1, msgCount);
1126 message[msgCount].m_size = 0;
1127 message[msgCount].m_lines = 0;
1128 rec_rmqueue();
1130 if (nmail || transparent)
1131 transflags(omessage, omsgCount, transparent);
1132 else
1133 setdot(message);
1134 NYD_LEAVE;
1137 FL int
1138 imap_setfile(const char *xserver, enum fedit_mode fm)
1140 struct url url;
1141 int rv;
1142 NYD_ENTER;
1144 if (!url_parse(&url, CPROTO_IMAP, xserver)) {
1145 rv = 1;
1146 goto jleave;
1148 if (!ok_blook(v15_compat) &&
1149 (!url.url_had_user || url.url_pass.s != NULL))
1150 fprintf(stderr, "New-style URL used without *v15-compat* being set!\n");
1152 _imap_rdonly = ((fm & FEDIT_RDONLY) != 0);
1153 rv = _imap_setfile1(&url, fm, 0);
1154 jleave:
1155 NYD_LEAVE;
1156 return rv;
1159 static bool_t
1160 _imap_getcred(struct mailbox *mbp, struct ccred *ccredp, struct url *urlp)
1162 bool_t rv = FAL0;
1163 NYD_ENTER;
1165 if (ok_blook(v15_compat))
1166 rv = ccred_lookup(ccredp, urlp);
1167 else {
1168 char *var, *old;
1170 if ((var = mbp->mb_imap_pass) != NULL) {
1171 var = savecat("password-", urlp->url_u_h_p.s);
1172 old = vok_vlook(var);
1173 vok_vset(var, mbp->mb_imap_pass);
1175 rv = ccred_lookup_old(ccredp, CPROTO_IMAP, urlp->url_u_h_p.s);
1176 if (var != NULL) {
1177 if (old != NULL)
1178 vok_vset(var, old);
1179 else
1180 vok_vclear(var);
1184 NYD_LEAVE;
1185 return rv;
1188 static int
1189 _imap_setfile1(struct url *urlp, enum fedit_mode fm, int volatile transparent)
1191 struct sock so;
1192 struct ccred ccred;
1193 sighandler_type volatile saveint, savepipe;
1194 char const *cp;
1195 int rv;
1196 int volatile prevcount = 0;
1197 enum mbflags same_flags;
1198 NYD_ENTER;
1200 if (fm & FEDIT_NEWMAIL) {
1201 saveint = safe_signal(SIGINT, SIG_IGN);
1202 savepipe = safe_signal(SIGPIPE, SIG_IGN);
1203 if (saveint != SIG_IGN)
1204 safe_signal(SIGINT, imapcatch);
1205 if (savepipe != SIG_IGN)
1206 safe_signal(SIGPIPE, imapcatch);
1207 imaplock = 1;
1208 goto jnmail;
1211 same_flags = mb.mb_flags;
1212 same_imap_account = 0;
1213 if (mb.mb_imap_account != NULL &&
1214 (mb.mb_type == MB_IMAP || mb.mb_type == MB_CACHE)) {
1215 if (mb.mb_sock.s_fd > 0 && mb.mb_sock.s_rsz >= 0 &&
1216 !strcmp(mb.mb_imap_account, urlp->url_p_eu_h_p) &&
1217 disconnected(mb.mb_imap_account) == 0) {
1218 same_imap_account = 1;
1219 if (urlp->url_pass.s == NULL && mb.mb_imap_pass != NULL)
1220 goto jduppass;
1221 } else if ((transparent || mb.mb_type == MB_CACHE) &&
1222 !strcmp(mb.mb_imap_account, urlp->url_p_eu_h_p) &&
1223 urlp->url_pass.s == NULL && mb.mb_imap_pass != NULL)
1224 jduppass:
1225 urlp->url_pass.l = strlen(urlp->url_pass.s = savestr(mb.mb_imap_pass));
1228 if (!_imap_getcred(&mb, &ccred, urlp)) {
1229 rv = -1;
1230 goto jleave;
1233 so.s_fd = -1;
1234 if (!same_imap_account) {
1235 if (!disconnected(urlp->url_p_eu_h_p) && !sopen(&so, urlp)) {
1236 rv = -1;
1237 goto jleave;
1239 } else
1240 so = mb.mb_sock;
1241 if (!transparent)
1242 quit();
1244 edit = !(fm & FEDIT_SYSBOX);
1245 if (mb.mb_imap_account != NULL)
1246 free(mb.mb_imap_account);
1247 if (mb.mb_imap_pass != NULL)
1248 free(mb.mb_imap_pass);
1249 mb.mb_imap_account = sstrdup(urlp->url_p_eu_h_p);
1250 /* TODO This is a hack to allow '@boxname'; in the end everything will be an
1251 * TODO object, and mailbox will naturally have an URL and credentials */
1252 mb.mb_imap_pass = sbufdup(ccred.cc_pass.s, ccred.cc_pass.l);
1254 if (!same_imap_account) {
1255 if (mb.mb_sock.s_fd >= 0)
1256 sclose(&mb.mb_sock);
1258 same_imap_account = 0;
1260 if (!transparent) {
1261 if (mb.mb_itf) {
1262 fclose(mb.mb_itf);
1263 mb.mb_itf = NULL;
1265 if (mb.mb_otf) {
1266 fclose(mb.mb_otf);
1267 mb.mb_otf = NULL;
1269 if (mb.mb_imap_mailbox != NULL)
1270 free(mb.mb_imap_mailbox);
1271 mb.mb_imap_mailbox = sstrdup((urlp->url_path.s != NULL)
1272 ? urlp->url_path.s : "INBOX");
1273 initbox(urlp->url_p_eu_h_p_p);
1275 mb.mb_type = MB_VOID;
1276 mb.mb_active = MB_NONE;
1278 imaplock = 1;
1279 saveint = safe_signal(SIGINT, SIG_IGN);
1280 savepipe = safe_signal(SIGPIPE, SIG_IGN);
1281 if (sigsetjmp(imapjmp, 1)) {
1282 /* Not safe to use &so; save to use mb.mb_sock?? :-( TODO */
1283 sclose(&mb.mb_sock);
1284 safe_signal(SIGINT, saveint);
1285 safe_signal(SIGPIPE, savepipe);
1286 imaplock = 0;
1288 mb.mb_type = MB_VOID;
1289 mb.mb_active = MB_NONE;
1290 rv = -1;
1291 goto jleave;
1293 if (saveint != SIG_IGN)
1294 safe_signal(SIGINT, imapcatch);
1295 if (savepipe != SIG_IGN)
1296 safe_signal(SIGPIPE, imapcatch);
1298 if (mb.mb_sock.s_fd < 0) {
1299 if (disconnected(mb.mb_imap_account)) {
1300 if (cache_setptr(fm, transparent) == STOP)
1301 fprintf(stderr, "Mailbox \"%s\" is not cached.\n",
1302 urlp->url_p_eu_h_p_p);
1303 goto jdone;
1305 if ((cp = ok_vlook(imap_keepalive)) != NULL) {
1306 if ((imapkeepalive = strtol(cp, NULL, 10)) > 0) {
1307 savealrm = safe_signal(SIGALRM, imapalarm);
1308 alarm(imapkeepalive);
1312 mb.mb_sock = so;
1313 mb.mb_sock.s_desc = "IMAP";
1314 mb.mb_sock.s_onclose = imap_timer_off;
1315 if (imap_preauth(&mb, urlp->url_h_p.s, urlp->url_u_h_p.s) != OKAY ||
1316 imap_auth(&mb, &ccred) != OKAY) {
1317 sclose(&mb.mb_sock);
1318 imap_timer_off();
1319 safe_signal(SIGINT, saveint);
1320 safe_signal(SIGPIPE, savepipe);
1321 imaplock = 0;
1322 rv = -1;
1323 goto jleave;
1325 } else /* same account */
1326 mb.mb_flags |= same_flags;
1328 mb.mb_perm = ((options & OPT_R_FLAG) || (fm & FEDIT_RDONLY)) ? 0 : MB_DELE;
1329 mb.mb_type = MB_IMAP;
1330 cache_dequeue(&mb);
1331 if (imap_select(&mb, &mailsize, &msgCount,
1332 (urlp->url_path.s != NULL ? urlp->url_path.s : "INBOX")) != OKAY) {
1333 /*sclose(&mb.mb_sock);
1334 imap_timer_off();*/
1335 safe_signal(SIGINT, saveint);
1336 safe_signal(SIGPIPE, savepipe);
1337 imaplock = 0;
1338 mb.mb_type = MB_VOID;
1339 rv = -1;
1340 goto jleave;
1343 jnmail:
1344 imap_setptr(&mb, ((fm & FEDIT_NEWMAIL) != 0), transparent,
1345 UNVOLATILE(&prevcount));
1346 jdone:
1347 setmsize(msgCount);
1348 if (!(fm & FEDIT_NEWMAIL) && !transparent)
1349 sawcom = FAL0;
1350 safe_signal(SIGINT, saveint);
1351 safe_signal(SIGPIPE, savepipe);
1352 imaplock = 0;
1354 if (!(fm & FEDIT_NEWMAIL) && mb.mb_type == MB_IMAP)
1355 purgecache(&mb, message, msgCount);
1356 if (((fm & FEDIT_NEWMAIL) || transparent) && mb.mb_sorted) {
1357 mb.mb_threaded = 0;
1358 c_sort((void*)-1);
1361 if (!(fm & FEDIT_NEWMAIL) && !edit && msgCount == 0) {
1362 if ((mb.mb_type == MB_IMAP || mb.mb_type == MB_CACHE) &&
1363 !ok_blook(emptystart))
1364 fprintf(stderr, _("No mail at %s\n"), urlp->url_p_eu_h_p_p);
1365 rv = 1;
1366 goto jleave;
1368 if (fm & FEDIT_NEWMAIL)
1369 newmailinfo(prevcount);
1370 rv = 0;
1371 jleave:
1372 NYD_LEAVE;
1373 return rv;
1376 static int
1377 imap_fetchdata(struct mailbox *mp, struct message *m, size_t expected,
1378 int need, const char *head, size_t headsize, long headlines)
1380 char *line = NULL, *lp;
1381 size_t linesize = 0, linelen, size = 0;
1382 int emptyline = 0, lines = 0, excess = 0;
1383 off_t offset;
1384 NYD_ENTER;
1386 fseek(mp->mb_otf, 0L, SEEK_END);
1387 offset = ftell(mp->mb_otf);
1389 if (head)
1390 fwrite(head, 1, headsize, mp->mb_otf);
1392 while (sgetline(&line, &linesize, &linelen, &mp->mb_sock) > 0) {
1393 lp = line;
1394 if (linelen > expected) {
1395 excess = linelen - expected;
1396 linelen = expected;
1398 /* TODO >>
1399 * Need to mask 'From ' lines. This cannot be done properly
1400 * since some servers pass them as 'From ' and others as
1401 * '>From '. Although one could identify the first kind of
1402 * server in principle, it is not possible to identify the
1403 * second as '>From ' may also come from a server of the
1404 * first type as actual data. So do what is absolutely
1405 * necessary only - mask 'From '.
1407 * If the line is the first line of the message header, it
1408 * is likely a real 'From ' line. In this case, it is just
1409 * ignored since it violates all standards.
1410 * TODO can the latter *really* happen??
1411 * TODO <<
1413 /* Since we simply copy over data without doing any transfer
1414 * encoding reclassification/adjustment we *have* to perform
1415 * RFC 4155 compliant From_ quoting here */
1416 if (is_head(lp, linelen)) {
1417 if (lines + headlines == 0)
1418 goto jskip;
1419 fputc('>', mp->mb_otf);
1420 ++size;
1422 if (lp[linelen-1] == '\n' && (linelen == 1 || lp[linelen-2] == '\r')) {
1423 emptyline = linelen <= 2;
1424 if (linelen > 2) {
1425 fwrite(lp, 1, linelen - 2, mp->mb_otf);
1426 size += linelen - 1;
1427 } else
1428 ++size;
1429 fputc('\n', mp->mb_otf);
1430 } else {
1431 emptyline = 0;
1432 fwrite(lp, 1, linelen, mp->mb_otf);
1433 size += linelen;
1435 ++lines;
1436 jskip:
1437 if ((expected -= linelen) <= 0)
1438 break;
1440 if (!emptyline) {
1441 /* This is very ugly; but some IMAP daemons don't end a
1442 * message with \r\n\r\n, and we need \n\n for mbox format */
1443 fputc('\n', mp->mb_otf);
1444 ++lines;
1445 ++size;
1447 fflush(mp->mb_otf);
1449 if (m != NULL) {
1450 m->m_size = size + headsize;
1451 m->m_lines = lines + headlines;
1452 m->m_block = mailx_blockof(offset);
1453 m->m_offset = mailx_offsetof(offset);
1454 switch (need) {
1455 case NEED_HEADER:
1456 m->m_have |= HAVE_HEADER;
1457 break;
1458 case NEED_BODY:
1459 m->m_have |= HAVE_HEADER | HAVE_BODY;
1460 m->m_xlines = m->m_lines;
1461 m->m_xsize = m->m_size;
1462 break;
1465 free(line);
1466 NYD_LEAVE;
1467 return excess;
1470 static void
1471 imap_putstr(struct mailbox *mp, struct message *m, const char *str,
1472 const char *head, size_t headsize, long headlines)
1474 off_t offset;
1475 size_t len;
1476 NYD_ENTER;
1478 len = strlen(str);
1479 fseek(mp->mb_otf, 0L, SEEK_END);
1480 offset = ftell(mp->mb_otf);
1481 if (head)
1482 fwrite(head, 1, headsize, mp->mb_otf);
1483 if (len > 0) {
1484 fwrite(str, 1, len, mp->mb_otf);
1485 fputc('\n', mp->mb_otf);
1486 ++len;
1488 fflush(mp->mb_otf);
1490 if (m != NULL) {
1491 m->m_size = headsize + len;
1492 m->m_lines = headlines + 1;
1493 m->m_block = mailx_blockof(offset);
1494 m->m_offset = mailx_offsetof(offset);
1495 m->m_have |= HAVE_HEADER | HAVE_BODY;
1496 m->m_xlines = m->m_lines;
1497 m->m_xsize = m->m_size;
1499 NYD_LEAVE;
1502 static enum okay
1503 imap_get(struct mailbox *mp, struct message *m, enum needspec need)
1505 char o[LINESIZE];
1506 struct message mt;
1507 sighandler_type volatile saveint, savepipe;
1508 char * volatile head;
1509 char const *cp, *loc, * volatile item, * volatile resp;
1510 size_t expected;
1511 size_t volatile headsize;
1512 int number;
1513 FILE *queuefp;
1514 long volatile headlines;
1515 long n;
1516 ul_it volatile u;
1517 enum okay ok;
1518 NYD_X;
1520 saveint = savepipe = SIG_IGN;
1521 head = NULL;
1522 cp = loc = item = resp = NULL;
1523 headsize = 0;
1524 number = (int)PTR2SIZE(m - message + 1);
1525 queuefp = NULL;
1526 headlines = 0;
1527 n = -1;
1528 u = 0;
1529 ok = STOP;
1531 if (getcache(mp, m, need) == OKAY)
1532 return OKAY;
1533 if (mp->mb_type == MB_CACHE) {
1534 fprintf(stderr, "Message %u not available.\n", number);
1535 return STOP;
1538 if (mp->mb_sock.s_fd < 0) {
1539 fprintf(stderr, "IMAP connection closed.\n");
1540 return STOP;
1543 switch (need) {
1544 case NEED_HEADER:
1545 resp = item = "RFC822.HEADER";
1546 break;
1547 case NEED_BODY:
1548 item = "BODY.PEEK[]";
1549 resp = "BODY[]";
1550 if (m->m_flag & HAVE_HEADER && m->m_size) {
1551 char *hdr = smalloc(m->m_size);
1552 fflush(mp->mb_otf);
1553 if (fseek(mp->mb_itf, (long)mailx_positionof(m->m_block, m->m_offset),
1554 SEEK_SET) < 0 ||
1555 fread(hdr, 1, m->m_size, mp->mb_itf) != m->m_size) {
1556 free(hdr);
1557 break;
1559 head = hdr;
1560 headsize = m->m_size;
1561 headlines = m->m_lines;
1562 item = "BODY.PEEK[TEXT]";
1563 resp = "BODY[TEXT]";
1565 break;
1566 case NEED_UNSPEC:
1567 return STOP;
1570 imaplock = 1;
1571 savepipe = safe_signal(SIGPIPE, SIG_IGN);
1572 if (sigsetjmp(imapjmp, 1)) {
1573 safe_signal(SIGINT, saveint);
1574 safe_signal(SIGPIPE, savepipe);
1575 imaplock = 0;
1576 return STOP;
1578 if ((saveint = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN)
1579 safe_signal(SIGINT, &_imap_maincatch);
1580 if (savepipe != SIG_IGN)
1581 safe_signal(SIGPIPE, imapcatch);
1583 if (m->m_uid)
1584 snprintf(o, sizeof o, "%s UID FETCH %lu (%s)\r\n",
1585 tag(1), m->m_uid, item);
1586 else {
1587 if (check_expunged() == STOP)
1588 goto out;
1589 snprintf(o, sizeof o, "%s FETCH %u (%s)\r\n", tag(1), number, item);
1591 IMAP_OUT(o, MB_COMD, goto out)
1592 for (;;) {
1593 ok = imap_answer(mp, 1);
1594 if (ok == STOP)
1595 break;
1596 if (response_status != RESPONSE_OTHER ||
1597 response_other != MESSAGE_DATA_FETCH)
1598 continue;
1599 if ((loc = asccasestr(responded_other_text, resp)) == NULL)
1600 continue;
1601 if (m->m_uid) {
1602 if ((cp = asccasestr(responded_other_text, "UID "))) {
1603 u = atol(&cp[4]);
1604 n = 0;
1605 } else {
1606 n = -1;
1607 u = 0;
1609 } else
1610 n = responded_other_number;
1611 if ((cp = strrchr(responded_other_text, '{')) == NULL) {
1612 if (m->m_uid ? m->m_uid != u : n != number)
1613 continue;
1614 if ((cp = strchr(loc, '"')) != NULL) {
1615 cp = imap_unquotestr(cp);
1616 imap_putstr(mp, m, cp, head, headsize, headlines);
1617 } else {
1618 m->m_have |= HAVE_HEADER|HAVE_BODY;
1619 m->m_xlines = m->m_lines;
1620 m->m_xsize = m->m_size;
1622 goto out;
1624 expected = atol(&cp[1]);
1625 if (m->m_uid ? n == 0 && m->m_uid != u : n != number) {
1626 imap_fetchdata(mp, NULL, expected, need, NULL, 0, 0);
1627 continue;
1629 mt = *m;
1630 imap_fetchdata(mp, &mt, expected, need, head, headsize, headlines);
1631 if (n >= 0) {
1632 commitmsg(mp, m, &mt, mt.m_have);
1633 break;
1635 if (n == -1 && sgetline(&imapbuf, &imapbufsize, NULL, &mp->mb_sock) > 0) {
1636 if (options & OPT_VERBVERB)
1637 fputs(imapbuf, stderr);
1638 if ((cp = asccasestr(imapbuf, "UID ")) != NULL) {
1639 u = atol(&cp[4]);
1640 if (u == m->m_uid) {
1641 commitmsg(mp, m, &mt, mt.m_have);
1642 break;
1647 out:
1648 while (mp->mb_active & MB_COMD)
1649 ok = imap_answer(mp, 1);
1651 if (saveint != SIG_IGN)
1652 safe_signal(SIGINT, saveint);
1653 if (savepipe != SIG_IGN)
1654 safe_signal(SIGPIPE, savepipe);
1655 imaplock--;
1657 if (ok == OKAY)
1658 putcache(mp, m);
1659 if (head != NULL)
1660 free(head);
1661 if (interrupts)
1662 onintr(0);
1663 return ok;
1666 FL enum okay
1667 imap_header(struct message *m)
1669 enum okay rv;
1670 NYD_ENTER;
1672 rv = imap_get(&mb, m, NEED_HEADER);
1673 NYD_LEAVE;
1674 return rv;
1678 FL enum okay
1679 imap_body(struct message *m)
1681 enum okay rv;
1682 NYD_ENTER;
1684 rv = imap_get(&mb, m, NEED_BODY);
1685 NYD_LEAVE;
1686 return rv;
1689 static void
1690 commitmsg(struct mailbox *mp, struct message *tomp, struct message *frommp,
1691 enum havespec have)
1693 NYD_ENTER;
1694 tomp->m_size = frommp->m_size;
1695 tomp->m_lines = frommp->m_lines;
1696 tomp->m_block = frommp->m_block;
1697 tomp->m_offset = frommp->m_offset;
1698 tomp->m_have = have;
1699 if (have & HAVE_BODY) {
1700 tomp->m_xlines = frommp->m_lines;
1701 tomp->m_xsize = frommp->m_size;
1703 putcache(mp, tomp);
1704 NYD_LEAVE;
1707 static enum okay
1708 imap_fetchheaders(struct mailbox *mp, struct message *m, int bot, int topp)
1710 /* bot > topp */
1711 char o[LINESIZE];
1712 char const *cp;
1713 struct message mt;
1714 size_t expected;
1715 int n = 0, u;
1716 FILE *queuefp = NULL;
1717 enum okay ok;
1718 NYD_X;
1720 if (m[bot].m_uid)
1721 snprintf(o, sizeof o, "%s UID FETCH %lu:%lu (RFC822.HEADER)\r\n",
1722 tag(1), m[bot-1].m_uid, m[topp-1].m_uid);
1723 else {
1724 if (check_expunged() == STOP)
1725 return STOP;
1726 snprintf(o, sizeof o, "%s FETCH %u:%u (RFC822.HEADER)\r\n",
1727 tag(1), bot, topp);
1729 IMAP_OUT(o, MB_COMD, return STOP)
1731 srelax_hold();
1732 for (;;) {
1733 ok = imap_answer(mp, 1);
1734 if (response_status != RESPONSE_OTHER)
1735 break;
1736 if (response_other != MESSAGE_DATA_FETCH)
1737 continue;
1738 if (ok == STOP || (cp=strrchr(responded_other_text, '{')) == 0)
1739 return STOP;
1740 if (asccasestr(responded_other_text, "RFC822.HEADER") == NULL)
1741 continue;
1742 expected = atol(&cp[1]);
1743 if (m[bot-1].m_uid) {
1744 if ((cp = asccasestr(responded_other_text, "UID ")) != NULL) {
1745 u = atoi(&cp[4]);
1746 for (n = bot; n <= topp; n++)
1747 if ((unsigned long)u == m[n-1].m_uid)
1748 break;
1749 if (n > topp) {
1750 imap_fetchdata(mp, NULL, expected, NEED_HEADER, NULL, 0, 0);
1751 continue;
1753 } else
1754 n = -1;
1755 } else {
1756 n = responded_other_number;
1757 if (n <= 0 || n > msgCount) {
1758 imap_fetchdata(mp, NULL, expected, NEED_HEADER, NULL, 0, 0);
1759 continue;
1762 imap_fetchdata(mp, &mt, expected, NEED_HEADER, NULL, 0, 0);
1763 if (n >= 0 && !(m[n-1].m_have & HAVE_HEADER))
1764 commitmsg(mp, &m[n-1], &mt, HAVE_HEADER);
1765 if (n == -1 && sgetline(&imapbuf, &imapbufsize, NULL, &mp->mb_sock) > 0) {
1766 if (options & OPT_VERBVERB)
1767 fputs(imapbuf, stderr);
1768 if ((cp = asccasestr(imapbuf, "UID ")) != NULL) {
1769 u = atoi(&cp[4]);
1770 for (n = bot; n <= topp; n++)
1771 if ((unsigned long)u == m[n-1].m_uid)
1772 break;
1773 if (n <= topp && !(m[n-1].m_have & HAVE_HEADER))
1774 commitmsg(mp, &m[n-1], &mt,HAVE_HEADER);
1775 n = 0;
1778 srelax();
1780 srelax_rele();
1782 while (mp->mb_active & MB_COMD)
1783 ok = imap_answer(mp, 1);
1784 return ok;
1787 FL void
1788 imap_getheaders(int volatile bot, int volatile topp) /* TODO iterator!! */
1790 sighandler_type saveint, savepipe;
1791 /*enum okay ok = STOP;*/
1792 int i, chunk = 256;
1793 NYD_X;
1795 if (mb.mb_type == MB_CACHE)
1796 return;
1797 if (bot < 1)
1798 bot = 1;
1799 if (topp > msgCount)
1800 topp = msgCount;
1801 for (i = bot; i < topp; i++) {
1802 if (message[i-1].m_have & HAVE_HEADER ||
1803 getcache(&mb, &message[i-1], NEED_HEADER) == OKAY)
1804 bot = i+1;
1805 else
1806 break;
1808 for (i = topp; i > bot; i--) {
1809 if (message[i-1].m_have & HAVE_HEADER ||
1810 getcache(&mb, &message[i-1], NEED_HEADER) == OKAY)
1811 topp = i-1;
1812 else
1813 break;
1815 if (bot >= topp)
1816 return;
1818 imaplock = 1;
1819 if ((saveint = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN)
1820 safe_signal(SIGINT, &_imap_maincatch);
1821 savepipe = safe_signal(SIGPIPE, SIG_IGN);
1822 if (sigsetjmp(imapjmp, 1) == 0) {
1823 if (savepipe != SIG_IGN)
1824 safe_signal(SIGPIPE, imapcatch);
1826 for (i = bot; i <= topp; i += chunk) {
1827 int j = i + chunk - 1;
1828 j = MIN(j, topp);
1829 if (visible(message + j))
1830 /*ok = */imap_fetchheaders(&mb, message, i, j);
1831 if (interrupts)
1832 onintr(0); /* XXX imaplock? */
1835 safe_signal(SIGINT, saveint);
1836 safe_signal(SIGPIPE, savepipe);
1837 imaplock = 0;
1840 static enum okay
1841 __imap_exit(struct mailbox *mp)
1843 char o[LINESIZE];
1844 FILE *queuefp = NULL;
1845 NYD_X;
1847 mp->mb_active |= MB_BYE;
1848 snprintf(o, sizeof o, "%s LOGOUT\r\n", tag(1));
1849 IMAP_OUT(o, MB_COMD, return STOP)
1850 IMAP_ANSWER()
1851 return OKAY;
1854 static enum okay
1855 imap_exit(struct mailbox *mp)
1857 enum okay rv;
1858 NYD_ENTER;
1860 rv = __imap_exit(mp);
1861 #if 0 /* TODO the option today: memory leak(s) and halfway reuse or nottin */
1862 free(mp->mb_imap_pass);
1863 free(mp->mb_imap_account);
1864 free(mp->mb_imap_mailbox);
1865 if (mp->mb_cache_directory != NULL)
1866 free(mp->mb_cache_directory);
1867 #ifndef HAVE_DEBUG /* TODO ASSERT LEGACY */
1868 mp->mb_imap_account =
1869 mp->mb_imap_mailbox =
1870 mp->mb_cache_directory = "";
1871 #else
1872 mp->mb_imap_account = NULL; /* for assert legacy time.. */
1873 mp->mb_imap_mailbox = NULL;
1874 mp->mb_cache_directory = NULL;
1875 #endif
1876 #endif
1877 sclose(&mp->mb_sock);
1878 NYD_LEAVE;
1879 return rv;
1882 static enum okay
1883 imap_delete(struct mailbox *mp, int n, struct message *m, int needstat)
1885 NYD_ENTER;
1886 imap_store(mp, m, n, '+', "\\Deleted", needstat);
1887 if (mp->mb_type == MB_IMAP)
1888 delcache(mp, m);
1889 NYD_LEAVE;
1890 return OKAY;
1893 static enum okay
1894 imap_close(struct mailbox *mp)
1896 char o[LINESIZE];
1897 FILE *queuefp = NULL;
1898 NYD_X;
1900 snprintf(o, sizeof o, "%s CLOSE\r\n", tag(1));
1901 IMAP_OUT(o, MB_COMD, return STOP)
1902 IMAP_ANSWER()
1903 return OKAY;
1906 static enum okay
1907 imap_update(struct mailbox *mp)
1909 struct message *m;
1910 int dodel, c, gotcha = 0, held = 0, modflags = 0, needstat, stored = 0;
1911 NYD_ENTER;
1913 if (!edit && mp->mb_perm != 0) {
1914 holdbits();
1915 c = 0;
1916 for (m = message; PTRCMP(m, <, message + msgCount); ++m)
1917 if (m->m_flag & MBOX)
1918 ++c;
1919 if (c > 0)
1920 if (makembox() == STOP)
1921 goto jbypass;
1924 gotcha = held = 0;
1925 for (m = message; PTRCMP(m, <, message + msgCount); ++m) {
1926 if (mp->mb_perm == 0)
1927 dodel = 0;
1928 else if (edit)
1929 dodel = ((m->m_flag & MDELETED) != 0);
1930 else
1931 dodel = !((m->m_flag & MPRESERVE) || !(m->m_flag & MTOUCH));
1933 /* Fetch the result after around each 800 STORE commands
1934 * sent (approx. 32k data sent). Otherwise, servers will
1935 * try to flush the return queue at some point, leading
1936 * to a deadlock if we are still writing commands but not
1937 * reading their results */
1938 needstat = stored > 0 && stored % 800 == 0;
1939 /* Even if this message has been deleted, continue
1940 * to set further flags. This is necessary to support
1941 * Gmail semantics, where "delete" actually means
1942 * "archive", and the flags are applied to the copy
1943 * in "All Mail" */
1944 if ((m->m_flag & (MREAD | MSTATUS)) == (MREAD | MSTATUS)) {
1945 imap_store(mp, m, m-message+1, '+', "\\Seen", needstat);
1946 stored++;
1948 if (m->m_flag & MFLAG) {
1949 imap_store(mp, m, m-message+1, '+', "\\Flagged", needstat);
1950 stored++;
1952 if (m->m_flag & MUNFLAG) {
1953 imap_store(mp, m, m-message+1, '-', "\\Flagged", needstat);
1954 stored++;
1956 if (m->m_flag & MANSWER) {
1957 imap_store(mp, m, m-message+1, '+', "\\Answered", needstat);
1958 stored++;
1960 if (m->m_flag & MUNANSWER) {
1961 imap_store(mp, m, m-message+1, '-', "\\Answered", needstat);
1962 stored++;
1964 if (m->m_flag & MDRAFT) {
1965 imap_store(mp, m, m-message+1, '+', "\\Draft", needstat);
1966 stored++;
1968 if (m->m_flag & MUNDRAFT) {
1969 imap_store(mp, m, m-message+1, '-', "\\Draft", needstat);
1970 stored++;
1973 if (dodel) {
1974 imap_delete(mp, m-message+1, m, needstat);
1975 stored++;
1976 gotcha++;
1977 } else if (mp->mb_type != MB_CACHE ||
1978 (!edit && !(m->m_flag & (MBOXED | MSAVED | MDELETED))) ||
1979 (m->m_flag & (MBOXED | MPRESERVE | MTOUCH)) ==
1980 (MPRESERVE | MTOUCH) || (edit && !(m->m_flag & MDELETED)))
1981 held++;
1982 if (m->m_flag & MNEW) {
1983 m->m_flag &= ~MNEW;
1984 m->m_flag |= MSTATUS;
1987 jbypass:
1988 if (gotcha)
1989 imap_close(mp);
1991 for (m = &message[0]; PTRCMP(m, <, message + msgCount); ++m)
1992 if (!(m->m_flag & MUNLINKED) &&
1993 m->m_flag & (MBOXED | MDELETED | MSAVED | MSTATUS | MFLAG |
1994 MUNFLAG | MANSWER | MUNANSWER | MDRAFT | MUNDRAFT)) {
1995 putcache(mp, m);
1996 modflags++;
1999 if ((gotcha || modflags) && edit) {
2000 printf(_("\"%s\" "), displayname);
2001 printf((ok_blook(bsdcompat) || ok_blook(bsdmsgs))
2002 ? _("complete\n") : _("updated.\n"));
2003 } else if (held && !edit && mp->mb_perm != 0) {
2004 if (held == 1)
2005 printf(_("Held 1 message in %s\n"), displayname);
2006 else
2007 printf(_("Held %d messages in %s\n"), held, displayname);
2009 fflush(stdout);
2010 NYD_LEAVE;
2011 return OKAY;
2014 FL void
2015 imap_quit(void)
2017 sighandler_type volatile saveint, savepipe;
2018 NYD_ENTER;
2020 if (mb.mb_type == MB_CACHE) {
2021 imap_update(&mb);
2022 goto jleave;
2025 if (mb.mb_sock.s_fd < 0) {
2026 fprintf(stderr, "IMAP connection closed.\n");
2027 goto jleave;
2030 imaplock = 1;
2031 saveint = safe_signal(SIGINT, SIG_IGN);
2032 savepipe = safe_signal(SIGPIPE, SIG_IGN);
2033 if (sigsetjmp(imapjmp, 1)) {
2034 safe_signal(SIGINT, saveint);
2035 safe_signal(SIGPIPE, saveint);
2036 imaplock = 0;
2037 goto jleave;
2039 if (saveint != SIG_IGN)
2040 safe_signal(SIGINT, imapcatch);
2041 if (savepipe != SIG_IGN)
2042 safe_signal(SIGPIPE, imapcatch);
2044 imap_update(&mb);
2045 if (!same_imap_account)
2046 imap_exit(&mb);
2048 safe_signal(SIGINT, saveint);
2049 safe_signal(SIGPIPE, savepipe);
2050 imaplock = 0;
2051 jleave:
2052 NYD_LEAVE;
2055 static enum okay
2056 imap_store(struct mailbox *mp, struct message *m, int n, int c, const char *sp,
2057 int needstat)
2059 char o[LINESIZE];
2060 FILE *queuefp = NULL;
2061 NYD_X;
2063 if (mp->mb_type == MB_CACHE && (queuefp = cache_queue(mp)) == NULL)
2064 return STOP;
2065 if (m->m_uid)
2066 snprintf(o, sizeof o, "%s UID STORE %lu %cFLAGS (%s)\r\n",
2067 tag(1), m->m_uid, c, sp);
2068 else {
2069 if (check_expunged() == STOP)
2070 return STOP;
2071 snprintf(o, sizeof o, "%s STORE %u %cFLAGS (%s)\r\n", tag(1), n, c, sp);
2073 IMAP_OUT(o, MB_COMD, return STOP)
2074 if (needstat)
2075 IMAP_ANSWER()
2076 else
2077 mb.mb_active &= ~MB_COMD;
2078 if (queuefp != NULL)
2079 Fclose(queuefp);
2080 return OKAY;
2083 FL enum okay
2084 imap_undelete(struct message *m, int n)
2086 enum okay rv;
2087 NYD_ENTER;
2089 rv = imap_unstore(m, n, "\\Deleted");
2090 NYD_LEAVE;
2091 return rv;
2094 FL enum okay
2095 imap_unread(struct message *m, int n)
2097 enum okay rv;
2098 NYD_ENTER;
2100 rv = imap_unstore(m, n, "\\Seen");
2101 NYD_LEAVE;
2102 return rv;
2105 static enum okay
2106 imap_unstore(struct message *m, int n, const char *flag)
2108 sighandler_type saveint, savepipe;
2109 enum okay rv = STOP;
2110 NYD_ENTER;
2112 imaplock = 1;
2113 if ((saveint = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN)
2114 safe_signal(SIGINT, &_imap_maincatch);
2115 savepipe = safe_signal(SIGPIPE, SIG_IGN);
2116 if (sigsetjmp(imapjmp, 1) == 0) {
2117 if (savepipe != SIG_IGN)
2118 safe_signal(SIGPIPE, imapcatch);
2120 rv = imap_store(&mb, m, n, '-', flag, 1);
2122 safe_signal(SIGINT, saveint);
2123 safe_signal(SIGPIPE, savepipe);
2124 imaplock = 0;
2126 NYD_LEAVE;
2127 if (interrupts)
2128 onintr(0);
2129 return rv;
2132 static const char *
2133 tag(int new)
2135 static char ts[20];
2136 static long n;
2137 NYD2_ENTER;
2139 if (new)
2140 ++n;
2141 snprintf(ts, sizeof ts, "T%lu", n);
2142 NYD2_LEAVE;
2143 return ts;
2146 FL int
2147 c_imap_imap(void *vp)
2149 char o[LINESIZE];
2150 sighandler_type saveint, savepipe;
2151 struct mailbox *mp = &mb;
2152 FILE *queuefp = NULL;
2153 enum okay volatile ok = STOP;
2154 NYD_X;
2156 if (mp->mb_type != MB_IMAP) {
2157 printf("Not operating on an IMAP mailbox.\n");
2158 return 1;
2160 imaplock = 1;
2161 if ((saveint = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN)
2162 safe_signal(SIGINT, &_imap_maincatch);
2163 savepipe = safe_signal(SIGPIPE, SIG_IGN);
2164 if (sigsetjmp(imapjmp, 1) == 0) {
2165 if (savepipe != SIG_IGN)
2166 safe_signal(SIGPIPE, imapcatch);
2168 snprintf(o, sizeof o, "%s %s\r\n", tag(1), (char *)vp);
2169 IMAP_OUT(o, MB_COMD, goto out)
2170 while (mp->mb_active & MB_COMD) {
2171 ok = imap_answer(mp, 0);
2172 fputs(responded_text, stdout);
2175 out:
2176 safe_signal(SIGINT, saveint);
2177 safe_signal(SIGPIPE, savepipe);
2178 imaplock = 0;
2180 if (interrupts)
2181 onintr(0);
2182 return ok != OKAY;
2185 FL int
2186 imap_newmail(int nmail)
2188 NYD_ENTER;
2190 if (nmail && had_exists < 0 && had_expunge < 0) {
2191 imaplock = 1;
2192 imap_noop();
2193 imaplock = 0;
2196 if (had_exists == msgCount && had_expunge < 0)
2197 /* Some servers always respond with EXISTS to NOOP. If
2198 * the mailbox has been changed but the number of messages
2199 * has not, an EXPUNGE must also had been sent; otherwise,
2200 * nothing has changed */
2201 had_exists = -1;
2202 NYD_LEAVE;
2203 return (had_expunge >= 0 ? 2 : (had_exists >= 0 ? 1 : 0));
2206 static char *
2207 imap_putflags(int f)
2209 const char *cp;
2210 char *buf, *bp;
2211 NYD2_ENTER;
2213 bp = buf = salloc(100);
2214 if (f & (MREAD | MFLAGGED | MANSWERED | MDRAFTED)) {
2215 *bp++ = '(';
2216 if (f & MREAD) {
2217 if (bp[-1] != '(')
2218 *bp++ = ' ';
2219 for (cp = "\\Seen"; *cp; cp++)
2220 *bp++ = *cp;
2222 if (f & MFLAGGED) {
2223 if (bp[-1] != '(')
2224 *bp++ = ' ';
2225 for (cp = "\\Flagged"; *cp; cp++)
2226 *bp++ = *cp;
2228 if (f & MANSWERED) {
2229 if (bp[-1] != '(')
2230 *bp++ = ' ';
2231 for (cp = "\\Answered"; *cp; cp++)
2232 *bp++ = *cp;
2234 if (f & MDRAFT) {
2235 if (bp[-1] != '(')
2236 *bp++ = ' ';
2237 for (cp = "\\Draft"; *cp; cp++)
2238 *bp++ = *cp;
2240 *bp++ = ')';
2241 *bp++ = ' ';
2243 *bp = '\0';
2244 NYD2_LEAVE;
2245 return buf;
2248 static void
2249 imap_getflags(const char *cp, char const **xp, enum mflag *f)
2251 NYD2_ENTER;
2252 while (*cp != ')') {
2253 if (*cp == '\\') {
2254 if (ascncasecmp(cp, "\\Seen", 5) == 0)
2255 *f |= MREAD;
2256 else if (ascncasecmp(cp, "\\Recent", 7) == 0)
2257 *f |= MNEW;
2258 else if (ascncasecmp(cp, "\\Deleted", 8) == 0)
2259 *f |= MDELETED;
2260 else if (ascncasecmp(cp, "\\Flagged", 8) == 0)
2261 *f |= MFLAGGED;
2262 else if (ascncasecmp(cp, "\\Answered", 9) == 0)
2263 *f |= MANSWERED;
2264 else if (ascncasecmp(cp, "\\Draft", 6) == 0)
2265 *f |= MDRAFTED;
2267 cp++;
2270 if (xp != NULL)
2271 *xp = cp;
2272 NYD2_LEAVE;
2275 static enum okay
2276 imap_append1(struct mailbox *mp, const char *name, FILE *fp, off_t off1,
2277 long xsize, enum mflag flag, time_t t)
2279 char o[LINESIZE], *buf;
2280 size_t bufsize, buflen, cnt;
2281 long size, lines, ysize;
2282 int twice = 0;
2283 FILE *queuefp = NULL;
2284 enum okay rv;
2285 NYD_ENTER;
2287 if (mp->mb_type == MB_CACHE) {
2288 queuefp = cache_queue(mp);
2289 if (queuefp == NULL) {
2290 rv = STOP;
2291 buf = NULL;
2292 goto jleave;
2294 rv = OKAY;
2295 } else
2296 rv = STOP;
2298 buf = smalloc(bufsize = LINESIZE);
2299 buflen = 0;
2300 jagain:
2301 size = xsize;
2302 cnt = fsize(fp);
2303 if (fseek(fp, off1, SEEK_SET) < 0) {
2304 rv = STOP;
2305 goto jleave;
2308 snprintf(o, sizeof o, "%s APPEND %s %s%s {%ld}\r\n",
2309 tag(1), imap_quotestr(name), imap_putflags(flag),
2310 imap_make_date_time(t), size);
2311 IMAP_XOUT(o, MB_COMD, goto jleave, rv=STOP;goto jleave)
2312 while (mp->mb_active & MB_COMD) {
2313 rv = imap_answer(mp, twice);
2314 if (response_type == RESPONSE_CONT)
2315 break;
2318 if (mp->mb_type != MB_CACHE && rv == STOP) {
2319 if (twice == 0)
2320 goto jtrycreate;
2321 else
2322 goto jleave;
2325 lines = ysize = 0;
2326 while (size > 0) {
2327 fgetline(&buf, &bufsize, &cnt, &buflen, fp, 1);
2328 lines++;
2329 ysize += buflen;
2330 buf[buflen - 1] = '\r';
2331 buf[buflen] = '\n';
2332 if (mp->mb_type != MB_CACHE)
2333 swrite1(&mp->mb_sock, buf, buflen+1, 1);
2334 else if (queuefp)
2335 fwrite(buf, 1, buflen+1, queuefp);
2336 size -= buflen + 1;
2338 if (mp->mb_type != MB_CACHE)
2339 swrite(&mp->mb_sock, "\r\n");
2340 else if (queuefp)
2341 fputs("\r\n", queuefp);
2342 while (mp->mb_active & MB_COMD) {
2343 rv = imap_answer(mp, 0);
2344 if (response_status == RESPONSE_NO /*&&
2345 ascncasecmp(responded_text,
2346 "[TRYCREATE] ", 12) == 0*/) {
2347 jtrycreate:
2348 if (twice++) {
2349 rv = STOP;
2350 goto jleave;
2352 snprintf(o, sizeof o, "%s CREATE %s\r\n", tag(1), imap_quotestr(name));
2353 IMAP_XOUT(o, MB_COMD, goto jleave, rv=STOP;goto jleave)
2354 while (mp->mb_active & MB_COMD)
2355 rv = imap_answer(mp, 1);
2356 if (rv == STOP)
2357 goto jleave;
2358 imap_created_mailbox++;
2359 goto jagain;
2360 } else if (rv != OKAY)
2361 fprintf(stderr, _("IMAP error: %s"), responded_text);
2362 else if (response_status == RESPONSE_OK && (mp->mb_flags & MB_UIDPLUS))
2363 imap_appenduid(mp, fp, t, off1, xsize, ysize, lines, flag, name);
2365 jleave:
2366 if (queuefp != NULL)
2367 Fclose(queuefp);
2368 if (buf != NULL)
2369 free(buf);
2370 NYD_LEAVE;
2371 return rv;
2374 static enum okay
2375 imap_append0(struct mailbox *mp, const char *name, FILE *fp)
2377 char *buf, *bp, *lp;
2378 size_t bufsize, buflen, cnt;
2379 off_t off1 = -1, offs;
2380 int inhead = 1, flag = MNEW | MNEWEST;
2381 long size = 0;
2382 time_t tim;
2383 enum okay rv;
2384 NYD_ENTER;
2386 buf = smalloc(bufsize = LINESIZE);
2387 buflen = 0;
2388 cnt = fsize(fp);
2389 offs = ftell(fp);
2390 time(&tim);
2392 do {
2393 bp = fgetline(&buf, &bufsize, &cnt, &buflen, fp, 1);
2394 if (bp == NULL || strncmp(buf, "From ", 5) == 0) {
2395 if (off1 != (off_t)-1) {
2396 rv = imap_append1(mp, name, fp, off1, size, flag, tim);
2397 if (rv == STOP)
2398 goto jleave;
2399 fseek(fp, offs+buflen, SEEK_SET);
2401 off1 = offs + buflen;
2402 size = 0;
2403 inhead = 1;
2404 flag = MNEW;
2405 if (bp != NULL)
2406 tim = unixtime(buf);
2407 } else
2408 size += buflen+1;
2409 offs += buflen;
2411 if (bp && buf[0] == '\n')
2412 inhead = 0;
2413 else if (bp && inhead && ascncasecmp(buf, "status", 6) == 0) {
2414 lp = &buf[6];
2415 while (whitechar(*lp))
2416 lp++;
2417 if (*lp == ':')
2418 while (*++lp != '\0')
2419 switch (*lp) {
2420 case 'R':
2421 flag |= MREAD;
2422 break;
2423 case 'O':
2424 flag &= ~MNEW;
2425 break;
2427 } else if (bp && inhead && ascncasecmp(buf, "x-status", 8) == 0) {
2428 lp = &buf[8];
2429 while (whitechar(*lp))
2430 lp++;
2431 if (*lp == ':')
2432 while (*++lp != '\0')
2433 switch (*lp) {
2434 case 'F':
2435 flag |= MFLAGGED;
2436 break;
2437 case 'A':
2438 flag |= MANSWERED;
2439 break;
2440 case 'T':
2441 flag |= MDRAFTED;
2442 break;
2445 } while (bp != NULL);
2446 rv = OKAY;
2447 jleave:
2448 free(buf);
2449 NYD_LEAVE;
2450 return rv;
2453 FL enum okay
2454 imap_append(const char *xserver, FILE *fp)
2456 sighandler_type volatile saveint, savepipe;
2457 struct url url;
2458 struct ccred ccred;
2459 char const * volatile mbx;
2460 enum okay rv = STOP;
2461 NYD_ENTER;
2463 if (!url_parse(&url, CPROTO_IMAP, xserver))
2464 goto j_leave;
2465 if (!ok_blook(v15_compat) &&
2466 (!url.url_had_user || url.url_pass.s != NULL))
2467 fprintf(stderr, "New-style URL used without *v15-compat* being set!\n");
2468 mbx = (url.url_path.s != NULL) ? url.url_path.s : "INBOX";
2470 imaplock = 1;
2471 if ((saveint = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN)
2472 safe_signal(SIGINT, &_imap_maincatch);
2473 savepipe = safe_signal(SIGPIPE, SIG_IGN);
2474 if (sigsetjmp(imapjmp, 1))
2475 goto jleave;
2476 if (savepipe != SIG_IGN)
2477 safe_signal(SIGPIPE, imapcatch);
2479 if ((mb.mb_type == MB_CACHE || mb.mb_sock.s_fd > 0) && mb.mb_imap_account &&
2480 !strcmp(url.url_p_eu_h_p, mb.mb_imap_account)) {
2481 rv = imap_append0(&mb, mbx, fp);
2482 } else {
2483 struct mailbox mx;
2485 memset(&mx, 0, sizeof mx);
2487 if (!_imap_getcred(&mx, &ccred, &url))
2488 goto jleave;
2490 if (disconnected(url.url_p_eu_h_p) == 0) {
2491 if (!sopen(&mx.mb_sock, &url))
2492 goto jfail;
2493 mx.mb_sock.s_desc = "IMAP";
2494 mx.mb_type = MB_IMAP;
2495 mx.mb_imap_account = UNCONST(url.url_p_eu_h_p);
2496 /* TODO the code now did
2497 * TODO mx.mb_imap_mailbox = mbx;
2498 * TODO though imap_mailbox is sfree()d and mbx
2499 * TODO is possibly even a constant
2500 * TODO i changed this to sstrdup() sofar, as is used
2501 * TODO somewhere else in this file for this! */
2502 mx.mb_imap_mailbox = sstrdup(mbx);
2503 if (imap_preauth(&mx, url.url_h_p.s, url.url_u_h_p.s) != OKAY ||
2504 imap_auth(&mx, &ccred) != OKAY) {
2505 sclose(&mx.mb_sock);
2506 goto jfail;
2508 rv = imap_append0(&mx, mbx, fp);
2509 imap_exit(&mx);
2510 } else {
2511 mx.mb_imap_account = UNCONST(url.url_p_eu_h_p);
2512 mx.mb_imap_mailbox = sstrdup(mbx); /* TODO as above */
2513 mx.mb_type = MB_CACHE;
2514 rv = imap_append0(&mx, mbx, fp);
2516 jfail:
2520 jleave:
2521 safe_signal(SIGINT, saveint);
2522 safe_signal(SIGPIPE, savepipe);
2523 imaplock = 0;
2524 j_leave:
2525 NYD_LEAVE;
2526 if (interrupts)
2527 onintr(0);
2528 return rv;
2531 static enum okay
2532 imap_list1(struct mailbox *mp, const char *base, struct list_item **list,
2533 struct list_item **lend, int level)
2535 char o[LINESIZE], *cp;
2536 const char *bp;
2537 FILE *queuefp = NULL;
2538 struct list_item *lp;
2539 enum okay ok = STOP;
2540 NYD_X;
2542 *list = *lend = NULL;
2543 snprintf(o, sizeof o, "%s LIST %s %%\r\n", tag(1), imap_quotestr(base));
2544 IMAP_OUT(o, MB_COMD, return STOP)
2545 while (mp->mb_active & MB_COMD) {
2546 ok = imap_answer(mp, 1);
2547 if (response_status == RESPONSE_OTHER &&
2548 response_other == MAILBOX_DATA_LIST && imap_parse_list() == OKAY) {
2549 cp = imap_unquotestr(list_name);
2550 lp = csalloc(1, sizeof *lp);
2551 lp->l_name = cp;
2552 for (bp = base; *bp != '\0' && *bp == *cp; ++bp)
2553 ++cp;
2554 lp->l_base = *cp ? cp : savestr(base);
2555 lp->l_attr = list_attributes;
2556 lp->l_level = level+1;
2557 lp->l_delim = list_hierarchy_delimiter;
2558 if (*list && *lend) {
2559 (*lend)->l_next = lp;
2560 *lend = lp;
2561 } else
2562 *list = *lend = lp;
2565 return ok;
2568 static enum okay
2569 imap_list(struct mailbox *mp, const char *base, int strip, FILE *fp)
2571 struct list_item *list, *lend, *lp, *lx, *ly;
2572 int n, depth;
2573 const char *bp;
2574 char *cp;
2575 enum okay rv;
2576 NYD_ENTER;
2578 depth = (cp = ok_vlook(imap_list_depth)) != NULL ? atoi(cp) : 2;
2579 if ((rv = imap_list1(mp, base, &list, &lend, 0)) == STOP)
2580 goto jleave;
2581 rv = OKAY;
2582 if (list == NULL || lend == NULL)
2583 goto jleave;
2585 for (lp = list; lp; lp = lp->l_next)
2586 if (lp->l_delim != '/' && lp->l_delim != EOF && lp->l_level < depth &&
2587 !(lp->l_attr & LIST_NOINFERIORS)) {
2588 cp = salloc((n = strlen(lp->l_name)) + 2);
2589 memcpy(cp, lp->l_name, n);
2590 cp[n] = lp->l_delim;
2591 cp[n+1] = '\0';
2592 if (imap_list1(mp, cp, &lx, &ly, lp->l_level) == OKAY && lx && ly) {
2593 lp->l_has_children = 1;
2594 if (strcmp(cp, lx->l_name) == 0)
2595 lx = lx->l_next;
2596 if (lx) {
2597 lend->l_next = lx;
2598 lend = ly;
2603 for (lp = list; lp; lp = lp->l_next) {
2604 if (strip) {
2605 cp = lp->l_name;
2606 for (bp = base; *bp && *bp == *cp; bp++)
2607 cp++;
2608 } else
2609 cp = lp->l_name;
2610 if (!(lp->l_attr & LIST_NOSELECT))
2611 fprintf(fp, "%s\n", *cp ? cp : base);
2612 else if (lp->l_has_children == 0)
2613 fprintf(fp, "%s%c\n", *cp ? cp : base,
2614 (lp->l_delim != EOF ? lp->l_delim : '\n'));
2616 jleave:
2617 NYD_LEAVE;
2618 return rv;
2621 FL void
2622 imap_folders(const char * volatile name, int strip)
2624 sighandler_type saveint, savepipe;
2625 const char *fold, *cp, *sp;
2626 FILE * volatile fp;
2627 NYD_ENTER;
2629 cp = protbase(name);
2630 sp = mb.mb_imap_account;
2631 if (sp == NULL || strcmp(cp, sp)) {
2632 fprintf(stderr, _(
2633 "Cannot perform `folders' but when on the very IMAP "
2634 "account; the current one is\n `%s' -- "
2635 "try `folders @'.\n"),
2636 (sp != NULL ? sp : _("[NONE]")));
2637 goto jleave;
2640 fold = imap_fileof(name);
2641 if (options & OPT_TTYOUT) {
2642 if ((fp = Ftmp(NULL, "imapfold", OF_RDWR | OF_UNLINK | OF_REGISTER,
2643 0600)) == NULL) {
2644 perror("tmpfile");
2645 goto jleave;
2647 } else
2648 fp = stdout;
2650 imaplock = 1;
2651 if ((saveint = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN)
2652 safe_signal(SIGINT, &_imap_maincatch);
2653 savepipe = safe_signal(SIGPIPE, SIG_IGN);
2654 if (sigsetjmp(imapjmp, 1)) /* TODO imaplock? */
2655 goto junroll;
2656 if (savepipe != SIG_IGN)
2657 safe_signal(SIGPIPE, imapcatch);
2659 if (mb.mb_type == MB_CACHE)
2660 cache_list(&mb, fold, strip, fp);
2661 else
2662 imap_list(&mb, fold, strip, fp);
2664 imaplock = 0;
2665 if (interrupts) {
2666 if (options & OPT_TTYOUT)
2667 Fclose(fp);
2668 goto jleave;
2670 fflush(fp);
2672 if (options & OPT_TTYOUT) {
2673 rewind(fp);
2674 if (fsize(fp) > 0)
2675 dopr(fp);
2676 else
2677 fprintf(stderr, "Folder not found.\n");
2679 junroll:
2680 safe_signal(SIGINT, saveint);
2681 safe_signal(SIGPIPE, savepipe);
2682 if (options & OPT_TTYOUT)
2683 Fclose(fp);
2684 jleave:
2685 NYD_LEAVE;
2686 if (interrupts)
2687 onintr(0);
2690 static void
2691 dopr(FILE *fp)
2693 char o[LINESIZE];
2694 int c;
2695 long n = 0, mx = 0, columns, width;
2696 FILE *out;
2697 NYD_ENTER;
2699 if ((out = Ftmp(NULL, "imapdopr", OF_RDWR | OF_UNLINK | OF_REGISTER, 0600))
2700 == NULL) {
2701 perror("tmpfile");
2702 goto jleave;
2705 while ((c = getc(fp)) != EOF) {
2706 if (c == '\n') {
2707 if (n > mx)
2708 mx = n;
2709 n = 0;
2710 } else
2711 ++n;
2713 rewind(fp);
2715 width = scrnwidth;
2716 if (mx < width / 2) {
2717 columns = width / (mx+2);
2718 snprintf(o, sizeof o, "sort | pr -%lu -w%lu -t", columns, width);
2719 } else
2720 strncpy(o, "sort", sizeof o)[sizeof o - 1] = '\0';
2721 run_command(XSHELL, 0, fileno(fp), fileno(out), "-c", o, NULL);
2722 page_or_print(out, 0);
2723 Fclose(out);
2724 jleave:
2725 NYD_LEAVE;
2728 static enum okay
2729 imap_copy1(struct mailbox *mp, struct message *m, int n, const char *name)
2731 char o[LINESIZE];
2732 const char *qname;
2733 int twice = 0, stored = 0;
2734 FILE *queuefp = NULL;
2735 enum okay ok = STOP;
2736 NYD_X;
2738 if (mp->mb_type == MB_CACHE) {
2739 if ((queuefp = cache_queue(mp)) == NULL)
2740 return STOP;
2741 ok = OKAY;
2743 qname = imap_quotestr(name = imap_fileof(name));
2744 /* Since it is not possible to set flags on the copy, recently
2745 * set flags must be set on the original to include it in the copy */
2746 if ((m->m_flag & (MREAD | MSTATUS)) == (MREAD | MSTATUS))
2747 imap_store(mp, m, n, '+', "\\Seen", 0);
2748 if (m->m_flag&MFLAG)
2749 imap_store(mp, m, n, '+', "\\Flagged", 0);
2750 if (m->m_flag&MUNFLAG)
2751 imap_store(mp, m, n, '-', "\\Flagged", 0);
2752 if (m->m_flag&MANSWER)
2753 imap_store(mp, m, n, '+', "\\Answered", 0);
2754 if (m->m_flag&MUNANSWER)
2755 imap_store(mp, m, n, '-', "\\Flagged", 0);
2756 if (m->m_flag&MDRAFT)
2757 imap_store(mp, m, n, '+', "\\Draft", 0);
2758 if (m->m_flag&MUNDRAFT)
2759 imap_store(mp, m, n, '-', "\\Draft", 0);
2760 again:
2761 if (m->m_uid)
2762 snprintf(o, sizeof o, "%s UID COPY %lu %s\r\n", tag(1), m->m_uid, qname);
2763 else {
2764 if (check_expunged() == STOP)
2765 goto out;
2766 snprintf(o, sizeof o, "%s COPY %u %s\r\n", tag(1), n, qname);
2768 IMAP_OUT(o, MB_COMD, goto out)
2769 while (mp->mb_active & MB_COMD)
2770 ok = imap_answer(mp, twice);
2772 if (mp->mb_type == MB_IMAP && mp->mb_flags & MB_UIDPLUS &&
2773 response_status == RESPONSE_OK)
2774 imap_copyuid(mp, m, name);
2776 if (response_status == RESPONSE_NO && twice++ == 0) {
2777 snprintf(o, sizeof o, "%s CREATE %s\r\n", tag(1), qname);
2778 IMAP_OUT(o, MB_COMD, goto out)
2779 while (mp->mb_active & MB_COMD)
2780 ok = imap_answer(mp, 1);
2781 if (ok == OKAY) {
2782 imap_created_mailbox++;
2783 goto again;
2787 if (queuefp != NULL)
2788 Fclose(queuefp);
2790 /* ... and reset the flag to its initial value so that the 'exit'
2791 * command still leaves the message unread */
2792 out:
2793 if ((m->m_flag & (MREAD | MSTATUS)) == (MREAD | MSTATUS)) {
2794 imap_store(mp, m, n, '-', "\\Seen", 0);
2795 stored++;
2797 if (m->m_flag & MFLAG) {
2798 imap_store(mp, m, n, '-', "\\Flagged", 0);
2799 stored++;
2801 if (m->m_flag & MUNFLAG) {
2802 imap_store(mp, m, n, '+', "\\Flagged", 0);
2803 stored++;
2805 if (m->m_flag & MANSWER) {
2806 imap_store(mp, m, n, '-', "\\Answered", 0);
2807 stored++;
2809 if (m->m_flag & MUNANSWER) {
2810 imap_store(mp, m, n, '+', "\\Answered", 0);
2811 stored++;
2813 if (m->m_flag & MDRAFT) {
2814 imap_store(mp, m, n, '-', "\\Draft", 0);
2815 stored++;
2817 if (m->m_flag & MUNDRAFT) {
2818 imap_store(mp, m, n, '+', "\\Draft", 0);
2819 stored++;
2821 if (stored) {
2822 mp->mb_active |= MB_COMD;
2823 (void)imap_finish(mp);
2825 return ok;
2828 FL enum okay
2829 imap_copy(struct message *m, int n, const char *name)
2831 sighandler_type saveint, savepipe;
2832 enum okay rv = STOP;
2833 NYD_ENTER;
2835 imaplock = 1;
2836 if ((saveint = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN)
2837 safe_signal(SIGINT, &_imap_maincatch);
2838 savepipe = safe_signal(SIGPIPE, SIG_IGN);
2839 if (sigsetjmp(imapjmp, 1) == 0) {
2840 if (savepipe != SIG_IGN)
2841 safe_signal(SIGPIPE, imapcatch);
2843 rv = imap_copy1(&mb, m, n, name);
2845 safe_signal(SIGINT, saveint);
2846 safe_signal(SIGPIPE, savepipe);
2847 imaplock = 0;
2849 NYD_LEAVE;
2850 if (interrupts)
2851 onintr(0);
2852 return rv;
2855 static enum okay
2856 imap_copyuid_parse(const char *cp, unsigned long *uidvalidity,
2857 unsigned long *olduid, unsigned long *newuid)
2859 char *xp, *yp, *zp;
2860 enum okay rv;
2861 NYD_ENTER;
2863 *uidvalidity = strtoul(cp, &xp, 10);
2864 *olduid = strtoul(xp, &yp, 10);
2865 *newuid = strtoul(yp, &zp, 10);
2866 rv = (*uidvalidity && *olduid && *newuid && xp > cp && *xp == ' ' &&
2867 yp > xp && *yp == ' ' && zp > yp && *zp == ']');
2868 NYD_LEAVE;
2869 return rv;
2872 static enum okay
2873 imap_appenduid_parse(const char *cp, unsigned long *uidvalidity,
2874 unsigned long *uid)
2876 char *xp, *yp;
2877 enum okay rv;
2878 NYD_ENTER;
2880 *uidvalidity = strtoul(cp, &xp, 10);
2881 *uid = strtoul(xp, &yp, 10);
2882 rv = (*uidvalidity && *uid && xp > cp && *xp == ' ' && yp > xp &&
2883 *yp == ']');
2884 NYD_LEAVE;
2885 return rv;
2888 static enum okay
2889 imap_copyuid(struct mailbox *mp, struct message *m, const char *name)
2891 struct mailbox xmb;
2892 struct message xm;
2893 const char *cp;
2894 unsigned long uidvalidity, olduid, newuid;
2895 enum okay rv;
2896 NYD_ENTER;
2898 rv = STOP;
2899 if ((cp = asccasestr(responded_text, "[COPYUID ")) == NULL ||
2900 imap_copyuid_parse(&cp[9], &uidvalidity, &olduid, &newuid) == STOP)
2901 goto jleave;
2902 rv = OKAY;
2904 xmb = *mp;
2905 xmb.mb_cache_directory = NULL;
2906 xmb.mb_imap_mailbox = savestr(name);
2907 xmb.mb_uidvalidity = uidvalidity;
2908 initcache(&xmb);
2909 if (m == NULL) {
2910 memset(&xm, 0, sizeof xm);
2911 xm.m_uid = olduid;
2912 if ((rv = getcache1(mp, &xm, NEED_UNSPEC, 3)) != OKAY)
2913 goto jleave;
2914 getcache(mp, &xm, NEED_HEADER);
2915 getcache(mp, &xm, NEED_BODY);
2916 } else {
2917 if ((m->m_flag & HAVE_HEADER) == 0)
2918 getcache(mp, m, NEED_HEADER);
2919 if ((m->m_flag & HAVE_BODY) == 0)
2920 getcache(mp, m, NEED_BODY);
2921 xm = *m;
2923 xm.m_uid = newuid;
2924 xm.m_flag &= ~MFULLYCACHED;
2925 putcache(&xmb, &xm);
2926 jleave:
2927 NYD_LEAVE;
2928 return rv;
2931 static enum okay
2932 imap_appenduid(struct mailbox *mp, FILE *fp, time_t t, long off1, long xsize,
2933 long size, long lines, int flag, const char *name)
2935 struct mailbox xmb;
2936 struct message xm;
2937 const char *cp;
2938 unsigned long uidvalidity, uid;
2939 enum okay rv;
2940 NYD_ENTER;
2942 rv = STOP;
2943 if ((cp = asccasestr(responded_text, "[APPENDUID ")) == NULL ||
2944 imap_appenduid_parse(&cp[11], &uidvalidity, &uid) == STOP)
2945 goto jleave;
2946 rv = OKAY;
2948 xmb = *mp;
2949 xmb.mb_cache_directory = NULL;
2950 xmb.mb_imap_mailbox = savestr(name);
2951 xmb.mb_uidvalidity = uidvalidity;
2952 xmb.mb_otf = xmb.mb_itf = fp;
2953 initcache(&xmb);
2954 memset(&xm, 0, sizeof xm);
2955 xm.m_flag = (flag & MREAD) | MNEW;
2956 xm.m_time = t;
2957 xm.m_block = mailx_blockof(off1);
2958 xm.m_offset = mailx_offsetof(off1);
2959 xm.m_size = size;
2960 xm.m_xsize = xsize;
2961 xm.m_lines = xm.m_xlines = lines;
2962 xm.m_uid = uid;
2963 xm.m_have = HAVE_HEADER | HAVE_BODY;
2964 putcache(&xmb, &xm);
2965 jleave:
2966 NYD_LEAVE;
2967 return rv;
2970 static enum okay
2971 imap_appenduid_cached(struct mailbox *mp, FILE *fp)
2973 FILE *tp = NULL;
2974 time_t t;
2975 long size, xsize, ysize, lines;
2976 enum mflag flag = MNEW;
2977 char *name, *buf, *bp;
2978 char const *cp;
2979 size_t bufsize, buflen, cnt;
2980 enum okay rv = STOP;
2981 NYD_ENTER;
2983 buf = smalloc(bufsize = LINESIZE);
2984 buflen = 0;
2985 cnt = fsize(fp);
2986 if (fgetline(&buf, &bufsize, &cnt, &buflen, fp, 0) == NULL)
2987 goto jstop;
2989 for (bp = buf; *bp != ' '; ++bp) /* strip old tag */
2991 while (*bp == ' ')
2992 ++bp;
2994 if ((cp = strrchr(bp, '{')) == NULL)
2995 goto jstop;
2997 xsize = atol(&cp[1]) + 2;
2998 if ((name = imap_strex(&bp[7], &cp)) == NULL)
2999 goto jstop;
3000 while (*cp == ' ')
3001 cp++;
3003 if (*cp == '(') {
3004 imap_getflags(cp, &cp, &flag);
3005 while (*++cp == ' ')
3008 t = imap_read_date_time(cp);
3010 if ((tp = Ftmp(NULL, "imapapui", OF_RDWR | OF_UNLINK | OF_REGISTER, 0600)) ==
3011 NULL)
3012 goto jstop;
3014 size = xsize;
3015 ysize = lines = 0;
3016 while (size > 0) {
3017 if (fgetline(&buf, &bufsize, &cnt, &buflen, fp, 0) == NULL)
3018 goto jstop;
3019 size -= buflen;
3020 buf[--buflen] = '\0';
3021 buf[buflen-1] = '\n';
3022 fwrite(buf, 1, buflen, tp);
3023 ysize += buflen;
3024 ++lines;
3026 fflush(tp);
3027 rewind(tp);
3029 imap_appenduid(mp, tp, t, 0, xsize-2, ysize-1, lines-1, flag,
3030 imap_unquotestr(name));
3031 rv = OKAY;
3032 jstop:
3033 free(buf);
3034 if (tp)
3035 Fclose(tp);
3036 NYD_LEAVE;
3037 return rv;
3040 #ifdef HAVE_IMAP_SEARCH
3041 static enum okay
3042 imap_search2(struct mailbox *mp, struct message *m, int cnt, const char *spec,
3043 int f)
3045 char *o, *xp, *cs, c;
3046 size_t osize;
3047 FILE *queuefp = NULL;
3048 int i;
3049 unsigned long n;
3050 const char *cp;
3051 enum okay ok = STOP;
3052 NYD_X;
3054 c = 0;
3055 for (cp = spec; *cp; cp++)
3056 c |= *cp;
3057 if (c & 0200) {
3058 cp = charset_get_lc();
3059 # ifdef HAVE_ICONV
3060 if (asccasecmp(cp, "utf-8") && asccasecmp(cp, "utf8")) {
3061 iconv_t it;
3062 char *nsp, *nspec;
3063 size_t sz, nsz;
3065 if ((it = n_iconv_open("utf-8", cp)) != (iconv_t)-1) {
3066 sz = strlen(spec) + 1;
3067 nsp = nspec = salloc(nsz = 6*strlen(spec) + 1);
3068 if (n_iconv_buf(it, &spec, &sz, &nsp, &nsz, FAL0) == 0 &&
3069 sz == 0) {
3070 spec = nspec;
3071 cp = "utf-8";
3073 n_iconv_close(it);
3076 # endif
3077 cp = imap_quotestr(cp);
3078 cs = salloc(n = strlen(cp) + 10);
3079 snprintf(cs, n, "CHARSET %s ", cp);
3080 } else
3081 cs = UNCONST("");
3083 o = ac_alloc(osize = strlen(spec) + 60);
3084 snprintf(o, osize, "%s UID SEARCH %s%s\r\n", tag(1), cs, spec);
3085 IMAP_OUT(o, MB_COMD, goto out)
3086 while (mp->mb_active & MB_COMD) {
3087 ok = imap_answer(mp, 0);
3088 if (response_status == RESPONSE_OTHER &&
3089 response_other == MAILBOX_DATA_SEARCH) {
3090 xp = responded_other_text;
3091 while (*xp && *xp != '\r') {
3092 n = strtoul(xp, &xp, 10);
3093 for (i = 0; i < cnt; i++)
3094 if (m[i].m_uid == n && !(m[i].m_flag & MHIDDEN) &&
3095 (f == MDELETED || !(m[i].m_flag & MDELETED)))
3096 mark(i+1, f);
3100 out:
3101 ac_free(o);
3102 return ok;
3105 FL enum okay
3106 imap_search1(const char * volatile spec, int f)
3108 sighandler_type saveint, savepipe;
3109 enum okay volatile rv = STOP;
3110 NYD_ENTER;
3112 if (mb.mb_type != MB_IMAP)
3113 goto jleave;
3115 imaplock = 1;
3116 if ((saveint = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN)
3117 safe_signal(SIGINT, &_imap_maincatch);
3118 savepipe = safe_signal(SIGPIPE, SIG_IGN);
3119 if (sigsetjmp(imapjmp, 1) == 0) {
3120 if (savepipe != SIG_IGN)
3121 safe_signal(SIGPIPE, imapcatch);
3123 rv = imap_search2(&mb, message, msgCount, spec, f);
3125 safe_signal(SIGINT, saveint);
3126 safe_signal(SIGPIPE, savepipe);
3127 imaplock = 0;
3128 jleave:
3129 NYD_LEAVE;
3130 if (interrupts)
3131 onintr(0);
3132 return rv;
3134 #endif /* HAVE_IMAP_SEARCH */
3136 FL int
3137 imap_thisaccount(const char *cp)
3139 int rv;
3140 NYD_ENTER;
3142 if (mb.mb_type != MB_CACHE && mb.mb_type != MB_IMAP)
3143 rv = 0;
3144 else if ((mb.mb_type != MB_CACHE && mb.mb_sock.s_fd < 0) ||
3145 mb.mb_imap_account == NULL)
3146 rv = 0;
3147 else
3148 rv = !strcmp(protbase(cp), mb.mb_imap_account);
3149 NYD_LEAVE;
3150 return rv;
3153 FL enum okay
3154 imap_remove(const char * volatile name)
3156 sighandler_type volatile saveint, savepipe;
3157 enum okay rv = STOP;
3158 NYD_ENTER;
3160 if (mb.mb_type != MB_IMAP) {
3161 fprintf(stderr, "Refusing to remove \"%s\" in disconnected mode.\n",
3162 name);
3163 goto jleave;
3166 if (!imap_thisaccount(name)) {
3167 fprintf(stderr, "Can only remove mailboxes on current IMAP "
3168 "server: \"%s\" not removed.\n", name);
3169 goto jleave;
3172 imaplock = 1;
3173 if ((saveint = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN)
3174 safe_signal(SIGINT, &_imap_maincatch);
3175 savepipe = safe_signal(SIGPIPE, SIG_IGN);
3176 if (sigsetjmp(imapjmp, 1) == 0) {
3177 if (savepipe != SIG_IGN)
3178 safe_signal(SIGPIPE, imapcatch);
3180 rv = imap_remove1(&mb, imap_fileof(name));
3182 safe_signal(SIGINT, saveint);
3183 safe_signal(SIGPIPE, savepipe);
3184 imaplock = 0;
3186 if (rv == OKAY)
3187 rv = cache_remove(name);
3188 jleave:
3189 NYD_LEAVE;
3190 if (interrupts)
3191 onintr(0);
3192 return rv;
3195 static enum okay
3196 imap_remove1(struct mailbox *mp, const char *name)
3198 FILE *queuefp = NULL;
3199 char *o;
3200 int os;
3201 enum okay ok = STOP;
3202 NYD_X;
3204 o = ac_alloc(os = 2*strlen(name) + 100);
3205 snprintf(o, os, "%s DELETE %s\r\n", tag(1), imap_quotestr(name));
3206 IMAP_OUT(o, MB_COMD, goto out)
3207 while (mp->mb_active & MB_COMD)
3208 ok = imap_answer(mp, 1);
3209 out:
3210 ac_free(o);
3211 return ok;
3214 FL enum okay
3215 imap_rename(const char *old, const char *new)
3217 sighandler_type saveint, savepipe;
3218 enum okay rv = STOP;
3219 NYD_ENTER;
3221 if (mb.mb_type != MB_IMAP) {
3222 fprintf(stderr, "Refusing to rename mailboxes in disconnected mode.\n");
3223 goto jleave;
3226 if (!imap_thisaccount(old) || !imap_thisaccount(new)) {
3227 fprintf(stderr, "Can only rename mailboxes on current IMAP "
3228 "server: \"%s\" not renamed to \"%s\".\n", old, new);
3229 goto jleave;
3232 imaplock = 1;
3233 if ((saveint = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN)
3234 safe_signal(SIGINT, &_imap_maincatch);
3235 savepipe = safe_signal(SIGPIPE, SIG_IGN);
3236 if (sigsetjmp(imapjmp, 1) == 0) {
3237 if (savepipe != SIG_IGN)
3238 safe_signal(SIGPIPE, imapcatch);
3240 rv = imap_rename1(&mb, imap_fileof(old), imap_fileof(new));
3242 safe_signal(SIGINT, saveint);
3243 safe_signal(SIGPIPE, savepipe);
3244 imaplock = 0;
3246 if (rv == OKAY)
3247 rv = cache_rename(old, new);
3248 jleave:
3249 NYD_LEAVE;
3250 if (interrupts)
3251 onintr(0);
3252 return rv;
3255 static enum okay
3256 imap_rename1(struct mailbox *mp, const char *old, const char *new)
3258 FILE *queuefp = NULL;
3259 char *o;
3260 int os;
3261 enum okay ok = STOP;
3262 NYD_X;
3264 o = ac_alloc(os = 2*strlen(old) + 2*strlen(new) + 100);
3265 snprintf(o, os, "%s RENAME %s %s\r\n", tag(1), imap_quotestr(old),
3266 imap_quotestr(new));
3267 IMAP_OUT(o, MB_COMD, goto out)
3268 while (mp->mb_active & MB_COMD)
3269 ok = imap_answer(mp, 1);
3270 out:
3271 ac_free(o);
3272 return ok;
3275 FL enum okay
3276 imap_dequeue(struct mailbox *mp, FILE *fp)
3278 char o[LINESIZE], *newname, *buf, *bp, *cp, iob[4096];
3279 size_t bufsize, buflen, cnt;
3280 long offs, offs1, offs2, octets;
3281 int twice, gotcha = 0;
3282 FILE *queuefp = NULL;
3283 enum okay ok = OKAY, rok = OKAY;
3284 NYD_X;
3286 buf = smalloc(bufsize = LINESIZE);
3287 buflen = 0;
3288 cnt = fsize(fp);
3289 while ((offs1 = ftell(fp)) >= 0 &&
3290 fgetline(&buf, &bufsize, &cnt, &buflen, fp, 0) != NULL) {
3291 for (bp = buf; *bp != ' '; ++bp) /* strip old tag */
3293 while (*bp == ' ')
3294 ++bp;
3295 twice = 0;
3296 if ((offs = ftell(fp)) < 0)
3297 goto fail;
3298 again:
3299 snprintf(o, sizeof o, "%s %s", tag(1), bp);
3300 if (ascncasecmp(bp, "UID COPY ", 9) == 0) {
3301 cp = &bp[9];
3302 while (digitchar(*cp))
3303 cp++;
3304 if (*cp != ' ')
3305 goto fail;
3306 while (*cp == ' ')
3307 cp++;
3308 if ((newname = imap_strex(cp, NULL)) == NULL)
3309 goto fail;
3310 IMAP_OUT(o, MB_COMD, continue)
3311 while (mp->mb_active & MB_COMD)
3312 ok = imap_answer(mp, twice);
3313 if (response_status == RESPONSE_NO && twice++ == 0)
3314 goto trycreate;
3315 if (response_status == RESPONSE_OK && mp->mb_flags & MB_UIDPLUS) {
3316 imap_copyuid(mp, NULL, imap_unquotestr(newname));
3318 } else if (ascncasecmp(bp, "UID STORE ", 10) == 0) {
3319 IMAP_OUT(o, MB_COMD, continue)
3320 while (mp->mb_active & MB_COMD)
3321 ok = imap_answer(mp, 1);
3322 if (ok == OKAY)
3323 gotcha++;
3324 } else if (ascncasecmp(bp, "APPEND ", 7) == 0) {
3325 if ((cp = strrchr(bp, '{')) == NULL)
3326 goto fail;
3327 octets = atol(&cp[1]) + 2;
3328 if ((newname = imap_strex(&bp[7], NULL)) == NULL)
3329 goto fail;
3330 IMAP_OUT(o, MB_COMD, continue)
3331 while (mp->mb_active & MB_COMD) {
3332 ok = imap_answer(mp, twice);
3333 if (response_type == RESPONSE_CONT)
3334 break;
3336 if (ok == STOP) {
3337 if (twice++ == 0 && fseek(fp, offs, SEEK_SET) >= 0)
3338 goto trycreate;
3339 goto fail;
3341 while (octets > 0) {
3342 size_t n = (UICMP(z, octets, >, sizeof iob)
3343 ? sizeof iob : (size_t)octets);
3344 octets -= n;
3345 if (n != fread(iob, 1, n, fp))
3346 goto fail;
3347 swrite1(&mp->mb_sock, iob, n, 1);
3349 swrite(&mp->mb_sock, "");
3350 while (mp->mb_active & MB_COMD) {
3351 ok = imap_answer(mp, 0);
3352 if (response_status == RESPONSE_NO && twice++ == 0) {
3353 if (fseek(fp, offs, SEEK_SET) < 0)
3354 goto fail;
3355 goto trycreate;
3358 if (response_status == RESPONSE_OK && mp->mb_flags & MB_UIDPLUS) {
3359 if ((offs2 = ftell(fp)) < 0)
3360 goto fail;
3361 fseek(fp, offs1, SEEK_SET);
3362 if (imap_appenduid_cached(mp, fp) == STOP) {
3363 (void)fseek(fp, offs2, SEEK_SET);
3364 goto fail;
3367 } else {
3368 fail:
3369 fprintf(stderr, "Invalid command in IMAP cache queue: \"%s\"\n", bp);
3370 rok = STOP;
3372 continue;
3373 trycreate:
3374 snprintf(o, sizeof o, "%s CREATE %s\r\n", tag(1), newname);
3375 IMAP_OUT(o, MB_COMD, continue)
3376 while (mp->mb_active & MB_COMD)
3377 ok = imap_answer(mp, 1);
3378 if (ok == OKAY)
3379 goto again;
3381 fflush(fp);
3382 rewind(fp);
3383 ftruncate(fileno(fp), 0);
3384 if (gotcha)
3385 imap_close(mp);
3386 free(buf);
3387 return rok;
3390 static char *
3391 imap_strex(char const *cp, char const **xp)
3393 char const *cq;
3394 char *n = NULL;
3395 NYD_ENTER;
3397 if (*cp != '"')
3398 goto jleave;
3400 for (cq = cp + 1; *cq != '\0'; ++cq) {
3401 if (*cq == '\\')
3402 cq++;
3403 else if (*cq == '"')
3404 break;
3406 if (*cq != '"')
3407 goto jleave;
3409 n = salloc(cq - cp + 2);
3410 memcpy(n, cp, cq - cp +1);
3411 n[cq - cp + 1] = '\0';
3412 if (xp != NULL)
3413 *xp = cq + 1;
3414 jleave:
3415 NYD_LEAVE;
3416 return n;
3419 static enum okay
3420 check_expunged(void)
3422 enum okay rv;
3423 NYD_ENTER;
3425 if (expunged_messages > 0) {
3426 fprintf(stderr, "Command not executed - messages have been expunged\n");
3427 rv = STOP;
3428 } else
3429 rv = OKAY;
3430 NYD_LEAVE;
3431 return rv;
3434 FL int
3435 c_connect(void *vp) /* TODO v15-compat mailname<->URL (with password) */
3437 struct url url;
3438 int rv, omsgCount = msgCount;
3439 NYD_ENTER;
3440 UNUSED(vp);
3442 if (mb.mb_type == MB_IMAP && mb.mb_sock.s_fd > 0) {
3443 fprintf(stderr, "Already connected.\n");
3444 rv = 1;
3445 goto jleave;
3448 if (!url_parse(&url, CPROTO_IMAP, mailname)) {
3449 rv = 1;
3450 goto jleave;
3452 var_clear_allow_undefined = TRU1;
3453 ok_bclear(disconnected);
3454 vok_bclear(savecat("disconnected-", url.url_u_h_p.s));
3455 var_clear_allow_undefined = FAL0;
3457 if (mb.mb_type == MB_CACHE) {
3458 enum fedit_mode fm = FEDIT_NONE;
3459 if (_imap_rdonly)
3460 fm |= FEDIT_RDONLY;
3461 if (!edit)
3462 fm |= FEDIT_SYSBOX;
3463 _imap_setfile1(&url, fm, 1);
3464 if (msgCount > omsgCount)
3465 newmailinfo(omsgCount);
3467 rv = 0;
3468 jleave:
3469 NYD_LEAVE;
3470 return rv;
3473 FL int
3474 c_disconnect(void *vp) /* TODO v15-compat mailname<->URL (with password) */
3476 struct url url;
3477 int rv = 1, *msgvec = vp;
3478 NYD_ENTER;
3480 if (mb.mb_type == MB_CACHE) {
3481 fprintf(stderr, "Not connected.\n");
3482 goto jleave;
3484 if (mb.mb_type != MB_IMAP || cached_uidvalidity(&mb) == 0) {
3485 fprintf(stderr, "The current mailbox is not cached.\n");
3486 goto jleave;
3489 if (!url_parse(&url, CPROTO_IMAP, mailname))
3490 goto jleave;
3492 if (*msgvec)
3493 c_cache(vp);
3494 ok_bset(disconnected, TRU1);
3495 if (mb.mb_type == MB_IMAP) {
3496 enum fedit_mode fm = FEDIT_NONE;
3497 if (_imap_rdonly)
3498 fm |= FEDIT_RDONLY;
3499 if (!edit)
3500 fm |= FEDIT_SYSBOX;
3501 sclose(&mb.mb_sock);
3502 _imap_setfile1(&url, fm, 1);
3504 rv = 0;
3505 jleave:
3506 NYD_LEAVE;
3507 return rv;
3510 FL int
3511 c_cache(void *vp)
3513 int rv = 1, *msgvec = vp, *ip;
3514 struct message *mp;
3515 NYD_ENTER;
3517 if (mb.mb_type != MB_IMAP) {
3518 fprintf(stderr, "Not connected to an IMAP server.\n");
3519 goto jleave;
3521 if (cached_uidvalidity(&mb) == 0) {
3522 fprintf(stderr, "The current mailbox is not cached.\n");
3523 goto jleave;
3526 srelax_hold();
3527 for (ip = msgvec; *ip; ++ip) {
3528 mp = &message[*ip - 1];
3529 if (!(mp->m_have & HAVE_BODY)) {
3530 get_body(mp);
3531 srelax();
3534 srelax_rele();
3535 rv = 0;
3536 jleave:
3537 NYD_LEAVE;
3538 return rv;
3541 FL int
3542 disconnected(const char *file)
3544 struct url url;
3545 int rv = 1;
3546 NYD_ENTER;
3548 if (ok_blook(disconnected)) {
3549 rv = 1;
3550 goto jleave;
3553 if (!url_parse(&url, CPROTO_IMAP, file)) {
3554 rv = 0;
3555 goto jleave;
3557 rv = vok_blook(savecat("disconnected-", url.url_u_h_p.s));
3559 jleave:
3560 NYD_LEAVE;
3561 return rv;
3564 FL void
3565 transflags(struct message *omessage, long omsgCount, int transparent)
3567 struct message *omp, *nmp, *newdot, *newprevdot;
3568 int hf;
3569 NYD_ENTER;
3571 omp = omessage;
3572 nmp = message;
3573 newdot = message;
3574 newprevdot = NULL;
3575 while (PTRCMP(omp, <, omessage + omsgCount) &&
3576 PTRCMP(nmp, <, message + msgCount)) {
3577 if (dot && nmp->m_uid == dot->m_uid)
3578 newdot = nmp;
3579 if (prevdot && nmp->m_uid == prevdot->m_uid)
3580 newprevdot = nmp;
3581 if (omp->m_uid == nmp->m_uid) {
3582 hf = nmp->m_flag & MHIDDEN;
3583 if (transparent && mb.mb_type == MB_IMAP)
3584 omp->m_flag &= ~MHIDDEN;
3585 *nmp++ = *omp++;
3586 if (transparent && mb.mb_type == MB_CACHE)
3587 nmp[-1].m_flag |= hf;
3588 } else if (omp->m_uid < nmp->m_uid)
3589 ++omp;
3590 else
3591 ++nmp;
3593 dot = newdot;
3594 setdot(newdot);
3595 prevdot = newprevdot;
3596 free(omessage);
3597 NYD_LEAVE;
3600 FL time_t
3601 imap_read_date_time(const char *cp)
3603 char buf[3];
3604 time_t t;
3605 int i, year, month, day, hour, minute, second, sign = -1;
3606 NYD2_ENTER;
3608 /* "25-Jul-2004 15:33:44 +0200"
3609 * | | | | | |
3610 * 0 5 10 15 20 25 */
3611 if (cp[0] != '"' || strlen(cp) < 28 || cp[27] != '"')
3612 goto jinvalid;
3613 day = strtol(&cp[1], NULL, 10);
3614 for (i = 0;;) {
3615 if (ascncasecmp(&cp[4], month_names[i], 3) == 0)
3616 break;
3617 if (month_names[++i][0] == '\0')
3618 goto jinvalid;
3620 month = i + 1;
3621 year = strtol(&cp[8], NULL, 10);
3622 hour = strtol(&cp[13], NULL, 10);
3623 minute = strtol(&cp[16], NULL, 10);
3624 second = strtol(&cp[19], NULL, 10);
3625 if ((t = combinetime(year, month, day, hour, minute, second)) == (time_t)-1)
3626 goto jinvalid;
3627 switch (cp[22]) {
3628 case '-':
3629 sign = 1;
3630 break;
3631 case '+':
3632 break;
3633 default:
3634 goto jinvalid;
3636 buf[2] = '\0';
3637 buf[0] = cp[23];
3638 buf[1] = cp[24];
3639 t += strtol(buf, NULL, 10) * sign * 3600;
3640 buf[0] = cp[25];
3641 buf[1] = cp[26];
3642 t += strtol(buf, NULL, 10) * sign * 60;
3643 jleave:
3644 NYD2_LEAVE;
3645 return t;
3646 jinvalid:
3647 time(&t);
3648 goto jleave;
3651 FL const char *
3652 imap_make_date_time(time_t t)
3654 static char s[30];
3655 struct tm *tmptr;
3656 int tzdiff, tzdiff_hour, tzdiff_min;
3657 NYD2_ENTER;
3659 tzdiff = t - mktime(gmtime(&t));
3660 tzdiff_hour = (int)(tzdiff / 60);
3661 tzdiff_min = tzdiff_hour % 60;
3662 tzdiff_hour /= 60;
3663 tmptr = localtime(&t);
3664 if (tmptr->tm_isdst > 0)
3665 tzdiff_hour++;
3666 snprintf(s, sizeof s, "\"%02d-%s-%04d %02d:%02d:%02d %+03d%02d\"",
3667 tmptr->tm_mday, month_names[tmptr->tm_mon], tmptr->tm_year + 1900,
3668 tmptr->tm_hour, tmptr->tm_min, tmptr->tm_sec, tzdiff_hour, tzdiff_min);
3669 NYD2_LEAVE;
3670 return s;
3672 #endif /* HAVE_IMAP */
3674 #if defined HAVE_IMAP || defined HAVE_IMAP_SEARCH
3675 FL char *
3676 imap_quotestr(char const *s)
3678 char *n, *np;
3679 NYD2_ENTER;
3681 np = n = salloc(2 * strlen(s) + 3);
3682 *np++ = '"';
3683 while (*s) {
3684 if (*s == '"' || *s == '\\')
3685 *np++ = '\\';
3686 *np++ = *s++;
3688 *np++ = '"';
3689 *np = '\0';
3690 NYD2_LEAVE;
3691 return n;
3694 FL char *
3695 imap_unquotestr(char const *s)
3697 char *n, *np;
3698 NYD2_ENTER;
3700 if (*s != '"') {
3701 n = savestr(s);
3702 goto jleave;
3705 np = n = salloc(strlen(s) + 1);
3706 while (*++s) {
3707 if (*s == '\\')
3708 s++;
3709 else if (*s == '"')
3710 break;
3711 *np++ = *s;
3713 *np = '\0';
3714 jleave:
3715 NYD2_LEAVE;
3716 return n;
3718 #endif /* defined HAVE_IMAP || defined HAVE_IMAP_SEARCH */
3720 /* s-it-mode */