imapext-2007

view src/imapd/imapd.c @ 1:28a55bc1110c

[mq]: imapext
author yuuji@gentei.org
date Mon, 14 Sep 2009 19:23:11 +0900
parents ada5e610ab86
children 2366b362676d 20c025a380ab
line source
1 /* ========================================================================
2 * Copyright 1988-2008 University of Washington
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 *
11 * ========================================================================
12 */
14 /*
15 * Program: IMAP4rev1 server
16 *
17 * Author: Mark Crispin
18 * UW Technology
19 * University of Washington
20 * Seattle, WA 98195
21 * Internet: MRC@Washington.EDU
22 *
23 * Date: 5 November 1990
24 * Last Edited: 3 March 2008
25 */
27 /* Parameter files */
29 #include <stdio.h>
30 #include <ctype.h>
31 #include <errno.h>
32 extern int errno; /* just in case */
33 #include <signal.h>
34 #include <setjmp.h>
35 #include <time.h>
36 #include "c-client.h"
37 #include "newsrc.h"
38 #include <sys/stat.h>
41 #define CRLF PSOUT ("\015\012") /* primary output terpri */
44 /* Timeouts and timers */
46 #define MINUTES *60
48 #define LOGINTIMEOUT 3 MINUTES /* not logged in autologout timer */
49 #define TIMEOUT 30 MINUTES /* RFC 3501 minimum autologout timer */
50 #define INPUTTIMEOUT 5 MINUTES /* timer for additional command input */
51 #define ALERTTIMER 1 MINUTES /* alert check timer */
52 #define SHUTDOWNTIMER 1 MINUTES /* shutdown dally timer */
53 #define IDLETIMER 1 MINUTES /* IDLE command poll timer */
54 #define CHECKTIMER 15 MINUTES /* IDLE command last checkpoint timer */
57 #define LITSTKLEN 20 /* length of literal stack */
58 #define MAXCLIENTLIT 10000 /* maximum non-APPEND client literal size
59 * must be smaller than 4294967295
60 */
61 #define MAXAPPENDTXT 0x40000000 /* maximum APPEND literal size
62 * must be smaller than 4294967295
63 */
64 #define CMDLEN 65536 /* size of command buffer */
67 /* Server states */
69 #define LOGIN 0
70 #define SELECT 1
71 #define OPEN 2
72 #define LOGOUT 3
74 /* Body text fetching */
76 typedef struct text_args {
77 char *section; /* body section */
78 STRINGLIST *lines; /* header lines */
79 unsigned long first; /* first octet to fetch */
80 unsigned long last; /* number of octets to fetch */
81 long flags; /* fetch flags */
82 long binary; /* binary flags */
83 } TEXTARGS;
85 #define FTB_BINARY 0x1 /* fetch as binary */
86 #define FTB_SIZE 0x2 /* fetch size only */
89 /* Append data */
91 typedef struct append_data {
92 unsigned char *arg; /* append argument pointer */
93 char *flags; /* message flags */
94 char *date; /* message date */
95 char *msg; /* message text */
96 STRING *message; /* message stringstruct */
97 } APPENDDATA;
100 /* Message pointer */
102 typedef struct msg_data {
103 MAILSTREAM *stream; /* stream */
104 unsigned long msgno; /* message number */
105 char *flags; /* current flags */
106 char *date; /* current date */
107 STRING *message; /* stringstruct of message */
108 } MSGDATA;
110 /* Function prototypes */
112 int main (int argc,char *argv[]);
113 void ping_mailbox (unsigned long uid);
114 time_t palert (char *file,time_t oldtime);
115 void msg_string_init (STRING *s,void *data,unsigned long size);
116 char msg_string_next (STRING *s);
117 void msg_string_setpos (STRING *s,unsigned long i);
118 void new_flags (MAILSTREAM *stream);
119 void settimeout (unsigned int i);
120 void clkint (void);
121 void kodint (void);
122 void hupint (void);
123 void trmint (void);
124 void staint (void);
125 char *sout (char *s,char *t);
126 char *nout (char *s,unsigned long n,unsigned long base);
127 void slurp (char *s,int n,unsigned long timeout);
128 void inliteral (char *s,unsigned long n);
129 unsigned char *flush (void);
130 void ioerror (FILE *f,char *reason);
131 unsigned char *parse_astring (unsigned char **arg,unsigned long *i,
132 unsigned char *del);
133 unsigned char *snarf (unsigned char **arg);
134 unsigned char *snarf_base64 (unsigned char **arg);
135 unsigned char *snarf_list (unsigned char **arg);
136 STRINGLIST *parse_stringlist (unsigned char **s,int *list);
137 unsigned long uidmax (MAILSTREAM *stream);
138 long parse_criteria (SEARCHPGM *pgm,unsigned char **arg,unsigned long maxmsg,
139 unsigned long maxuid,unsigned long depth);
140 long parse_criterion (SEARCHPGM *pgm,unsigned char **arg,unsigned long msgmsg,
141 unsigned long maxuid,unsigned long depth);
142 long crit_date (unsigned short *date,unsigned char **arg);
143 long crit_date_work (unsigned short *date,unsigned char **arg);
144 long crit_set (SEARCHSET **set,unsigned char **arg,unsigned long maxima);
145 long crit_number (unsigned long *number,unsigned char **arg);
146 long crit_string (STRINGLIST **string,unsigned char **arg);
148 void fetch (char *t,unsigned long uid);
149 typedef void (*fetchfn_t) (unsigned long i,void *args);
150 void fetch_work (char *t,unsigned long uid,fetchfn_t f[],void *fa[]);
151 void fetch_bodystructure (unsigned long i,void *args);
152 void fetch_body (unsigned long i,void *args);
153 void fetch_body_part_mime (unsigned long i,void *args);
154 void fetch_body_part_contents (unsigned long i,void *args);
155 void fetch_body_part_binary (unsigned long i,void *args);
156 void fetch_body_part_header (unsigned long i,void *args);
157 void fetch_body_part_text (unsigned long i,void *args);
158 void remember (unsigned long uid,char *id,SIZEDTEXT *st);
159 void fetch_envelope (unsigned long i,void *args);
160 void fetch_encoding (unsigned long i,void *args);
161 void changed_flags (unsigned long i,int f);
162 void fetch_flags (unsigned long i,void *args);
163 void put_flag (int *c,char *s);
164 void fetch_internaldate (unsigned long i,void *args);
165 void fetch_uid (unsigned long i,void *args);
166 void fetch_rfc822 (unsigned long i,void *args);
167 void fetch_rfc822_header (unsigned long i,void *args);
168 void fetch_rfc822_size (unsigned long i,void *args);
169 void fetch_rfc822_text (unsigned long i,void *args);
170 void penv (ENVELOPE *env);
171 void pbodystructure (BODY *body);
172 void pbody (BODY *body);
173 void pparam (PARAMETER *param);
174 void paddr (ADDRESS *a);
175 void pset (SEARCHSET **set);
176 void pnum (unsigned long i);
177 void pstring (char *s);
178 void pnstring (char *s);
179 void pastring (char *s);
180 void psizedquoted (SIZEDTEXT *s);
181 void psizedliteral (SIZEDTEXT *s,STRING *st);
182 void psizedstring (SIZEDTEXT *s,STRING *st);
183 void psizedastring (SIZEDTEXT *s);
184 void pastringlist (STRINGLIST *s);
185 void pnstringorlist (STRINGLIST *s);
186 void pbodypartstring (unsigned long msgno,char *id,SIZEDTEXT *st,STRING *bs,
187 TEXTARGS *ta);
188 void ptext (SIZEDTEXT *s,STRING *st);
189 void pthread (THREADNODE *thr);
190 void pcapability (long flag);
191 long nameok (char *ref,char *name);
192 char *bboardname (char *cmd,char *name);
193 long isnewsproxy (char *name);
194 long newsproxypattern (char *ref,char *pat,char *pattern,long flag);
195 char *imap_responder (void *challenge,unsigned long clen,unsigned long *rlen);
196 long proxycopy (MAILSTREAM *stream,char *sequence,char *mailbox,long options);
197 long proxy_append (MAILSTREAM *stream,void *data,char **flags,char **date,
198 STRING **message);
199 long append_msg (MAILSTREAM *stream,void *data,char **flags,char **date,
200 STRING **message);
201 void copyuid (MAILSTREAM *stream,char *mailbox,unsigned long uidvalidity,
202 SEARCHSET *sourceset,SEARCHSET *destset);
203 void appenduid (char *mailbox,unsigned long uidvalidity,SEARCHSET *set);
204 char *referral (MAILSTREAM *stream,char *url,long code);
205 void mm_list_work (char *what,int delimiter,char *name,long attributes);
206 char *lasterror (void);
208 /* Global storage */
210 char *version = "404"; /* edit number of this server */
211 char *logout = "Logout"; /* syslogreason for logout */
212 char *goodbye = NIL; /* bye reason */
213 time_t alerttime = 0; /* time of last alert */
214 time_t sysalerttime = 0; /* time of last system alert */
215 time_t useralerttime = 0; /* time of last user alert */
216 time_t lastcheck = 0; /* time of last checkpoint */
217 time_t shutdowntime = 0; /* time of last shutdown */
218 int state = LOGIN; /* server state */
219 int cancelled = NIL; /* authenticate cancelled */
220 int trycreate = 0; /* saw a trycreate */
221 int finding = NIL; /* doing old FIND command */
222 int anonymous = 0; /* non-zero if anonymous */
223 int critical = NIL; /* non-zero if in critical code */
224 int quell_events = NIL; /* non-zero if in FETCH response */
225 int existsquelled = NIL; /* non-zero if an EXISTS was quelled */
226 int proxylist = NIL; /* doing a proxy LIST */
227 MAILSTREAM *stream = NIL; /* mailbox stream */
228 DRIVER *curdriver = NIL; /* note current driver */
229 MAILSTREAM *tstream = NIL; /* temporary mailbox stream */
230 unsigned int nflags = 0; /* current number of keywords */
231 unsigned long nmsgs =0xffffffff;/* last reported # of messages and recent */
232 unsigned long recent = 0xffffffff;
233 char *nntpproxy = NIL; /* NNTP proxy name */
234 unsigned char *user = NIL; /* user name */
235 unsigned char *pass = NIL; /* password */
236 unsigned char *initial = NIL; /* initial response */
237 unsigned char cmdbuf[CMDLEN]; /* command buffer */
238 char *status = "starting up"; /* server status */
239 char *tag; /* tag portion of command */
240 unsigned char *cmd; /* command portion of command */
241 unsigned char *arg; /* pointer to current argument of command */
242 char *lstwrn = NIL; /* last warning message from c-client */
243 char *lsterr = NIL; /* last error message from c-client */
244 char *lstref = NIL; /* last referral from c-client */
245 char *response = NIL; /* command response */
246 struct {
247 unsigned long size; /* size of current LITERAL+ */
248 unsigned int ok : 1; /* LITERAL+ in effect */
249 } litplus;
250 int litsp = 0; /* literal stack pointer */
251 char *litstk[LITSTKLEN]; /* stack to hold literals */
252 unsigned long uidvalidity = 0; /* last reported UID validity */
253 unsigned long lastuid = 0; /* last fetched uid */
254 char *lastid = NIL; /* last fetched body id for this message */
255 char *lastsel = NIL; /* last selected mailbox name */
256 SIZEDTEXT lastst = {NIL,0}; /* last sizedtext */
257 unsigned long cauidvalidity = 0;/* UIDVALIDITY for COPYUID/APPENDUID */
258 SEARCHSET *csset = NIL; /* COPYUID source set */
259 SEARCHSET *caset = NIL; /* COPYUID/APPENDUID destination set */
260 jmp_buf jmpenv; /* stack context for setjmp */
263 /* Response texts which appear in multiple places */
265 char *win = "%.80s OK ";
266 char *rowin = "%.80s OK [READ-ONLY] %.80s completed\015\012";
267 char *rwwin = "%.80s OK [READ-WRITE] %.80s completed\015\012";
268 char *lose = "%.80s NO ";
269 char *logwin = "%.80s OK [";
270 char *losetry = "%.80s NO [TRYCREATE] %.80s failed: %.900s\015\012";
271 char *loseunknowncte = "%.80s NO [UNKNOWN-CTE] %.80s failed: %.900s\015\012";
272 char *badcmd = "%.80s BAD Command unrecognized: %.80s\015\012";
273 char *misarg = "%.80s BAD Missing or invalid argument to %.80s\015\012";
274 char *badarg = "%.80s BAD Argument given to %.80s when none expected\015\012";
275 char *badseq = "%.80s BAD Bogus sequence in %.80s: %.80s\015\012";
276 char *badatt = "%.80s BAD Bogus attribute list in %.80s\015\012";
277 char *badbin = "%.80s BAD Syntax error in binary specifier\015\012";
279 /* Message string driver for message stringstructs */
281 STRINGDRIVER msg_string = {
282 msg_string_init, /* initialize string structure */
283 msg_string_next, /* get next byte in string structure */
284 msg_string_setpos /* set position in string structure */
285 };
287 /* Main program */
289 int main (int argc,char *argv[])
290 {
291 unsigned long i,uid;
292 long f;
293 unsigned char *s,*t,*u,*v,tmp[MAILTMPLEN];
294 struct stat sbuf;
295 logouthook_t lgoh;
296 int ret = 0;
297 time_t autologouttime = 0;
298 char *pgmname;
299 /* if case we get borked immediately */
300 if (setjmp (jmpenv)) _exit (1);
301 pgmname = (argc && argv[0]) ?
302 (((s = strrchr (argv[0],'/')) || (s = strrchr (argv[0],'\\'))) ?
303 (char *) s+1 : argv[0]) : "imapd";
304 /* set service name before linkage */
305 mail_parameters (NIL,SET_SERVICENAME,(void *) "imap");
306 #include "linkage.c"
307 rfc822_date (tmp); /* get date/time at startup */
308 /* initialize server */
309 server_init (pgmname,"imap","imaps",clkint,kodint,hupint,trmint,staint);
310 /* forbid automatic untagged expunge */
311 mail_parameters (NIL,SET_EXPUNGEATPING,NIL);
312 /* arm proxy copy callback */
313 mail_parameters (NIL,SET_MAILPROXYCOPY,(void *) proxycopy);
314 /* arm referral callback */
315 mail_parameters (NIL,SET_IMAPREFERRAL,(void *) referral);
316 /* arm COPYUID callback */
317 mail_parameters (NIL,SET_COPYUID,(void *) copyuid);
318 /* arm APPENDUID callback */
319 mail_parameters (NIL,SET_APPENDUID,(void *) appenduid);
321 if (stat (SHUTDOWNFILE,&sbuf)) {
322 char proxy[MAILTMPLEN];
323 FILE *nntp = fopen (NNTPFILE,"r");
324 if (nntp) { /* desire NNTP proxy? */
325 if (fgets (proxy,MAILTMPLEN,nntp)) {
326 /* remove newline and set NNTP proxy */
327 if (s = strchr (proxy,'\n')) *s = '\0';
328 nntpproxy = cpystr (proxy);
329 /* disable the news driver */
330 mail_parameters (NIL,DISABLE_DRIVER,"news");
331 }
332 fclose (nntp); /* done reading proxy name */
333 }
334 s = myusername_full (&i); /* get user name and flags */
335 switch (i) {
336 case MU_NOTLOGGEDIN:
337 PSOUT ("* OK ["); /* not logged in, ordinary startup */
338 pcapability (-1);
339 break;
340 case MU_ANONYMOUS:
341 anonymous = T; /* anonymous user, fall into default */
342 s = "ANONYMOUS";
343 case MU_LOGGEDIN:
344 PSOUT ("* PREAUTH ["); /* already logged in, pre-authorized */
345 pcapability (1);
346 user = cpystr (s); /* copy user name */
347 pass = cpystr ("*"); /* set fake password */
348 state = SELECT; /* enter select state */
349 break;
350 default:
351 fatal ("Unknown state from myusername_full()");
352 }
353 PSOUT ("] ");
354 if (user) { /* preauthenticated as someone? */
355 PSOUT ("Pre-authenticated user ");
356 PSOUT (user);
357 PBOUT (' ');
358 }
359 }
360 else { /* login disabled */
361 PSOUT ("* BYE Service not available ");
362 state = LOGOUT;
363 }
364 PSOUT (tcp_serverhost ());
365 PSOUT (" IMAP4rev1 ");
366 PSOUT (CCLIENTVERSION);
367 PBOUT ('.');
368 PSOUT (version);
369 PSOUT (" at ");
370 PSOUT (tmp);
371 CRLF;
372 PFLUSH (); /* dump output buffer */
373 switch (state) { /* do this after the banner */
374 case LOGIN:
375 autologouttime = time (0) + LOGINTIMEOUT;
376 break;
377 case SELECT:
378 syslog (LOG_INFO,"Preauthenticated user=%.80s host=%.80s",
379 user,tcp_clienthost ());
380 break;
381 }
383 if (setjmp (jmpenv)) { /* die if a signal handler say so */
384 /* in case we get borked now */
385 if (setjmp (jmpenv)) _exit (1);
386 /* need to close stream gracefully? */
387 if (stream && !stream->lock && (stream->dtb->flags & DR_XPOINT))
388 stream = mail_close (stream);
389 ret = 1; /* set exit status */
390 }
391 else while (state != LOGOUT) {/* command processing loop */
392 slurp (cmdbuf,CMDLEN,TIMEOUT);
393 /* no more last error or literal */
394 if (lstwrn) fs_give ((void **) &lstwrn);
395 if (lsterr) fs_give ((void **) &lsterr);
396 if (lstref) fs_give ((void **) &lstref);
397 while (litsp) fs_give ((void **) &litstk[--litsp]);
398 /* find end of line */
399 if (!strchr (cmdbuf,'\012')) {
400 if (t = strchr (cmdbuf,' ')) *t = '\0';
401 if ((t - cmdbuf) > 100) t = NIL;
402 flush (); /* flush excess */
403 if (state == LOGIN) /* error if NLI */
404 syslog (LOG_INFO,"Line too long before authentication host=%.80s",
405 tcp_clienthost ());
406 sprintf (tmp,response,t ? (char *) cmdbuf : "*");
407 PSOUT (tmp);
408 }
409 else if (!(tag = strtok (cmdbuf," \015\012"))) {
410 if (state == LOGIN) /* error if NLI */
411 syslog (LOG_INFO,"Null command before authentication host=%.80s",
412 tcp_clienthost ());
413 PSOUT ("* BAD Null command\015\012");
414 }
415 else if (strlen (tag) > 50) PSOUT ("* BAD Excessively long tag\015\012");
416 else if (!(s = strtok (NIL," \015\012"))) {
417 if (state == LOGIN) /* error if NLI */
418 syslog (LOG_INFO,"Missing command before authentication host=%.80s",
419 tcp_clienthost ());
420 PSOUT (tag);
421 PSOUT (" BAD Missing command\015\012");
422 }
423 else { /* parse command */
424 response = win; /* set default response */
425 finding = NIL; /* no longer FINDing */
426 ucase (s); /* canonicalize command case */
427 /* UID command? */
428 if (!strcmp (s,"UID") && strtok (NIL," \015\012")) {
429 uid = T; /* a UID command */
430 s[3] = ' '; /* restore the space delimiter */
431 ucase (s); /* make sure command all uppercase */
432 }
433 else uid = NIL; /* not a UID command */
434 /* flush previous saved command */
435 if (cmd) fs_give ((void **) &cmd);
436 cmd = cpystr (s); /* save current command */
437 /* snarf argument, see if possible litplus */
438 if ((arg = strtok (NIL,"\015\012")) && ((i = strlen (arg)) > 3) &&
439 (arg[i - 1] == '}') && (arg[i - 2] == '+') && isdigit (arg[i - 3])) {
440 /* back over possible count */
441 for (i -= 4; i && isdigit (arg[i]); i--);
442 if (arg[i] == '{') { /* found a literal? */
443 litplus.ok = T; /* yes, note LITERAL+ in effect, set size */
444 litplus.size = strtoul (arg + i + 1,NIL,10);
445 }
446 }
448 /* these commands always valid */
449 if (!strcmp (cmd,"NOOP")) {
450 if (arg) response = badarg;
451 else if (stream) /* allow untagged EXPUNGE */
452 mail_parameters (stream,SET_ONETIMEEXPUNGEATPING,(void *) stream);
453 }
454 else if (!strcmp (cmd,"LOGOUT")) {
455 if (arg) response = badarg;
456 else { /* time to say farewell */
457 server_init (NIL,NIL,NIL,SIG_IGN,SIG_IGN,SIG_IGN,SIG_IGN,SIG_IGN);
458 if (lastsel) fs_give ((void **) &lastsel);
459 if (state == OPEN) stream = mail_close (stream);
460 state = LOGOUT;
461 PSOUT ("* BYE ");
462 PSOUT (mylocalhost ());
463 PSOUT (" IMAP4rev1 server terminating connection\015\012");
464 }
465 }
466 else if (!strcmp (cmd,"CAPABILITY")) {
467 if (arg) response = badarg;
468 else {
469 PSOUT ("* ");
470 pcapability (0); /* print capabilities */
471 CRLF;
472 }
473 if (stream) /* allow untagged EXPUNGE */
474 mail_parameters (stream,SET_ONETIMEEXPUNGEATPING,(void *) stream);
475 }
476 #ifdef NETSCAPE_BRAIN_DAMAGE
477 else if (!strcmp (cmd,"NETSCAPE")) {
478 PSOUT ("* OK [NETSCAPE]\015\012* VERSION 1.0 UNIX\015\012* ACCOUNT-URL \"");
479 PSOUT (NETSCAPE_BRAIN_DAMAGE);
480 PBOUT ('"');
481 CRLF;
482 }
483 #endif
485 else switch (state) { /* dispatch depending upon state */
486 case LOGIN: /* waiting to get logged in */
487 /* new style authentication */
488 if (!strcmp (cmd,"AUTHENTICATE")) {
489 if (user) fs_give ((void **) &user);
490 if (pass) fs_give ((void **) &pass);
491 initial = NIL; /* no initial argument */
492 cancelled = NIL; /* not cancelled */
493 /* mandatory first argument */
494 if (!(s = snarf (&arg))) response = misarg;
495 else if (arg && !(initial = snarf_base64 (&arg)))
496 response = misarg; /* optional second argument */
497 else if (arg) response = badarg;
498 else if (!strcmp (ucase (s),"ANONYMOUS") && !stat (ANOFILE,&sbuf)) {
499 if (!(s = imap_responder ("",0,NIL)))
500 response ="%.80s BAD AUTHENTICATE ANONYMOUS cancelled\015\012";
501 else if (anonymous_login (argc,argv)) {
502 anonymous = T; /* note we are anonymous */
503 user = cpystr ("ANONYMOUS");
504 pass = cpystr ("*");
505 state = SELECT; /* make select */
506 alerttime = 0; /* force alert */
507 response = logwin;/* return logged-in capabilities */
508 syslog (LOG_INFO,"Authenticated anonymous=%.80s host=%.80s",s,
509 tcp_clienthost ());
510 fs_give ((void **) &s);
511 }
512 else response ="%.80s NO AUTHENTICATE ANONYMOUS failed\015\012";
513 }
514 else if (user = cpystr (mail_auth (s,imap_responder,argc,argv))) {
515 pass = cpystr ("*");
516 state = SELECT; /* make select */
517 alerttime = 0; /* force alert */
518 response = logwin; /* return logged-in capabilities */
519 syslog (LOG_INFO,"Authenticated user=%.80s host=%.80s mech=%.80s",
520 user,tcp_clienthost (),s);
521 }
523 else {
524 AUTHENTICATOR *auth = mail_lookup_auth (1);
525 char *msg = (char *) fs_get (strlen (cmd) + strlen (s) + 2);
526 sprintf (msg,"%s %s",cmd,s);
527 fs_give ((void **) &cmd);
528 cmd = msg;
529 for (i = !mail_parameters (NIL,GET_DISABLEPLAINTEXT,NIL);
530 auth && compare_cstring (s,auth->name); auth = auth->next);
531 /* Failed authentication when hidden looks like invalid command.
532 * This is intentional but confused me when I was debugging.
533 */
534 if (auth && auth->server && !(auth->flags & AU_DISABLE) &&
535 !(auth->flags & AU_HIDE) && (i || (auth->flags & AU_SECURE))) {
536 response = lose;
537 if (cancelled) {
538 if (lsterr) fs_give ((void **) &lsterr);
539 lsterr = cpystr ("cancelled by user");
540 }
541 if (!lsterr) /* catch-all */
542 lsterr = cpystr ("Invalid authentication credentials");
543 syslog (LOG_INFO,"AUTHENTICATE %.80s failure host=%.80s",s,
544 tcp_clienthost ());
545 }
546 else {
547 response = badcmd;
548 syslog (LOG_INFO,"AUTHENTICATE %.80s invalid host=%.80s",s,
549 tcp_clienthost ());
550 }
551 }
552 }
554 /* plaintext login with password */
555 else if (!strcmp (cmd,"LOGIN")) {
556 #ifdef QMAIL
557 extern char* conv_virtualdomain(char*);
558 #endif
559 if (user) fs_give ((void **) &user);
560 if (pass) fs_give ((void **) &pass);
561 /* two arguments */
562 if (!((user = cpystr (snarf (&arg))) &&
563 (pass = cpystr (snarf (&arg))))) response = misarg;
564 else if (arg) response = badarg;
565 /* see if we allow anonymous */
566 else if (!compare_cstring (user,"ANONYMOUS") &&
567 !stat (ANOFILE,&sbuf) && anonymous_login (argc,argv)) {
568 anonymous = T; /* note we are anonymous */
569 ucase (user); /* make all uppercase for consistency */
570 state = SELECT; /* make select */
571 alerttime = 0; /* force alert */
572 response = logwin; /* return logged-in capabilities */
573 syslog (LOG_INFO,"Login anonymous=%.80s host=%.80s",pass,
574 tcp_clienthost ());
575 }
576 else { /* delimit user from possible admin */
577 if (s = strchr (user,'*')) *s++ ='\0';
578 /* see if username and password are OK */
579 #ifdef QMAIL
580 if (server_login (conv_virtualdomain(user),pass,s,argc,argv)) {
581 #else
582 if (server_login (user,pass,s,argc,argv)) {
583 #endif
584 state = SELECT; /* make select */
585 alerttime = 0; /* force alert */
586 response = logwin;/* return logged-in capabilities */
587 syslog (LOG_INFO,"Login user=%.80s host=%.80s",user,
588 tcp_clienthost ());
589 }
590 else {
591 response = lose;
592 if (!lsterr) lsterr = cpystr ("Invalid login credentials");
593 }
594 }
595 }
596 /* start TLS security */
597 else if (!strcmp (cmd,"STARTTLS")) {
598 if (arg) response = badarg;
599 else if (lsterr = ssl_start_tls (pgmname)) response = lose;
600 }
601 else response = badcmd;
602 break;
604 case OPEN: /* valid only when mailbox open */
605 /* fetch mailbox attributes */
606 if (!strcmp (cmd,"FETCH") || !strcmp (cmd,"UID FETCH")) {
607 if (!(arg && (s = strtok (arg," ")) && (t = strtok(NIL,"\015\012"))))
608 response = misarg;
609 else if (uid ? mail_uid_sequence (stream,s) :
610 mail_sequence (stream,s)) fetch (t,uid);
611 else response = badseq;
612 }
613 /* store mailbox attributes */
614 else if (!strcmp (cmd,"STORE") || !strcmp (cmd,"UID STORE")) {
615 /* must have three arguments */
616 if (!(arg && (s = strtok (arg," ")) && (v = strtok (NIL," ")) &&
617 (t = strtok (NIL,"\015\012")))) response = misarg;
618 else if (!(uid ? mail_uid_sequence (stream,s) :
619 mail_sequence (stream,s))) response = badseq;
620 else {
621 f = ST_SET | (uid ? ST_UID : NIL)|((v[5]&&v[6]) ? ST_SILENT : NIL);
622 if (!strcmp (ucase (v),"FLAGS") || !strcmp (v,"FLAGS.SILENT")) {
623 strcpy (tmp,"\\Answered \\Flagged \\Deleted \\Draft \\Seen");
624 for (i = 0, u = tmp;
625 (i < NUSERFLAGS) && (v = stream->user_flags[i]); i++)
626 if (strlen (v) <
627 ((size_t) (MAILTMPLEN - ((u += strlen (u)) + 2 - tmp)))) {
628 *u++ = ' '; /* write next flag */
629 strcpy (u,v);
630 }
631 mail_flag (stream,s,tmp,f & ~ST_SET);
632 }
633 else if (!strcmp (v,"-FLAGS") || !strcmp (v,"-FLAGS.SILENT"))
634 f &= ~ST_SET; /* clear flags */
635 else if (strcmp (v,"+FLAGS") && strcmp (v,"+FLAGS.SILENT")) {
636 response = badatt;
637 break;
638 }
639 /* find last keyword */
640 for (i = 0; (i < NUSERFLAGS) && stream->user_flags[i]; i++);
641 mail_flag (stream,s,t,f);
642 /* any new keywords appeared? */
643 if (i < NUSERFLAGS && stream->user_flags[i]) new_flags (stream);
644 /* return flags if silence not wanted */
645 if (uid ? mail_uid_sequence (stream,s) : mail_sequence (stream,s))
646 for (i = 1; i <= nmsgs; i++) if (mail_elt(stream,i)->sequence)
647 mail_elt (stream,i)->spare2 = (f & ST_SILENT) ? NIL : T;
648 }
649 }
651 /* check for new mail */
652 else if (!strcmp (cmd,"CHECK")) {
653 /* no arguments */
654 if (arg) response = badarg;
655 else if (!anonymous) {
656 mail_check (stream);
657 /* remember last check time */
658 lastcheck = time (0);
659 }
660 }
661 /* expunge deleted messages */
662 else if (!(anonymous || (strcmp (cmd,"EXPUNGE") &&
663 strcmp (cmd,"UID EXPUNGE")))) {
664 if (uid && !arg) response = misarg;
665 else if (!uid && arg) response = badarg;
666 else { /* expunge deleted or specified UIDs */
667 mail_expunge_full (stream,arg,arg ? EX_UID : NIL);
668 /* remember last checkpoint */
669 lastcheck = time (0);
670 }
671 }
672 /* close mailbox */
673 else if (!strcmp (cmd,"CLOSE") || !strcmp (cmd,"UNSELECT")) {
674 /* no arguments */
675 if (arg) response = badarg;
676 else {
677 /* no last uid */
678 uidvalidity = lastuid = 0;
679 if (lastsel) fs_give ((void **) &lastsel);
680 if (lastid) fs_give ((void **) &lastid);
681 if (lastst.data) fs_give ((void **) &lastst.data);
682 stream = mail_close_full (stream,((*cmd == 'C') && !anonymous) ?
683 CL_EXPUNGE : NIL);
684 state = SELECT; /* no longer opened */
685 lastcheck = 0; /* no last checkpoint */
686 }
687 }
688 else if (!anonymous && /* copy message(s) */
689 (!strcmp (cmd,"COPY") || !strcmp (cmd,"UID COPY"))) {
690 trycreate = NIL; /* no trycreate status */
691 if (!(arg && (s = strtok (arg," ")) && (arg = strtok(NIL,"\015\012"))
692 && (t = snarf (&arg)))) response = misarg;
693 else if (arg) response = badarg;
694 else if (!nmsgs) {
695 response = lose;
696 if (!lsterr) lsterr = cpystr ("Mailbox is empty");
697 }
698 else if (!(uid ? mail_uid_sequence (stream,s) :
699 mail_sequence (stream,s))) response = badseq;
700 /* try copy */
701 else if (!mail_copy_full (stream,s,t,uid ? CP_UID : NIL)) {
702 response = trycreate ? losetry : lose;
703 if (!lsterr) lsterr = cpystr ("No such destination mailbox");
704 }
705 }
707 /* sort mailbox */
708 else if (!strcmp (cmd,"SORT") || !strcmp (cmd,"UID SORT")) {
709 /* must have four arguments */
710 if (!(arg && (*arg == '(') && (t = strchr (s = arg + 1,')')) &&
711 (t[1] == ' ') && (*(arg = t + 2)))) response = misarg;
712 else { /* read criteria */
713 SEARCHPGM *spg = NIL;
714 char *cs = NIL;
715 SORTPGM *pgm = NIL,*pg = NIL;
716 unsigned long *slst,*sl;
717 *t = NIL; /* tie off criteria list */
718 if (!(s = strtok (ucase (s)," "))) response = badatt;
719 else {
720 do { /* parse sort attributes */
721 if (pg) pg = pg->next = mail_newsortpgm ();
722 else pgm = pg = mail_newsortpgm ();
723 if (!strcmp (s,"REVERSE")) {
724 pg->reverse = T;
725 if (!(s = strtok (NIL," "))) {
726 s = ""; /* end of attributes */
727 break;
728 }
729 }
730 if (!strcmp (s,"DATE")) pg->function = SORTDATE;
731 else if (!strcmp (s,"ARRIVAL")) pg->function = SORTARRIVAL;
732 else if (!strcmp (s,"FROM")) pg->function = SORTFROM;
733 else if (!strcmp (s,"SUBJECT")) pg->function = SORTSUBJECT;
734 else if (!strcmp (s,"TO")) pg->function = SORTTO;
735 else if (!strcmp (s,"CC")) pg->function = SORTCC;
736 else if (!strcmp (s,"SIZE")) pg->function = SORTSIZE;
737 else break;
738 } while (s = strtok (NIL," "));
739 /* bad SORT attribute */
740 if (s) response = badatt;
741 /* get charset and search criteria */
742 else if (!((t = snarf (&arg)) && (cs = cpystr (t)) && arg &&
743 *arg)) response = misarg;
744 /* parse search criteria */
745 else if (!parse_criteria (spg = mail_newsearchpgm (),&arg,nmsgs,
746 uidmax (stream),0)) response = badatt;
747 else if (arg && *arg) response = badarg;
748 else if (slst = mail_sort (stream,cs,spg,pgm,uid ? SE_UID:NIL)) {
749 PSOUT ("* SORT");
750 for (sl = slst; *sl; sl++) {
751 PBOUT (' ');
752 pnum (*sl);
753 }
754 CRLF;
755 fs_give ((void **) &slst);
756 }
757 }
758 if (pgm) mail_free_sortpgm (&pgm);
759 if (spg) mail_free_searchpgm (&spg);
760 if (cs) fs_give ((void **) &cs);
761 }
762 }
764 /* thread mailbox */
765 else if (!strcmp (cmd,"THREAD") || !strcmp (cmd,"UID THREAD")) {
766 THREADNODE *thr;
767 SEARCHPGM *spg = NIL;
768 char *cs = NIL;
769 /* must have four arguments */
770 if (!(arg && (s = strtok (arg," ")) && (cs = strtok (NIL," ")) &&
771 (cs = cpystr (cs)) && (arg = strtok (NIL,"\015\012"))))
772 response = misarg;
773 else if (!parse_criteria (spg = mail_newsearchpgm (),&arg,nmsgs,
774 uidmax (stream),0)) response = badatt;
775 else if (arg && *arg) response = badarg;
776 else {
777 if (thr = mail_thread (stream,s,cs,spg,uid ? SE_UID : NIL)) {
778 PSOUT ("* THREAD ");
779 pthread (thr);
780 mail_free_threadnode (&thr);
781 }
782 else PSOUT ("* THREAD");
783 CRLF;
784 }
785 if (spg) mail_free_searchpgm (&spg);
786 if (cs) fs_give ((void **) &cs);
787 }
789 /* search mailbox */
790 else if (!strcmp (cmd,"SEARCH") || !strcmp (cmd,"UID SEARCH")) {
791 int retval = NIL;
792 char *charset = NIL;
793 SEARCHPGM *pgm;
794 response = misarg; /* assume failure */
795 if (!arg) break; /* one or more arguments required */
796 if (((arg[0] == 'R') || (arg[0] == 'r')) &&
797 ((arg[1] == 'E') || (arg[1] == 'e')) &&
798 ((arg[2] == 'T') || (arg[2] == 't')) &&
799 ((arg[3] == 'U') || (arg[3] == 'u')) &&
800 ((arg[4] == 'R') || (arg[4] == 'r')) &&
801 ((arg[5] == 'N') || (arg[5] == 'n')) &&
802 (arg[6] == ' ') && (arg[7] == '(')) {
803 retval = 0x4000; /* return is specified */
804 for (arg += 8; *arg && (*arg != ')'); ) {
805 if (((arg[0] == 'M') || (arg[0] == 'm')) &&
806 ((arg[1] == 'I') || (arg[1] == 'i')) &&
807 ((arg[2] == 'N') || (arg[2] == 'n')) &&
808 ((arg[3] == ' ') || (arg[3] == ')'))) {
809 retval |= 0x1;
810 arg += 3;
811 }
812 else if (((arg[0] == 'M') || (arg[0] == 'm')) &&
813 ((arg[1] == 'A') || (arg[1] == 'a')) &&
814 ((arg[2] == 'X') || (arg[2] == 'x')) &&
815 ((arg[3] == ' ') || (arg[3] == ')'))) {
816 retval |= 0x2;
817 arg += 3;
818 }
819 else if (((arg[0] == 'A') || (arg[0] == 'a')) &&
820 ((arg[1] == 'L') || (arg[1] == 'l')) &&
821 ((arg[2] == 'L') || (arg[2] == 'l')) &&
822 ((arg[3] == ' ') || (arg[3] == ')'))) {
823 retval |= 0x4;
824 arg += 3;
825 }
826 else if (((arg[0] == 'C') || (arg[0] == 'c')) &&
827 ((arg[1] == 'O') || (arg[1] == 'o')) &&
828 ((arg[2] == 'U') || (arg[2] == 'u')) &&
829 ((arg[3] == 'N') || (arg[3] == 'n')) &&
830 ((arg[4] == 'T') || (arg[4] == 't')) &&
831 ((arg[5] == ' ') || (arg[5] == ')'))) {
832 retval |= 0x10;
833 arg += 5;
834 }
835 else break; /* unknown return value */
836 /* more return values to come */
837 if ((*arg == ' ') && (arg[1] != ')')) ++arg;
838 }
839 /* RETURN list must be properly terminated */
840 if ((*arg++ != ')') || (*arg++ != ' ')) break;
841 /* default return value is ALL */
842 if (!(retval &= 0x3fff)) retval = 0x4;
843 }
845 /* character set specified? */
846 if (((arg[0] == 'C') || (arg[0] == 'c')) &&
847 ((arg[1] == 'H') || (arg[1] == 'h')) &&
848 ((arg[2] == 'A') || (arg[2] == 'a')) &&
849 ((arg[3] == 'R') || (arg[3] == 'r')) &&
850 ((arg[4] == 'S') || (arg[4] == 's')) &&
851 ((arg[5] == 'E') || (arg[5] == 'e')) &&
852 ((arg[6] == 'T') || (arg[6] == 't')) &&
853 (arg[7] == ' ')) {
854 arg += 8; /* yes, skip over CHARSET token */
855 if (s = snarf (&arg)) charset = cpystr (s);
856 else break; /* missing character set */
857 }
858 /* must have arguments here */
859 if (!(arg && *arg)) break;
860 if (parse_criteria (pgm = mail_newsearchpgm (),&arg,nmsgs,
861 uidmax (stream),0) && !*arg) {
862 response = win; /* looks good, try the search */
863 mail_search_full (stream,charset,pgm,SE_FREE);
864 /* output search results if success */
865 if (response == win) {
866 if (retval) { /* ESEARCH desired */
867 PSOUT ("* ESEARCH (TAG ");
868 pstring (tag);
869 PBOUT (')');
870 if (uid) PSOUT (" UID");
871 /* wants MIN */
872 if (retval & 0x1) {
873 for (i = 1; (i <= nmsgs) && !mail_elt (stream,i)->searched;
874 ++i);
875 if (i <= nmsgs) {
876 PSOUT (" MIN ");
877 pnum (uid ? mail_uid (stream,i) : i);
878 }
879 }
880 /* wants MAX */
881 if (retval & 0x2) {
882 for (i = nmsgs; i && !mail_elt (stream,i)->searched; --i);
883 if (i) {
884 PSOUT (" MAX ");
885 pnum (uid ? mail_uid (stream,i) : i);
886 }
887 }
889 /* wants ALL */
890 if (retval & 0x4) {
891 unsigned long j;
892 /* find first match */
893 for (i = 1; (i <= nmsgs) && !mail_elt (stream,i)->searched;
894 ++i);
895 if (i <= nmsgs) {
896 PSOUT (" ALL ");
897 pnum (uid ? mail_uid (stream,i) : i);
898 j = i; /* last message output */
899 }
900 while (++i <= nmsgs) {
901 if (mail_elt (stream,i)->searched) {
902 while ((++i <= nmsgs) && mail_elt (stream,i)->searched);
903 /* previous message is end of range */
904 if (j != --i) {
905 PBOUT (':');
906 pnum (uid ? mail_uid (stream,i) : i);
907 }
908 }
909 /* search for next match */
910 while ((++i <= nmsgs) && !mail_elt (stream,i)->searched);
911 if (i <= nmsgs) {
912 PBOUT (',');
913 pnum (uid ? mail_uid (stream,i) : i);
914 j = i; /* last message output */
915 }
916 }
917 }
918 /* wants COUNT */
919 if (retval & 0x10) {
920 unsigned long j;
921 for (i = 1, j = 0; i <= nmsgs; ++i)
922 if (mail_elt (stream,i)->searched) ++j;
923 PSOUT (" COUNT ");
924 pnum (j);
925 }
926 }
927 else { /* standard search */
928 PSOUT ("* SEARCH");
929 for (i = 1; i <= nmsgs; ++i)
930 if (mail_elt (stream,i)->searched) {
931 PBOUT (' ');
932 pnum (uid ? mail_uid (stream,i) : i);
933 }
934 }
935 CRLF;
936 }
937 }
938 else mail_free_searchpgm (&pgm);
939 if (charset) fs_give ((void **) &charset);
940 }
942 else /* fall into select case */
943 case SELECT: /* valid whenever logged in */
944 /* select new mailbox */
945 if (!(strcmp (cmd,"SELECT") && strcmp (cmd,"EXAMINE") &&
946 strcmp (cmd,"BBOARD"))) {
947 /* single argument */
948 if (!(s = snarf (&arg))) response = misarg;
949 else if (arg) response = badarg;
950 else if (nameok (NIL,s = bboardname (cmd,s))) {
951 DRIVER *factory = mail_valid (NIL,s,NIL);
952 f = (anonymous ? OP_ANONYMOUS + OP_READONLY : NIL) |
953 ((*cmd == 'S') ? NIL : OP_READONLY);
954 curdriver = NIL; /* no drivers known */
955 /* no last uid */
956 uidvalidity = lastuid = 0;
957 if (lastid) fs_give ((void **) &lastid);
958 if (lastst.data) fs_give ((void **) &lastst.data);
959 nflags = 0; /* force update */
960 nmsgs = recent = 0xffffffff;
961 if (factory && !strcmp (factory->name,"phile") &&
962 (stream = mail_open (stream,s,f | OP_SILENT)) &&
963 (response == win)) {
964 BODY *b;
965 /* see if proxy open */
966 if ((mail_elt (stream,1)->rfc822_size < 400) &&
967 mail_fetchstructure (stream,1,&b) && (b->type == TYPETEXT) &&
968 (t = mail_fetch_text (stream,1,NIL,&i,NIL)) &&
969 (i < MAILTMPLEN) && (t[0] == '{')) {
970 /* copy and tie off */
971 strncpy (tmp,t,i)[i] = '\0';
972 /* nuke any trailing newline */
973 if (t = strpbrk (tmp,"\r\n")) *t = '\0';
974 /* try to open proxy */
975 if ((tstream = mail_open (NIL,tmp,f | OP_SILENT)) &&
976 (response == win) && tstream->nmsgs) {
977 s = tmp; /* got it, close the link */
978 mail_close (stream);
979 stream = tstream;
980 tstream = NIL;
981 }
982 }
983 /* now give the exists event */
984 stream->silent = NIL;
985 mm_exists (stream,stream->nmsgs);
986 }
987 else if (!factory && isnewsproxy (s)) {
988 sprintf (tmp,"{%.300s/nntp}%.300s",nntpproxy,(char *) s+6);
989 stream = mail_open (stream,tmp,f);
990 }
991 /* open stream normally then */
992 else stream = mail_open (stream,s,f);
994 if (stream && (response == win)) {
995 state = OPEN; /* note state open */
996 if (lastsel) fs_give ((void **) &lastsel);
997 /* canonicalize INBOX */
998 if (!compare_cstring (s,"#MHINBOX"))
999 lastsel = cpystr ("#MHINBOX");
1000 else lastsel = cpystr (compare_cstring (s,"INBOX") ?
1001 (char *) s : "INBOX");
1002 /* note readonly/readwrite */
1003 response = stream->rdonly ? rowin : rwwin;
1004 if (anonymous)
1005 syslog (LOG_INFO,"Anonymous select of %.80s host=%.80s",
1006 stream->mailbox,tcp_clienthost ());
1007 lastcheck = 0; /* no last check */
1009 else { /* failed, nuke old selection */
1010 if (stream) stream = mail_close (stream);
1011 state = SELECT; /* no mailbox open now */
1012 if (lastsel) fs_give ((void **) &lastsel);
1013 response = lose; /* open failed */
1018 /* APPEND message to mailbox */
1019 else if (!(anonymous || strcmp (cmd,"APPEND"))) {
1020 /* parse mailbox name */
1021 if ((s = snarf (&arg)) && arg) {
1022 STRING st; /* message stringstruct */
1023 APPENDDATA ad;
1024 ad.arg = arg; /* command arguments */
1025 /* no message yet */
1026 ad.flags = ad.date = ad.msg = NIL;
1027 ad.message = &st; /* pointer to stringstruct to use */
1028 trycreate = NIL; /* no trycreate status */
1029 if (!mail_append_multiple (NIL,s,append_msg,(void *) &ad)) {
1030 if (response == win) response = trycreate ? losetry : lose;
1031 /* this can happen with #driver. hack */
1032 if (!lsterr) lsterr = cpystr ("No such destination mailbox");
1034 /* clean up any message text left behind */
1035 if (ad.flags) fs_give ((void **) &ad.flags);
1036 if (ad.date) fs_give ((void **) &ad.date);
1037 if (ad.msg) fs_give ((void **) &ad.msg);
1039 else response = misarg;
1040 if (stream) /* allow untagged EXPUNGE */
1041 mail_parameters (stream,SET_ONETIMEEXPUNGEATPING,(void *) stream);
1043 /* list mailboxes */
1044 else if (!strcmp (cmd,"LIST") || !strcmp (cmd,"RLIST")) {
1045 /* get reference and mailbox argument */
1046 if (!((s = snarf (&arg)) && (t = snarf_list (&arg))))
1047 response = misarg;
1048 else if (arg) response = badarg;
1049 /* make sure anonymous can't do bad things */
1050 else if (nameok (s,t)) {
1051 if (newsproxypattern (s,t,tmp,LONGT)) {
1052 proxylist = T;
1053 mail_list (NIL,"",tmp);
1054 proxylist = NIL;
1056 else mail_list (NIL,s,t);
1058 if (stream) /* allow untagged EXPUNGE */
1059 mail_parameters (stream,SET_ONETIMEEXPUNGEATPING,(void *) stream);
1061 /* scan mailboxes */
1062 else if (!strcmp (cmd,"SCAN")) {
1063 /* get arguments */
1064 if (!((s = snarf (&arg)) && (t = snarf_list (&arg)) &&
1065 (u = snarf (&arg)))) response = misarg;
1066 else if (arg) response = badarg;
1067 /* make sure anonymous can't do bad things */
1068 else if (nameok (s,t)) {
1069 if (newsproxypattern (s,t,tmp,NIL))
1070 mm_log ("SCAN not permitted for news",ERROR);
1071 else mail_scan (NIL,s,t,u);
1073 if (stream) /* allow untagged EXPUNGE */
1074 mail_parameters (stream,SET_ONETIMEEXPUNGEATPING,(void *) stream);
1076 /* list subscribed mailboxes */
1077 else if (!strcmp (cmd,"LSUB") || !strcmp (cmd,"RLSUB")) {
1078 /* get reference and mailbox argument */
1079 if (!((s = snarf (&arg)) && (t = snarf_list (&arg))))
1080 response = misarg;
1081 else if (arg) response = badarg;
1082 /* make sure anonymous can't do bad things */
1083 else if (nameok (s,t)) {
1084 if (newsproxypattern (s,t,tmp,NIL)) newsrc_lsub (NIL,tmp);
1085 else mail_lsub (NIL,s,t);
1087 if (stream) /* allow untagged EXPUNGE */
1088 mail_parameters (stream,SET_ONETIMEEXPUNGEATPING,(void *) stream);
1091 /* find mailboxes */
1092 else if (!strcmp (cmd,"FIND")) {
1093 /* get subcommand and true argument */
1094 if (!(arg && (s = strtok (arg," \015\012")) && (s == cmd + 5) &&
1095 (cmd[4] = ' ') && ucase (s) &&
1096 (arg = strtok (NIL,"\015\012")) && (s = snarf_list (&arg))))
1097 response = misarg; /* missing required argument */
1098 else if (arg) response = badarg;
1099 /* punt on single-char wildcards */
1100 else if (strpbrk (s,"%?")) response =
1101 "%.80s NO IMAP2 ? and %% wildcards not supported: %.80s\015\012";
1102 else if (nameok (NIL,s)) {
1103 finding = T; /* note that we are FINDing */
1104 /* dispatch based on type */
1105 if (!strcmp (cmd,"FIND MAILBOXES") && !anonymous)
1106 mail_lsub (NIL,NIL,s);
1107 else if (!strcmp (cmd,"FIND ALL.MAILBOXES")) {
1108 /* convert * to % for compatible behavior */
1109 for (t = s; *t; t++) if (*t == '*') *t = '%';
1110 mail_list (NIL,NIL,s);
1112 else response = badcmd;
1114 if (stream) /* allow untagged EXPUNGE */
1115 mail_parameters (stream,SET_ONETIMEEXPUNGEATPING,(void *) stream);
1118 /* status of mailbox */
1119 else if (!strcmp (cmd,"STATUS")) {
1120 if (!((s = snarf (&arg)) && arg && (*arg++ == '(') &&
1121 (t = strchr (arg,')')) && (t - arg) && !t[1]))
1122 response = misarg;
1123 else {
1124 f = NIL; /* initially no flags */
1125 *t = '\0'; /* tie off flag string */
1126 /* read flags */
1127 t = strtok (ucase (arg)," ");
1128 do { /* parse each one; unknown generate warning */
1129 if (!strcmp (t,"MESSAGES")) f |= SA_MESSAGES;
1130 else if (!strcmp (t,"RECENT")) f |= SA_RECENT;
1131 else if (!strcmp (t,"UNSEEN")) f |= SA_UNSEEN;
1132 else if (!strcmp (t,"UIDNEXT")) f |= SA_UIDNEXT;
1133 else if (!strcmp (t,"UIDVALIDITY")) f |= SA_UIDVALIDITY;
1134 else {
1135 PSOUT ("* NO Unknown status flag ");
1136 PSOUT (t);
1137 CRLF;
1139 } while (t = strtok (NIL," "));
1140 ping_mailbox (uid); /* in case the fool did STATUS on open mbx */
1141 PFLUSH (); /* make sure stdout is dumped in case slave */
1142 if (!compare_cstring (s,"INBOX")) s = "INBOX";
1143 else if (!compare_cstring (s,"#MHINBOX")) s = "#MHINBOX";
1144 if (state == LOGOUT) response = lose;
1145 /* get mailbox status */
1146 else if (lastsel && (!strcmp (s,lastsel) ||
1147 (stream && !strcmp (s,stream->mailbox)))) {
1148 unsigned long unseen;
1149 /* snarl at cretins which do this */
1150 PSOUT ("* NO CLIENT BUG DETECTED: STATUS on selected mailbox: ");
1151 PSOUT (s);
1152 CRLF;
1153 tmp[0] = ' '; tmp[1] = '\0';
1154 if (f & SA_MESSAGES)
1155 sprintf (tmp + strlen (tmp)," MESSAGES %lu",stream->nmsgs);
1156 if (f & SA_RECENT)
1157 sprintf (tmp + strlen (tmp)," RECENT %lu",stream->recent);
1158 if (f & SA_UNSEEN) {
1159 for (i = 1,unseen = 0; i <= stream->nmsgs; i++)
1160 if (!mail_elt (stream,i)->seen) unseen++;
1161 sprintf (tmp + strlen (tmp)," UNSEEN %lu",unseen);
1163 if (f & SA_UIDNEXT)
1164 sprintf (tmp + strlen (tmp)," UIDNEXT %lu",stream->uid_last+1);
1165 if (f & SA_UIDVALIDITY)
1166 sprintf (tmp + strlen(tmp)," UIDVALIDITY %lu",
1167 stream->uid_validity);
1168 tmp[1] = '(';
1169 strcat (tmp,")\015\012");
1170 PSOUT ("* STATUS ");
1171 pastring (s);
1172 PSOUT (tmp);
1174 else if (isnewsproxy (s)) {
1175 sprintf (tmp,"{%.300s/nntp}%.300s",nntpproxy,(char *) s+6);
1176 if (!mail_status (NIL,tmp,f)) response = lose;
1178 else if (!mail_status (NIL,s,f)) response = lose;
1180 if (stream) /* allow untagged EXPUNGE */
1181 mail_parameters (stream,SET_ONETIMEEXPUNGEATPING,(void *) stream);
1184 /* subscribe to mailbox */
1185 else if (!(anonymous || strcmp (cmd,"SUBSCRIBE"))) {
1186 /* get <mailbox> or MAILBOX <mailbox> */
1187 if (!(s = snarf (&arg))) response = misarg;
1188 else if (arg) { /* IMAP2bis form */
1189 if (compare_cstring (s,"MAILBOX")) response = badarg;
1190 else if (!(s = snarf (&arg))) response = misarg;
1191 else if (arg) response = badarg;
1192 else mail_subscribe (NIL,s);
1194 else if (isnewsproxy (s)) newsrc_update (NIL,s+6,':');
1195 else mail_subscribe (NIL,s);
1196 if (stream) /* allow untagged EXPUNGE */
1197 mail_parameters (stream,SET_ONETIMEEXPUNGEATPING,(void *) stream);
1199 /* unsubscribe to mailbox */
1200 else if (!(anonymous || strcmp (cmd,"UNSUBSCRIBE"))) {
1201 /* get <mailbox> or MAILBOX <mailbox> */
1202 if (!(s = snarf (&arg))) response = misarg;
1203 else if (arg) { /* IMAP2bis form */
1204 if (compare_cstring (s,"MAILBOX")) response = badarg;
1205 else if (!(s = snarf (&arg))) response = misarg;
1206 else if (arg) response = badarg;
1207 else if (isnewsproxy (s)) newsrc_update (NIL,s+6,'!');
1208 else mail_unsubscribe (NIL,s);
1210 else mail_unsubscribe (NIL,s);
1211 if (stream) /* allow untagged EXPUNGE */
1212 mail_parameters (stream,SET_ONETIMEEXPUNGEATPING,(void *) stream);
1215 else if (!strcmp (cmd,"NAMESPACE")) {
1216 if (arg) response = badarg;
1217 else {
1218 NAMESPACE **ns = (NAMESPACE **) mail_parameters(NIL,GET_NAMESPACE,
1219 NIL);
1220 NAMESPACE *n;
1221 PARAMETER *p;
1222 PSOUT ("* NAMESPACE");
1223 if (ns) for (i = 0; i < 3; i++) {
1224 if (n = ns[i]) {
1225 PSOUT (" (");
1226 do {
1227 PBOUT ('(');
1228 pstring (n->name);
1229 switch (n->delimiter) {
1230 case '\\': /* quoted delimiter */
1231 case '"':
1232 PSOUT (" \"\\\\\"");
1233 break;
1234 case '\0': /* no delimiter */
1235 PSOUT (" NIL");
1236 break;
1237 default: /* unquoted delimiter */
1238 PSOUT (" \"");
1239 PBOUT (n->delimiter);
1240 PBOUT ('"');
1241 break;
1243 /* NAMESPACE extensions are hairy */
1244 if (p = n->param) do {
1245 PBOUT (' ');
1246 pstring (p->attribute);
1247 PSOUT (" (");
1248 do pstring (p->value);
1249 while (p->next && !p->next->attribute && (p = p->next));
1250 PBOUT (')');
1251 } while (p = p->next);
1252 PBOUT (')');
1253 } while (n = n->next);
1254 PBOUT (')');
1256 else PSOUT (" NIL");
1258 else PSOUT (" NIL NIL NIL");
1259 CRLF;
1261 if (stream) /* allow untagged EXPUNGE */
1262 mail_parameters (stream,SET_ONETIMEEXPUNGEATPING,(void *) stream);
1265 /* create mailbox */
1266 else if (!(anonymous || strcmp (cmd,"CREATE"))) {
1267 if (!(s = snarf (&arg))) response = misarg;
1268 else if (arg) response = badarg;
1269 else mail_create (NIL,s);
1270 if (stream) /* allow untagged EXPUNGE */
1271 mail_parameters (stream,SET_ONETIMEEXPUNGEATPING,(void *) stream);
1273 /* delete mailbox */
1274 else if (!(anonymous || strcmp (cmd,"DELETE"))) {
1275 if (!(s = snarf (&arg))) response = misarg;
1276 else if (arg) response = badarg;
1277 else { /* make sure not selected */
1278 if (lastsel && (!strcmp (s,lastsel) ||
1279 (stream && !strcmp (s,stream->mailbox))))
1280 mm_log ("Can not DELETE the selected mailbox",ERROR);
1281 else mail_delete (NIL,s);
1283 if (stream) /* allow untagged EXPUNGE */
1284 mail_parameters (stream,SET_ONETIMEEXPUNGEATPING,(void *) stream);
1286 /* rename mailbox */
1287 else if (!(anonymous || strcmp (cmd,"RENAME"))) {
1288 if (!((s = snarf (&arg)) && (t = snarf (&arg)))) response = misarg;
1289 else if (arg) response = badarg;
1290 else { /* make sure not selected */
1291 if (!compare_cstring (s,"INBOX")) s = "INBOX";
1292 else if (!compare_cstring (s,"#MHINBOX")) s = "#MHINBOX";
1293 if (lastsel && (!strcmp (s,lastsel) ||
1294 (stream && !strcmp (s,stream->mailbox))))
1295 mm_log ("Can not RENAME the selected mailbox",ERROR);
1296 else mail_rename (NIL,s,t);
1298 if (stream) /* allow untagged EXPUNGE */
1299 mail_parameters (stream,SET_ONETIMEEXPUNGEATPING,(void *) stream);
1302 /* idle mode */
1303 else if (!strcmp (cmd,"IDLE")) {
1304 /* no arguments */
1305 if (arg) response = badarg;
1306 else { /* tell client ready for argument */
1307 unsigned long donefake = 0;
1308 PSOUT ("+ Waiting for DONE\015\012");
1309 PFLUSH (); /* dump output buffer */
1310 /* inactivity countdown */
1311 i = ((TIMEOUT) / (IDLETIMER)) + 1;
1312 do { /* main idle loop */
1313 if (!donefake) { /* don't ping mailbox if faking */
1314 mail_parameters (stream,SET_ONETIMEEXPUNGEATPING,
1315 (void *) stream);
1316 ping_mailbox (uid);
1317 /* maybe do a checkpoint if not anonymous */
1318 if (!anonymous && stream && (time (0) > lastcheck + CHECKTIMER)) {
1319 mail_check (stream);
1320 /* cancel likely altwin from mail_check() */
1321 if (lsterr) fs_give ((void **) &lsterr);
1322 if (lstwrn) fs_give ((void **) &lstwrn);
1323 /* remember last checkpoint */
1324 lastcheck = time (0);
1327 if (lstwrn) { /* have a warning? */
1328 PSOUT ("* NO ");
1329 PSOUT (lstwrn);
1330 CRLF;
1331 fs_give ((void **) &lstwrn);
1333 if (!(i % 2)) { /* prevent NAT timeouts */
1334 sprintf (tmp,"* OK Timeout in %lu minutes\015\012",
1335 (i * IDLETIMER) / 60);
1336 PSOUT (tmp);
1338 /* two minutes before the end... */
1339 if ((state == OPEN) && (i <= 2)) {
1340 sprintf (tmp,"* %lu EXISTS\015\012* %lu RECENT\015\012",
1341 donefake = nmsgs + 1,recent + 1);
1342 PSOUT (tmp); /* prod client to wake up */
1344 PFLUSH (); /* dump output buffer */
1345 } while ((state != LOGOUT) && !INWAIT (IDLETIMER) && --i);
1347 /* time to exit idle loop */
1348 if (state != LOGOUT) {
1349 if (i) { /* still have time left? */
1350 /* yes, read expected DONE */
1351 slurp (tmp,MAILTMPLEN,INPUTTIMEOUT);
1352 if (((tmp[0] != 'D') && (tmp[0] != 'd')) ||
1353 ((tmp[1] != 'O') && (tmp[1] != 'o')) ||
1354 ((tmp[2] != 'N') && (tmp[2] != 'n')) ||
1355 ((tmp[3] != 'E') && (tmp[3] != 'e')) ||
1356 (((tmp[4] != '\015') || (tmp[5] != '\012')) &&
1357 (tmp[4] != '\012')))
1358 response = "%.80s BAD Bogus IDLE continuation\015\012";
1359 if (donefake) { /* if faking at the end */
1360 /* send EXPUNGE (should be just 1) */
1361 while (donefake > nmsgs) {
1362 sprintf (tmp,"* %lu EXPUNGE\015\012",donefake--);
1363 PSOUT (tmp);
1365 sprintf (tmp,"* %lu EXISTS\015\012* %lu RECENT\015\012",
1366 nmsgs,recent);
1367 PSOUT (tmp);
1370 else clkint (); /* otherwise do autologout action */
1374 else response = badcmd;
1375 break;
1376 default:
1377 response = "%.80s BAD Unknown state for %.80s command\015\012";
1378 break;
1381 while (litplus.ok) { /* any unread LITERAL+? */
1382 litplus.ok = NIL; /* yes, cancel it now */
1383 clearerr (stdin); /* clear stdin errors */
1384 status = "discarding unread literal";
1385 /* read literal and discard it */
1386 while (i = (litplus.size > MAILTMPLEN) ? MAILTMPLEN : litplus.size) {
1387 if (state == LOGOUT) litplus.size = 0;
1388 else {
1389 settimeout (INPUTTIMEOUT);
1390 if (PSINR (tmp,i)) litplus.size -= i;
1391 else {
1392 ioerror (stdin,status);
1393 litplus.size = 0; /* in case it continues */
1397 settimeout (0); /* stop timeout */
1398 /* get new command tail */
1399 slurp (tmp,MAILTMPLEN,INPUTTIMEOUT);
1400 /* locate end of line */
1401 if (t = strchr (tmp,'\012')) {
1402 /* back over CR */
1403 if ((t > tmp) && (t[-1] == '\015')) --t;
1404 *t = NIL; /* tie off CRLF */
1405 /* possible LITERAL+? */
1406 if (((i = strlen (tmp)) > 3) && (tmp[i - 1] == '}') &&
1407 (tmp[i - 2] == '+') && isdigit (tmp[i - 3])) {
1408 /* back over possible count */
1409 for (i -= 4; i && isdigit (tmp[i]); i--);
1410 if (tmp[i] == '{') { /* found a literal? */
1411 litplus.ok = T; /* yes, note LITERAL+ in effect, set size */
1412 litplus.size = strtoul (tmp + i + 1,NIL,10);
1416 else flush (); /* overlong line after LITERAL+, punt */
1418 ping_mailbox (uid); /* update mailbox status before response */
1419 if (lstwrn && lsterr) { /* output most recent warning */
1420 PSOUT ("* NO ");
1421 PSOUT (lstwrn);
1422 CRLF;
1423 fs_give ((void **) &lstwrn);
1426 if (response == logwin) { /* authentication win message */
1427 sprintf (tmp,response,lstref ? "*" : tag);
1428 PSOUT (tmp); /* start response */
1429 pcapability (1); /* print logged-in capabilities */
1430 PSOUT ("] User ");
1431 PSOUT (user);
1432 PSOUT (" authenticated\015\012");
1433 if (lstref) {
1434 sprintf (tmp,response,tag);
1435 PSOUT (tmp); /* start response */
1436 PSOUT ("[REFERRAL ");
1437 PSOUT (lstref);
1438 PSOUT ("] ");
1439 PSOUT (lasterror ());
1440 CRLF;
1443 else if ((response == win) || (response == lose)) {
1444 sprintf (tmp,response,tag);
1445 PSOUT (tmp);
1446 if (cauidvalidity) { /* COPYUID/APPENDUID response? */
1447 sprintf (tmp,"[%.80sUID %lu ",(char *)
1448 ((s = strchr (cmd,' ')) ? s+1 : cmd),cauidvalidity);
1449 PSOUT (tmp);
1450 cauidvalidity = 0; /* cancel response for future */
1451 if (csset) {
1452 pset (&csset);
1453 PBOUT (' ');
1455 pset (&caset);
1456 PSOUT ("] ");
1458 else if (lstref) { /* have a referral? */
1459 PSOUT ("[REFERRAL ");
1460 PSOUT (lstref);
1461 PSOUT ("] ");
1463 if (lsterr || lstwrn) PSOUT (lasterror ());
1464 else {
1465 PSOUT (cmd);
1466 PSOUT ((response == win) ? " completed" : "failed");
1468 CRLF;
1470 else { /* normal response */
1471 if ((response == rowin) || (response == rwwin)) {
1472 if (lstwrn) { /* output most recent warning */
1473 PSOUT ("* NO ");
1474 PSOUT (lstwrn);
1475 CRLF;
1476 fs_give ((void **) &lstwrn);
1479 sprintf (tmp,response,tag,cmd,lasterror ());
1480 PSOUT (tmp); /* output response */
1483 PFLUSH (); /* make sure output blatted */
1485 if (autologouttime) { /* have an autologout in effect? */
1486 /* cancel if no longer waiting for login */
1487 if (state != LOGIN) autologouttime = 0;
1488 /* took too long to login */
1489 else if (autologouttime < time (0)) {
1490 logout = goodbye = "Autologout";
1491 stream = NIL;
1492 state = LOGOUT; /* sayonara */
1496 if (goodbye && !quell_events){/* have a goodbye message? */
1497 PSOUT ("* BYE "); /* utter it */
1498 PSOUT (goodbye);
1499 CRLF;
1500 PFLUSH (); /* make sure blatted */
1502 syslog (LOG_INFO,"%s user=%.80s host=%.80s",logout,
1503 user ? (char *) user : "???",tcp_clienthost ());
1504 /* do logout hook if needed */
1505 if (lgoh = (logouthook_t) mail_parameters (NIL,GET_LOGOUTHOOK,NIL))
1506 (*lgoh) (mail_parameters (NIL,GET_LOGOUTDATA,NIL));
1507 _exit (ret); /* all done */
1508 return ret; /* stupid compilers */
1511 /* Ping mailbox during each cycle. Also check alerts
1512 * Accepts: last command was UID flag
1513 */
1515 void ping_mailbox (unsigned long uid)
1517 unsigned long i;
1518 char tmp[MAILTMPLEN];
1519 if (state == OPEN) {
1520 if (!mail_ping (stream)) { /* make sure stream still alive */
1521 PSOUT ("* BYE ");
1522 PSOUT (mylocalhost ());
1523 PSOUT (" Fatal mailbox error: ");
1524 PSOUT (lasterror ());
1525 CRLF;
1526 stream = NIL; /* don't try to clean up stream */
1527 state = LOGOUT; /* go away */
1528 syslog (LOG_INFO,
1529 "Fatal mailbox error user=%.80s host=%.80s mbx=%.80s: %.80s",
1530 user ? (char *) user : "???",tcp_clienthost (),
1531 (stream && stream->mailbox) ? stream->mailbox : "???",
1532 lasterror ());
1533 return;
1535 /* change in number of messages? */
1536 if (existsquelled || (nmsgs != stream->nmsgs)) {
1537 PSOUT ("* ");
1538 pnum (nmsgs = stream->nmsgs);
1539 PSOUT (" EXISTS\015\012");
1541 /* change in recent messages? */
1542 if (existsquelled || (recent != stream->recent)) {
1543 PSOUT ("* ");
1544 pnum (recent = stream->recent);
1545 PSOUT (" RECENT\015\012");
1547 existsquelled = NIL; /* don't do this until asked again */
1548 if (stream->uid_validity && (stream->uid_validity != uidvalidity)) {
1549 PSOUT ("* OK [UIDVALIDITY ");
1550 pnum (stream->uid_validity);
1551 PSOUT ("] UID validity status\015\012* OK [UIDNEXT ");
1552 pnum (stream->uid_last + 1);
1553 PSOUT ("] Predicted next UID\015\012");
1554 if (stream->uid_nosticky) {
1555 PSOUT ("* NO [UIDNOTSTICKY] Non-permanent unique identifiers: ");
1556 PSOUT (stream->mailbox);
1557 CRLF;
1559 uidvalidity = stream->uid_validity;
1562 /* don't bother if driver changed */
1563 if (curdriver == stream->dtb) {
1564 /* first report any new flags */
1565 if ((nflags < NUSERFLAGS) && stream->user_flags[nflags])
1566 new_flags (stream);
1567 for (i = 1; i <= nmsgs; i++) if (mail_elt (stream,i)->spare2) {
1568 PSOUT ("* ");
1569 pnum (i);
1570 PSOUT (" FETCH (");
1571 fetch_flags (i,NIL); /* output changed flags */
1572 if (uid) { /* need to include UIDs in response? */
1573 PBOUT (' ');
1574 fetch_uid (i,NIL);
1576 PSOUT (")\015\012");
1579 else { /* driver changed */
1580 new_flags (stream); /* send mailbox flags */
1581 if (curdriver) { /* note readonly/write if possible change */
1582 PSOUT ("* OK [READ-");
1583 PSOUT (stream->rdonly ? "ONLY" : "WRITE");
1584 PSOUT ("] Mailbox status\015\012");
1586 curdriver = stream->dtb;
1587 if (nmsgs) { /* get flags for all messages */
1588 sprintf (tmp,"1:%lu",nmsgs);
1589 mail_fetch_flags (stream,tmp,NIL);
1590 /* don't do this if newsrc already did */
1591 if (!(curdriver->flags & DR_NEWS)) {
1592 /* find first unseen message */
1593 for (i = 1; i <= nmsgs && mail_elt (stream,i)->seen; i++);
1594 if (i <= nmsgs) {
1595 PSOUT ("* OK [UNSEEN ");
1596 pnum (i);
1597 PSOUT ("] first unseen message in ");
1598 PSOUT (stream->mailbox);
1599 CRLF;
1605 if (shutdowntime && (time (0) > shutdowntime + SHUTDOWNTIMER)) {
1606 PSOUT ("* BYE Server shutting down\015\012");
1607 state = LOGOUT;
1609 /* don't do these stat()s every cycle */
1610 else if (time (0) > alerttime + ALERTTIMER) {
1611 struct stat sbuf;
1612 /* have a shutdown file? */
1613 if (!stat (SHUTDOWNFILE,&sbuf)) {
1614 PSOUT ("* OK [ALERT] Server shutting down shortly\015\012");
1615 shutdowntime = time (0);
1617 alerttime = time (0); /* output any new alerts */
1618 sysalerttime = palert (ALERTFILE,sysalerttime);
1619 if (state != LOGIN) /* do user alert if logged in */
1620 useralerttime = palert (mailboxfile (tmp,USERALERTFILE),useralerttime);
1624 /* Print an alert file
1625 * Accepts: path of alert file
1626 * time of last printed alert file
1627 * Returns: updated time of last printed alert file
1628 */
1630 time_t palert (char *file,time_t oldtime)
1632 FILE *alf;
1633 struct stat sbuf;
1634 int c,lc = '\012';
1635 /* have a new alert file? */
1636 if (stat (file,&sbuf) || (sbuf.st_mtime <= oldtime) ||
1637 !(alf = fopen (file,"r"))) return oldtime;
1638 /* yes, display it */
1639 while ((c = getc (alf)) != EOF) {
1640 if (lc == '\012') PSOUT ("* OK [ALERT] ");
1641 switch (c) { /* output character */
1642 case '\012': /* newline means do CRLF */
1643 CRLF;
1644 case '\015': /* flush CRs */
1645 case '\0': /* flush nulls */
1646 break;
1647 default:
1648 PBOUT (c); /* output all other characters */
1649 break;
1651 lc = c; /* note previous character */
1653 fclose (alf);
1654 if (lc != '\012') CRLF; /* final terminating CRLF */
1655 return sbuf.st_mtime; /* return updated last alert time */
1658 /* Initialize file string structure for file stringstruct
1659 * Accepts: string structure
1660 * pointer to message data structure
1661 * size of string
1662 */
1664 void msg_string_init (STRING *s,void *data,unsigned long size)
1666 MSGDATA *md = (MSGDATA *) data;
1667 s->data = data; /* note stream/msgno and header length */
1668 #if 0
1669 s->size = size; /* message size */
1670 s->curpos = s->chunk = /* load header */
1671 mail_fetchheader_full (md->stream,md->msgno,NIL,&s->data1,
1672 FT_PREFETCHTEXT | FT_PEEK);
1673 #else /* This kludge is necessary because of broken mail stores */
1674 mail_fetchtext_full (md->stream,md->msgno,&s->size,FT_PEEK);
1675 s->curpos = s->chunk = /* load header */
1676 mail_fetchheader_full (md->stream,md->msgno,NIL,&s->data1,FT_PEEK);
1677 s->size += s->data1; /* header + body size */
1678 #endif
1679 s->cursize = s->chunksize = s->data1;
1680 s->offset = 0; /* offset is start of message */
1684 /* Get next character from file stringstruct
1685 * Accepts: string structure
1686 * Returns: character, string structure chunk refreshed
1687 */
1689 char msg_string_next (STRING *s)
1691 char c = *s->curpos++; /* get next byte */
1692 SETPOS (s,GETPOS (s)); /* move to next chunk */
1693 return c; /* return the byte */
1697 /* Set string pointer position for file stringstruct
1698 * Accepts: string structure
1699 * new position
1700 */
1702 void msg_string_setpos (STRING *s,unsigned long i)
1704 MSGDATA *md = (MSGDATA *) s->data;
1705 if (i < s->data1) { /* want header? */
1706 s->chunk = mail_fetchheader_full (md->stream,md->msgno,NIL,NIL,FT_PEEK);
1707 s->chunksize = s->data1; /* header length */
1708 s->offset = 0; /* offset is start of message */
1710 else if (i < s->size) { /* want body */
1711 s->chunk = mail_fetchtext_full (md->stream,md->msgno,NIL,FT_PEEK);
1712 s->chunksize = s->size - s->data1;
1713 s->offset = s->data1; /* offset is end of header */
1715 else { /* off end of message */
1716 s->chunk = NIL; /* make sure that we crack on this then */
1717 s->chunksize = 1; /* make sure SNX cracks the right way... */
1718 s->offset = i;
1720 /* initial position and size */
1721 s->curpos = s->chunk + (i -= s->offset);
1722 s->cursize = s->chunksize - i;
1725 /* Send flags for stream
1726 * Accepts: MAIL stream
1727 * scratch buffer
1728 */
1730 void new_flags (MAILSTREAM *stream)
1732 int i,c;
1733 PSOUT ("* FLAGS (");
1734 for (i = 0; i < NUSERFLAGS; i++) if (stream->user_flags[i]) {
1735 PSOUT (stream->user_flags[i]);
1736 PBOUT (' ');
1737 nflags = i + 1;
1739 PSOUT ("\\Answered \\Flagged \\Deleted \\Draft \\Seen)\015\012* OK [PERMANENTFLAGS (");
1740 for (i = c = 0; i < NUSERFLAGS; i++)
1741 if ((stream->perm_user_flags & (1 << i)) && stream->user_flags[i])
1742 put_flag (&c,stream->user_flags[i]);
1743 if (stream->kwd_create) put_flag (&c,"\\*");
1744 if (stream->perm_answered) put_flag (&c,"\\Answered");
1745 if (stream->perm_flagged) put_flag (&c,"\\Flagged");
1746 if (stream->perm_deleted) put_flag (&c,"\\Deleted");
1747 if (stream->perm_draft) put_flag (&c,"\\Draft");
1748 if (stream->perm_seen) put_flag (&c,"\\Seen");
1749 PSOUT (")] Permanent flags\015\012");
1752 /* Set timeout
1753 * Accepts: desired interval
1754 */
1756 void settimeout (unsigned int i)
1758 /* limit if not logged in */
1759 if (i) alarm ((state == LOGIN) ? LOGINTIMEOUT : i);
1760 else alarm (0);
1764 /* Clock interrupt
1765 * Returns only if critical code in progress
1766 */
1768 void clkint (void)
1770 settimeout (0); /* disable all interrupts */
1771 server_init (NIL,NIL,NIL,SIG_IGN,SIG_IGN,SIG_IGN,SIG_IGN,SIG_IGN);
1772 logout = "Autologout";
1773 goodbye = "Autologout (idle for too long)";
1774 if (critical) { /* must defer if in critical code(?) */
1775 close (0); /* kill stdin */
1776 state = LOGOUT; /* die as soon as we can */
1778 else longjmp (jmpenv,1); /* die now */
1782 /* Kiss Of Death interrupt
1783 * Returns only if critical code in progress
1784 */
1786 void kodint (void)
1788 settimeout (0); /* disable all interrupts */
1789 server_init (NIL,NIL,NIL,SIG_IGN,SIG_IGN,SIG_IGN,SIG_IGN,SIG_IGN);
1790 logout = goodbye = "Killed (lost mailbox lock)";
1791 if (critical) { /* must defer if in critical code */
1792 close (0); /* kill stdin */
1793 state = LOGOUT; /* die as soon as we can */
1795 else longjmp (jmpenv,1); /* die now */
1798 /* Hangup interrupt
1799 * Returns only if critical code in progress
1800 */
1802 void hupint (void)
1804 settimeout (0); /* disable all interrupts */
1805 server_init (NIL,NIL,NIL,SIG_IGN,SIG_IGN,SIG_IGN,SIG_IGN,SIG_IGN);
1806 logout = "Hangup";
1807 goodbye = NIL; /* other end is already gone */
1808 if (critical) { /* must defer if in critical code */
1809 close (0); /* kill stdin */
1810 close (1); /* and stdout */
1811 state = LOGOUT; /* die as soon as we can */
1813 else longjmp (jmpenv,1); /* die now */
1817 /* Termination interrupt
1818 * Returns only if critical code in progress
1819 */
1821 void trmint (void)
1823 settimeout (0); /* disable all interrupts */
1824 server_init (NIL,NIL,NIL,SIG_IGN,SIG_IGN,SIG_IGN,SIG_IGN,SIG_IGN);
1825 logout = goodbye = "Killed (terminated)";
1826 /* Make no attempt at graceful closure since a shutdown may be in
1827 * progress, and we won't have any time to do mail_close() actions
1828 */
1829 stream = NIL;
1830 if (critical) { /* must defer if in critical code */
1831 close (0); /* kill stdin */
1832 close (1); /* and stdout */
1833 state = LOGOUT; /* die as soon as we can */
1835 else longjmp (jmpenv,1); /* die now */
1838 /* The routines on this and the next page eschew the use of non-syscall libc
1839 * routines (especially stdio) for a reason. Also, these hideous #if
1840 * condtionals need to be replaced.
1841 */
1843 #ifndef unix
1844 #define unix 0
1845 #endif
1848 /* Status request interrupt
1849 * Always returns
1850 */
1852 void staint (void)
1854 #if unix
1855 int fd;
1856 char *s,buf[8*MAILTMPLEN];
1857 unsigned long pid = getpid ();
1858 /* build file name */
1859 s = nout (sout (buf,"/tmp/imapd-status."),pid,10);
1860 if (user) s = sout (sout (s,"."),user);
1861 *s = '\0'; /* tie off file name */
1862 if ((fd = open (buf,O_WRONLY | O_CREAT | O_TRUNC,0666)) >= 0) {
1863 fchmod (fd,0666);
1864 s = nout (sout (buf,"PID="),pid,10);
1865 if (user) s = sout (sout (s,", user="),user);
1866 switch (state) {
1867 case LOGIN:
1868 s = sout (s,", not logged in");
1869 break;
1870 case SELECT:
1871 s = sout (s,", logged in");
1872 break;
1873 case OPEN:
1874 s = sout (s,", mailbox open");
1875 break;
1876 case LOGOUT:
1877 s = sout (s,", logging out");
1878 break;
1880 if (stream && stream->mailbox)
1881 s = sout (sout (s,"\nmailbox="),stream->mailbox);
1882 *s++ = '\n';
1883 if (status) {
1884 s = sout (s,status);
1885 if (cmd) s = sout (sout (s,", last command="),cmd);
1887 else s = sout (sout (s,cmd)," in progress");
1888 *s++ = '\n';
1889 write (fd,buf,s-buf);
1890 close (fd);
1892 #endif
1895 /* Write string
1896 * Accepts: destination string pointer
1897 * string
1898 * Returns: updated string pointer
1899 */
1901 char *sout (char *s,char *t)
1903 while (*t) *s++ = *t++;
1904 return s;
1908 /* Write number
1909 * Accepts: destination string pointer
1910 * number
1911 * base
1912 * Returns: updated string pointer
1913 */
1915 char *nout (char *s,unsigned long n,unsigned long base)
1917 char stack[256];
1918 char *t = stack;
1919 /* push PID digits on stack */
1920 do *t++ = (char) (n % base) + '0';
1921 while (n /= base);
1922 /* pop digits from stack */
1923 while (t > stack) *s++ = *--t;
1924 return s;
1927 /* Slurp a command line
1928 * Accepts: buffer pointer
1929 * buffer size
1930 * input timeout
1931 */
1933 void slurp (char *s,int n,unsigned long timeout)
1935 memset (s,'\0',n); /* zap buffer */
1936 if (state != LOGOUT) { /* get a command under timeout */
1937 settimeout (timeout);
1938 clearerr (stdin); /* clear stdin errors */
1939 status = "reading line";
1940 if (!PSIN (s,n-1)) ioerror (stdin,status);
1941 settimeout (0); /* make sure timeout disabled */
1942 status = NIL;
1947 /* Read a literal
1948 * Accepts: destination buffer (must be size+1 for trailing NUL)
1949 * size of buffer (must be less than 4294967295)
1950 */
1952 void inliteral (char *s,unsigned long n)
1954 unsigned long i;
1955 if (litplus.ok) { /* no more LITERAL+ to worry about */
1956 litplus.ok = NIL;
1957 litplus.size = 0;
1959 else { /* otherwise tell client ready for argument */
1960 PSOUT ("+ Ready for argument\015\012");
1961 PFLUSH (); /* dump output buffer */
1963 clearerr (stdin); /* clear stdin errors */
1964 memset (s,'\0',n+1); /* zap buffer */
1965 status = "reading literal";
1966 while (n) { /* get data under timeout */
1967 if (state == LOGOUT) n = 0;
1968 else {
1969 settimeout (INPUTTIMEOUT);
1970 i = min (n,8192); /* must read at least 8K within timeout */
1971 if (PSINR (s,i)) {
1972 s += i;
1973 n -= i;
1975 else {
1976 ioerror (stdin,status);
1977 n = 0; /* in case it continues */
1979 settimeout (0); /* stop timeout */
1984 /* Flush until newline seen
1985 * Returns: NIL, always
1986 */
1988 unsigned char *flush (void)
1990 int c;
1991 if (state != LOGOUT) {
1992 settimeout (INPUTTIMEOUT);
1993 clearerr (stdin); /* clear stdin errors */
1994 status = "flushing line";
1995 while ((c = PBIN ()) != '\012') if (c == EOF) ioerror (stdin,status);
1996 settimeout (0); /* make sure timeout disabled */
1998 response = "%.80s BAD Command line too long\015\012";
1999 status = NIL;
2000 return NIL;
2004 /* Report command stream error and die
2005 * Accepts: stdin or stdout (whichever got the error)
2006 * reason (what caller was doing)
2007 */
2009 void ioerror (FILE *f,char *reason)
2011 static char msg[MAILTMPLEN];
2012 char *s,*t;
2013 if (logout) { /* say nothing if already dying */
2014 settimeout (0); /* disable all interrupts */
2015 server_init (NIL,NIL,NIL,SIG_IGN,SIG_IGN,SIG_IGN,SIG_IGN,SIG_IGN);
2016 /* write error string */
2017 for (s = ferror (f) ? strerror (errno) : "Unexpected client disconnect",
2018 t = logout = msg; *s; *t++ = *s++);
2019 for (s = ", while "; *s; *t++ = *s++);
2020 for (s = reason; *s; *t++ = *s++);
2021 if (critical) { /* must defer if in critical code */
2022 close (0); /* kill stdin */
2023 close (1); /* and stdout */
2024 state = LOGOUT; /* die as soon as we can */
2026 else longjmp (jmpenv,1); /* die now */
2030 /* Parse an IMAP astring
2031 * Accepts: pointer to argument text pointer
2032 * pointer to returned size
2033 * pointer to returned delimiter
2034 * Returns: argument
2035 */
2037 unsigned char *parse_astring (unsigned char **arg,unsigned long *size,
2038 unsigned char *del)
2040 unsigned long i;
2041 unsigned char c,*s,*t,*v;
2042 if (!*arg) return NIL; /* better be an argument */
2043 switch (**arg) { /* see what the argument is */
2044 default: /* atom */
2045 for (s = t = *arg, i = 0;
2046 (*t > ' ') && (*t < 0x7f) && (*t != '(') && (*t != ')') &&
2047 (*t != '{') && (*t != '%') && (*t != '*') && (*t != '"') &&
2048 (*t != '\\'); ++t,++i);
2049 if (*size = i) break; /* got atom if non-empty */
2050 case ')': case '%': case '*': case '\\': case '\0': case ' ':
2051 return NIL; /* empty atom is a bogon */
2052 case '"': /* hunt for trailing quote */
2053 for (s = t = v = *arg + 1; (c = *t++) != '"'; *v++ = c) {
2054 /* quote next character */
2055 if (c == '\\') switch (c = *t++) {
2056 case '"': case '\\': break;
2057 default: return NIL; /* invalid quote-next */
2059 /* else must be a CHAR */
2060 if (!c || (c & 0x80)) return NIL;
2062 *v = '\0'; /* tie off string */
2063 *size = v - s; /* return size */
2064 break;
2066 case '{': /* literal string */
2067 s = *arg + 1; /* get size */
2068 if (!isdigit (*s)) return NIL;
2069 if ((*size = i = strtoul (s,(char **) &t,10)) > MAXCLIENTLIT) {
2070 mm_notify (NIL,"Absurdly long client literal",ERROR);
2071 syslog (LOG_INFO,"Overlong (%lu) client literal user=%.80s host=%.80s",
2072 i,user ? (char *) user : "???",tcp_clienthost ());
2073 return NIL;
2075 switch (*t) { /* validate end of literal */
2076 case '+': /* non-blocking literal */
2077 if (*++t != '}') return NIL;
2078 case '}':
2079 if (!t[1]) break; /* OK if end of line */
2080 default:
2081 return NIL; /* bad literal */
2083 if (litsp >= LITSTKLEN) { /* make sure don't overflow stack */
2084 mm_notify (NIL,"Too many literals in command",ERROR);
2085 return NIL;
2087 /* get a literal buffer */
2088 inliteral (s = litstk[litsp++] = (char *) fs_get (i+1),i);
2089 /* get new command tail */
2090 slurp (*arg = t,CMDLEN - (t - cmdbuf),INPUTTIMEOUT);
2091 if (!strchr (t,'\012')) return flush ();
2092 /* reset strtok mechanism, tie off if done */
2093 if (!strtok (t,"\015\012")) *t = '\0';
2094 /* possible LITERAL+? */
2095 if (((i = strlen (t)) > 3) && (t[i - 1] == '}') &&
2096 (t[i - 2] == '+') && isdigit (t[i - 3])) {
2097 /* back over possible count */
2098 for (i -= 4; i && isdigit (t[i]); i--);
2099 if (t[i] == '{') { /* found a literal? */
2100 litplus.ok = T; /* yes, note LITERAL+ in effect, set size */
2101 litplus.size = strtoul (t + i + 1,NIL,10);
2104 break;
2106 if (*del = *t) { /* have a delimiter? */
2107 *t++ = '\0'; /* yes, stomp on it */
2108 *arg = t; /* update argument pointer */
2110 else *arg = NIL; /* no more arguments */
2111 return s;
2114 /* Snarf a command argument (simple jacket into parse_astring())
2115 * Accepts: pointer to argument text pointer
2116 * Returns: argument
2117 */
2119 unsigned char *snarf (unsigned char **arg)
2121 unsigned long i;
2122 unsigned char c;
2123 unsigned char *s = parse_astring (arg,&i,&c);
2124 return ((c == ' ') || !c) ? s : NIL;
2128 /* Snarf a BASE64 argument for SASL-IR
2129 * Accepts: pointer to argument text pointer
2130 * Returns: argument
2131 */
2133 unsigned char *snarf_base64 (unsigned char **arg)
2135 unsigned char *ret = *arg;
2136 unsigned char *s = ret + 1;
2137 static char base64mask[256] = {
2138 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2139 0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,
2140 0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,
2141 0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,
2142 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2143 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2144 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2145 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
2146 };
2147 if (*(ret = *arg) == '='); /* easy case if zero-length argument */
2148 /* must be at least one BASE64 char */
2149 else if (!base64mask[*ret]) return NIL;
2150 else { /* quick and dirty */
2151 while (base64mask[*s++]); /* scan until end of BASE64 */
2152 if (*s == '=') ++s; /* allow up to two padding chars */
2153 if (*s == '=') ++s;
2155 switch (*s) { /* anything following the argument? */
2156 case ' ': /* another argument */
2157 *s++ = '\0'; /* tie off previous argument */
2158 *arg = s; /* and update argument pointer */
2159 break;
2160 case '\0': /* end of command */
2161 *arg = NIL;
2162 break;
2163 default: /* syntax error */
2164 return NIL;
2166 return ret; /* return BASE64 string */
2169 /* Snarf a list command argument (simple jacket into parse_astring())
2170 * Accepts: pointer to argument text pointer
2171 * Returns: argument
2172 */
2174 unsigned char *snarf_list (unsigned char **arg)
2176 unsigned long i;
2177 unsigned char c,*s,*t;
2178 if (!*arg) return NIL; /* better be an argument */
2179 switch (**arg) {
2180 default: /* atom and/or wildcard chars */
2181 for (s = t = *arg, i = 0;
2182 (*t > ' ') && (*t != '(') && (*t != ')') && (*t != '{') &&
2183 (*t != '"') && (*t != '\\'); ++t,++i);
2184 if (c = *t) { /* have a delimiter? */
2185 *t++ = '\0'; /* stomp on it */
2186 *arg = t; /* update argument pointer */
2188 else *arg = NIL;
2189 break;
2190 case ')': case '\\': case '\0': case ' ':
2191 return NIL; /* empty name is bogus */
2192 case '"': /* quoted string? */
2193 case '{': /* or literal? */
2194 s = parse_astring (arg,&i,&c);
2195 break;
2197 return ((c == ' ') || !c) ? s : NIL;
2200 /* Get a list of header lines
2201 * Accepts: pointer to string pointer
2202 * pointer to list flag
2203 * Returns: string list
2204 */
2206 STRINGLIST *parse_stringlist (unsigned char **s,int *list)
2208 char c = ' ',*t;
2209 unsigned long i;
2210 STRINGLIST *ret = NIL,*cur = NIL;
2211 if (*s && **s == '(') { /* proper list? */
2212 ++*s; /* for each item in list */
2213 while ((c == ' ') && (t = parse_astring (s,&i,&c))) {
2214 /* get new block */
2215 if (cur) cur = cur->next = mail_newstringlist ();
2216 else cur = ret = mail_newstringlist ();
2217 /* note text */
2218 cur->text.data = (unsigned char *) fs_get (i + 1);
2219 memcpy (cur->text.data,t,i);
2220 cur->text.size = i; /* and size */
2222 /* must be end of list */
2223 if (c != ')') mail_free_stringlist (&ret);
2225 if (t = *s) { /* need to reload strtok() state? */
2226 /* end of a list? */
2227 if (*list && (*t == ')') && !t[1]) *list = NIL;
2228 else {
2229 *--t = ' '; /* patch a space back in */
2230 *--t = 'x'; /* and a hokey character before that */
2231 t = strtok (t," "); /* reset to *s */
2234 return ret;
2237 /* Get value of UID * for criteria parsing
2238 * Accepts: stream
2239 * Returns: maximum UID
2240 */
2242 unsigned long uidmax (MAILSTREAM *stream)
2244 return stream->nmsgs ? mail_uid (stream,stream->nmsgs) : 0xffffffff;
2248 /* Parse search criteria
2249 * Accepts: search program to write criteria into
2250 * pointer to argument text pointer
2251 * maximum message number
2252 * maximum UID
2253 * logical nesting depth
2254 * Returns: T if success, NIL if error
2255 */
2257 long parse_criteria (SEARCHPGM *pgm,unsigned char **arg,unsigned long maxmsg,
2258 unsigned long maxuid,unsigned long depth)
2260 if (arg && *arg) { /* must be an argument */
2261 /* parse criteria */
2262 do if (!parse_criterion (pgm,arg,maxmsg,maxuid,depth)) return NIL;
2263 /* as long as a space delimiter */
2264 while (**arg == ' ' && (*arg)++);
2265 /* failed if not end of criteria */
2266 if (**arg && **arg != ')') return NIL;
2268 return T; /* success */
2271 /* Parse a search criterion
2272 * Accepts: search program to write criterion into
2273 * pointer to argument text pointer
2274 * maximum message number
2275 * maximum UID
2276 * logical nesting depth
2277 * Returns: T if success, NIL if error
2278 */
2280 long parse_criterion (SEARCHPGM *pgm,unsigned char **arg,unsigned long maxmsg,
2281 unsigned long maxuid,unsigned long depth)
2283 unsigned long i;
2284 unsigned char c = NIL,*s,*t,*v,*tail,*del;
2285 SEARCHSET **set;
2286 SEARCHPGMLIST **not;
2287 SEARCHOR **or;
2288 SEARCHHEADER **hdr;
2289 long ret = NIL;
2290 /* better be an argument */
2291 if ((depth > 500) || !(arg && *arg));
2292 else if (**arg == '(') { /* list of criteria? */
2293 (*arg)++; /* yes, parse the criteria */
2294 if (parse_criteria (pgm,arg,maxmsg,maxuid,depth+1) && **arg == ')') {
2295 (*arg)++; /* skip closing paren */
2296 ret = T; /* successful parse of list */
2299 else { /* find end of criterion */
2300 if (!(tail = strpbrk ((s = *arg)," )"))) tail = *arg + strlen (*arg);
2301 c = *(del = tail); /* remember the delimiter */
2302 *del = '\0'; /* tie off criterion */
2303 switch (*ucase (s)) { /* dispatch based on character */
2304 case '*': /* sequence */
2305 case '0': case '1': case '2': case '3': case '4':
2306 case '5': case '6': case '7': case '8': case '9':
2307 if (*(set = &pgm->msgno)){/* already a sequence? */
2308 /* silly, but not as silly as the client! */
2309 for (not = &pgm->not; *not; not = &(*not)->next);
2310 *not = mail_newsearchpgmlist ();
2311 set = &((*not)->pgm->not = mail_newsearchpgmlist ())->pgm->msgno;
2313 ret = crit_set (set,&s,maxmsg) && (tail == s);
2314 break;
2315 case 'A': /* possible ALL, ANSWERED */
2316 if (!strcmp (s+1,"LL")) ret = T;
2317 else if (!strcmp (s+1,"NSWERED")) ret = pgm->answered = T;
2318 break;
2320 case 'B': /* possible BCC, BEFORE, BODY */
2321 if (!strcmp (s+1,"CC") && c == ' ' && *++tail)
2322 ret = crit_string (&pgm->bcc,&tail);
2323 else if (!strcmp (s+1,"EFORE") && c == ' ' && *++tail)
2324 ret = crit_date (&pgm->before,&tail);
2325 else if (!strcmp (s+1,"ODY") && c == ' ' && *++tail)
2326 ret = crit_string (&pgm->body,&tail);
2327 break;
2328 case 'C': /* possible CC */
2329 if (!strcmp (s+1,"C") && c == ' ' && *++tail)
2330 ret = crit_string (&pgm->cc,&tail);
2331 break;
2332 case 'D': /* possible DELETED */
2333 if (!strcmp (s+1,"ELETED")) ret = pgm->deleted = T;
2334 if (!strcmp (s+1,"RAFT")) ret = pgm->draft = T;
2335 break;
2336 case 'F': /* possible FLAGGED, FROM */
2337 if (!strcmp (s+1,"LAGGED")) ret = pgm->flagged = T;
2338 else if (!strcmp (s+1,"ROM") && c == ' ' && *++tail)
2339 ret = crit_string (&pgm->from,&tail);
2340 break;
2341 case 'H': /* possible HEADER */
2342 if (!strcmp (s+1,"EADER") && c == ' ' && *(v = tail + 1) &&
2343 (s = parse_astring (&v,&i,&c)) && i && c == ' ' &&
2344 (t = parse_astring (&v,&i,&c))) {
2345 for (hdr = &pgm->header; *hdr; hdr = &(*hdr)->next);
2346 *hdr = mail_newsearchheader (s,t);
2347 /* update tail, restore delimiter */
2348 *(tail = v ? v - 1 : t + i) = c;
2349 ret = T; /* success */
2351 break;
2352 case 'K': /* possible KEYWORD */
2353 if (!strcmp (s+1,"EYWORD") && c == ' ' && *++tail)
2354 ret = crit_string (&pgm->keyword,&tail);
2355 break;
2356 case 'L':
2357 if (!strcmp (s+1,"ARGER") && c == ' ' && *++tail)
2358 ret = crit_number (&pgm->larger,&tail);
2359 break;
2360 case 'N': /* possible NEW, NOT */
2361 if (!strcmp (s+1,"EW")) ret = pgm->recent = pgm->unseen = T;
2362 else if (!strcmp (s+1,"OT") && c == ' ' && *++tail) {
2363 for (not = &pgm->not; *not; not = &(*not)->next);
2364 *not = mail_newsearchpgmlist ();
2365 ret = parse_criterion ((*not)->pgm,&tail,maxmsg,maxuid,depth+1);
2367 break;
2369 case 'O': /* possible OLD, ON */
2370 if (!strcmp (s+1,"LD")) ret = pgm->old = T;
2371 else if (!strcmp (s+1,"N") && c == ' ' && *++tail)
2372 ret = crit_date (&pgm->on,&tail);
2373 else if (!strcmp (s+1,"R") && c == ' ') {
2374 for (or = &pgm->or; *or; or = &(*or)->next);
2375 *or = mail_newsearchor ();
2376 ret = *++tail && parse_criterion((*or)->first,&tail,maxmsg,maxuid,
2377 depth+1) &&
2378 (*tail == ' ') && *++tail &&
2379 parse_criterion ((*or)->second,&tail,maxmsg,maxuid,depth+1);
2381 else if (!strcmp (s+1,"LDER") && c == ' ' && *++tail)
2382 ret = crit_number (&pgm->older,&tail);
2383 break;
2384 case 'R': /* possible RECENT */
2385 if (!strcmp (s+1,"ECENT")) ret = pgm->recent = T;
2386 break;
2387 case 'S': /* possible SEEN, SINCE, SUBJECT */
2388 if (!strcmp (s+1,"EEN")) ret = pgm->seen = T;
2389 else if (!strcmp (s+1,"ENTBEFORE") && c == ' ' && *++tail)
2390 ret = crit_date (&pgm->sentbefore,&tail);
2391 else if (!strcmp (s+1,"ENTON") && c == ' ' && *++tail)
2392 ret = crit_date (&pgm->senton,&tail);
2393 else if (!strcmp (s+1,"ENTSINCE") && c == ' ' && *++tail)
2394 ret = crit_date (&pgm->sentsince,&tail);
2395 else if (!strcmp (s+1,"INCE") && c == ' ' && *++tail)
2396 ret = crit_date (&pgm->since,&tail);
2397 else if (!strcmp (s+1,"MALLER") && c == ' ' && *++tail)
2398 ret = crit_number (&pgm->smaller,&tail);
2399 else if (!strcmp (s+1,"UBJECT") && c == ' ' && *++tail)
2400 ret = crit_string (&pgm->subject,&tail);
2401 break;
2402 case 'T': /* possible TEXT, TO */
2403 if (!strcmp (s+1,"EXT") && c == ' ' && *++tail)
2404 ret = crit_string (&pgm->text,&tail);
2405 else if (!strcmp (s+1,"O") && c == ' ' && *++tail)
2406 ret = crit_string (&pgm->to,&tail);
2407 break;
2409 case 'U': /* possible UID, UN* */
2410 if (!strcmp (s+1,"ID") && c== ' ' && *++tail) {
2411 if (*(set = &pgm->uid)){/* already a sequence? */
2412 /* silly, but not as silly as the client! */
2413 for (not = &pgm->not; *not; not = &(*not)->next);
2414 *not = mail_newsearchpgmlist ();
2415 set = &((*not)->pgm->not = mail_newsearchpgmlist ())->pgm->uid;
2417 ret = crit_set (set,&tail,maxuid);
2419 else if (!strcmp (s+1,"NANSWERED")) ret = pgm->unanswered = T;
2420 else if (!strcmp (s+1,"NDELETED")) ret = pgm->undeleted = T;
2421 else if (!strcmp (s+1,"NDRAFT")) ret = pgm->undraft = T;
2422 else if (!strcmp (s+1,"NFLAGGED")) ret = pgm->unflagged = T;
2423 else if (!strcmp (s+1,"NKEYWORD") && c == ' ' && *++tail)
2424 ret = crit_string (&pgm->unkeyword,&tail);
2425 else if (!strcmp (s+1,"NSEEN")) ret = pgm->unseen = T;
2426 break;
2427 case 'Y': /* possible YOUNGER */
2428 if (!strcmp (s+1,"OUNGER") && c == ' ' && *++tail)
2429 ret = crit_number (&pgm->younger,&tail);
2430 break;
2431 default: /* oh dear */
2432 break;
2434 if (ret) { /* only bother if success */
2435 *del = c; /* restore delimiter */
2436 *arg = tail; /* update argument pointer */
2439 return ret; /* return more to come */
2442 /* Parse a search date criterion
2443 * Accepts: date to write into
2444 * pointer to argument text pointer
2445 * Returns: T if success, NIL if error
2446 */
2448 long crit_date (unsigned short *date,unsigned char **arg)
2450 if (*date) return NIL; /* can't double this value */
2451 /* handle quoted form */
2452 if (**arg != '"') return crit_date_work (date,arg);
2453 (*arg)++; /* skip past opening quote */
2454 if (!(crit_date_work (date,arg) && (**arg == '"'))) return NIL;
2455 (*arg)++; /* skip closing quote */
2456 return T;
2459 /* Worker routine to parse a search date criterion
2460 * Accepts: date to write into
2461 * pointer to argument text pointer
2462 * Returns: T if success, NIL if error
2463 */
2465 long crit_date_work (unsigned short *date,unsigned char **arg)
2467 int d,m,y;
2468 /* day */
2469 if (isdigit (d = *(*arg)++) || ((d == ' ') && isdigit (**arg))) {
2470 if (d == ' ') d = 0; /* leading space */
2471 else d -= '0'; /* first digit */
2472 if (isdigit (**arg)) { /* if a second digit */
2473 d *= 10; /* slide over first digit */
2474 d += *(*arg)++ - '0'; /* second digit */
2476 if ((**arg == '-') && (y = *++(*arg))) {
2477 m = (y >= 'a' ? y - 'a' : y - 'A') * 1024;
2478 if ((y = *++(*arg))) {
2479 m += (y >= 'a' ? y - 'a' : y - 'A') * 32;
2480 if ((y = *++(*arg))) {
2481 m += (y >= 'a' ? y - 'a' : y - 'A');
2482 switch (m) { /* determine the month */
2483 case (('J'-'A') * 1024) + (('A'-'A') * 32) + ('N'-'A'): m = 1; break;
2484 case (('F'-'A') * 1024) + (('E'-'A') * 32) + ('B'-'A'): m = 2; break;
2485 case (('M'-'A') * 1024) + (('A'-'A') * 32) + ('R'-'A'): m = 3; break;
2486 case (('A'-'A') * 1024) + (('P'-'A') * 32) + ('R'-'A'): m = 4; break;
2487 case (('M'-'A') * 1024) + (('A'-'A') * 32) + ('Y'-'A'): m = 5; break;
2488 case (('J'-'A') * 1024) + (('U'-'A') * 32) + ('N'-'A'): m = 6; break;
2489 case (('J'-'A') * 1024) + (('U'-'A') * 32) + ('L'-'A'): m = 7; break;
2490 case (('A'-'A') * 1024) + (('U'-'A') * 32) + ('G'-'A'): m = 8; break;
2491 case (('S'-'A') * 1024) + (('E'-'A') * 32) + ('P'-'A'): m = 9; break;
2492 case (('O'-'A') * 1024) + (('C'-'A') * 32) + ('T'-'A'): m = 10;break;
2493 case (('N'-'A') * 1024) + (('O'-'A') * 32) + ('V'-'A'): m = 11;break;
2494 case (('D'-'A') * 1024) + (('E'-'A') * 32) + ('C'-'A'): m = 12;break;
2495 default: return NIL;
2497 if ((*++(*arg) == '-') && isdigit (*++(*arg))) {
2498 y = 0; /* init year */
2499 do {
2500 y *= 10; /* add this number */
2501 y += *(*arg)++ - '0';
2503 while (isdigit (**arg));
2504 /* minimal validity check of date */
2505 if (d < 1 || d > 31 || m < 1 || m > 12 || y < 0) return NIL;
2506 /* time began on UNIX in 1970 */
2507 if (y < 100) y += (y >= (BASEYEAR - 1900)) ? 1900 : 2000;
2508 /* return value */
2509 *date = mail_shortdate (y - BASEYEAR,m,d);
2510 return T; /* success */
2516 return NIL; /* else error */
2519 /* Parse a search set criterion
2520 * Accepts: set to write into
2521 * pointer to argument text pointer
2522 * maximum value permitted
2523 * Returns: T if success, NIL if error
2524 */
2526 long crit_set (SEARCHSET **set,unsigned char **arg,unsigned long maxima)
2528 unsigned long i = 0;
2529 if (*set) return NIL; /* can't double this value */
2530 *set = mail_newsearchset (); /* instantiate a new search set */
2531 if (**arg == '*') { /* maxnum? */
2532 (*arg)++; /* skip past that number */
2533 (*set)->first = maxima;
2535 else if (crit_number (&i,arg) && i) (*set)->first = i;
2536 else return NIL; /* bogon */
2537 switch (**arg) { /* decide based on delimiter */
2538 case ':': /* sequence range */
2539 i = 0; /* reset for crit_number() */
2540 if (*++(*arg) == '*') { /* maxnum? */
2541 (*arg)++; /* skip past that number */
2542 (*set)->last = maxima;
2544 else if (crit_number (&i,arg) && i) {
2545 if (i < (*set)->first) { /* backwards range */
2546 (*set)->last = (*set)->first;
2547 (*set)->first = i;
2549 else (*set)->last = i; /* set last number */
2551 else return NIL; /* bogon */
2552 if (**arg != ',') break; /* drop into comma case if comma seen */
2553 case ',':
2554 (*arg)++; /* skip past delimiter */
2555 return crit_set (&(*set)->next,arg,maxima);
2556 default:
2557 break;
2559 return T; /* return success */
2562 /* Parse a search number criterion
2563 * Accepts: number to write into
2564 * pointer to argument text pointer
2565 * Returns: T if success, NIL if error
2566 */
2568 long crit_number (unsigned long *number,unsigned char **arg)
2570 /* can't double this value */
2571 if (*number || !isdigit (**arg)) return NIL;
2572 *number = 0;
2573 while (isdigit (**arg)) { /* found a digit? */
2574 *number *= 10; /* add a decade */
2575 *number += *(*arg)++ - '0'; /* add number */
2577 return T;
2581 /* Parse a search string criterion
2582 * Accepts: date to write into
2583 * pointer to argument text pointer
2584 * Returns: T if success, NIL if error
2585 */
2587 long crit_string (STRINGLIST **string,unsigned char **arg)
2589 unsigned long i;
2590 char c;
2591 char *s = parse_astring (arg,&i,&c);
2592 if (!s) return NIL;
2593 /* find tail of list */
2594 while (*string) string = &(*string)->next;
2595 *string = mail_newstringlist ();
2596 (*string)->text.data = (unsigned char *) fs_get (i + 1);
2597 memcpy ((*string)->text.data,s,i);
2598 (*string)->text.data[i] = '\0';
2599 (*string)->text.size = i;
2600 /* if end of arguments, wrap it up here */
2601 if (!*arg) *arg = (char *) (*string)->text.data + i;
2602 else (*--(*arg) = c); /* back up pointer, restore delimiter */
2603 return T;
2606 /* Fetch message data
2607 * Accepts: string of data items to be fetched (must be writeable)
2608 * UID fetch flag
2609 */
2611 #define MAXFETCH 100
2613 void fetch (char *t,unsigned long uid)
2615 fetchfn_t f[MAXFETCH +2];
2616 void *fa[MAXFETCH + 2];
2617 int k;
2618 memset ((void *) f,NIL,sizeof (f));
2619 memset ((void *) fa,NIL,sizeof (fa));
2620 fetch_work (t,uid,f,fa); /* do the work */
2621 /* clean up arguments */
2622 for (k = 1; f[k]; k++) if (fa[k]) (*f[k]) (0,fa[k]);
2626 /* Fetch message data worker routine
2627 * Accepts: string of data items to be fetched (must be writeable)
2628 * UID fetch flag
2629 * function dispatch vector
2630 * function argument vector
2631 */
2633 void fetch_work (char *t,unsigned long uid,fetchfn_t f[],void *fa[])
2635 unsigned char *s,*v;
2636 unsigned long i;
2637 unsigned long k = 0;
2638 BODY *b;
2639 int list = NIL;
2640 int parse_envs = NIL;
2641 int parse_bodies = NIL;
2642 if (uid) { /* need to fetch UIDs? */
2643 fa[k] = NIL; /* no argument */
2644 f[k++] = fetch_uid; /* push a UID fetch on the stack */
2647 /* process macros */
2648 if (!strcmp (ucase (t),"ALL"))
2649 strcpy (t,"(FLAGS INTERNALDATE RFC822.SIZE ENVELOPE)");
2650 else if (!strcmp (t,"FULL"))
2651 strcpy (t,"(FLAGS INTERNALDATE RFC822.SIZE ENVELOPE BODY)");
2652 else if (!strcmp (t,"FAST")) strcpy (t,"(FLAGS INTERNALDATE RFC822.SIZE)");
2653 if (list = (*t == '(')) t++; /* skip open paren */
2654 if (s = strtok (t," ")) do { /* parse attribute list */
2655 if (list && (i = strlen (s)) && (s[i-1] == ')')) {
2656 list = NIL; /* done with list */
2657 s[i-1] = '\0'; /* tie off last item */
2659 fa[k] = NIL; /* default to no argument */
2660 if (!strcmp (s,"UID")) { /* no-op if implicit */
2661 if (!uid) f[k++] = fetch_uid;
2663 else if (!strcmp (s,"FLAGS")) f[k++] = fetch_flags;
2664 else if (!strcmp (s,"INTERNALDATE")) f[k++] = fetch_internaldate;
2665 else if (!strcmp (s,"RFC822.SIZE")) f[k++] = fetch_rfc822_size;
2666 else if (!strcmp (s,"ENVELOPE")) {
2667 parse_envs = T; /* we will need to parse envelopes */
2668 f[k++] = fetch_envelope;
2670 else if (!strcmp (s,"BODY")) {
2671 parse_envs = parse_bodies = T;
2672 f[k++] = fetch_body;
2674 else if (!strcmp (s,"BODYSTRUCTURE")) {
2675 parse_envs = parse_bodies = T;
2676 f[k++] = fetch_bodystructure;
2678 else if (!strcmp (s,"RFC822")) {
2679 fa[k] = s[6] ? (void *) FT_PEEK : NIL;
2680 f[k++] = fetch_rfc822;
2682 else if (!strcmp (s,"RFC822.HEADER")) f[k++] = fetch_rfc822_header;
2683 else if (!strcmp (s,"RFC822.TEXT")) {
2684 fa[k] = s[11] ? (void *) FT_PEEK : NIL;
2685 f[k++] = fetch_rfc822_text;
2688 else if (!strncmp (s,"BODY[",5) || !strncmp (s,"BODY.PEEK[",10) ||
2689 !strncmp (s,"BINARY[",7) || !strncmp (s,"BINARY.PEEK[",12) ||
2690 !strncmp (s,"BINARY.SIZE[",12)) {
2691 TEXTARGS *ta = (TEXTARGS *)
2692 memset (fs_get (sizeof (TEXTARGS)),0,sizeof (TEXTARGS));
2693 if (s[1] == 'I') { /* body or binary? */
2694 ta->binary = FTB_BINARY;/* binary */
2695 f[k] = fetch_body_part_binary;
2696 if (s[6] == '.') { /* wanted peek or size? */
2697 if (s[7] == 'P') ta->flags = FT_PEEK;
2698 else ta->binary |= FTB_SIZE;
2699 s += 12; /* skip to section specifier */
2701 else s += 7; /* skip to section specifier */
2702 if (!isdigit (*s)) { /* make sure top-level digit */
2703 fs_give ((void **) &ta);
2704 response = badbin;
2705 return;
2708 else { /* body */
2709 f[k] = fetch_body_part_contents;
2710 if (s[4] == '.') { /* wanted peek? */
2711 ta->flags = FT_PEEK;
2712 s += 10; /* skip to section specifier */
2714 else s += 5; /* skip to section specifier */
2716 if (*(v = s) != ']') { /* non-empty section specifier? */
2717 if (isdigit (*v)) { /* have section specifier? */
2718 /* need envelopes and bodies */
2719 parse_envs = parse_bodies = T;
2720 while (isdigit (*v)) /* scan to end of section specifier */
2721 if ((*++v == '.') && isdigit (v[1])) v++;
2722 /* any IMAP4rev1 stuff following? */
2723 if ((*v == '.') && isalpha (v[1])) {
2724 if (ta->binary) { /* not if binary you don't */
2725 fs_give ((void **) &ta);
2726 response = badbin;
2727 return;
2729 *v++ = '\0'; /* yes, tie off section specifier */
2730 if (!strncmp (v,"MIME",4)) {
2731 v += 4; /* found <section>.MIME */
2732 f[k] = fetch_body_part_mime;
2735 else if (*v != ']') { /* better be the end if no IMAP4rev1 stuff */
2736 fs_give ((void **) &ta);/* clean up */
2737 response = "%.80s BAD Syntax error in section specifier\015\012";
2738 return;
2742 if (*v != ']') { /* IMAP4rev1 stuff here? */
2743 if (!strncmp (v,"HEADER",6)) {
2744 *v = '\0'; /* tie off in case top level */
2745 v += 6; /* found [<section>.]HEADER */
2746 f[k] = fetch_body_part_header;
2747 /* partial headers wanted? */
2748 if (!strncmp (v,".FIELDS",7)) {
2749 v += 7; /* yes */
2750 if (!strncmp (v,".NOT",4)) {
2751 v += 4; /* want to exclude named headers */
2752 ta->flags |= FT_NOT;
2754 if (*v || !(v = strtok (NIL,"\015\012")) ||
2755 !(ta->lines = parse_stringlist (&v,&list))) {
2756 fs_give ((void **) &ta);/* clean up */
2757 response = "%.80s BAD Syntax error in header fields\015\012";
2758 return;
2762 else if (!strncmp (v,"TEXT",4)) {
2763 *v = '\0'; /* tie off in case top level */
2764 v += 4; /* found [<section>.]TEXT */
2765 f[k] = fetch_body_part_text;
2767 else {
2768 fs_give ((void **) &ta);/* clean up */
2769 response = "%.80s BAD Unknown section text specifier\015\012";
2770 return;
2774 /* tie off section */
2775 if (*v == ']') *v++ = '\0';
2776 else { /* bogon */
2777 if (ta->lines) mail_free_stringlist (&ta->lines);
2778 fs_give ((void **) &ta);/* clean up */
2779 response = "%.80s BAD Section specifier not terminated\015\012";
2780 return;
2783 if ((*v == '<') && /* partial specifier? */
2784 ((ta->binary & FTB_SIZE) ||
2785 !(isdigit (v[1]) && ((ta->first = strtoul (v+1,(char **) &v,10)) ||
2786 v) &&
2787 (*v++ == '.') && (ta->last = strtoul (v,(char **) &v,10)) &&
2788 (*v++ == '>')))) {
2789 if (ta->lines) mail_free_stringlist (&ta->lines);
2790 fs_give ((void **) &ta);
2791 response ="%.80s BAD Syntax error in partial text specifier\015\012";
2792 return;
2794 switch (*v) { /* what's there now? */
2795 case ' ': /* more follows */
2796 *--v = ' '; /* patch a space back in */
2797 *--v = 'x'; /* and a hokey character before that */
2798 strtok (v," "); /* reset strtok mechanism */
2799 break;
2800 case '\0': /* none */
2801 break;
2802 case ')': /* end of list */
2803 if (list && !v[1]) { /* make sure of that */
2804 list = NIL;
2805 strtok (v," "); /* reset strtok mechanism */
2806 break; /* all done */
2808 /* otherwise it's a bogon, drop in */
2809 default: /* bogon */
2810 if (ta->lines) mail_free_stringlist (&ta->lines);
2811 fs_give ((void **) &ta);
2812 response = "%.80s BAD Syntax error after section specifier\015\012";
2813 return;
2815 /* make copy of section specifier */
2816 if (s && *s) ta->section = cpystr (s);
2817 fa[k++] = (void *) ta; /* set argument */
2819 else { /* unknown attribute */
2820 response = badatt;
2821 return;
2823 } while ((s = strtok (NIL," ")) && (k < MAXFETCH) && list);
2824 else {
2825 response = misarg; /* missing attribute list */
2826 return;
2829 if (s) { /* too many attributes? */
2830 response = "%.80s BAD Excessively complex FETCH attribute list\015\012";
2831 return;
2833 if (list) { /* too many attributes? */
2834 response = "%.80s BAD Unterminated FETCH attribute list\015\012";
2835 return;
2837 f[k] = NIL; /* tie off attribute list */
2838 /* c-client clobbers sequence, use spare */
2839 for (i = 1; i <= nmsgs; i++)
2840 mail_elt (stream,i)->spare = mail_elt (stream,i)->sequence;
2841 /* for each requested message */
2842 for (i = 1; (i <= nmsgs) && (response != loseunknowncte); i++) {
2843 /* kill if dying */
2844 if (state == LOGOUT) longjmp (jmpenv,1);
2845 if (mail_elt (stream,i)->spare) {
2846 /* parse envelope, set body, do warnings */
2847 if (parse_envs) mail_fetchstructure (stream,i,parse_bodies ? &b : NIL);
2848 quell_events = T; /* can't do any events now */
2849 PSOUT ("* "); /* leader */
2850 pnum (i);
2851 PSOUT (" FETCH (");
2852 (*f[0]) (i,fa[0]); /* do first attribute */
2853 /* for each subsequent attribute */
2854 for (k = 1; f[k] && (response != loseunknowncte); k++) {
2855 PBOUT (' '); /* delimit with space */
2856 (*f[k]) (i,fa[k]); /* do that attribute */
2858 PSOUT (")\015\012"); /* trailer */
2859 quell_events = NIL; /* events alright now */
2864 /* Fetch message body structure (extensible)
2865 * Accepts: message number
2866 * extra argument
2867 */
2869 void fetch_bodystructure (unsigned long i,void *args)
2871 BODY *body;
2872 mail_fetchstructure (stream,i,&body);
2873 PSOUT ("BODYSTRUCTURE ");
2874 pbodystructure (body); /* output body */
2878 /* Fetch message body structure (non-extensible)
2879 * Accepts: message number
2880 * extra argument
2881 */
2884 void fetch_body (unsigned long i,void *args)
2886 BODY *body;
2887 mail_fetchstructure (stream,i,&body);
2888 PSOUT ("BODY "); /* output attribute */
2889 pbody (body); /* output body */
2892 /* Fetch body part MIME header
2893 * Accepts: message number
2894 * extra argument
2895 */
2897 void fetch_body_part_mime (unsigned long i,void *args)
2899 TEXTARGS *ta = (TEXTARGS *) args;
2900 if (i) { /* do work? */
2901 SIZEDTEXT st;
2902 unsigned long uid = mail_uid (stream,i);
2903 char *tmp = (char *) fs_get (100 + strlen (ta->section));
2904 sprintf (tmp,"BODY[%s.MIME]",ta->section);
2905 /* try to use remembered text */
2906 if (lastuid && (uid == lastuid) && !strcmp (tmp,lastid)) st = lastst;
2907 else { /* get data */
2908 st.data = (unsigned char *)
2909 mail_fetch_mime (stream,i,ta->section,&st.size,ta->flags);
2910 if (ta->first || ta->last) remember (uid,tmp,&st);
2912 pbodypartstring (i,tmp,&st,NIL,ta);
2913 fs_give ((void **) &tmp);
2915 else { /* clean up the arguments */
2916 fs_give ((void **) &ta->section);
2917 fs_give ((void **) &args);
2922 /* Fetch body part contents
2923 * Accepts: message number
2924 * extra argument
2925 */
2927 void fetch_body_part_contents (unsigned long i,void *args)
2929 TEXTARGS *ta = (TEXTARGS *) args;
2930 if (i) { /* do work? */
2931 SIZEDTEXT st;
2932 char *tmp = (char *) fs_get (100+(ta->section ? strlen (ta->section) : 0));
2933 unsigned long uid = mail_uid (stream,i);
2934 sprintf (tmp,"BODY[%s]",ta->section ? ta->section : "");
2935 /* try to use remembered text */
2936 if (lastuid && (uid == lastuid) && !strcmp (tmp,lastid)) st = lastst;
2937 /* get data */
2938 else if ((st.data = (unsigned char *)
2939 mail_fetch_body (stream,i,ta->section,&st.size,
2940 ta->flags | FT_RETURNSTRINGSTRUCT)) &&
2941 (ta->first || ta->last)) remember (uid,tmp,&st);
2942 pbodypartstring (i,tmp,&st,&stream->private.string,ta);
2943 fs_give ((void **) &tmp);
2945 else { /* clean up the arguments */
2946 if (ta->section) fs_give ((void **) &ta->section);
2947 fs_give ((void **) &args);
2951 /* Fetch body part binary
2952 * Accepts: message number
2953 * extra argument
2954 * Someday fix this to use stringstruct instead of memory
2955 */
2957 void fetch_body_part_binary (unsigned long i,void *args)
2959 TEXTARGS *ta = (TEXTARGS *) args;
2960 if (i) { /* do work? */
2961 SIZEDTEXT st,cst;
2962 BODY *body = mail_body (stream,i,ta->section);
2963 char *tmp = (char *) fs_get (100+(ta->section ? strlen (ta->section) : 0));
2964 unsigned long uid = mail_uid (stream,i);
2965 /* try to use remembered text */
2966 if (lastuid && (uid == lastuid) && !strcmp (tmp,lastid)) st = lastst;
2967 else { /* get data */
2968 st.data = (unsigned char *)
2969 mail_fetch_body (stream,i,ta->section,&st.size,ta->flags);
2970 if (ta->first || ta->last) remember (uid,tmp,&st);
2972 /* what encoding was used? */
2973 if (body) switch (body->encoding) {
2974 case ENCBASE64:
2975 if (cst.data = rfc822_base64 (st.data,st.size,&cst.size)) break;
2976 fetch_uid (i,NIL); /* wrote a space, so must do something */
2977 if (lsterr) fs_give ((void **) &lsterr);
2978 lsterr = cpystr ("Undecodable BASE64 contents");
2979 response = loseunknowncte;
2980 fs_give ((void **) &tmp);
2981 return;
2982 case ENCQUOTEDPRINTABLE:
2983 if (cst.data = rfc822_qprint (st.data,st.size,&cst.size)) break;
2984 fetch_uid (i,NIL); /* wrote a space, so must do something */
2985 if (lsterr) fs_give ((void **) &lsterr);
2986 lsterr = cpystr ("Undecodable QUOTED-PRINTABLE contents");
2987 response = loseunknowncte;
2988 fs_give ((void **) &tmp);
2989 return;
2990 case ENC7BIT: /* no need to convert any of these */
2991 case ENC8BIT:
2992 case ENCBINARY:
2993 cst.data = NIL; /* no converted data to free */
2994 break;
2995 default: /* unknown encoding, oops */
2996 fetch_uid (i,NIL); /* wrote a space, so must do something */
2997 if (lsterr) fs_give ((void **) &lsterr);
2998 lsterr = cpystr ("Unknown Content-Transfer-Encoding");
2999 response = loseunknowncte;
3000 fs_give ((void **) &tmp);
3001 return;
3003 else {
3004 if (lsterr) fs_give ((void **) &lsterr);
3005 lsterr = cpystr ("Invalid body part");
3006 response = loseunknowncte;
3007 fs_give ((void **) &tmp);
3008 return;
3011 /* use decoded version if exists */
3012 if (cst.data) memcpy ((void *) &st,(void *) &cst,sizeof (SIZEDTEXT));
3013 if (ta->binary & FTB_SIZE) {/* just want size? */
3014 sprintf (tmp,"BINARY.SIZE[%s] %lu",ta->section ? ta->section : "",
3015 st.size);
3016 PSOUT (tmp);
3018 else { /* no, blat binary data */
3019 int f = mail_elt (stream,i)->seen;
3020 if (st.data) { /* only if have useful data */
3021 /* partial specifier */
3022 if (ta->first || ta->last)
3023 sprintf (tmp,"BINARY[%s]<%lu> ",
3024 ta->section ? ta->section : "",ta->first);
3025 else sprintf (tmp,"BINARY[%s] ",ta->section ? ta->section : "");
3026 /* in case first byte beyond end of text */
3027 if (st.size <= ta->first) st.size = ta->first = 0;
3028 else { /* offset and truncate */
3029 st.data += ta->first; /* move to desired position */
3030 st.size -= ta->first; /* reduced size */
3031 if (ta->last && (st.size > ta->last)) st.size = ta->last;
3033 if (st.size) sprintf (tmp + strlen (tmp),"{%lu}\015\012",st.size);
3034 else strcat (tmp,"\"\"");
3035 PSOUT (tmp); /* write binary output */
3036 if (st.size && (PSOUTR (&st) == EOF)) ioerror(stdout,"writing binary");
3038 else {
3039 sprintf (tmp,"BINARY[%s] NIL",ta->section ? ta->section : "");
3040 PSOUT (tmp);
3042 changed_flags (i,f); /* write changed flags */
3044 /* free converted data */
3045 if (cst.data) fs_give ((void **) &cst.data);
3046 fs_give ((void **) &tmp); /* and temporary string */
3048 else { /* clean up the arguments */
3049 if (ta->section) fs_give ((void **) &ta->section);
3050 fs_give ((void **) &args);
3054 /* Fetch MESSAGE/RFC822 body part header
3055 * Accepts: message number
3056 * extra argument
3057 */
3059 void fetch_body_part_header (unsigned long i,void *args)
3061 TEXTARGS *ta = (TEXTARGS *) args;
3062 unsigned long len = 100 + (ta->section ? strlen (ta->section) : 0);
3063 STRINGLIST *s;
3064 for (s = ta->lines; s; s = s->next) len += s->text.size + 1;
3065 if (i) { /* do work? */
3066 SIZEDTEXT st;
3067 char *tmp = (char *) fs_get (len);
3068 PSOUT ("BODY[");
3069 /* output attribute */
3070 if (ta->section && *ta->section) {
3071 PSOUT (ta->section);
3072 PBOUT ('.');
3074 PSOUT ("HEADER");
3075 if (ta->lines) {
3076 PSOUT ((ta->flags & FT_NOT) ? ".FIELDS.NOT " : ".FIELDS ");
3077 pastringlist (ta->lines);
3079 strcpy (tmp,"]"); /* close section specifier */
3080 st.data = (unsigned char *) /* get data (no hope in using remember here) */
3081 mail_fetch_header (stream,i,ta->section,ta->lines,&st.size,ta->flags);
3082 pbodypartstring (i,tmp,&st,NIL,ta);
3083 fs_give ((void **) &tmp);
3085 else { /* clean up the arguments */
3086 if (ta->lines) mail_free_stringlist (&ta->lines);
3087 if (ta->section) fs_give ((void **) &ta->section);
3088 fs_give ((void **) &args);
3092 /* Fetch MESSAGE/RFC822 body part text
3093 * Accepts: message number
3094 * extra argument
3095 */
3097 void fetch_body_part_text (unsigned long i,void *args)
3099 TEXTARGS *ta = (TEXTARGS *) args;
3100 if (i) { /* do work? */
3101 SIZEDTEXT st;
3102 char *tmp = (char *) fs_get (100+(ta->section ? strlen (ta->section) : 0));
3103 unsigned long uid = mail_uid (stream,i);
3104 /* output attribute */
3105 if (ta->section && *ta->section) sprintf (tmp,"BODY[%s.TEXT]",ta->section);
3106 else strcpy (tmp,"BODY[TEXT]");
3107 /* try to use remembered text */
3108 if (lastuid && (uid == lastuid) && !strcmp (tmp,lastid)) st = lastst;
3109 /* get data */
3110 else if ((st.data = (unsigned char *)
3111 mail_fetch_text (stream,i,ta->section,&st.size,
3112 ta->flags | FT_RETURNSTRINGSTRUCT)) &&
3113 (ta->first || ta->last)) remember (uid,tmp,&st);
3114 pbodypartstring (i,tmp,&st,&stream->private.string,ta);
3115 fs_give ((void **) &tmp);
3117 else { /* clean up the arguments */
3118 if (ta->section) fs_give ((void **) &ta->section);
3119 fs_give ((void **) &args);
3124 /* Remember body part text for subsequent partial fetching
3125 * Accepts: message UID
3126 * body part id
3127 * text
3128 * string
3129 */
3131 void remember (unsigned long uid,char *id,SIZEDTEXT *st)
3133 lastuid = uid; /* remember UID */
3134 if (lastid) fs_give ((void **) &lastid);
3135 lastid = cpystr (id); /* remember body part id */
3136 if (lastst.data) fs_give ((void **) &lastst.data);
3137 /* remember text */
3138 lastst.data = (unsigned char *)
3139 memcpy (fs_get (st->size + 1),st->data,st->size);
3140 lastst.size = st->size;
3144 /* Fetch envelope
3145 * Accepts: message number
3146 * extra argument
3147 */
3149 void fetch_envelope (unsigned long i,void *args)
3151 ENVELOPE *env = mail_fetchenvelope (stream,i);
3152 PSOUT ("ENVELOPE "); /* output attribute */
3153 penv (env); /* output envelope */
3156 /* Fetch flags
3157 * Accepts: message number
3158 * extra argument
3159 */
3161 void fetch_flags (unsigned long i,void *args)
3163 unsigned long u;
3164 char *t,tmp[MAILTMPLEN];
3165 int c = NIL;
3166 MESSAGECACHE *elt = mail_elt (stream,i);
3167 if (!elt->valid) { /* have valid flags yet? */
3168 sprintf (tmp,"%lu",i);
3169 mail_fetch_flags (stream,tmp,NIL);
3171 PSOUT ("FLAGS ("); /* output attribute */
3172 /* output system flags */
3173 if (elt->recent) put_flag (&c,"\\Recent");
3174 if (elt->seen) put_flag (&c,"\\Seen");
3175 if (elt->deleted) put_flag (&c,"\\Deleted");
3176 if (elt->flagged) put_flag (&c,"\\Flagged");
3177 if (elt->answered) put_flag (&c,"\\Answered");
3178 if (elt->draft) put_flag (&c,"\\Draft");
3179 if (u = elt->user_flags) do /* any user flags? */
3180 if (t = stream->user_flags[find_rightmost_bit (&u)]) put_flag (&c,t);
3181 while (u); /* until no more user flags */
3182 PBOUT (')'); /* end of flags */
3183 elt->spare2 = NIL; /* we've sent the update */
3187 /* Output a flag
3188 * Accepts: pointer to current delimiter character
3189 * flag to output
3190 * Changes delimiter character to space
3191 */
3193 void put_flag (int *c,char *s)
3195 if (*c) PBOUT (*c); /* put delimiter */
3196 PSOUT (s); /* dump flag */
3197 *c = ' '; /* change delimiter if necessary */
3201 /* Output flags if was unseen
3202 * Accepts: message number
3203 * prior value of Seen flag
3204 */
3206 void changed_flags (unsigned long i,int f)
3208 /* was unseen, now seen? */
3209 if (!f && mail_elt (stream,i)->seen) {
3210 PBOUT (' '); /* yes, delimit with space */
3211 fetch_flags (i,NIL); /* output flags */
3215 /* Fetch message internal date
3216 * Accepts: message number
3217 * extra argument
3218 */
3220 void fetch_internaldate (unsigned long i,void *args)
3222 char tmp[MAILTMPLEN];
3223 MESSAGECACHE *elt = mail_elt (stream,i);
3224 if (!elt->day) { /* have internal date yet? */
3225 sprintf (tmp,"%lu",i);
3226 mail_fetch_fast (stream,tmp,NIL);
3228 PSOUT ("INTERNALDATE \"");
3229 PSOUT (mail_date (tmp,elt));
3230 PBOUT ('"');
3234 /* Fetch unique identifier
3235 * Accepts: message number
3236 * extra argument
3237 */
3239 void fetch_uid (unsigned long i,void *args)
3241 PSOUT ("UID ");
3242 pnum (mail_uid (stream,i));
3245 /* Fetch complete RFC-822 format message
3246 * Accepts: message number
3247 * extra argument
3248 */
3250 void fetch_rfc822 (unsigned long i,void *args)
3252 if (i) { /* do work? */
3253 int f = mail_elt (stream,i)->seen;
3254 #if 0
3255 SIZEDTEXT st;
3256 st.data = (unsigned char *)
3257 mail_fetch_message (stream,i,&st.size,(long) args);
3258 pbodypartstring (i,"RFC822",&st,NIL,NIL);
3259 #else
3260 /* Yes, this version is bletcherous, but mail_fetch_message() requires
3261 too much memory */
3262 SIZEDTEXT txt,hdr;
3263 char *s = mail_fetch_header (stream,i,NIL,NIL,&hdr.size,FT_PEEK);
3264 hdr.data = (unsigned char *) memcpy (fs_get (hdr.size),s,hdr.size);
3265 txt.data = (unsigned char *)
3266 mail_fetch_text (stream,i,NIL,&txt.size,
3267 ((long) args) | FT_RETURNSTRINGSTRUCT);
3268 PSOUT ("RFC822 {");
3269 pnum (hdr.size + txt.size);
3270 PSOUT ("}\015\012");
3271 ptext (&hdr,NIL);
3272 ptext (&txt,&stream->private.string);
3273 fs_give ((void **) &hdr.data);
3274 #endif
3275 changed_flags (i,f); /* output changed flags */
3280 /* Fetch RFC-822 header
3281 * Accepts: message number
3282 * extra argument
3283 */
3285 void fetch_rfc822_header (unsigned long i,void *args)
3287 SIZEDTEXT st;
3288 st.data = (unsigned char *)
3289 mail_fetch_header (stream,i,NIL,NIL,&st.size,FT_PEEK);
3290 pbodypartstring (i,"RFC822.HEADER",&st,NIL,NIL);
3294 /* Fetch RFC-822 message length
3295 * Accepts: message number
3296 * extra argument
3297 */
3299 void fetch_rfc822_size (unsigned long i,void *args)
3301 char tmp[MAILTMPLEN];
3302 MESSAGECACHE *elt = mail_elt (stream,i);
3303 if (!elt->rfc822_size) { /* have message size yet? */
3304 sprintf (tmp,"%lu",i);
3305 mail_fetch_fast (stream,tmp,NIL);
3307 PSOUT ("RFC822.SIZE ");
3308 pnum (elt->rfc822_size);
3311 /* Fetch RFC-822 text only
3312 * Accepts: message number
3313 * extra argument
3314 */
3316 void fetch_rfc822_text (unsigned long i,void *args)
3318 if (i) { /* do work? */
3319 int f = mail_elt (stream,i)->seen;
3320 SIZEDTEXT st;
3321 st.data = (unsigned char *)
3322 mail_fetch_text (stream,i,NIL,&st.size,
3323 ((long) args) | FT_RETURNSTRINGSTRUCT);
3324 pbodypartstring (i,"RFC822.TEXT",&st,&stream->private.string,NIL);
3328 /* Print envelope
3329 * Accepts: body
3330 */
3332 void penv (ENVELOPE *env)
3334 PBOUT ('('); /* delimiter */
3335 if (env) { /* only if there is an envelope */
3336 pnstring (env->date); /* output envelope fields */
3337 PBOUT (' ');
3338 pnstring (env->subject);
3339 PBOUT (' ');
3340 paddr (env->from);
3341 PBOUT (' ');
3342 paddr (env->sender);
3343 PBOUT (' ');
3344 paddr (env->reply_to);
3345 PBOUT (' ');
3346 paddr (env->to);
3347 PBOUT (' ');
3348 paddr (env->cc);
3349 PBOUT (' ');
3350 paddr (env->bcc);
3351 PBOUT (' ');
3352 pnstring (env->in_reply_to);
3353 PBOUT (' ');
3354 pnstring (env->message_id);
3356 /* no envelope */
3357 else PSOUT ("NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL");
3358 PBOUT (')'); /* end of envelope */
3361 /* Print body structure (extensible)
3362 * Accepts: body
3363 */
3365 void pbodystructure (BODY *body)
3367 PBOUT ('('); /* delimiter */
3368 if (body) { /* only if there is a body */
3369 PART *part;
3370 /* multipart type? */
3371 if (body->type == TYPEMULTIPART) {
3372 /* print each part */
3373 if (part = body->nested.part)
3374 for (; part; part = part->next) pbodystructure (&(part->body));
3375 else pbodystructure (NIL);
3376 PBOUT (' '); /* space delimiter */
3377 pstring (body->subtype); /* subtype */
3378 PBOUT (' ');
3379 pparam (body->parameter); /* multipart body extension data */
3380 PBOUT (' ');
3381 if (body->disposition.type) {
3382 PBOUT ('(');
3383 pstring (body->disposition.type);
3384 PBOUT (' ');
3385 pparam (body->disposition.parameter);
3386 PBOUT (')');
3388 else PSOUT ("NIL");
3389 PBOUT (' ');
3390 pnstringorlist (body->language);
3391 PBOUT (' ');
3392 pnstring (body->location);
3395 else { /* non-multipart body type */
3396 pstring ((char *) body_types[body->type]);
3397 PBOUT (' ');
3398 pstring (body->subtype);
3399 PBOUT (' ');
3400 pparam (body->parameter);
3401 PBOUT (' ');
3402 pnstring (body->id);
3403 PBOUT (' ');
3404 pnstring (body->description);
3405 PBOUT (' ');
3406 pstring ((char *) body_encodings[body->encoding]);
3407 PBOUT (' ');
3408 pnum (body->size.bytes);
3409 switch (body->type) { /* extra stuff depends upon body type */
3410 case TYPEMESSAGE:
3411 /* can't do this if not RFC822 */
3412 if (strcmp (body->subtype,"RFC822")) break;
3413 PBOUT (' ');
3414 penv (body->nested.msg->env);
3415 PBOUT (' ');
3416 pbodystructure (body->nested.msg->body);
3417 case TYPETEXT:
3418 PBOUT (' ');
3419 pnum (body->size.lines);
3420 break;
3421 default:
3422 break;
3424 PBOUT (' ');
3425 pnstring (body->md5);
3426 PBOUT (' ');
3427 if (body->disposition.type) {
3428 PBOUT ('(');
3429 pstring (body->disposition.type);
3430 PBOUT (' ');
3431 pparam (body->disposition.parameter);
3432 PBOUT (')');
3434 else PSOUT ("NIL");
3435 PBOUT (' ');
3436 pnstringorlist (body->language);
3437 PBOUT (' ');
3438 pnstring (body->location);
3441 /* no body */
3442 else PSOUT ("\"TEXT\" \"PLAIN\" (\"CHARSET\" \"US-ASCII\") NIL NIL \"7BIT\" 0 0 NIL NIL NIL NIL");
3443 PBOUT (')'); /* end of body */
3446 /* Print body (non-extensible)
3447 * Accepts: body
3448 */
3450 void pbody (BODY *body)
3452 PBOUT ('('); /* delimiter */
3453 if (body) { /* only if there is a body */
3454 PART *part;
3455 /* multipart type? */
3456 if (body->type == TYPEMULTIPART) {
3457 /* print each part */
3458 if (part = body->nested.part)
3459 for (; part; part = part->next) pbody (&(part->body));
3460 else pbody (NIL);
3461 PBOUT (' '); /* space delimiter */
3462 pstring (body->subtype); /* and finally the subtype */
3464 else { /* non-multipart body type */
3465 pstring ((char *) body_types[body->type]);
3466 PBOUT (' ');
3467 pstring (body->subtype);
3468 PBOUT (' ');
3469 pparam (body->parameter);
3470 PBOUT (' ');
3471 pnstring (body->id);
3472 PBOUT (' ');
3473 pnstring (body->description);
3474 PBOUT (' ');
3475 pstring ((char *) body_encodings[body->encoding]);
3476 PBOUT (' ');
3477 pnum (body->size.bytes);
3478 switch (body->type) { /* extra stuff depends upon body type */
3479 case TYPEMESSAGE:
3480 /* can't do this if not RFC822 */
3481 if (strcmp (body->subtype,"RFC822")) break;
3482 PBOUT (' ');
3483 penv (body->nested.msg ? body->nested.msg->env : NIL);
3484 PBOUT (' ');
3485 pbody (body->nested.msg ? body->nested.msg->body : NIL);
3486 case TYPETEXT:
3487 PBOUT (' ');
3488 pnum (body->size.lines);
3489 break;
3490 default:
3491 break;
3495 /* no body */
3496 else PSOUT ("\"TEXT\" \"PLAIN\" (\"CHARSET\" \"US-ASCII\") NIL NIL \"7BIT\" 0 0");
3497 PBOUT (')'); /* end of body */
3500 /* Print parameter list
3501 * Accepts: paramter
3502 */
3504 void pparam (PARAMETER *param)
3506 if (param) { /* one specified? */
3507 PBOUT ('(');
3508 do {
3509 pstring (param->attribute);
3510 PBOUT (' ');
3511 pstring (param->value);
3512 if (param = param->next) PBOUT (' ');
3513 } while (param);
3514 PBOUT (')'); /* end of parameters */
3516 else PSOUT ("NIL");
3520 /* Print address list
3521 * Accepts: address list
3522 */
3524 void paddr (ADDRESS *a)
3526 if (a) { /* have anything in address? */
3527 PBOUT ('('); /* open the address list */
3528 do { /* for each address */
3529 PBOUT ('('); /* open the address */
3530 pnstring (a->personal); /* personal name */
3531 PBOUT (' ');
3532 pnstring (a->adl); /* at-domain-list */
3533 PBOUT (' ');
3534 pnstring (a->mailbox); /* mailbox */
3535 PBOUT (' ');
3536 pnstring (a->host); /* domain name of mailbox's host */
3537 PBOUT (')'); /* terminate address */
3538 } while (a = a->next); /* until end of address */
3539 PBOUT (')'); /* close address list */
3541 else PSOUT ("NIL"); /* empty address */
3544 /* Print set
3545 * Accepts: set
3546 */
3548 void pset (SEARCHSET **set)
3550 SEARCHSET *cur = *set;
3551 while (cur) { /* while there's a set to do */
3552 pnum (cur->first); /* output first value */
3553 if (cur->last) { /* if range, output second value of range */
3554 PBOUT (':');
3555 pnum (cur->last);
3557 if (cur = cur->next) PBOUT (',');
3559 mail_free_searchset (set); /* flush set */
3563 /* Print number
3564 * Accepts: number
3565 */
3567 void pnum (unsigned long i)
3569 char tmp[MAILTMPLEN];
3570 sprintf (tmp,"%lu",i);
3571 PSOUT (tmp);
3575 /* Print string
3576 * Accepts: string
3577 */
3579 void pstring (char *s)
3581 SIZEDTEXT st;
3582 st.data = (unsigned char *) s;/* set up sized text */
3583 st.size = strlen (s);
3584 psizedstring (&st,NIL); /* print string */
3588 /* Print nstring
3589 * Accepts: string or NIL
3590 */
3592 void pnstring (char *s)
3594 if (s) pstring (s); /* print string */
3595 else PSOUT ("NIL");
3599 /* Print atom or string
3600 * Accepts: astring
3601 */
3603 void pastring (char *s)
3605 char *t;
3606 if (!*s) PSOUT ("\"\""); /* empty string */
3607 else { /* see if atom */
3608 for (t = s; (*t > ' ') && !(*t & 0x80) &&
3609 (*t != '"') && (*t != '\\') && (*t != '(') && (*t != ')') &&
3610 (*t != '{') && (*t != '%') && (*t != '*'); t++);
3611 if (*t) pstring (s); /* not an atom */
3612 else PSOUT (s); /* else plop down as atomic */
3616 /* Print sized text as quoted
3617 * Accepts: sized text
3618 */
3620 void psizedquoted (SIZEDTEXT *s)
3622 PBOUT ('"'); /* use quoted string */
3623 ptext (s,NIL);
3624 PBOUT ('"');
3628 /* Print sized text as literal
3629 * Accepts: sized text
3630 */
3632 void psizedliteral (SIZEDTEXT *s,STRING *st)
3634 PBOUT ('{'); /* print literal size */
3635 pnum (s->size);
3636 PSOUT ("}\015\012");
3637 ptext (s,st);
3640 /* Print sized text as literal or quoted string
3641 * Accepts: sized text
3642 * alternative stringstruct of text
3643 */
3645 void psizedstring (SIZEDTEXT *s,STRING *st)
3647 unsigned char c;
3648 unsigned long i;
3650 if (s->data) { /* if text, check if must use literal */
3651 for (i = 0; ((i < s->size) && ((c = s->data[i]) & 0xe0) &&
3652 !(c & 0x80) && (c != '"') && (c != '\\')); ++i);
3653 /* must use literal if not all QUOTED-CHAR */
3654 if (i < s->size) psizedliteral (s,st);
3655 else psizedquoted (s);
3657 else psizedliteral (s,st);
3661 /* Print sized text as literal or quoted string
3662 * Accepts: sized text
3663 */
3665 void psizedastring (SIZEDTEXT *s)
3667 unsigned long i;
3668 unsigned int atomp = s->size ? T : NIL;
3669 for (i = 0; i < s->size; i++){/* check if must use literal */
3670 if (!(s->data[i] & 0xe0) || (s->data[i] & 0x80) ||
3671 (s->data[i] == '"') || (s->data[i] == '\\')) {
3672 psizedliteral (s,NIL);
3673 return;
3675 else switch (s->data[i]) { /* else see if any atom-specials */
3676 case '(': case ')': case '{': case ' ':
3677 case '%': case '*': /* list-wildcards */
3678 case ']': /* resp-specials */
3679 /* CTL and quoted-specials in literal check */
3680 atomp = NIL; /* not an atom */
3683 if (atomp) ptext (s,NIL); /* print as atom */
3684 else psizedquoted (s); /* print as quoted string */
3687 /* Print string list
3688 * Accepts: string list
3689 */
3691 void pastringlist (STRINGLIST *s)
3693 PBOUT ('('); /* start list */
3694 do {
3695 psizedastring (&s->text); /* output list member */
3696 if (s->next) PBOUT (' ');
3697 } while (s = s->next);
3698 PBOUT (')'); /* terminate list */
3702 /* Print nstring or list of strings
3703 * Accepts: string / string list
3704 */
3706 void pnstringorlist (STRINGLIST *s)
3708 if (!s) PSOUT ("NIL"); /* no argument given */
3709 else if (s->next) { /* output list as list of strings*/
3710 PBOUT ('('); /* start list */
3711 do { /* output list member */
3712 psizedstring (&s->text,NIL);
3713 if (s->next) PBOUT (' ');
3714 } while (s = s->next);
3715 PBOUT (')'); /* terminate list */
3717 /* and single-element list as string */
3718 else psizedstring (&s->text,NIL);
3721 /* Print body part string
3722 * Accepts: message number
3723 * body part id (note: must have space at end to append stuff)
3724 * sized text of string
3725 * alternative stringstruct of string
3726 * text printing arguments
3727 */
3729 void pbodypartstring (unsigned long msgno,char *id,SIZEDTEXT *st,STRING *bs,
3730 TEXTARGS *ta)
3732 int f = mail_elt (stream,msgno)->seen;
3733 /* ignore stringstruct if non-initialized */
3734 if (bs && !bs->curpos) bs = NIL;
3735 if (ta && st->size) { /* only if have useful data */
3736 /* partial specifier */
3737 if (ta->first || ta->last) sprintf (id + strlen (id),"<%lu>",ta->first);
3738 /* in case first byte beyond end of text */
3739 if (st->size <= ta->first) st->size = ta->first = 0;
3740 else {
3741 if (st->data) { /* offset and truncate */
3742 st->data += ta->first; /* move to desired position */
3743 st->size -= ta->first; /* reduced size */
3745 else if (bs && (SIZE (bs) >= ta->first))
3746 SETPOS (bs,ta->first + GETPOS (bs));
3747 else st->size = 0; /* shouldn't happen */
3748 if (ta->last && (st->size > ta->last)) st->size = ta->last;
3751 PSOUT (id);
3752 PBOUT (' ');
3753 psizedstring (st,bs); /* output string */
3754 changed_flags (msgno,f); /* and changed flags */
3757 /* RFC 3501 technically forbids NULs in literals. Normally, the delivering
3758 * MTA would take care of MIME converting the message text so that it is
3759 * NUL-free. If it doesn't, then we have the choice of either violating
3760 * IMAP by sending NULs, corrupting the data, or going to lots of work to do
3761 * MIME conversion in the IMAP server.
3762 */
3764 /* Print raw sized text
3765 * Accepts: sizedtext
3766 */
3768 void ptext (SIZEDTEXT *txt,STRING *st)
3770 unsigned char c,*s;
3771 unsigned long i = txt->size;
3772 if (s = txt->data) while (i && ((PBOUT ((c = *s++) ? c : 0x80) != EOF))) --i;
3773 else if (st) while (i && (PBOUT ((c = SNX (st)) ? c : 0x80) != EOF)) --i;
3774 /* failed to complete? */
3775 if (i) ioerror (stdout,"writing text");
3778 /* Print thread
3779 * Accepts: thread
3780 */
3782 void pthread (THREADNODE *thr)
3784 THREADNODE *t;
3785 while (thr) { /* for each branch */
3786 PBOUT ('('); /* open branch */
3787 if (thr->num) { /* first node message number */
3788 pnum (thr->num);
3789 if (t = thr->next) { /* any subsequent nodes? */
3790 PBOUT (' ');
3791 while (t) { /* for each subsequent node */
3792 if (t->branch) { /* branches? */
3793 pthread (t); /* yes, recurse to do branch */
3794 t = NIL; /* done */
3796 else { /* just output this number */
3797 pnum (t->num);
3798 t = t->next; /* and do next message */
3800 if (t) PBOUT (' '); /* delimit if more to come */
3804 else pthread (thr->next); /* nest for dummy */
3805 PBOUT (')'); /* done with this branch */
3806 thr = thr->branch; /* do next branch */
3810 /* Print capabilities
3811 * Accepts: option flag
3812 */
3814 void pcapability (long flag)
3816 unsigned long i;
3817 char *s;
3818 struct stat sbuf;
3819 AUTHENTICATOR *auth;
3820 THREADER *thr = (THREADER *) mail_parameters (NIL,GET_THREADERS,NIL);
3821 /* always output protocol level */
3822 PSOUT ("CAPABILITY IMAP4REV1 I18NLEVEL=1 LITERAL+");
3823 #ifdef NETSCAPE_BRAIN_DAMAGE
3824 PSOUT (" X-NETSCAPE");
3825 #endif
3826 if (flag >= 0) { /* want post-authentication capabilities? */
3827 PSOUT (" IDLE UIDPLUS NAMESPACE CHILDREN MAILBOX-REFERRALS BINARY UNSELECT ESEARCH WITHIN SCAN SORT");
3828 while (thr) { /* threaders */
3829 PSOUT (" THREAD=");
3830 PSOUT (thr->name);
3831 thr = thr->next;
3833 if (!anonymous) PSOUT (" MULTIAPPEND");
3835 if (flag <= 0) { /* want pre-authentication capabilities? */
3836 PSOUT (" SASL-IR LOGIN-REFERRALS");
3837 if (s = ssl_start_tls (NIL)) fs_give ((void **) &s);
3838 else PSOUT (" STARTTLS");
3839 /* disable plaintext */
3840 if (!(i = !mail_parameters (NIL,GET_DISABLEPLAINTEXT,NIL)))
3841 PSOUT (" LOGINDISABLED");
3842 for (auth = mail_lookup_auth (1); auth; auth = auth->next)
3843 if (auth->server && !(auth->flags & AU_DISABLE) &&
3844 !(auth->flags & AU_HIDE) && (i || (auth->flags & AU_SECURE))) {
3845 PSOUT (" AUTH=");
3846 PSOUT (auth->name);
3848 if (!stat (ANOFILE,&sbuf)) PSOUT (" AUTH=ANONYMOUS");
3852 /* Anonymous users may only use these mailboxes in these namespaces */
3854 char *oktab[] = {"#news.", "#ftp/", "#public/", 0};
3857 /* Check if mailbox name is OK
3858 * Accepts: reference name
3859 * mailbox name
3860 */
3862 long nameok (char *ref,char *name)
3864 int i;
3865 unsigned char *s,*t;
3866 if (!name) return NIL; /* failure if missing name */
3867 if (!anonymous) return T; /* otherwise OK if not anonymous */
3868 /* validate reference */
3869 if (ref && ((*ref == '#') || (*ref == '{')))
3870 for (i = 0; oktab[i]; i++) {
3871 for (s = ref, t = oktab[i]; *t && !compare_uchar (*s,*t); s++, t++);
3872 if (!*t) { /* reference OK */
3873 if (*name == '#') break;/* check name if override */
3874 else return T; /* otherwise done */
3877 /* ordinary names are OK */
3878 if ((*name != '#') && (*name != '{')) return T;
3879 for (i = 0; oktab[i]; i++) { /* validate mailbox */
3880 for (s = name, t = oktab[i]; *t && !compare_uchar (*s,*t); s++, t++);
3881 if (!*t) return T; /* name is OK */
3883 response = "%.80s NO Anonymous may not %.80s this name\015\012";
3884 return NIL;
3888 /* Convert possible BBoard name to actual name
3889 * Accepts: command
3890 * mailbox name
3891 * Returns: maibox name
3892 */
3894 char *bboardname (char *cmd,char *name)
3896 if (cmd[0] == 'B') { /* want bboard? */
3897 char *s = litstk[litsp++] = (char *) fs_get (strlen (name) + 9);
3898 sprintf (s,"#public/%s",(*name == '/') ? name+1 : name);
3899 name = s;
3901 return name;
3904 /* Test if name is news proxy
3905 * Accepts: name
3906 * Returns: T if news proxy, NIL otherwise
3907 */
3909 long isnewsproxy (char *name)
3911 return (nntpproxy && (name[0] == '#') &&
3912 ((name[1] == 'N') || (name[1] == 'n')) &&
3913 ((name[2] == 'E') || (name[2] == 'e')) &&
3914 ((name[3] == 'W') || (name[3] == 'w')) &&
3915 ((name[4] == 'S') || (name[4] == 's')) && (name[5] == '.')) ?
3916 LONGT : NIL;
3920 /* News proxy generate canonical pattern
3921 * Accepts: reference
3922 * pattern
3923 * buffer to return canonical pattern
3924 * Returns: T on success with pattern in buffer, NIL on failure
3925 */
3927 long newsproxypattern (char *ref,char *pat,char *pattern,long flag)
3929 if (!nntpproxy) return NIL;
3930 if (strlen (ref) > NETMAXMBX) {
3931 sprintf (pattern,"Invalid reference specification: %.80s",ref);
3932 mm_log (pattern,ERROR);
3933 return NIL;
3935 if (strlen (pat) > NETMAXMBX) {
3936 sprintf (pattern,"Invalid pattern specification: %.80s",pat);
3937 mm_log (pattern,ERROR);
3938 return NIL;
3940 if (flag) { /* prepend proxy specifier */
3941 sprintf (pattern,"{%.300s/nntp}",nntpproxy);
3942 pattern += strlen (pattern);
3944 if (*ref) { /* have a reference */
3945 strcpy (pattern,ref); /* copy reference to pattern */
3946 /* # overrides mailbox field in reference */
3947 if (*pat == '#') strcpy (pattern,pat);
3948 /* pattern starts, reference ends, with . */
3949 else if ((*pat == '.') && (pattern[strlen (pattern) - 1] == '.'))
3950 strcat (pattern,pat + 1); /* append, omitting one of the period */
3951 else strcat (pattern,pat); /* anything else is just appended */
3953 else strcpy (pattern,pat); /* just have basic name */
3954 return isnewsproxy (pattern);
3957 /* IMAP4rev1 Authentication responder
3958 * Accepts: challenge
3959 * length of challenge
3960 * pointer to response length return location if non-NIL
3961 * Returns: response
3962 */
3964 #define RESPBUFLEN 8*MAILTMPLEN
3966 char *imap_responder (void *challenge,unsigned long clen,unsigned long *rlen)
3968 unsigned long i,j;
3969 unsigned char *t,resp[RESPBUFLEN];
3970 if (initial) { /* initial response given? */
3971 if (clen) return NIL; /* not permitted */
3972 /* set up response */
3973 i = strlen ((char *) (t = initial));
3974 initial = NIL; /* no more initial response */
3975 if ((*t == '=') && !t[1]) { /* SASL-IR does this for 0-length response */
3976 if (rlen) *rlen = 0; /* set length zero if empty */
3977 return cpystr (""); /* and return empty string as response */
3980 else { /* issue challenge, get response */
3981 PSOUT ("+ ");
3982 for (t = rfc822_binary ((void *) challenge,clen,&i),j = 0; j < i; j++)
3983 if (t[j] > ' ') PBOUT (t[j]);
3984 fs_give ((void **) &t);
3985 CRLF;
3986 PFLUSH (); /* dump output buffer */
3987 /* slurp response buffer */
3988 slurp ((char *) resp,RESPBUFLEN,INPUTTIMEOUT);
3989 if (!(t = (unsigned char *) strchr ((char *) resp,'\012')))
3990 return (char *) flush ();
3991 if (t[-1] == '\015') --t; /* remove CR */
3992 *t = '\0'; /* tie off buffer */
3993 if (resp[0] == '*') {
3994 cancelled = T;
3995 return NIL;
3997 i = t - resp; /* length of response */
3998 t = resp; /* set up for return call */
4000 return (i % 4) ? NIL : /* return if valid BASE64 */
4001 (char *) rfc822_base64 (t,i,rlen ? rlen : &i);
4004 /* Proxy copy across mailbox formats
4005 * Accepts: mail stream
4006 * sequence to copy on this stream
4007 * destination mailbox
4008 * option flags
4009 * Returns: T if success, else NIL
4010 */
4012 long proxycopy (MAILSTREAM *stream,char *sequence,char *mailbox,long options)
4014 MAILSTREAM *ts;
4015 STRING st;
4016 MSGDATA md;
4017 SEARCHSET *set;
4018 char tmp[MAILTMPLEN];
4019 unsigned long i,j;
4020 md.stream = stream;
4021 md.msgno = 0;
4022 md.flags = md.date = NIL;
4023 md.message = &st;
4024 /* Currently ignores CP_MOVE and CP_DEBUG */
4025 if (!((options & CP_UID) ? /* validate sequence */
4026 mail_uid_sequence (stream,sequence) : mail_sequence (stream,sequence)))
4027 return NIL;
4028 response = win; /* cancel previous errors */
4029 if (lsterr) fs_give ((void **) &lsterr);
4030 /* c-client clobbers sequence, use spare */
4031 for (i = 1,j = 0,set = mail_newsearchset (); i <= nmsgs; i++)
4032 if (mail_elt (stream,i)->spare = mail_elt (stream,i)->sequence) {
4033 mail_append_set (set,mail_uid (stream,i));
4034 if (!j) md.msgno = (j = i) - 1;
4036 /* only if at least one message to copy */
4037 if (j && !mail_append_multiple (NIL,mailbox,proxy_append,(void *) &md)) {
4038 response = trycreate ? losetry : lose;
4039 if (set) mail_free_searchset (&set);
4040 return NIL;
4042 if (caset) csset = set; /* set for return value now */
4043 else if (set) mail_free_searchset (&set);
4044 response = win; /* stomp any previous babble */
4045 if (md.msgno) { /* get new driver name if was dummy */
4046 sprintf (tmp,"Cross-format (%.80s -> %.80s) COPY completed",
4047 stream->dtb->name,(ts = mail_open (NIL,mailbox,OP_PROTOTYPE)) ?
4048 ts->dtb->name : "unknown");
4049 mm_log (tmp,NIL);
4051 return LONGT;
4054 /* Proxy append message callback
4055 * Accepts: MAIL stream
4056 * append data package
4057 * pointer to return initial flags
4058 * pointer to return message internal date
4059 * pointer to return stringstruct of message or NIL to stop
4060 * Returns: T if success (have message or stop), NIL if error
4061 */
4063 long proxy_append (MAILSTREAM *stream,void *data,char **flags,char **date,
4064 STRING **message)
4066 MESSAGECACHE *elt;
4067 unsigned long i;
4068 char *s,*t,tmp[MAILTMPLEN];
4069 MSGDATA *md = (MSGDATA *) data;
4070 if (md->flags) fs_give ((void **) &md->flags);
4071 if (md->date) fs_give ((void **) &md->date);
4072 *message = NIL; /* assume all done */
4073 *flags = *date = NIL;
4074 while (++md->msgno <= nmsgs)
4075 if ((elt = mail_elt (md->stream,md->msgno))->spare) {
4076 if (!(elt->valid && elt->day)) {
4077 sprintf (tmp,"%lu",md->msgno);
4078 mail_fetch_fast (md->stream,tmp,NIL);
4080 memset (s = tmp,0,MAILTMPLEN);
4081 /* copy flags */
4082 if (elt->seen) strcat (s," \\Seen");
4083 if (elt->deleted) strcat (s," \\Deleted");
4084 if (elt->flagged) strcat (s," \\Flagged");
4085 if (elt->answered) strcat (s," \\Answered");
4086 if (elt->draft) strcat (s," \\Draft");
4087 if (i = elt->user_flags) do
4088 if ((t = md->stream->user_flags[find_rightmost_bit (&i)]) && *t &&
4089 (strlen (t) < ((size_t) (MAILTMPLEN-((s += strlen (s))+2-tmp))))) {
4090 *s++ = ' '; /* space delimiter */
4091 strcpy (s,t);
4092 } while (i); /* until no more user flags */
4093 *message = md->message; /* set up return values */
4094 *flags = md->flags = cpystr (tmp + 1);
4095 *date = md->date = cpystr (mail_date (tmp,elt));
4096 INIT (md->message,msg_string,(void *) md,elt->rfc822_size);
4097 break; /* process this message */
4099 return LONGT;
4102 /* Append message callback
4103 * Accepts: MAIL stream
4104 * append data package
4105 * pointer to return initial flags
4106 * pointer to return message internal date
4107 * pointer to return stringstruct of message or NIL to stop
4108 * Returns: T if success (have message or stop), NIL if error
4109 */
4111 long append_msg (MAILSTREAM *stream,void *data,char **flags,char **date,
4112 STRING **message)
4114 unsigned long i,j;
4115 char *t;
4116 APPENDDATA *ad = (APPENDDATA *) data;
4117 unsigned char *arg = ad->arg;
4118 /* flush text of previous message */
4119 if (t = ad->flags) fs_give ((void **) &ad->flags);
4120 if (t = ad->date) fs_give ((void **) &ad->date);
4121 if (t = ad->msg) fs_give ((void **) &ad->msg);
4122 *flags = *date = NIL; /* assume no flags or date */
4123 if (t) { /* have previous message? */
4124 if (!*arg) { /* if least one message, and no more coming */
4125 *message = NIL; /* set stop */
4126 return LONGT; /* return success */
4128 else if (*arg++ != ' ') { /* must have a delimiter to next argument */
4129 response = misarg; /* oops */
4130 return NIL;
4133 *message = ad->message; /* return pointer to message stringstruct */
4134 if (*arg == '(') { /* parse optional flag list */
4135 t = ++arg; /* pointer to flag list contents */
4136 while (*arg && (*arg != ')')) arg++;
4137 if (*arg) *arg++ = '\0';
4138 if (*arg == ' ') arg++;
4139 *flags = ad->flags = cpystr (t);
4141 /* parse optional date */
4142 if (*arg == '"') *date = ad->date = cpystr (snarf (&arg));
4143 if (!arg || (*arg != '{')) /* parse message */
4144 response = "%.80s BAD Missing literal in %.80s\015\012";
4145 else if (!isdigit (arg[1]))
4146 response = "%.80s BAD Missing message to %.80s\015\012";
4147 else if (!(i = strtoul (arg+1,&t,10)))
4148 response = "%.80s NO Empty message to %.80s\015\012";
4149 else if (i > MAXAPPENDTXT) /* maybe relax this a little */
4150 response = "%.80s NO Excessively large message to %.80s\015\012";
4151 else if (((*t == '+') && (t[1] == '}') && !t[2]) || ((*t == '}') && !t[1])) {
4152 /* get a literal buffer */
4153 inliteral (ad->msg = (char *) fs_get (i+1),i);
4154 /* get new command tail */
4155 slurp (ad->arg,CMDLEN - (ad->arg - cmdbuf),INPUTTIMEOUT);
4156 if (strchr (ad->arg,'\012')) {
4157 /* reset strtok mechanism, tie off if done */
4158 if (!strtok (ad->arg,"\015\012")) *ad->arg = '\0';
4159 /* possible LITERAL+? */
4160 if (((j = strlen (ad->arg)) > 3) && (ad->arg[j - 1] == '}') &&
4161 (ad->arg[j - 2] == '+') && isdigit (ad->arg[j - 3])) {
4162 /* back over possible count */
4163 for (j -= 4; j && isdigit (ad->arg[j]); j--);
4164 if (ad->arg[j] == '{') {/* found a literal? */
4165 litplus.ok = T; /* yes, note LITERAL+ in effect, set size */
4166 litplus.size = strtoul (ad->arg + j + 1,NIL,10);
4169 /* initialize stringstruct */
4170 INIT (ad->message,mail_string,(void *) ad->msg,i);
4171 return LONGT; /* ready to go */
4173 flush (); /* didn't find end of line? */
4174 fs_give ((void **) &ad->msg);
4176 else response = badarg; /* not a literal */
4177 return NIL; /* error */
4180 /* Got COPY UID data
4181 * Accepts: MAIL stream
4182 * mailbox name
4183 * UID validity
4184 * source set of UIDs
4185 * destination set of UIDs
4186 */
4188 void copyuid (MAILSTREAM *stream,char *mailbox,unsigned long uidvalidity,
4189 SEARCHSET *sourceset,SEARCHSET *destset)
4191 if (cauidvalidity) fatal ("duplicate COPYUID/APPENDUID data");
4192 cauidvalidity = uidvalidity;
4193 csset = sourceset;
4194 caset = destset;
4198 /* Got APPEND UID data
4199 * Accepts: mailbox name
4200 * UID validity
4201 * destination set of UIDs
4202 */
4204 void appenduid (char *mailbox,unsigned long uidvalidity,SEARCHSET *set)
4206 copyuid (NIL,mailbox,uidvalidity,NIL,set);
4210 /* Got a referral
4211 * Accepts: MAIL stream
4212 * URL
4213 * referral type code
4214 */
4216 char *referral (MAILSTREAM *stream,char *url,long code)
4218 if (lstref) fs_give ((void **) &lstref);
4219 lstref = cpystr (url); /* set referral */
4220 /* set error if not a logged in referral */
4221 if (code != REFAUTH) response = lose;
4222 if (!lsterr) lsterr = cpystr ("Try referral URL");
4223 return NIL; /* don't chase referrals for now */
4226 /* Co-routines from MAIL library */
4229 /* Message matches a search
4230 * Accepts: MAIL stream
4231 * message number
4232 */
4234 void mm_searched (MAILSTREAM *s,unsigned long msgno)
4236 /* nothing to do here */
4240 /* Message exists (i.e. there are that many messages in the mailbox)
4241 * Accepts: MAIL stream
4242 * message number
4243 */
4245 void mm_exists (MAILSTREAM *s,unsigned long number)
4247 /* note change in number of messages */
4248 if ((s != tstream) && (nmsgs != number)) {
4249 nmsgs = number; /* always update number of messages */
4250 if (quell_events) existsquelled = T;
4251 else {
4252 PSOUT ("* ");
4253 pnum (nmsgs);
4254 PSOUT (" EXISTS\015\012");
4256 recent = 0xffffffff; /* make sure update recent too */
4261 /* Message expunged
4262 * Accepts: MAIL stream
4263 * message number
4264 */
4266 void mm_expunged (MAILSTREAM *s,unsigned long number)
4268 if (quell_events) fatal ("Impossible EXPUNGE event");
4269 if (s != tstream) {
4270 PSOUT ("* ");
4271 pnum (number);
4272 PSOUT (" EXPUNGE\015\012");
4274 nmsgs--;
4275 existsquelled = T; /* do EXISTS when command done */
4279 /* Message status changed
4280 * Accepts: MAIL stream
4281 * message number
4282 */
4284 void mm_flags (MAILSTREAM *s,unsigned long number)
4286 if (s != tstream) mail_elt (s,number)->spare2 = T;
4289 /* Mailbox found
4290 * Accepts: hierarchy delimiter
4291 * mailbox name
4292 * attributes
4293 */
4295 void mm_list (MAILSTREAM *stream,int delimiter,char *name,long attributes)
4297 mm_list_work ("LIST",delimiter,name,attributes);
4301 /* Subscribed mailbox found
4302 * Accepts: hierarchy delimiter
4303 * mailbox name
4304 * attributes
4305 */
4307 void mm_lsub (MAILSTREAM *stream,int delimiter,char *name,long attributes)
4309 mm_list_work ("LSUB",delimiter,name,attributes);
4313 /* Mailbox status
4314 * Accepts: MAIL stream
4315 * mailbox name
4316 * mailbox status
4317 */
4319 void mm_status (MAILSTREAM *stream,char *mailbox,MAILSTATUS *status)
4321 if (!quell_events) {
4322 char tmp[MAILTMPLEN];
4323 tmp[0] = tmp[1] = '\0';
4324 if (status->flags & SA_MESSAGES)
4325 sprintf (tmp + strlen (tmp)," MESSAGES %lu",status->messages);
4326 if (status->flags & SA_RECENT)
4327 sprintf (tmp + strlen (tmp)," RECENT %lu",status->recent);
4328 if (status->flags & SA_UNSEEN)
4329 sprintf (tmp + strlen (tmp)," UNSEEN %lu",status->unseen);
4330 if (status->flags & SA_UIDNEXT)
4331 sprintf (tmp + strlen (tmp)," UIDNEXT %lu",status->uidnext);
4332 if (status->flags & SA_UIDVALIDITY)
4333 sprintf (tmp + strlen(tmp)," UIDVALIDITY %lu",status->uidvalidity);
4334 PSOUT ("* STATUS ");
4335 pastring (mailbox);
4336 PSOUT (" (");
4337 PSOUT (tmp+1);
4338 PBOUT (')');
4339 CRLF;
4343 /* Worker routine for LIST and LSUB
4344 * Accepts: name of response
4345 * hierarchy delimiter
4346 * mailbox name
4347 * attributes
4348 */
4350 void mm_list_work (char *what,int delimiter,char *name,long attributes)
4352 char *s;
4353 if (!quell_events) {
4354 char tmp[MAILTMPLEN];
4355 if (finding) {
4356 PSOUT ("* MAILBOX ");
4357 PSOUT (name);
4359 /* new form */
4360 else if ((cmd[0] == 'R') || !(attributes & LATT_REFERRAL)) {
4361 PSOUT ("* ");
4362 PSOUT (what);
4363 PSOUT (" (");
4364 tmp[0] = tmp[1] = '\0';
4365 if (attributes & LATT_NOINFERIORS) strcat (tmp," \\NoInferiors");
4366 if (attributes & LATT_NOSELECT) strcat (tmp," \\NoSelect");
4367 if (attributes & LATT_MARKED) strcat (tmp," \\Marked");
4368 if (attributes & LATT_UNMARKED) strcat (tmp," \\UnMarked");
4369 if (attributes & LATT_HASCHILDREN) strcat (tmp," \\HasChildren");
4370 if (attributes & LATT_HASNOCHILDREN) strcat (tmp," \\HasNoChildren");
4371 PSOUT (tmp+1);
4372 switch (delimiter) {
4373 case '\\': /* quoted delimiter */
4374 case '"':
4375 PSOUT (") \"\\");
4376 PBOUT (delimiter);
4377 PBOUT ('"');
4378 break;
4379 case '\0': /* no delimiter */
4380 PSOUT (") NIL");
4381 break;
4382 default: /* unquoted delimiter */
4383 PSOUT (") \"");
4384 PBOUT (delimiter);
4385 PBOUT ('"');
4386 break;
4388 PBOUT (' ');
4389 /* output mailbox name */
4390 if (proxylist && (s = strchr (name,'}'))) pastring (s+1);
4391 else pastring (name);
4393 CRLF;
4397 /* Notification event
4398 * Accepts: MAIL stream
4399 * string to log
4400 * error flag
4401 */
4403 void mm_notify (MAILSTREAM *stream,char *string,long errflg)
4405 SIZEDTEXT msg;
4406 char *s,*code;
4407 if (!quell_events && (!tstream || (stream != tstream))) {
4408 switch (errflg) {
4409 case NIL: /* information message, set as OK response */
4410 if ((string[0] == '[') &&
4411 ((string[1] == 'T') || (string[1] == 't')) &&
4412 ((string[2] == 'R') || (string[2] == 'r')) &&
4413 ((string[3] == 'Y') || (string[3] == 'y')) &&
4414 ((string[4] == 'C') || (string[4] == 'c')) &&
4415 ((string[5] == 'R') || (string[5] == 'r')) &&
4416 ((string[6] == 'E') || (string[6] == 'e')) &&
4417 ((string[7] == 'A') || (string[7] == 'a')) &&
4418 ((string[8] == 'T') || (string[8] == 't')) &&
4419 ((string[9] == 'E') || (string[9] == 'e')) && (string[10] == ']'))
4420 trycreate = T;
4421 case BYE: /* some other server signing off */
4422 case PARSE: /* parse glitch, output unsolicited OK */
4423 code = "* OK ";
4424 break;
4425 case WARN: /* warning, output unsolicited NO (kludge!) */
4426 code = "* NO ";
4427 break;
4428 case ERROR: /* error that broke command */
4429 default: /* default should never happen */
4430 code = "* BAD ";
4431 break;
4433 PSOUT (code);
4434 msg.size = (s = strpbrk ((char *) (msg.data = (unsigned char *) string),
4435 "\015\012")) ?
4436 (s - string) : strlen (string);
4437 PSOUTR (&msg);
4438 CRLF;
4439 PFLUSH (); /* let client see it immediately */
4443 /* Log an event for the user to see
4444 * Accepts: string to log
4445 * error flag
4446 */
4448 void mm_log (char *string,long errflg)
4450 SIZEDTEXT msg;
4451 char *s;
4452 msg.size =
4453 (s = strpbrk ((char *) (msg.data = (unsigned char *) string),"\015\012")) ?
4454 (s - string) : strlen (string);
4455 switch (errflg) {
4456 case NIL: /* information message, set as OK response */
4457 if (response == win) { /* only if no other response yet */
4458 if (lsterr) { /* if there was a previous message */
4459 if (!quell_events) {
4460 PSOUT ("* OK "); /* blat it out */
4461 PSOUT (lsterr);
4462 CRLF;
4463 PFLUSH (); /* let client see it immediately */
4465 fs_give ((void **) &lsterr);
4467 lsterr = cpystr (string); /* copy string for later use */
4468 if (s) lsterr[s - string] = NIL;
4470 break;
4471 case PARSE: /* parse glitch, output unsolicited OK */
4472 if (!quell_events) {
4473 PSOUT ("* OK [PARSE] ");
4474 PSOUTR (&msg);
4475 CRLF;
4476 PFLUSH (); /* let client see it immediately */
4478 break;
4479 case WARN: /* warning, output unsolicited NO */
4480 /* ignore "Mailbox is empty" (KLUDGE!) */
4481 if (strcmp (string,"Mailbox is empty")) {
4482 if (lstwrn) { /* have previous warning? */
4483 if (!quell_events) {
4484 PSOUT ("* NO ");
4485 PSOUT (lstwrn);
4486 CRLF;
4487 PFLUSH (); /* make sure client sees it immediately */
4489 fs_give ((void **) &lstwrn);
4491 lstwrn = cpystr (string); /* note last warning */
4492 if (s) lstwrn[s - string] = NIL;
4494 break;
4495 case ERROR: /* error that broke command */
4496 default: /* default should never happen */
4497 response = trycreate ? losetry : lose;
4498 if (lsterr) fs_give ((void **) &lsterr);
4499 lsterr = cpystr (string); /* note last error */
4500 if (s) lsterr[s - string] = NIL;
4501 break;
4505 /* Return last error
4506 */
4508 char *lasterror (void)
4510 if (lsterr) return lsterr;
4511 if (lstwrn) return lstwrn;
4512 return "<unknown>";
4516 /* Log an event to debugging telemetry
4517 * Accepts: string to log
4518 */
4520 void mm_dlog (char *string)
4522 mm_log (string,WARN); /* shouldn't happen normally */
4525 /* Get user name and password for this host
4526 * Accepts: parse of network user name
4527 * where to return user name
4528 * where to return password
4529 * trial count
4530 */
4532 void mm_login (NETMBX *mb,char *username,char *password,long trial)
4534 /* set user name */
4535 strncpy (username,*mb->user ? mb->user : (char *) user,NETMAXUSER);
4536 strncpy (password,pass,256); /* and password */
4540 /* About to enter critical code
4541 * Accepts: stream
4542 */
4544 void mm_critical (MAILSTREAM *s)
4546 ++critical;
4550 /* About to exit critical code
4551 * Accepts: stream
4552 */
4554 void mm_nocritical (MAILSTREAM *s)
4556 /* go non-critical, pending death? */
4557 if (!--critical && (state == LOGOUT)) {
4558 /* clean up iff needed */
4559 if (s && (stream != s) && !s->lock && (s->dtb->flags & DR_XPOINT))
4560 s = mail_close (s);
4561 longjmp (jmpenv,1); /* die now */
4565 /* Disk error found
4566 * Accepts: stream
4567 * system error code
4568 * flag indicating that mailbox may be clobbered
4569 * Returns: abort flag
4570 */
4572 long mm_diskerror (MAILSTREAM *s,long errcode,long serious)
4574 if (serious) { /* try your damnest if clobberage likely */
4575 mm_notify (s,"Retrying to fix probable mailbox damage!",ERROR);
4576 PFLUSH (); /* dump output buffer */
4577 syslog (LOG_ALERT,
4578 "Retrying after disk error user=%.80s host=%.80s mbx=%.80s: %.80s",
4579 user ? (char *) user : "???",tcp_clienthost (),
4580 (stream && stream->mailbox) ? stream->mailbox : "???",
4581 strerror (errcode));
4582 settimeout (0); /* make damn sure timeout disabled */
4583 sleep (60); /* give it some time to clear up */
4584 return NIL;
4586 if (!quell_events) { /* otherwise die before more damage is done */
4587 PSOUT ("* NO Disk error: ");
4588 PSOUT (strerror (errcode));
4589 CRLF;
4591 return T;
4595 /* Log a fatal error event
4596 * Accepts: string to log
4597 */
4599 void mm_fatal (char *string)
4601 SIZEDTEXT msg;
4602 char *s;
4603 msg.size =
4604 (s = strpbrk ((char *) (msg.data = (unsigned char *) string),"\015\012")) ?
4605 (s - string) : strlen (string);
4606 if (!quell_events) {
4607 PSOUT ("* BYE [ALERT] IMAP4rev1 server crashing: ");
4608 PSOUTR (&msg);
4609 CRLF;
4610 PFLUSH ();
4612 syslog (LOG_ALERT,"Fatal error user=%.80s host=%.80s mbx=%.80s: %.80s",
4613 user ? (char *) user : "???",tcp_clienthost (),
4614 (stream && stream->mailbox) ? stream->mailbox : "???",string);

UW-IMAP'd extensions by yuuji