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