For the SSL-only ports, if crypto negotiation fails,
[citadel.git] / citadel / modules / pop3 / serv_pop3.c
1 /*
2  * $Id$ 
3  *
4  * POP3 service for the Citadel system
5  * Copyright (C) 1998-2001 by Art Cancro and others.
6  * This code is released under the terms of the GNU General Public License.
7  *
8  * Current status of standards conformance:
9  *
10  * -> All required POP3 commands described in RFC1939 are implemented.
11  * -> All optional POP3 commands described in RFC1939 are also implemented.
12  * -> The deprecated "LAST" command is included in this implementation, because
13  *    there exist mail clients which insist on using it (such as Bynari
14  *    TradeMail, and certain versions of Eudora).
15  * -> Capability detection via the method described in RFC2449 is implemented.
16  * 
17  */
18
19 #include "sysdep.h"
20 #include <stdlib.h>
21 #include <unistd.h>
22 #include <stdio.h>
23 #include <fcntl.h>
24 #include <signal.h>
25 #include <pwd.h>
26 #include <errno.h>
27 #include <sys/types.h>
28
29 #if TIME_WITH_SYS_TIME
30 # include <sys/time.h>
31 # include <time.h>
32 #else
33 # if HAVE_SYS_TIME_H
34 #  include <sys/time.h>
35 # else
36 #  include <time.h>
37 # endif
38 #endif
39
40 #include <sys/wait.h>
41 #include <string.h>
42 #include <limits.h>
43 #include <ctype.h>
44 #include "citadel.h"
45 #include "server.h"
46 #include "citserver.h"
47 #include "support.h"
48 #include "config.h"
49 #include "room_ops.h"
50 #include "user_ops.h"
51 #include "policy.h"
52 #include "database.h"
53 #include "msgbase.h"
54 #include "tools.h"
55 #include "internet_addressing.h"
56 #include "serv_pop3.h"
57 #include "md5.h"
58
59
60
61 #include "ctdl_module.h"
62
63
64
65 /*
66  * This cleanup function blows away the temporary memory and files used by
67  * the POP3 server.
68  */
69 void pop3_cleanup_function(void) {
70
71         /* Don't do this stuff if this is not a POP3 session! */
72         if (CC->h_command_function != pop3_command_loop) return;
73
74         lprintf(CTDL_DEBUG, "Performing POP3 cleanup hook\n");
75         if (POP3->msgs != NULL) free(POP3->msgs);
76
77         free(POP3);
78 }
79
80
81
82 /*
83  * Here's where our POP3 session begins its happy day.
84  */
85 void pop3_greeting(void) {
86         strcpy(CC->cs_clientname, "POP3 session");
87         CC->internal_pgm = 1;
88         POP3 = malloc(sizeof(struct citpop3));
89         memset(POP3, 0, sizeof(struct citpop3));
90
91         cprintf("+OK Citadel POP3 server %s\r\n",
92                 CC->cs_nonce);
93 }
94
95
96 /*
97  * POP3S is just like POP3, except it goes crypto right away.
98  */
99 void pop3s_greeting(void) {
100         CtdlModuleStartCryptoMsgs(NULL, NULL, NULL);
101         if (!CC->redirect_ssl) CC->kill_me = 1;         /* kill session if no crypto */
102         pop3_greeting();
103 }
104
105
106
107 /*
108  * Specify user name (implements POP3 "USER" command)
109  */
110 void pop3_user(char *argbuf) {
111         char username[SIZ];
112
113         if (CC->logged_in) {
114                 cprintf("-ERR You are already logged in.\r\n");
115                 return;
116         }
117
118         strcpy(username, argbuf);
119         striplt(username);
120
121         /* lprintf(CTDL_DEBUG, "Trying <%s>\n", username); */
122         if (CtdlLoginExistingUser(NULL, username) == login_ok) {
123                 cprintf("+OK Password required for %s\r\n", username);
124         }
125         else {
126                 cprintf("-ERR No such user.\r\n");
127         }
128 }
129
130
131
132 /*
133  * Back end for pop3_grab_mailbox()
134  */
135 void pop3_add_message(long msgnum, void *userdata) {
136         struct MetaData smi;
137
138         ++POP3->num_msgs;
139         if (POP3->num_msgs < 2) POP3->msgs = malloc(sizeof(struct pop3msg));
140         else POP3->msgs = realloc(POP3->msgs, 
141                 (POP3->num_msgs * sizeof(struct pop3msg)) ) ;
142         POP3->msgs[POP3->num_msgs-1].msgnum = msgnum;
143         POP3->msgs[POP3->num_msgs-1].deleted = 0;
144
145         /* We need to know the length of this message when it is printed in
146          * RFC822 format.  Perhaps we have cached this length in the message's
147          * metadata record.  If so, great; if not, measure it and then cache
148          * it for next time.
149          */
150         GetMetaData(&smi, msgnum);
151         if (smi.meta_rfc822_length <= 0L) {
152                 CC->redirect_buffer = malloc(SIZ);
153                 CC->redirect_len = 0;
154                 CC->redirect_alloc = SIZ;
155                 CtdlOutputMsg(msgnum, MT_RFC822, HEADERS_ALL, 0, 1, NULL);
156                 smi.meta_rfc822_length = CC->redirect_len;
157                 free(CC->redirect_buffer);
158                 CC->redirect_buffer = NULL;
159                 CC->redirect_len = 0;
160                 CC->redirect_alloc = 0;
161                 PutMetaData(&smi);
162         }
163         POP3->msgs[POP3->num_msgs-1].rfc822_length = smi.meta_rfc822_length;
164 }
165
166
167
168 /*
169  * Open the inbox and read its contents.
170  * (This should be called only once, by pop3_pass(), and returns the number
171  * of messages in the inbox, or -1 for error)
172  */
173 int pop3_grab_mailbox(void) {
174         struct visit vbuf;
175         int i;
176
177         if (getroom(&CC->room, MAILROOM) != 0) return(-1);
178
179         /* Load up the messages */
180         CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL,
181                 pop3_add_message, NULL);
182
183         /* Figure out which are old and which are new */
184         CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
185         POP3->lastseen = (-1);
186         if (POP3->num_msgs) for (i=0; i<POP3->num_msgs; ++i) {
187                 if (is_msg_in_sequence_set(vbuf.v_seen,
188                    (POP3->msgs[POP3->num_msgs-1].msgnum) )) {
189                         POP3->lastseen = i;
190                 }
191         }
192
193         return(POP3->num_msgs);
194 }
195
196 void pop3_login(void)
197 {
198         int msgs;
199         
200         msgs = pop3_grab_mailbox();
201         if (msgs >= 0) {
202                 cprintf("+OK %s is logged in (%d messages)\r\n",
203                         CC->user.fullname, msgs);
204                 lprintf(CTDL_NOTICE, "POP3 authenticated %s\n", CC->user.fullname);
205         }
206         else {
207                 cprintf("-ERR Can't open your mailbox\r\n");
208         }
209         
210 }
211
212 void pop3_apop(char *argbuf)
213 {
214    char username[SIZ];
215    char userdigest[MD5_HEXSTRING_SIZE];
216    char realdigest[MD5_HEXSTRING_SIZE];
217    char *sptr;
218    
219    if (CC->logged_in)
220    {
221         cprintf("-ERR You are already logged in; not in the AUTHORIZATION phase.\r\n");
222         return;
223    }
224    
225    if ((sptr = strchr(argbuf, ' ')) == NULL)
226    {
227         cprintf("-ERR Invalid APOP line.\r\n");
228         return;
229    }
230    
231    *sptr++ = '\0';
232    
233    while ((*sptr) && isspace(*sptr))
234       sptr++;
235    
236    strncpy(username, argbuf, sizeof(username)-1);
237    username[sizeof(username)-1] = '\0';
238    
239    memset(userdigest, MD5_HEXSTRING_SIZE, 0);
240    strncpy(userdigest, sptr, MD5_HEXSTRING_SIZE-1);
241    
242    if (CtdlLoginExistingUser(NULL, username) != login_ok)
243    {
244         cprintf("-ERR No such user.\r\n");
245         return;
246    }
247    
248    if (getuser(&CC->user, CC->curr_user))
249    {
250         cprintf("-ERR No such user.\r\n");
251         return;
252    }
253    
254    make_apop_string(CC->user.password, CC->cs_nonce, realdigest, sizeof realdigest);
255    if (!strncasecmp(realdigest, userdigest, MD5_HEXSTRING_SIZE-1))
256    {
257         do_login();
258         pop3_login();
259    }
260    else
261    {
262         cprintf("-ERR That is NOT the password.\r\n");
263    }
264 }
265
266
267 /*
268  * Authorize with password (implements POP3 "PASS" command)
269  */
270 void pop3_pass(char *argbuf) {
271         char password[SIZ];
272
273         strcpy(password, argbuf);
274         striplt(password);
275
276         /* lprintf(CTDL_DEBUG, "Trying <%s>\n", password); */
277         if (CtdlTryPassword(password) == pass_ok) {
278                 pop3_login();
279         }
280         else {
281                 cprintf("-ERR That is NOT the password.\r\n");
282         }
283 }
284
285
286
287 /*
288  * list available msgs
289  */
290 void pop3_list(char *argbuf) {
291         int i;
292         int which_one;
293
294         which_one = atoi(argbuf);
295
296         /* "list one" mode */
297         if (which_one > 0) {
298                 if (which_one > POP3->num_msgs) {
299                         cprintf("-ERR no such message, only %d are here\r\n",
300                                 POP3->num_msgs);
301                         return;
302                 }
303                 else if (POP3->msgs[which_one-1].deleted) {
304                         cprintf("-ERR Sorry, you deleted that message.\r\n");
305                         return;
306                 }
307                 else {
308                         cprintf("+OK %d %ld\r\n",
309                                 which_one,
310                                 (long)POP3->msgs[which_one-1].rfc822_length
311                                 );
312                         return;
313                 }
314         }
315
316         /* "list all" (scan listing) mode */
317         else {
318                 cprintf("+OK Here's your mail:\r\n");
319                 if (POP3->num_msgs > 0) for (i=0; i<POP3->num_msgs; ++i) {
320                         if (! POP3->msgs[i].deleted) {
321                                 cprintf("%d %ld\r\n",
322                                         i+1,
323                                         (long)POP3->msgs[i].rfc822_length);
324                         }
325                 }
326                 cprintf(".\r\n");
327         }
328 }
329
330
331 /*
332  * STAT (tally up the total message count and byte count) command
333  */
334 void pop3_stat(char *argbuf) {
335         int total_msgs = 0;
336         size_t total_octets = 0;
337         int i;
338         
339         if (POP3->num_msgs > 0) for (i=0; i<POP3->num_msgs; ++i) {
340                 if (! POP3->msgs[i].deleted) {
341                         ++total_msgs;
342                         total_octets += POP3->msgs[i].rfc822_length;
343                 }
344         }
345
346         cprintf("+OK %d %ld\r\n", total_msgs, (long)total_octets);
347 }
348
349
350
351 /*
352  * RETR command (fetch a message)
353  */
354 void pop3_retr(char *argbuf) {
355         int which_one;
356
357         which_one = atoi(argbuf);
358         if ( (which_one < 1) || (which_one > POP3->num_msgs) ) {
359                 cprintf("-ERR No such message.\r\n");
360                 return;
361         }
362
363         if (POP3->msgs[which_one - 1].deleted) {
364                 cprintf("-ERR Sorry, you deleted that message.\r\n");
365                 return;
366         }
367
368         cprintf("+OK Message %d:\r\n", which_one);
369         CtdlOutputMsg(POP3->msgs[which_one - 1].msgnum, MT_RFC822, HEADERS_ALL, 0, 1, NULL);
370         cprintf(".\r\n");
371 }
372
373
374 /*
375  * TOP command (dumb way of fetching a partial message or headers-only)
376  */
377 void pop3_top(char *argbuf) {
378         int which_one;
379         int lines_requested = 0;
380         int lines_dumped = 0;
381         char buf[1024];
382         char *msgtext;
383         char *ptr;
384         int in_body = 0;
385         int done = 0;
386
387         sscanf(argbuf, "%d %d", &which_one, &lines_requested);
388         if ( (which_one < 1) || (which_one > POP3->num_msgs) ) {
389                 cprintf("-ERR No such message.\r\n");
390                 return;
391         }
392
393         if (POP3->msgs[which_one - 1].deleted) {
394                 cprintf("-ERR Sorry, you deleted that message.\r\n");
395                 return;
396         }
397
398         CC->redirect_buffer = malloc(SIZ);
399         CC->redirect_len = 0;
400         CC->redirect_alloc = SIZ;
401         CtdlOutputMsg(POP3->msgs[which_one - 1].msgnum,
402                         MT_RFC822, HEADERS_ALL, 0, 1, NULL);
403         msgtext = CC->redirect_buffer;
404         CC->redirect_buffer = NULL;
405         CC->redirect_len = 0;
406         CC->redirect_alloc = 0;
407
408         cprintf("+OK Message %d:\r\n", which_one);
409
410         ptr = msgtext;
411
412         while (ptr = memreadline(ptr, buf, (sizeof buf - 2)),
413               ( (*ptr != 0) && (done == 0))) {
414                 strcat(buf, "\r\n");
415                 if (in_body == 1) {
416                         if (lines_dumped >= lines_requested) {
417                                 done = 1;
418                         }
419                 }
420                 if ((in_body == 0) || (done == 0)) {
421                         client_write(buf, strlen(buf));
422                 }
423                 if (in_body) {
424                         ++lines_dumped;
425                 }
426                 if ((buf[0]==13)||(buf[0]==10)) in_body = 1;
427         }
428
429         if (buf[strlen(buf)-1] != 10) cprintf("\n");
430         free(msgtext);
431
432         cprintf(".\r\n");
433 }
434
435
436 /*
437  * DELE (delete message from mailbox)
438  */
439 void pop3_dele(char *argbuf) {
440         int which_one;
441
442         which_one = atoi(argbuf);
443         if ( (which_one < 1) || (which_one > POP3->num_msgs) ) {
444                 cprintf("-ERR No such message.\r\n");
445                 return;
446         }
447
448         if (POP3->msgs[which_one - 1].deleted) {
449                 cprintf("-ERR You already deleted that message.\r\n");
450                 return;
451         }
452
453         /* Flag the message as deleted.  Will expunge during QUIT command. */
454         POP3->msgs[which_one - 1].deleted = 1;
455         cprintf("+OK Message %d deleted.\r\n",
456                 which_one);
457 }
458
459
460 /* Perform "UPDATE state" stuff
461  */
462 void pop3_update(void) {
463         int i;
464         struct visit vbuf;
465
466         long *deletemsgs = NULL;
467         int num_deletemsgs = 0;
468
469         /* Remove messages marked for deletion */
470         if (POP3->num_msgs > 0) {
471                 deletemsgs = malloc(POP3->num_msgs * sizeof(long));
472                 for (i=0; i<POP3->num_msgs; ++i) {
473                         if (POP3->msgs[i].deleted) {
474                                 deletemsgs[num_deletemsgs++] = POP3->msgs[i].msgnum;
475                         }
476                 }
477                 if (num_deletemsgs > 0) {
478                         CtdlDeleteMessages(MAILROOM, deletemsgs, num_deletemsgs, "");
479                 }
480                 free(deletemsgs);
481         }
482
483         /* Set last read pointer */
484         if (POP3->num_msgs > 0) {
485                 lgetuser(&CC->user, CC->curr_user);
486
487                 CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
488                 snprintf(vbuf.v_seen, sizeof vbuf.v_seen, "*:%ld",
489                         POP3->msgs[POP3->num_msgs-1].msgnum);
490                 CtdlSetRelationship(&vbuf, &CC->user, &CC->room);
491
492                 lputuser(&CC->user);
493         }
494
495 }
496
497
498 /* 
499  * RSET (reset, i.e. undelete any deleted messages) command
500  */
501 void pop3_rset(char *argbuf) {
502         int i;
503
504         if (POP3->num_msgs > 0) for (i=0; i<POP3->num_msgs; ++i) {
505                 if (POP3->msgs[i].deleted) {
506                         POP3->msgs[i].deleted = 0;
507                 }
508         }
509         cprintf("+OK Reset completed.\r\n");
510 }
511
512
513
514 /* 
515  * LAST (Determine which message is the last unread message)
516  */
517 void pop3_last(char *argbuf) {
518         cprintf("+OK %d\r\n", POP3->lastseen + 1);
519 }
520
521
522 /*
523  * CAPA is a command which tells the client which POP3 extensions
524  * are supported.
525  */
526 void pop3_capa(void) {
527         cprintf("+OK Capability list follows\r\n"
528                 "TOP\r\n"
529                 "USER\r\n"
530                 "UIDL\r\n"
531                 "IMPLEMENTATION %s\r\n"
532                 ".\r\n"
533                 ,
534                 CITADEL
535         );
536 }
537
538
539
540 /*
541  * UIDL (Universal IDentifier Listing) is easy.  Our 'unique' message
542  * identifiers are simply the Citadel message numbers in the database.
543  */
544 void pop3_uidl(char *argbuf) {
545         int i;
546         int which_one;
547
548         which_one = atoi(argbuf);
549
550         /* "list one" mode */
551         if (which_one > 0) {
552                 if (which_one > POP3->num_msgs) {
553                         cprintf("-ERR no such message, only %d are here\r\n",
554                                 POP3->num_msgs);
555                         return;
556                 }
557                 else if (POP3->msgs[which_one-1].deleted) {
558                         cprintf("-ERR Sorry, you deleted that message.\r\n");
559                         return;
560                 }
561                 else {
562                         cprintf("+OK %d %ld\r\n",
563                                 which_one,
564                                 POP3->msgs[which_one-1].msgnum
565                                 );
566                         return;
567                 }
568         }
569
570         /* "list all" (scan listing) mode */
571         else {
572                 cprintf("+OK Here's your mail:\r\n");
573                 if (POP3->num_msgs > 0) for (i=0; i<POP3->num_msgs; ++i) {
574                         if (! POP3->msgs[i].deleted) {
575                                 cprintf("%d %ld\r\n",
576                                         i+1,
577                                         POP3->msgs[i].msgnum);
578                         }
579                 }
580                 cprintf(".\r\n");
581         }
582 }
583
584
585 /*
586  * implements the STLS command (Citadel API version)
587  */
588 void pop3_stls(void)
589 {
590         char ok_response[SIZ];
591         char nosup_response[SIZ];
592         char error_response[SIZ];
593
594         sprintf(ok_response,
595                 "+OK Begin TLS negotiation now\r\n");
596         sprintf(nosup_response,
597                 "-ERR TLS not supported here\r\n");
598         sprintf(error_response,
599                 "-ERR Internal error\r\n");
600         CtdlModuleStartCryptoMsgs(ok_response, nosup_response, error_response);
601 }
602
603
604
605
606
607
608
609 /* 
610  * Main command loop for POP3 sessions.
611  */
612 void pop3_command_loop(void) {
613         char cmdbuf[SIZ];
614
615         time(&CC->lastcmd);
616         memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
617         if (client_getln(cmdbuf, sizeof cmdbuf) < 1) {
618                 lprintf(CTDL_ERR, "Client disconnected: ending session.\r\n");
619                 CC->kill_me = 1;
620                 return;
621         }
622         if (!strncasecmp(cmdbuf, "PASS", 4)) {
623                 lprintf(CTDL_INFO, "POP3: PASS...\r\n");
624         }
625         else {
626                 lprintf(CTDL_INFO, "POP3: %s\r\n", cmdbuf);
627         }
628         while (strlen(cmdbuf) < 5) strcat(cmdbuf, " ");
629
630         if (!strncasecmp(cmdbuf, "NOOP", 4)) {
631                 cprintf("+OK No operation.\r\n");
632         }
633
634         else if (!strncasecmp(cmdbuf, "CAPA", 4)) {
635                 pop3_capa();
636         }
637
638         else if (!strncasecmp(cmdbuf, "QUIT", 4)) {
639                 cprintf("+OK Goodbye...\r\n");
640                 pop3_update();
641                 CC->kill_me = 1;
642                 return;
643         }
644
645         else if (!strncasecmp(cmdbuf, "USER", 4)) {
646                 pop3_user(&cmdbuf[5]);
647         }
648
649         else if (!strncasecmp(cmdbuf, "PASS", 4)) {
650                 pop3_pass(&cmdbuf[5]);
651         }
652
653         else if (!strncasecmp(cmdbuf, "APOP", 4))
654         {
655                 pop3_apop(&cmdbuf[5]);
656         }
657
658 #ifdef HAVE_OPENSSL
659         else if (!strncasecmp(cmdbuf, "STLS", 4)) {
660                 pop3_stls();
661         }
662 #endif
663
664         else if (!CC->logged_in) {
665                 cprintf("-ERR Not logged in.\r\n");
666         }
667
668         else if (!strncasecmp(cmdbuf, "LIST", 4)) {
669                 pop3_list(&cmdbuf[5]);
670         }
671
672         else if (!strncasecmp(cmdbuf, "STAT", 4)) {
673                 pop3_stat(&cmdbuf[5]);
674         }
675
676         else if (!strncasecmp(cmdbuf, "RETR", 4)) {
677                 pop3_retr(&cmdbuf[5]);
678         }
679
680         else if (!strncasecmp(cmdbuf, "DELE", 4)) {
681                 pop3_dele(&cmdbuf[5]);
682         }
683
684         else if (!strncasecmp(cmdbuf, "RSET", 4)) {
685                 pop3_rset(&cmdbuf[5]);
686         }
687
688         else if (!strncasecmp(cmdbuf, "UIDL", 4)) {
689                 pop3_uidl(&cmdbuf[5]);
690         }
691
692         else if (!strncasecmp(cmdbuf, "TOP", 3)) {
693                 pop3_top(&cmdbuf[4]);
694         }
695
696         else if (!strncasecmp(cmdbuf, "LAST", 4)) {
697                 pop3_last(&cmdbuf[4]);
698         }
699
700         else {
701                 cprintf("-ERR I'm afraid I can't do that.\r\n");
702         }
703
704 }
705
706 const char *CitadelServicePop3="POP3";
707 const char *CitadelServicePop3S="POP3S";
708
709
710 CTDL_MODULE_INIT(pop3)
711 {
712         CtdlRegisterServiceHook(config.c_pop3_port,
713                                 NULL,
714                                 pop3_greeting,
715                                 pop3_command_loop,
716                                 NULL,
717                                 CitadelServicePop3);
718 #ifdef HAVE_OPENSSL
719         CtdlRegisterServiceHook(config.c_pop3s_port,
720                                 NULL,
721                                 pop3s_greeting,
722                                 pop3_command_loop,
723                                 NULL,
724                                 CitadelServicePop3S);
725 #endif
726         CtdlRegisterSessionHook(pop3_cleanup_function, EVT_STOP);
727
728         /* return our Subversion id for the Log */
729         return "$Id$";
730 }