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