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