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