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