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