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