]> code.citadel.org Git - citadel.git/blob - citadel/serv_imap.c
* IMAP server: added untagged, unsolicited server messages for newly arrived
[citadel.git] / citadel / serv_imap.c
1 /*
2  * $Id$ 
3  *
4  * IMAP server for the Citadel/UX system
5  * Copyright (C) 2000-2001 by Art Cancro and others.
6  * This code is released under the terms of the GNU General Public License.
7  *
8  * WARNING: this is an incomplete implementation, still in progress.  Parts of
9  * it work, but it's not really usable yet from a user perspective.
10  *
11  * WARNING: Mark Crispin is an idiot.  IMAP is the most brain-damaged protocol
12  * you will ever have the profound lack of pleasure to encounter.
13  * 
14  */
15
16 #include "sysdep.h"
17 #include <stdlib.h>
18 #include <unistd.h>
19 #include <stdio.h>
20 #include <fcntl.h>
21 #include <signal.h>
22 #include <pwd.h>
23 #include <errno.h>
24 #include <sys/types.h>
25 #include <sys/time.h>
26 #include <sys/wait.h>
27 #include <ctype.h>
28 #include <string.h>
29 #include <limits.h>
30 #include "citadel.h"
31 #include "server.h"
32 #include <time.h>
33 #include "sysdep_decls.h"
34 #include "citserver.h"
35 #include "support.h"
36 #include "config.h"
37 #include "dynloader.h"
38 #include "room_ops.h"
39 #include "user_ops.h"
40 #include "policy.h"
41 #include "database.h"
42 #include "msgbase.h"
43 #include "tools.h"
44 #include "internet_addressing.h"
45 #include "serv_imap.h"
46 #include "imap_tools.h"
47 #include "imap_fetch.h"
48 #include "imap_search.h"
49
50
51 long SYM_IMAP;
52
53
54 /*
55  * If there is a message ID map in memory, free it
56  */
57 void imap_free_msgids(void) {
58         if (IMAP->msgids != NULL) {
59                 phree(IMAP->msgids);
60                 IMAP->msgids = NULL;
61                 IMAP->num_msgs = 0;
62         }
63         if (IMAP->flags != NULL) {
64                 phree(IMAP->flags);
65                 IMAP->flags = NULL;
66         }
67 }
68
69
70 /*
71  * Back end for imap_load_msgids()
72  *
73  * FIXME: this should be optimized by figuring out a way to allocate memory
74  * once rather than doing a reallok() for each message.
75  */
76 void imap_add_single_msgid(long msgnum, void *userdata) {
77         
78         IMAP->num_msgs = IMAP->num_msgs + 1;
79         if (IMAP->msgids == NULL) {
80                 IMAP->msgids = mallok(IMAP->num_msgs * sizeof(long));
81         }
82         else {
83                 IMAP->msgids = reallok(IMAP->msgids,
84                         IMAP->num_msgs * sizeof(long));
85         }
86         if (IMAP->flags == NULL) {
87                 IMAP->flags = mallok(IMAP->num_msgs * sizeof(long));
88         }
89         else {
90                 IMAP->flags = reallok(IMAP->flags,
91                         IMAP->num_msgs * sizeof(long));
92         }
93         IMAP->msgids[IMAP->num_msgs - 1] = msgnum;
94         IMAP->flags[IMAP->num_msgs - 1] = 0;
95 }
96
97
98
99 /*
100  * Set up a message ID map for the current room (folder)
101  */
102 void imap_load_msgids(void) {
103          
104         if (IMAP->selected == 0) {
105                 lprintf(5, "imap_load_msgids() can't run; no room selected\n");
106                 return;
107         }
108
109         imap_free_msgids();     /* If there was already a map, free it */
110
111         CtdlForEachMessage(MSGS_ALL, 0L, (-63), NULL, NULL,
112                 imap_add_single_msgid, NULL);
113
114         lprintf(9, "imap_load_msgids() mapped %d messages\n", IMAP->num_msgs);
115 }
116
117
118 /*
119  * Re-scan the selected room (folder) and see if it's been changed at all
120  */
121 void imap_rescan_msgids(void) {
122
123         int original_num_msgs = 0;
124         long original_highest = 0L;
125         int i;
126         int count;
127
128         if (IMAP->selected == 0) {
129                 lprintf(5, "imap_load_msgids() can't run; no room selected\n");
130                 return;
131         }
132
133
134         /*
135          * Check to see if any of the messages we know about have been expunged
136          */
137         if (IMAP->num_msgs > 0)
138          for (i=0; i<IMAP->num_msgs; ++i)
139           if ((IMAP->flags[i] & IMAP_EXPUNGED) == 0) {
140
141                 count = CtdlForEachMessage(MSGS_EQ, IMAP->msgids[i],
142                         (-63), NULL, NULL, NULL, NULL);
143
144                 if (count == 0) {
145                         IMAP->flags[i] = IMAP->flags[i] | IMAP_EXPUNGED;
146                         cprintf("* %d EXPUNGE\r\n", i+1);
147                 }
148
149         }
150
151         /*
152          * Remember how many messages were here before we re-scanned.
153          */
154         original_num_msgs = IMAP->num_msgs;
155         if (IMAP->num_msgs > 0) {
156                 original_highest = IMAP->msgids[IMAP->num_msgs - 1];
157         }
158         else {
159                 original_highest = 0L;
160         }
161
162         /*
163          * Now peruse the room for *new* messages only.
164          */
165         CtdlForEachMessage(MSGS_GT, original_highest, (-63), NULL, NULL,
166                 imap_add_single_msgid, NULL);
167
168         /*
169          * If new messages have arrived, tell the client about them.
170          */
171         if (IMAP->num_msgs > original_num_msgs) {
172                 cprintf("* %d EXISTS\r\n", IMAP->num_msgs);
173         }
174
175 }
176
177
178
179
180
181
182
183 /*
184  * This cleanup function blows away the temporary memory and files used by
185  * the IMAP server.
186  */
187 void imap_cleanup_function(void) {
188
189         /* Don't do this stuff if this is not a IMAP session! */
190         if (CC->h_command_function != imap_command_loop) return;
191
192         lprintf(9, "Performing IMAP cleanup hook\n");
193         imap_free_msgids();
194         lprintf(9, "Finished IMAP cleanup hook\n");
195 }
196
197
198
199 /*
200  * Here's where our IMAP session begins its happy day.
201  */
202 void imap_greeting(void) {
203
204         strcpy(CC->cs_clientname, "IMAP session");
205         CtdlAllocUserData(SYM_IMAP, sizeof(struct citimap));
206         IMAP->authstate = imap_as_normal;
207
208         cprintf("* OK %s Citadel/UX IMAP4rev1 server ready\r\n",
209                 config.c_fqdn);
210 }
211
212
213 /*
214  * implements the LOGIN command (ordinary username/password login)
215  */
216 void imap_login(int num_parms, char *parms[]) {
217         if (CtdlLoginExistingUser(parms[2]) == login_ok) {
218                 if (CtdlTryPassword(parms[3]) == pass_ok) {
219                         cprintf("%s OK login successful\r\n", parms[0]);
220                         return;
221                 }
222         }
223
224         cprintf("%s BAD Login incorrect\r\n", parms[0]);
225 }
226
227
228 /*
229  * Implements the AUTHENTICATE command
230  */
231 void imap_authenticate(int num_parms, char *parms[]) {
232         char buf[SIZ];
233
234         if (num_parms != 3) {
235                 cprintf("%s BAD incorrect number of parameters\r\n", parms[0]);
236                 return;
237         }
238
239         if (!strcasecmp(parms[2], "LOGIN")) {
240                 encode_base64(buf, "Username:");
241                 cprintf("+ %s\r\n", buf);
242                 IMAP->authstate = imap_as_expecting_username;
243                 strcpy(IMAP->authseq, parms[0]);
244                 return;
245         }
246
247         else {
248                 cprintf("%s NO AUTHENTICATE %s failed\r\n",
249                         parms[0], parms[1]);
250         }
251 }
252
253 void imap_auth_login_user(char *cmd) {
254         char buf[SIZ];
255
256         decode_base64(buf, cmd);
257         CtdlLoginExistingUser(buf);
258         encode_base64(buf, "Password:");
259         cprintf("+ %s\r\n", buf);
260         IMAP->authstate = imap_as_expecting_password;
261         return;
262 }
263
264 void imap_auth_login_pass(char *cmd) {
265         char buf[SIZ];
266
267         decode_base64(buf, cmd);
268         if (CtdlTryPassword(buf) == pass_ok) {
269                 cprintf("%s OK authentication succeeded\r\n", IMAP->authseq);
270         }
271         else {
272                 cprintf("%s NO authentication failed\r\n", IMAP->authseq);
273         }
274         IMAP->authstate = imap_as_normal;
275         return;
276 }
277
278
279
280 /*
281  * implements the CAPABILITY command
282  */
283 void imap_capability(int num_parms, char *parms[]) {
284         cprintf("* CAPABILITY IMAP4 IMAP4REV1 AUTH=LOGIN\r\n");
285         cprintf("%s OK CAPABILITY completed\r\n", parms[0]);
286 }
287
288
289
290
291
292 /*
293  * implements the SELECT command
294  */
295 void imap_select(int num_parms, char *parms[]) {
296         char towhere[SIZ];
297         char augmented_roomname[SIZ];
298         int c = 0;
299         int ok = 0;
300         int ra = 0;
301         struct quickroom QRscratch;
302         int msgs, new;
303         int floornum;
304         int roomflags;
305         int i;
306
307         /* Convert the supplied folder name to a roomname */
308         i = imap_roomname(towhere, sizeof towhere, parms[2]);
309         if (i < 0) {
310                 cprintf("%s NO Invalid mailbox name.\r\n", parms[0]);
311                 IMAP->selected = 0;
312                 return;
313         }
314         floornum = (i & 0x00ff);
315         roomflags = (i & 0xff00);
316
317         /* First try a regular match */
318         c = getroom(&QRscratch, towhere);
319
320         /* Then try a mailbox name match */
321         if (c != 0) {
322                 MailboxName(augmented_roomname, &CC->usersupp, towhere);
323                 c = getroom(&QRscratch, augmented_roomname);
324                 if (c == 0)
325                         strcpy(towhere, augmented_roomname);
326         }
327
328         /* If the room exists, check security/access */
329         if (c == 0) {
330                 /* See if there is an existing user/room relationship */
331                 ra = CtdlRoomAccess(&QRscratch, &CC->usersupp);
332
333                 /* normal clients have to pass through security */
334                 if (ra & UA_KNOWN) {
335                         ok = 1;
336                 }
337         }
338
339         /* Fail here if no such room */
340         if (!ok) {
341                 cprintf("%s NO ... no such room, or access denied\r\n",
342                         parms[0]);
343                 IMAP->selected = 0;
344                 return;
345         }
346
347         /*
348          * usergoto() formally takes us to the desired room, happily returning
349          * the number of messages and number of new messages.
350          */
351         usergoto(QRscratch.QRname, 0, &msgs, &new);
352         IMAP->selected = 1;
353
354         if (!strcasecmp(parms[1], "EXAMINE")) {
355                 IMAP->readonly = 1;
356         }
357         else {
358                 IMAP->readonly = 0;
359         }
360
361         imap_load_msgids();
362
363         /* FIXME ... much more info needs to be supplied here */
364         cprintf("* %d EXISTS\r\n", msgs);
365         cprintf("* %d RECENT\r\n", new);
366         cprintf("* OK [UIDVALIDITY 0] UIDs valid\r\n");
367         cprintf("%s OK [%s] %s completed\r\n",
368                 parms[0],
369                 (IMAP->readonly ? "READ-ONLY" : "READ-WRITE"),
370                 parms[1]);
371 }
372
373
374
375 /*
376  * implements the CLOSE command
377  */
378 void imap_close(int num_parms, char *parms[]) {
379         IMAP->selected = 0;
380         IMAP->readonly = 0;
381         imap_free_msgids();
382         cprintf("%s OK CLOSE completed\r\n", parms[0]);
383 }
384
385
386
387
388 /*
389  * Used by LIST and LSUB to show the floors in the listing
390  */
391 void imap_list_floors(char *cmd) {
392         int i;
393         struct floor *fl;
394
395         for (i=0; i<MAXFLOORS; ++i) {
396                 fl = cgetfloor(i);
397                 if (fl->f_flags & F_INUSE) {
398                         cprintf("* %s (\\NoSelect) \"|\" ", cmd);
399                         imap_strout(fl->f_name);
400                         cprintf("\r\n");
401                 }
402         }
403 }
404
405
406
407 /*
408  * Back end for imap_lsub()
409  *
410  * IMAP "subscribed folder" is equivocated to Citadel "known rooms."  This
411  * may or may not be the desired behavior in the future.
412  */
413 void imap_lsub_listroom(struct quickroom *qrbuf, void *data) {
414         char buf[SIZ];
415         int ra;
416
417         /* Only list rooms to which the user has access!! */
418         ra = CtdlRoomAccess(qrbuf, &CC->usersupp);
419         if (ra & UA_KNOWN) {
420                 imap_mailboxname(buf, sizeof buf, qrbuf);
421                 cprintf("* LSUB () \"|\" ");
422                 imap_strout(buf);
423                 cprintf("\r\n");
424         }
425 }
426
427
428 /*
429  * Implements the LSUB command
430  *
431  * FIXME: Handle wildcards, please.
432  */
433 void imap_lsub(int num_parms, char *parms[]) {
434         imap_list_floors("LSUB");
435         ForEachRoom(imap_lsub_listroom, NULL);
436         cprintf("%s OK LSUB completed\r\n", parms[0]);
437 }
438
439
440
441 /*
442  * Back end for imap_list()
443  */
444 void imap_list_listroom(struct quickroom *qrbuf, void *data) {
445         char buf[SIZ];
446         int ra;
447
448         /* Only list rooms to which the user has access!! */
449         ra = CtdlRoomAccess(qrbuf, &CC->usersupp);
450         if ( (ra & UA_KNOWN) 
451           || ((ra & UA_GOTOALLOWED) && (ra & UA_ZAPPED))) {
452                 imap_mailboxname(buf, sizeof buf, qrbuf);
453                 cprintf("* LIST () \"|\" ");
454                 imap_strout(buf);
455                 cprintf("\r\n");
456         }
457 }
458
459
460 /*
461  * Implements the LIST command
462  *
463  * FIXME: Handle wildcards, please.
464  */
465 void imap_list(int num_parms, char *parms[]) {
466         imap_list_floors("LIST");
467         ForEachRoom(imap_list_listroom, NULL);
468         cprintf("%s OK LIST completed\r\n", parms[0]);
469 }
470
471
472
473 /*
474  * Implements the CREATE command
475  *
476  */
477 void imap_create(int num_parms, char *parms[]) {
478         int ret;
479         char roomname[SIZ];
480         int floornum;
481         int flags;
482         int newroomtype;
483
484         ret = imap_roomname(roomname, sizeof roomname, parms[2]);
485         if (ret < 0) {
486                 cprintf("%s NO Invalid mailbox name or location\r\n",
487                         parms[0]);
488                 return;
489         }
490         floornum = ( ret & 0x00ff );    /* lower 8 bits = floor number */
491         flags =    ( ret & 0xff00 );    /* upper 8 bits = flags        */
492
493         if (flags & IR_MAILBOX) {
494                 newroomtype = 4;        /* private mailbox */
495         }
496         else {
497                 newroomtype = 0;        /* public folder */
498         }
499
500         lprintf(7, "Create new room <%s> on floor <%d> with type <%d>\n",
501                 roomname, floornum, newroomtype);
502
503         ret = create_room(roomname, newroomtype, "", floornum, 1);
504         if (ret == 0) {
505                 cprintf("%s NO Mailbox already exists, or create failed\r\n",
506                         parms[0]);
507         }
508         else {
509                 cprintf("%s OK CREATE completed\r\n", parms[0]);
510         }
511 }
512
513
514
515 /* 
516  * Main command loop for IMAP sessions.
517  */
518 void imap_command_loop(void) {
519         char cmdbuf[SIZ];
520         char *parms[SIZ];
521         int num_parms;
522
523         time(&CC->lastcmd);
524         memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
525         if (client_gets(cmdbuf) < 1) {
526                 lprintf(3, "IMAP socket is broken.  Ending session.\r\n");
527                 CC->kill_me = 1;
528                 return;
529         }
530
531         lprintf(5, "citserver[%3d]: %s\r\n", CC->cs_pid, cmdbuf);
532         while (strlen(cmdbuf) < 5) strcat(cmdbuf, " ");
533
534
535         /* strip off l/t whitespace and CRLF */
536         if (cmdbuf[strlen(cmdbuf)-1]=='\n') cmdbuf[strlen(cmdbuf)-1]=0;
537         if (cmdbuf[strlen(cmdbuf)-1]=='\r') cmdbuf[strlen(cmdbuf)-1]=0;
538         striplt(cmdbuf);
539
540         /* If we're in the middle of a multi-line command, handle that */
541         if (IMAP->authstate == imap_as_expecting_username) {
542                 imap_auth_login_user(cmdbuf);
543                 return;
544         }
545         if (IMAP->authstate == imap_as_expecting_password) {
546                 imap_auth_login_pass(cmdbuf);
547                 return;
548         }
549
550
551         /* Ok, at this point we're in normal command mode */
552
553         /*
554          * Before processing the command that was just entered... if we happen
555          * to have a folder selected, we'd like to rescan that folder for new
556          * messages, and for deletions/changes of existing messages.  This
557          * could probably be optimized somehow, but IMAP sucks...
558          */
559         if (IMAP->selected) {
560                 imap_rescan_msgids();
561         }
562
563         /* Now for the command set. */
564
565         /* Grab the tag, command, and parameters.  Check syntax. */
566         num_parms = imap_parameterize(parms, cmdbuf);
567         if (num_parms < 2) {
568                 cprintf("BAD syntax error\r\n");
569         }
570
571         /* The commands below may be executed in any state */
572
573         else if ( (!strcasecmp(parms[1], "NOOP"))
574            || (!strcasecmp(parms[1], "CHECK")) ) {
575                 cprintf("%s OK This command successfully did nothing.\r\n",
576                         parms[0]);
577         }
578
579         else if (!strcasecmp(parms[1], "LOGOUT")) {
580                 cprintf("* BYE %s logging out\r\n", config.c_fqdn);
581                 cprintf("%s OK thank you for using Citadel IMAP\r\n", parms[0]);
582                 CC->kill_me = 1;
583                 return;
584         }
585
586         else if (!strcasecmp(parms[1], "LOGIN")) {
587                 imap_login(num_parms, parms);
588         }
589
590         else if (!strcasecmp(parms[1], "AUTHENTICATE")) {
591                 imap_authenticate(num_parms, parms);
592         }
593
594         else if (!strcasecmp(parms[1], "CAPABILITY")) {
595                 imap_capability(num_parms, parms);
596         }
597
598         else if (!CC->logged_in) {
599                 cprintf("%s BAD Not logged in.\r\n", parms[0]);
600         }
601
602         /* The commans below require a logged-in state */
603
604         else if (!strcasecmp(parms[1], "SELECT")) {
605                 imap_select(num_parms, parms);
606         }
607
608         else if (!strcasecmp(parms[1], "EXAMINE")) {
609                 imap_select(num_parms, parms);
610         }
611
612         else if (!strcasecmp(parms[1], "LSUB")) {
613                 imap_lsub(num_parms, parms);
614         }
615
616         else if (!strcasecmp(parms[1], "LIST")) {
617                 imap_list(num_parms, parms);
618         }
619
620         else if (!strcasecmp(parms[1], "CREATE")) {
621                 imap_create(num_parms, parms);
622         }
623
624         else if (IMAP->selected == 0) {
625                 cprintf("%s BAD no folder selected\r\n", parms[0]);
626         }
627
628         /* The commands below require the SELECT state on a mailbox */
629
630         else if (!strcasecmp(parms[1], "FETCH")) {
631                 imap_fetch(num_parms, parms);
632         }
633
634         else if ( (!strcasecmp(parms[1], "UID"))
635                 && (!strcasecmp(parms[2], "FETCH")) ) {
636                 imap_uidfetch(num_parms, parms);
637         }
638
639         else if (!strcasecmp(parms[1], "SEARCH")) {
640                 imap_search(num_parms, parms);
641         }
642
643         else if ( (!strcasecmp(parms[1], "UID"))
644                 && (!strcasecmp(parms[2], "SEARCH")) ) {
645                 imap_uidsearch(num_parms, parms);
646         }
647
648         else if (!strcasecmp(parms[1], "CLOSE")) {
649                 imap_close(num_parms, parms);
650         }
651
652         /* End of commands.  If we get here, the command is either invalid
653          * or unimplemented.
654          */
655
656         else {
657                 cprintf("%s BAD command unrecognized\r\n", parms[0]);
658         }
659
660 }
661
662
663
664 /*
665  * This function is called by dynloader.c to register the IMAP module
666  * with the Citadel server.
667  */
668 char *Dynamic_Module_Init(void)
669 {
670         SYM_IMAP = CtdlGetDynamicSymbol();
671         CtdlRegisterServiceHook(config.c_imap_port,
672                                 NULL,
673                                 imap_greeting,
674                                 imap_command_loop);
675         CtdlRegisterSessionHook(imap_cleanup_function, EVT_STOP);
676         return "$Id$";
677 }