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