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