imapext-2007

view src/ipopd/ipop3d.c @ 1:28a55bc1110c

[mq]: imapext
author yuuji@gentei.org
date Mon, 14 Sep 2009 19:23:11 +0900
parents ada5e610ab86
children 2366b362676d
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: IPOP3D - IMAP to POP3 conversion 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: 1 November 1990
24 * Last Edited: 19 February 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 <time.h>
35 #include "c-client.h"
38 #define CRLF PSOUT ("\015\012") /* primary output terpri */
41 /* Autologout timer */
42 #define KODTIMEOUT 60*5
43 #define LOGINTIMEOUT 60*3
44 #define TIMEOUT 60*10
47 /* Server states */
49 #define AUTHORIZATION 0
50 #define TRANSACTION 1
51 #define UPDATE 2
52 #define LOGOUT 3
54 /* Eudora food */
56 #define STATUS "Status: %s%s\015\012"
57 #define SLEN (sizeof (STATUS)-3)
60 /* Global storage */
62 char *version = "104"; /* edit number of this server */
63 short state = AUTHORIZATION; /* server state */
64 short critical = NIL; /* non-zero if in critical code */
65 MAILSTREAM *stream = NIL; /* mailbox stream */
66 time_t idletime = 0; /* time we went idle */
67 unsigned long nmsgs = 0; /* current number of messages */
68 unsigned long ndele = 0; /* number of deletes */
69 unsigned long nseen = 0; /* number of mark-seens */
70 unsigned long last = 0; /* highest message accessed */
71 unsigned long il = 0; /* initial last message */
72 char challenge[128]; /* challenge */
73 char *host = NIL; /* remote host name */
74 char *user = NIL; /* user name */
75 char *pass = NIL; /* password */
76 char *initial = NIL; /* initial response */
77 long *msg = NIL; /* message translation vector */
78 short *flags = NIL; /* flags */
79 char *logout = "Logout";
80 char *goodbye = "+OK Sayonara\015\012";
83 /* POP3 flags */
85 #define DELE 0x1
86 #define SEEN 0x2
89 /* Function prototypes */
91 int main (int argc,char *argv[]);
92 void sayonara (int status);
93 void clkint ();
94 void kodint ();
95 void hupint ();
96 void trmint ();
97 int pass_login (char *t,int argc,char *argv[]);
98 char *apop_login (char *chal,char *user,char *md5,int argc,char *argv[]);
99 #ifdef QMAIL
100 char* conv_virtualdomain(char *account);
101 #endif
102 char *responder (void *challenge,unsigned long clen,unsigned long *rlen);
103 int mbxopen (char *mailbox);
104 long blat (char *text,long lines,unsigned long size,STRING *st);
105 void rset ();
107 /* Main program */
109 int main (int argc,char *argv[])
110 {
111 unsigned long i,j,k;
112 char *s,*t;
113 char tmp[MAILTMPLEN];
114 time_t autologouttime;
115 char *pgmname = (argc && argv[0]) ?
116 (((s = strrchr (argv[0],'/')) || (s = strrchr (argv[0],'\\'))) ?
117 s+1 : argv[0]) : "ipop3d";
118 /* set service name before linkage */
119 mail_parameters (NIL,SET_SERVICENAME,(void *) "pop");
120 #include "linkage.c"
121 /* initialize server */
122 server_init (pgmname,"pop3","pop3s",clkint,kodint,hupint,trmint,NIL);
123 mail_parameters (NIL,SET_BLOCKENVINIT,VOIDT);
124 s = myusername_full (&i); /* get user name and flags */
125 mail_parameters (NIL,SET_BLOCKENVINIT,NIL);
126 if (i == MU_LOGGEDIN) { /* allow EXTERNAL if logged in already */
127 mail_parameters (NIL,UNHIDE_AUTHENTICATOR,(void *) "EXTERNAL");
128 mail_parameters (NIL,SET_EXTERNALAUTHID,(void *) s);
129 }
130 { /* set up MD5 challenge */
131 AUTHENTICATOR *auth = mail_lookup_auth (1);
132 while (auth && compare_cstring (auth->name,"CRAM-MD5")) auth = auth->next;
133 /* build challenge -- less than 128 chars */
134 #ifndef QMAIL
135 if (!(auth->flags & AU_DISABLE))
136 #else
137 if (auth && auth->server && !(auth->flags & AU_DISABLE))
138 #endif
139 sprintf (challenge,"<%lx.%lx@%.64s>",(unsigned long) getpid (),
140 (unsigned long) time (0),tcp_serverhost ());
141 else challenge[0] = '\0'; /* no MD5 authentication */
142 }
143 /* There are reports of POP3 clients which get upset if anything appears
144 * between the "+OK" and the "POP3" in the greeting.
145 */
146 PSOUT ("+OK POP3 ");
147 if (!challenge[0]) { /* if no MD5 enable, output host name */
148 PSOUT (tcp_serverhost ());
149 PBOUT (' ');
150 }
151 PSOUT (CCLIENTVERSION);
152 PBOUT ('.');
153 PSOUT (version);
154 PSOUT (" server ready");
155 if (challenge[0]) { /* if MD5 enable, output challenge here */
156 PBOUT (' ');
157 PSOUT (challenge);
158 }
159 CRLF;
160 PFLUSH (); /* dump output buffer */
161 autologouttime = time (0) + LOGINTIMEOUT;
162 /* command processing loop */
163 while ((state != UPDATE) && (state != LOGOUT)) {
164 idletime = time (0); /* get a command under timeout */
165 alarm ((state == TRANSACTION) ? TIMEOUT : LOGINTIMEOUT);
166 clearerr (stdin); /* clear stdin errors */
167 /* read command line */
168 while (!PSIN (tmp,MAILTMPLEN)) {
169 /* ignore if some interrupt */
170 if (ferror (stdin) && (errno == EINTR)) clearerr (stdin);
171 else {
172 char *e = ferror (stdin) ?
173 strerror (errno) : "Unexpected client disconnect";
174 alarm (0); /* disable all interrupts */
175 server_init (NIL,NIL,NIL,SIG_IGN,SIG_IGN,SIG_IGN,SIG_IGN,SIG_IGN);
176 sprintf (logout = tmp,"%.80s, while reading line",e);
177 goodbye = NIL;
178 rset (); /* try to gracefully close the stream */
179 if (state == TRANSACTION) mail_close (stream);
180 stream = NIL;
181 state = LOGOUT;
182 sayonara (1);
183 }
184 }
185 alarm (0); /* make sure timeout disabled */
186 idletime = 0; /* no longer idle */
188 if (!strchr (tmp,'\012')) /* find end of line */
189 PSOUT ("-ERR Command line too long\015\012");
190 else if (!(s = strtok (tmp," \015\012")))
191 PSOUT ("-ERR Null command\015\012");
192 else { /* dispatch based on command */
193 ucase (s); /* canonicalize case */
194 /* snarf argument */
195 t = strtok (NIL,"\015\012");
196 /* QUIT command always valid */
197 if (!strcmp (s,"QUIT")) state = UPDATE;
198 else if (!strcmp (s,"CAPA")) {
199 AUTHENTICATOR *auth;
200 PSOUT ("+OK Capability list follows:\015\012");
201 PSOUT ("TOP\015\012LOGIN-DELAY 180\015\012UIDL\015\012");
202 if (s = ssl_start_tls (NIL)) fs_give ((void **) &s);
203 else PSOUT ("STLS\015\012");
204 if (i = !mail_parameters (NIL,GET_DISABLEPLAINTEXT,NIL))
205 PSOUT ("USER\015\012");
206 /* display secure server authenticators */
207 for (auth = mail_lookup_auth (1), s = "SASL"; auth; auth = auth->next)
208 if (auth->server && !(auth->flags & AU_DISABLE) &&
209 !(auth->flags & AU_HIDE) && (i || (auth->flags & AU_SECURE))) {
210 if (s) {
211 PSOUT (s);
212 s = NIL;
213 }
214 PBOUT (' ');
215 PSOUT (auth->name);
216 }
217 PSOUT (s ? ".\015\012" : "\015\012.\015\012");
218 }
220 else switch (state) { /* else dispatch based on state */
221 case AUTHORIZATION: /* waiting to get logged in */
222 if (!strcmp (s,"AUTH")) {
223 if (t && *t) { /* mechanism given? */
224 if (host) fs_give ((void **) &host);
225 if (user) fs_give ((void **) &user);
226 if (pass) fs_give ((void **) &pass);
227 s = strtok (t," "); /* get mechanism name */
228 /* get initial response */
229 if (initial = strtok (NIL,"\015\012")) {
230 if ((*initial == '=') && !initial[1]) ++initial;
231 else if (!*initial) initial = NIL;
232 }
233 if (!(user = cpystr (mail_auth (s,responder,argc,argv)))) {
234 PSOUT ("-ERR Bad authentication\015\012");
235 syslog (LOG_INFO,"AUTHENTICATE %s failure host=%.80s",s,
236 tcp_clienthost ());
237 }
238 else if ((state = mbxopen ("INBOX")) == TRANSACTION)
239 syslog (LOG_INFO,"Auth user=%.80s host=%.80s nmsgs=%lu/%lu",
240 user,tcp_clienthost (),nmsgs,stream->nmsgs);
241 else syslog (LOG_INFO,"Auth user=%.80s host=%.80s no mailbox",
242 user,tcp_clienthost ());
243 }
244 else {
245 AUTHENTICATOR *auth;
246 PSOUT ("+OK Supported authentication mechanisms:\015\012");
247 i = !mail_parameters (NIL,GET_DISABLEPLAINTEXT,NIL);
248 for (auth = mail_lookup_auth (1); auth; auth = auth->next)
249 if (auth->server && !(auth->flags & AU_DISABLE) &&
250 !(auth->flags & AU_HIDE) &&
251 (i || (auth->flags & AU_SECURE))) {
252 PSOUT (auth->name);
253 CRLF;
254 }
255 PBOUT ('.');
256 CRLF;
257 }
258 }
260 else if (!strcmp (s,"APOP")) {
261 if (challenge[0]) { /* can do it if have an MD5 challenge */
262 if (host) fs_give ((void **) &host);
263 if (user) fs_give ((void **) &user);
264 if (pass) fs_give ((void **) &pass);
265 /* get user name */
266 if (!(t && *t && (s = strtok (t," ")) && (t = strtok(NIL,"\012"))))
267 PSOUT ("-ERR Missing APOP argument\015\012");
268 #ifdef QMAIL
269 else if (!(user = apop_login (challenge,conv_virtualdomain(s),t,argc,argv))) {
270 #else /* !QMAIL */
271 else if (!(user = apop_login (challenge,s,t,argc,argv))) {
272 #endif /* QMAIL */
273 PSOUT ("-ERR Bad APOP (Maybe your password is expired)\015\012");
274 user = cpystr (s);
275 syslog (LOG_INFO,"APOP login failure user=%.80s host=%.80s",
276 user,tcp_clienthost ());
277 } else if ((state = mbxopen ("INBOX")) == TRANSACTION)
278 syslog (LOG_INFO,"APOP user=%.80s host=%.80s nmsgs=%ld/%ld",
279 user,tcp_clienthost (),nmsgs,stream->nmsgs);
280 else syslog (LOG_INFO,"APOP user=%.80s host=%.80s no mailbox",
281 user,tcp_clienthost ());
282 }
283 else PSOUT ("-ERR Not supported\015\012");
284 }
285 /* (chuckle) */
286 else if (!strcmp (s,"RPOP"))
287 PSOUT ("-ERR Nice try, bunkie\015\012");
288 else if (!strcmp (s,"STLS")) {
289 if (t = ssl_start_tls (pgmname)) {
290 PSOUT ("-ERR STLS failed: ");
291 PSOUT (t);
292 CRLF;
293 }
294 else PSOUT ("+OK STLS completed\015\012");
295 }
296 #ifndef RESTRICT_POP
297 else if (!mail_parameters (NIL,GET_DISABLEPLAINTEXT,NIL) &&
298 !strcmp (s,"USER")) {
299 #else /* !RESTRICT_POP */
300 else if (!strcmp (s,"USER")) {
301 if (getenv("INTRANET") == NIL) {
302 PSOUT("-ERR Sorry, we don't allow POP3 from your network. Use APOP instead.\015\012");
303 user = cpystr(t);
304 syslog (LOG_INFO,"Plain POP3 is restricted user=%.80s host=%.80s",
305 user,tcp_clienthost ());
306 memset(user, '\0', strlen(user));
307 break;
308 }
309 #endif
310 if (host) fs_give ((void **) &host);
311 if (user) fs_give ((void **) &user);
312 if (pass) fs_give ((void **) &pass);
313 if (t && *t) { /* if user name given */
314 /* skip leading whitespace (bogus clients!) */
315 while (*t == ' ') ++t;
316 /* remote user name? */
317 if (s = strchr (t,':')) {
318 *s++ = '\0'; /* tie off host name */
319 host = cpystr (t);/* copy host name */
320 user = cpystr (s);/* copy user name */
321 }
322 /* local user name */
323 #ifdef QMAIL
324 else user = conv_virtualdomain(cpystr (t));
325 #else
326 else user = cpystr (t);
327 #endif
328 PSOUT ("+OK User name accepted, password please\015\012");
329 }
330 else PSOUT ("-ERR Missing username argument\015\012");
331 }
332 else if (!mail_parameters (NIL,GET_DISABLEPLAINTEXT,NIL) &&
333 user && *user && !strcmp (s,"PASS"))
334 state = pass_login (t,argc,argv);
335 else PSOUT ("-ERR Unknown AUTHORIZATION state command\015\012");
336 break;
338 case TRANSACTION: /* logged in */
339 if (!strcmp (s,"STAT")) {
340 for (i = 1,j = 0,k = 0; i <= nmsgs; i++)
341 /* message still exists? */
342 if (msg[i] && !(flags[i] & DELE)) {
343 j++; /* count one more undeleted message */
344 k += mail_elt (stream,msg[i])->rfc822_size + SLEN;
345 }
346 sprintf (tmp,"+OK %lu %lu\015\012",j,k);
347 PSOUT (tmp);
348 }
349 else if (!strcmp (s,"LIST")) {
350 if (t && *t) { /* argument do single message */
351 if ((i = strtoul (t,NIL,10)) && (i <= nmsgs) && msg[i] &&
352 !(flags[i] & DELE)) {
353 sprintf (tmp,"+OK %lu %lu\015\012",i,
354 mail_elt(stream,msg[i])->rfc822_size + SLEN);
355 PSOUT (tmp);
356 }
357 else PSOUT ("-ERR No such message\015\012");
358 }
359 else { /* entire mailbox */
360 PSOUT ("+OK Mailbox scan listing follows\015\012");
361 for (i = 1,j = 0,k = 0; i <= nmsgs; i++)
362 if (msg[i] && !(flags[i] & DELE)) {
363 sprintf (tmp,"%lu %lu\015\012",i,
364 mail_elt (stream,msg[i])->rfc822_size + SLEN);
365 PSOUT (tmp);
366 }
367 PBOUT ('.'); /* end of list */
368 CRLF;
369 }
370 }
371 else if (!strcmp (s,"UIDL")) {
372 if (t && *t) { /* argument do single message */
373 if ((i = strtoul (t,NIL,10)) && (i <= nmsgs) && msg[i] &&
374 !(flags[i] & DELE)) {
375 sprintf (tmp,"+OK %lu %08lx%08lx\015\012",i,stream->uid_validity,
376 mail_uid (stream,msg[i]));
377 PSOUT (tmp);
378 }
379 else PSOUT ("-ERR No such message\015\012");
380 }
381 else { /* entire mailbox */
382 PSOUT ("+OK Unique-ID listing follows\015\012");
383 for (i = 1,j = 0,k = 0; i <= nmsgs; i++)
384 if (msg[i] && !(flags[i] & DELE)) {
385 sprintf (tmp,"%lu %08lx%08lx\015\012",i,stream->uid_validity,
386 mail_uid (stream,msg[i]));
387 PSOUT (tmp);
388 }
389 PBOUT ('.'); /* end of list */
390 CRLF;
391 }
392 }
394 else if (!strcmp (s,"RETR")) {
395 if (t && *t) { /* must have an argument */
396 if ((i = strtoul (t,NIL,10)) && (i <= nmsgs) && msg[i] &&
397 !(flags[i] & DELE)) {
398 MESSAGECACHE *elt;
399 /* update highest message accessed */
400 if (i > last) last = i;
401 sprintf (tmp,"+OK %lu octets\015\012",
402 (elt = mail_elt (stream,msg[i]))->rfc822_size + SLEN);
403 PSOUT (tmp);
404 /* if not marked seen or noted to be marked */
405 if (!(elt->seen || (flags[i] & SEEN))) {
406 ++nseen; /* note that we need to mark it seen */
407 flags[i] |= SEEN;
408 }
409 /* get header */
410 t = mail_fetch_header (stream,msg[i],NIL,NIL,&k,FT_PEEK);
411 blat (t,-1,k,NIL);/* write up to trailing CRLF */
412 /* build status */
413 sprintf (tmp,STATUS,elt->seen ? "R" : " ",
414 elt->recent ? " " : "O");
415 if (k < 4) CRLF; /* don't write Status: if no header */
416 /* normal header ending with CRLF CRLF? */
417 else if (t[k-3] == '\012') {
418 PSOUT (tmp); /* write status */
419 CRLF; /* then write second CRLF */
420 }
421 else { /* abnormal - no blank line at end of header */
422 CRLF; /* write CRLF first then */
423 PSOUT (tmp);
424 }
425 /* output text */
426 t = mail_fetch_text (stream,msg[i],NIL,&k,
427 FT_RETURNSTRINGSTRUCT | FT_PEEK);
428 if (k) { /* only if there is a text body */
429 blat (t,-1,k,&stream->private.string);
430 CRLF; /* end of list */
431 }
432 PBOUT ('.');
433 CRLF;
434 }
435 else PSOUT ("-ERR No such message\015\012");
436 }
437 else PSOUT ("-ERR Missing message number argument\015\012");
438 }
440 else if (!strcmp (s,"DELE")) {
441 if (t && *t) { /* must have an argument */
442 if ((i = strtoul (t,NIL,10)) && (i <= nmsgs) && msg[i] &&
443 !(flags[i] & DELE)) {
444 /* update highest message accessed */
445 if (i > last) last = i;
446 flags[i] |= DELE; /* note that deletion is requested */
447 PSOUT ("+OK Message deleted\015\012");
448 ++ndele; /* one more message deleted */
449 }
450 else PSOUT ("-ERR No such message\015\012");
451 }
452 else PSOUT ("-ERR Missing message number argument\015\012");
453 }
454 else if (!strcmp (s,"NOOP"))
455 PSOUT ("+OK No-op to you too!\015\012");
456 else if (!strcmp (s,"LAST")) {
457 sprintf (tmp,"+OK %lu\015\012",last);
458 PSOUT (tmp);
459 }
460 else if (!strcmp (s,"RSET")) {
461 rset (); /* reset the mailbox */
462 PSOUT ("+OK Reset state\015\012");
463 }
465 else if (!strcmp (s,"TOP")) {
466 if (t && *t && (i =strtoul (t,&s,10)) && (i <= nmsgs) && msg[i] &&
467 !(flags[i] & DELE)) {
468 /* skip whitespace */
469 while (*s == ' ') s++;
470 /* make sure line count argument good */
471 if ((*s >= '0') && (*s <= '9')) {
472 MESSAGECACHE *elt = mail_elt (stream,msg[i]);
473 j = strtoul (s,NIL,10);
474 /* update highest message accessed */
475 if (i > last) last = i;
476 PSOUT ("+OK Top of message follows\015\012");
477 /* get header */
478 t = mail_fetch_header (stream,msg[i],NIL,NIL,&k,FT_PEEK);
479 blat (t,-1,k,NIL);/* write up to trailing CRLF */
480 /* build status */
481 sprintf (tmp,STATUS,elt->seen ? "R" : " ",
482 elt->recent ? " " : "O");
483 if (k < 4) CRLF; /* don't write Status: if no header */
484 /* normal header ending with CRLF CRLF? */
485 else if (t[k-3] == '\012') {
486 PSOUT (tmp); /* write status */
487 CRLF; /* then write second CRLF */
488 }
489 else { /* abnormal - no blank line at end of header */
490 CRLF; /* write CRLF first then */
491 PSOUT (tmp);
492 }
493 if (j) { /* want any text lines? */
494 /* output text */
495 t = mail_fetch_text (stream,msg[i],NIL,&k,
496 FT_PEEK | FT_RETURNSTRINGSTRUCT);
497 /* tie off final line if full text output */
498 if (k && (j -= blat (t,j,k,&stream->private.string))) CRLF;
499 }
500 PBOUT ('.'); /* end of list */
501 CRLF;
502 }
503 else PSOUT ("-ERR Bad line count argument\015\012");
504 }
505 else PSOUT ("-ERR Bad message number argument\015\012");
506 }
508 else if (!strcmp (s,"XTND"))
509 PSOUT ("-ERR Sorry I can't do that\015\012");
510 else PSOUT ("-ERR Unknown TRANSACTION state command\015\012");
511 break;
512 default:
513 PSOUT ("-ERR Server in unknown state\015\012");
514 break;
515 }
516 }
517 PFLUSH (); /* make sure output finished */
518 if (autologouttime) { /* have an autologout in effect? */
519 /* cancel if no longer waiting for login */
520 if (state != AUTHORIZATION) autologouttime = 0;
521 /* took too long to login */
522 else if (autologouttime < time (0)) {
523 goodbye = "-ERR Autologout\015\012";
524 logout = "Autologout";
525 state = LOGOUT; /* sayonara */
526 }
527 }
528 }
530 /* open and need to update? */
531 if (stream && (state == UPDATE)) {
532 if (nseen) { /* only bother if messages need marking seen */
533 *(s = tmp) = '\0'; /* clear sequence */
534 for (i = 1; i <= nmsgs; ++i) if (flags[i] & SEEN) {
535 for (j = i + 1, k = 0; (j <= nmsgs) && (flags[j] & SEEN); ++j) k = j;
536 if (k) sprintf (s,",%lu:%lu",i,k);
537 else sprintf (s,",%lu",i);
538 s += strlen (s); /* point to end of string */
539 if ((s - tmp) > (MAILTMPLEN - 30)) {
540 mail_setflag (stream,tmp + 1,"\\Seen");
541 *(s = tmp) = '\0'; /* restart sequence */
542 }
543 i = j; /* continue after the range */
544 }
545 if (tmp[0]) mail_setflag (stream,tmp + 1,"\\Seen");
546 }
547 if (ndele) { /* any messages to delete? */
548 *(s = tmp) = '\0'; /* clear sequence */
549 for (i = 1; i <= nmsgs; ++i) if (flags[i] & DELE) {
550 for (j = i + 1, k = 0; (j <= nmsgs) && (flags[j] & DELE); ++j) k = j;
551 if (k) sprintf (s,",%lu:%lu",i,k);
552 else sprintf (s,",%lu",i);
553 s += strlen (s); /* point to end of string */
554 if ((s - tmp) > (MAILTMPLEN - 30)) {
555 mail_setflag (stream,tmp + 1,"\\Deleted");
556 *(s = tmp) = '\0'; /* restart sequence */
557 }
558 i = j; /* continue after the range */
559 }
560 if (tmp[0]) mail_setflag (stream,tmp + 1,"\\Deleted");
561 mail_expunge (stream);
562 }
563 syslog (LOG_INFO,"Update user=%.80s host=%.80s nmsgs=%lu ndele=%lu nseen=%lu",
564 user,tcp_clienthost (),stream->nmsgs,ndele,nseen);
565 mail_close (stream);
566 }
567 sayonara (0);
568 return 0; /* stupid compilers */
569 }
572 /* Say goodbye
573 * Accepts: exit status
574 *
575 * Does not return
576 */
578 void sayonara (int status)
579 {
580 logouthook_t lgoh = (logouthook_t) mail_parameters (NIL,GET_LOGOUTHOOK,NIL);
581 if (goodbye) { /* have a goodbye message? */
582 PSOUT (goodbye);
583 PFLUSH (); /* make sure blatted */
584 }
585 syslog (LOG_INFO,"%s user=%.80s host=%.80s",logout,
586 user ? (char *) user : "???",tcp_clienthost ());
587 /* do logout hook if needed */
588 if (lgoh) (*lgoh) (mail_parameters (NIL,GET_LOGOUTDATA,NIL));
589 _exit (status); /* all done */
590 }
592 /* Clock interrupt
593 */
595 void clkint ()
596 {
597 alarm (0); /* disable all interrupts */
598 server_init (NIL,NIL,NIL,SIG_IGN,SIG_IGN,SIG_IGN,SIG_IGN,SIG_IGN);
599 goodbye = "-ERR Autologout; idle for too long\015\012";
600 logout = "Autologout";
601 if (critical) state = LOGOUT; /* badly hosed if in critical code */
602 else { /* try to gracefully close the stream */
603 if ((state == TRANSACTION) && !stream->lock) {
604 rset ();
605 mail_close (stream);
606 }
607 state = LOGOUT;
608 stream = NIL;
609 sayonara (1);
610 }
611 }
614 /* Kiss Of Death interrupt
615 */
617 void kodint ()
618 {
619 /* only if idle */
620 if (idletime && ((time (0) - idletime) > KODTIMEOUT)) {
621 alarm (0); /* disable all interrupts */
622 server_init (NIL,NIL,NIL,SIG_IGN,SIG_IGN,SIG_IGN,SIG_IGN,SIG_IGN);
623 goodbye = "-ERR Received Kiss of Death\015\012";
624 logout = "Killed (lost mailbox lock)";
625 if (critical) state =LOGOUT;/* must defer if in critical code */
626 else { /* try to gracefully close the stream */
627 if ((state == TRANSACTION) && !stream->lock) {
628 rset ();
629 mail_close (stream);
630 }
631 state = LOGOUT;
632 stream = NIL;
633 sayonara (1); /* die die die */
634 }
635 }
636 }
639 /* Hangup interrupt
640 */
642 void hupint ()
643 {
644 alarm (0); /* disable all interrupts */
645 server_init (NIL,NIL,NIL,SIG_IGN,SIG_IGN,SIG_IGN,SIG_IGN,SIG_IGN);
646 goodbye = NIL; /* nobody left to talk to */
647 logout = "Hangup";
648 if (critical) state = LOGOUT; /* must defer if in critical code */
649 else { /* try to gracefully close the stream */
650 if ((state == TRANSACTION) && !stream->lock) {
651 rset ();
652 mail_close (stream);
653 }
654 state = LOGOUT;
655 stream = NIL;
656 sayonara (1); /* die die die */
657 }
658 }
661 /* Termination interrupt
662 */
664 void trmint ()
665 {
666 alarm (0); /* disable all interrupts */
667 server_init (NIL,NIL,NIL,SIG_IGN,SIG_IGN,SIG_IGN,SIG_IGN,SIG_IGN);
668 goodbye = "-ERR Killed\015\012";
669 logout = "Killed";
670 if (critical) state = LOGOUT; /* must defer if in critical code */
671 /* Make no attempt at graceful closure since a shutdown may be in
672 * progress, and we won't have any time to do mail_close() actions.
673 */
674 else sayonara (1); /* die die die */
675 }
677 /* Parse PASS command
678 * Accepts: pointer to command argument
679 * Returns: new state
680 */
682 int pass_login (char *t,int argc,char *argv[])
683 {
684 char tmp[MAILTMPLEN];
685 /* flush old passowrd */
686 if (pass) fs_give ((void **) &pass);
687 if (!(t && *t)) { /* if no password given */
688 PSOUT ("-ERR Missing password argument\015\012");
689 return AUTHORIZATION;
690 }
691 pass = cpystr (t); /* copy password argument */
692 if (!host) { /* want remote mailbox? */
693 /* no, delimit user from possible admin */
694 if (t = strchr (user,'*')) *t++ ='\0';
695 /* attempt the login */
696 if (server_login (user,pass,t,argc,argv)) {
697 int ret = mbxopen ("INBOX");
698 if (ret == TRANSACTION) /* mailbox opened OK? */
699 syslog (LOG_INFO,"%sLogin user=%.80s host=%.80s nmsgs=%lu/%lu",
700 t ? "Admin " : "",user,tcp_clienthost (),nmsgs,stream->nmsgs);
701 else syslog (LOG_INFO,"%sLogin user=%.80s host=%.80s no mailbox",
702 t ? "Admin " : "",user,tcp_clienthost ());
703 return ret;
704 }
705 }
706 #ifndef DISABLE_POP_PROXY
707 /* remote; build remote INBOX */
708 else if (anonymous_login (argc,argv)) {
709 syslog (LOG_INFO,"IMAP login to host=%.80s user=%.80s host=%.80s",host,
710 user,tcp_clienthost ());
711 sprintf (tmp,"{%.128s/user=%.128s}INBOX",host,user);
712 /* disable rimap just in case */
713 mail_parameters (NIL,SET_RSHTIMEOUT,0);
714 return mbxopen (tmp);
715 }
716 #endif
717 /* vague error message to confuse crackers */
718 PSOUT ("-ERR Bad login\015\012");
719 return AUTHORIZATION;
720 }
722 /* Authentication responder
723 * Accepts: challenge
724 * length of challenge
725 * pointer to response length return location if non-NIL
726 * Returns: response
727 */
729 #define RESPBUFLEN 8*MAILTMPLEN
731 char *responder (void *challenge,unsigned long clen,unsigned long *rlen)
732 {
733 unsigned long i,j;
734 unsigned char *t,resp[RESPBUFLEN];
735 char tmp[MAILTMPLEN];
736 if (initial) { /* initial response given? */
737 if (clen) return NIL; /* not permitted */
738 /* set up response */
739 t = (unsigned char *) initial;
740 initial = NIL; /* no more initial response */
741 return (char *) rfc822_base64 (t,strlen ((char *) t),rlen ? rlen : &i);
742 }
743 PSOUT ("+ ");
744 for (t = rfc822_binary (challenge,clen,&i),j = 0; j < i; j++)
745 if (t[j] > ' ') PBOUT (t[j]);
746 fs_give ((void **) &t);
747 CRLF;
748 PFLUSH (); /* dump output buffer */
749 resp[RESPBUFLEN-1] = '\0'; /* last buffer character is guaranteed NUL */
750 alarm (LOGINTIMEOUT); /* get a response under timeout */
751 clearerr (stdin); /* clear stdin errors */
752 /* read buffer */
753 while (!PSIN ((char *) resp,RESPBUFLEN)) {
754 /* ignore if some interrupt */
755 if (ferror (stdin) && (errno == EINTR)) clearerr (stdin);
756 else {
757 char *e = ferror (stdin) ?
758 strerror (errno) : "Command stream end of file";
759 alarm (0); /* disable all interrupts */
760 server_init (NIL,NIL,NIL,SIG_IGN,SIG_IGN,SIG_IGN,SIG_IGN,SIG_IGN);
761 sprintf (logout = tmp,"%.80s, while reading authentication",e);
762 goodbye = NIL;
763 state = LOGOUT;
764 sayonara (1);
765 }
766 }
767 if (!(t = (unsigned char *) strchr ((char *) resp,'\012'))) {
768 int c;
769 while ((c = PBIN ()) != '\012') if (c == EOF) {
770 /* ignore if some interrupt */
771 if (ferror (stdin) && (errno == EINTR)) clearerr (stdin);
772 else {
773 char *e = ferror (stdin) ?
774 strerror (errno) : "Command stream end of file";
775 alarm (0); /* disable all interrupts */
776 server_init (NIL,NIL,NIL,SIG_IGN,SIG_IGN,SIG_IGN,SIG_IGN,SIG_IGN);
777 sprintf (logout = tmp,"%.80s, while reading auth char",e);
778 goodbye = NIL;
779 state = LOGOUT;
780 sayonara (1);
781 }
782 }
783 return NIL;
784 }
785 alarm (0); /* make sure timeout disabled */
786 if (t[-1] == '\015') --t; /* remove CR */
787 *t = '\0'; /* tie off buffer */
788 return (resp[0] != '*') ?
789 (char *) rfc822_base64 (resp,t-resp,rlen ? rlen : &i) : NIL;
790 }
792 /* Select mailbox
793 * Accepts: mailbox name
794 * Returns: new state
795 */
797 int mbxopen (char *mailbox)
798 {
799 unsigned long i,j;
800 char tmp[MAILTMPLEN];
801 MESSAGECACHE *elt;
802 if (msg) fs_give ((void **) &msg);
803 /* open mailbox */
804 if (!(stream = mail_open (stream,mailbox,NIL)))
805 goodbye = "-ERR Unable to open user's INBOX\015\012";
806 else if (stream->rdonly) /* make sure not readonly */
807 goodbye = "-ERR Can't get lock. Mailbox in use\015\012";
808 else {
809 nmsgs = 0; /* no messages yet */
810 if (j = stream->nmsgs) { /* if mailbox non-empty */
811 sprintf (tmp,"1:%lu",j); /* fetch fast information for all messages */
812 mail_fetch_fast (stream,tmp,NIL);
813 }
814 /* create 1-origin tables */
815 msg = (long *) fs_get (++j * sizeof (long));
816 flags = (short *) fs_get (j * sizeof (short));
817 /* build map */
818 for (i = 1; i < j; ++i) if (!(elt = mail_elt (stream,i))->deleted) {
819 msg[++nmsgs] = i; /* note the presence of this message */
820 if (elt->seen) il = nmsgs;/* and set up initial LAST */
821 }
822 /* make sure unused map entries are zero */
823 for (i = nmsgs + 1; i < j; ++i) msg[i] = 0;
824 rset (); /* do implicit RSET */
825 sprintf (tmp,"+OK Mailbox open, %lu messages\015\012",nmsgs);
826 PSOUT (tmp);
827 return TRANSACTION;
828 }
829 syslog (LOG_INFO,"Error opening or locking INBOX user=%.80s host=%.80s",
830 user,tcp_clienthost ());
831 return UPDATE;
832 }
834 /* Blat a string with dot checking
835 * Accepts: string
836 * maximum number of lines if greater than zero
837 * maximum number of bytes to output
838 * alternative stringstruct
839 * Returns: number of lines output
840 *
841 * This routine is uglier and kludgier than it should be, just to be robust
842 * in the case of a message which doesn't end in a newline. Yes, this routine
843 * does truncate the last two bytes from the text. Since it is normally a
844 * newline and the main routine adds it back, it usually does not make a
845 * difference. But if it isn't, since the newline is required and the octet
846 * counts have to match, there's no choice but to truncate.
847 */
849 long blat (char *text,long lines,unsigned long size,STRING *st)
850 {
851 char c,d,e;
852 long ret = 0;
853 /* no-op if zero lines or empty string */
854 if (!(lines && (size-- > 2))) return 0;
855 if (text) {
856 c = *text++; d = *text++; /* collect first two bytes */
857 if (c == '.') PBOUT ('.'); /* double string-leading dot if necessary */
858 while (lines && --size) { /* copy loop */
859 e = *text++; /* get next byte */
860 PBOUT (c); /* output character */
861 if (c == '\012') { /* end of line? */
862 ret++; --lines; /* count another line */
863 /* double leading dot as necessary */
864 if (lines && size && (d == '.')) PBOUT ('.');
865 }
866 c = d; d = e; /* move to next character */
867 }
868 }
869 else {
870 c = SNX (st); d = SNX (st); /* collect first two bytes */
871 if (c == '.') PBOUT ('.'); /* double string-leading dot if necessary */
872 while (lines && --size) { /* copy loop */
873 e = SNX (st); /* get next byte */
874 PBOUT (c); /* output character */
875 if (c == '\012') { /* end of line? */
876 ret++; --lines; /* count another line */
877 /* double leading dot as necessary */
878 if (lines && size && (d == '.')) PBOUT ('.');
879 }
880 c = d; d = e; /* move to next character */
881 }
882 }
883 return ret;
884 }
886 /* Reset mailbox
887 */
889 void rset ()
890 {
891 /* clear all flags */
892 if (flags) memset ((void *) flags,0,(nmsgs + 1) * sizeof (short));
893 ndele = nseen = 0; /* no more deleted or seen messages */
894 last = il; /* restore previous LAST value */
895 }
897 /* Co-routines from MAIL library */
900 /* Message matches a search
901 * Accepts: MAIL stream
902 * message number
903 */
905 void mm_searched (MAILSTREAM *stream,unsigned long msgno)
906 {
907 /* Never called */
908 }
911 /* Message exists (i.e. there are that many messages in the mailbox)
912 * Accepts: MAIL stream
913 * message number
914 */
916 void mm_exists (MAILSTREAM *stream,unsigned long number)
917 {
918 /* Can't use this mechanism. POP has no means of notifying the client of
919 new mail during the session. */
920 }
923 /* Message expunged
924 * Accepts: MAIL stream
925 * message number
926 */
928 void mm_expunged (MAILSTREAM *stream,unsigned long number)
929 {
930 unsigned long i = number + 1;
931 msg[number] = 0; /* I bet that this will annoy someone */
932 while (i <= nmsgs) --msg[i++];
933 }
936 /* Message flag status change
937 * Accepts: MAIL stream
938 * message number
939 */
941 void mm_flags (MAILSTREAM *stream,unsigned long number)
942 {
943 /* This isn't used */
944 }
947 /* Mailbox found
948 * Accepts: MAIL stream
949 * hierarchy delimiter
950 * mailbox name
951 * mailbox attributes
952 */
954 void mm_list (MAILSTREAM *stream,int delimiter,char *name,long attributes)
955 {
956 /* This isn't used */
957 }
960 /* Subscribe mailbox found
961 * Accepts: MAIL stream
962 * hierarchy delimiter
963 * mailbox name
964 * mailbox attributes
965 */
967 void mm_lsub (MAILSTREAM *stream,int delimiter,char *name,long attributes)
968 {
969 /* This isn't used */
970 }
973 /* Mailbox status
974 * Accepts: MAIL stream
975 * mailbox name
976 * mailbox status
977 */
979 void mm_status (MAILSTREAM *stream,char *mailbox,MAILSTATUS *status)
980 {
981 /* This isn't used */
982 }
984 /* Notification event
985 * Accepts: MAIL stream
986 * string to log
987 * error flag
988 */
990 void mm_notify (MAILSTREAM *stream,char *string,long errflg)
991 {
992 mm_log (string,errflg); /* just do mm_log action */
993 }
996 /* Log an event for the user to see
997 * Accepts: string to log
998 * error flag
999 */
1001 void mm_log (char *string,long errflg)
1003 switch (errflg) {
1004 case NIL: /* information message */
1005 case PARSE: /* parse glitch */
1006 break; /* too many of these to log */
1007 case WARN: /* warning */
1008 syslog (LOG_DEBUG,"%s",string);
1009 break;
1010 case BYE: /* driver broke connection */
1011 if (state != UPDATE) {
1012 char tmp[MAILTMPLEN];
1013 alarm (0); /* disable all interrupts */
1014 server_init (NIL,NIL,NIL,SIG_IGN,SIG_IGN,SIG_IGN,SIG_IGN,SIG_IGN);
1015 sprintf (logout = tmp,"Mailbox closed (%.80s)",string);
1016 goodbye = NIL;
1017 state = LOGOUT;
1018 sayonara (1);
1020 break;
1021 case ERROR: /* error that broke command */
1022 default: /* default should never happen */
1023 syslog (LOG_NOTICE,"%s",string);
1024 break;
1029 /* Log an event to debugging telemetry
1030 * Accepts: string to log
1031 */
1033 void mm_dlog (char *string)
1035 /* Not doing anything here for now */
1039 /* Get user name and password for this host
1040 * Accepts: parse of network mailbox name
1041 * where to return user name
1042 * where to return password
1043 * trial count
1044 */
1046 void mm_login (NETMBX *mb,char *username,char *password,long trial)
1048 /* set user name */
1049 strncpy (username,*mb->user ? mb->user : user,NETMAXUSER-1);
1050 if (pass) {
1051 strncpy (password,pass,255);/* and password */
1052 fs_give ((void **) &pass);
1054 else memset (password,0,256); /* no password to send, abort login */
1055 username[NETMAXUSER] = password[255] = '\0';
1058 /* About to enter critical code
1059 * Accepts: stream
1060 */
1062 void mm_critical (MAILSTREAM *stream)
1064 ++critical;
1068 /* About to exit critical code
1069 * Accepts: stream
1070 */
1072 void mm_nocritical (MAILSTREAM *stream)
1074 --critical;
1078 /* Disk error found
1079 * Accepts: stream
1080 * system error code
1081 * flag indicating that mailbox may be clobbered
1082 * Returns: abort flag
1083 */
1085 long mm_diskerror (MAILSTREAM *stream,long errcode,long serious)
1087 if (serious) { /* try your damnest if clobberage likely */
1088 syslog (LOG_ALERT,
1089 "Retrying after disk error user=%.80s host=%.80s mbx=%.80s: %.80s",
1090 user,tcp_clienthost (),
1091 (stream && stream->mailbox) ? stream->mailbox : "???",
1092 strerror (errcode));
1093 alarm (0); /* make damn sure timeout disabled */
1094 sleep (60); /* give it some time to clear up */
1095 return NIL;
1097 syslog (LOG_ALERT,"Fatal disk error user=%.80s host=%.80s mbx=%.80s: %.80s",
1098 user,tcp_clienthost (),
1099 (stream && stream->mailbox) ? stream->mailbox : "???",
1100 strerror (errcode));
1101 return T;
1105 /* Log a fatal error event
1106 * Accepts: string to log
1107 */
1109 void mm_fatal (char *string)
1111 mm_log (string,ERROR); /* shouldn't happen normally */

UW-IMAP'd extensions by yuuji