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