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