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