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