]> code.citadel.org Git - citadel.git/blob - citadel/serv_imap.c
* Added a floor listing (complete with \NoSelect flag) to LIST and LSUB
[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
120 /*
121  * This cleanup function blows away the temporary memory and files used by
122  * the IMAP server.
123  */
124 void imap_cleanup_function(void) {
125
126         /* Don't do this stuff if this is not a IMAP session! */
127         if (CC->h_command_function != imap_command_loop) return;
128
129         lprintf(9, "Performing IMAP cleanup hook\n");
130         imap_free_msgids();
131         lprintf(9, "Finished IMAP cleanup hook\n");
132 }
133
134
135
136 /*
137  * Here's where our IMAP session begins its happy day.
138  */
139 void imap_greeting(void) {
140
141         strcpy(CC->cs_clientname, "IMAP session");
142         CtdlAllocUserData(SYM_IMAP, sizeof(struct citimap));
143         IMAP->authstate = imap_as_normal;
144
145         cprintf("* OK %s Citadel/UX IMAP4rev1 server ready\r\n",
146                 config.c_fqdn);
147 }
148
149
150 /*
151  * implements the LOGIN command (ordinary username/password login)
152  */
153 void imap_login(int num_parms, char *parms[]) {
154         if (CtdlLoginExistingUser(parms[2]) == login_ok) {
155                 if (CtdlTryPassword(parms[3]) == pass_ok) {
156                         cprintf("%s OK login successful\r\n", parms[0]);
157                         return;
158                 }
159         }
160
161         cprintf("%s BAD Login incorrect\r\n", parms[0]);
162 }
163
164
165 /*
166  * Implements the AUTHENTICATE command
167  */
168 void imap_authenticate(int num_parms, char *parms[]) {
169         char buf[SIZ];
170
171         if (num_parms != 3) {
172                 cprintf("%s BAD incorrect number of parameters\r\n", parms[0]);
173                 return;
174         }
175
176         if (!strcasecmp(parms[2], "LOGIN")) {
177                 encode_base64(buf, "Username:");
178                 cprintf("+ %s\r\n", buf);
179                 IMAP->authstate = imap_as_expecting_username;
180                 strcpy(IMAP->authseq, parms[0]);
181                 return;
182         }
183
184         else {
185                 cprintf("%s NO AUTHENTICATE %s failed\r\n",
186                         parms[0], parms[1]);
187         }
188 }
189
190 void imap_auth_login_user(char *cmd) {
191         char buf[SIZ];
192
193         decode_base64(buf, cmd);
194         CtdlLoginExistingUser(buf);
195         encode_base64(buf, "Password:");
196         cprintf("+ %s\r\n", buf);
197         IMAP->authstate = imap_as_expecting_password;
198         return;
199 }
200
201 void imap_auth_login_pass(char *cmd) {
202         char buf[SIZ];
203
204         decode_base64(buf, cmd);
205         if (CtdlTryPassword(buf) == pass_ok) {
206                 cprintf("%s OK authentication succeeded\r\n", IMAP->authseq);
207         }
208         else {
209                 cprintf("%s NO authentication failed\r\n", IMAP->authseq);
210         }
211         IMAP->authstate = imap_as_normal;
212         return;
213 }
214
215
216
217 /*
218  * implements the CAPABILITY command
219  */
220 void imap_capability(int num_parms, char *parms[]) {
221         cprintf("* CAPABILITY IMAP4 IMAP4REV1 AUTH=LOGIN\r\n");
222         cprintf("%s OK CAPABILITY completed\r\n", parms[0]);
223 }
224
225
226
227
228
229 /*
230  * implements the SELECT command
231  */
232 void imap_select(int num_parms, char *parms[]) {
233         char towhere[SIZ];
234         char augmented_roomname[SIZ];
235         int c = 0;
236         int ok = 0;
237         int ra = 0;
238         struct quickroom QRscratch;
239         int msgs, new;
240         int floornum;
241         int roomflags;
242         int i;
243
244         /* Convert the supplied folder name to a roomname */
245         i = imap_roomname(towhere, sizeof towhere, parms[2]);
246         if (i < 0) {
247                 cprintf("%s NO Invalid mailbox name.\r\n", parms[0]);
248                 IMAP->selected = 0;
249                 return;
250         }
251         floornum = (i & 0x00ff);
252         roomflags = (i & 0xff00);
253
254         /* First try a regular match */
255         c = getroom(&QRscratch, towhere);
256
257         /* Then try a mailbox name match */
258         if (c != 0) {
259                 MailboxName(augmented_roomname, &CC->usersupp, towhere);
260                 c = getroom(&QRscratch, augmented_roomname);
261                 if (c == 0)
262                         strcpy(towhere, augmented_roomname);
263         }
264
265         /* If the room exists, check security/access */
266         if (c == 0) {
267                 /* See if there is an existing user/room relationship */
268                 ra = CtdlRoomAccess(&QRscratch, &CC->usersupp);
269
270                 /* normal clients have to pass through security */
271                 if (ra & UA_KNOWN) {
272                         ok = 1;
273                 }
274         }
275
276         /* Fail here if no such room */
277         if (!ok) {
278                 cprintf("%s NO ... no such room, or access denied\r\n",
279                         parms[0]);
280                 IMAP->selected = 0;
281                 return;
282         }
283
284         /*
285          * usergoto() formally takes us to the desired room, happily returning
286          * the number of messages and number of new messages.
287          */
288         usergoto(QRscratch.QRname, 0, &msgs, &new);
289         IMAP->selected = 1;
290
291         if (!strcasecmp(parms[1], "EXAMINE")) {
292                 IMAP->readonly = 1;
293         }
294         else {
295                 IMAP->readonly = 0;
296         }
297
298         imap_load_msgids();
299
300         /* FIXME ... much more info needs to be supplied here */
301         cprintf("* %d EXISTS\r\n", msgs);
302         cprintf("* %d RECENT\r\n", new);
303         cprintf("* OK [UIDVALIDITY 0] UIDs valid\r\n");
304         cprintf("%s OK [%s] %s completed\r\n",
305                 parms[0],
306                 (IMAP->readonly ? "READ-ONLY" : "READ-WRITE"),
307                 parms[1]);
308 }
309
310
311
312 /*
313  * implements the CLOSE command
314  */
315 void imap_close(int num_parms, char *parms[]) {
316         IMAP->selected = 0;
317         IMAP->readonly = 0;
318         imap_free_msgids();
319         cprintf("%s OK CLOSE completed\r\n", parms[0]);
320 }
321
322
323
324
325 /*
326  * Used by LIST and LSUB to show the floors in the listing
327  */
328 void imap_list_floors(char *cmd) {
329         int i;
330         struct floor *fl;
331
332         for (i=0; i<MAXFLOORS; ++i) {
333                 fl = cgetfloor(i);
334                 if (fl->f_flags & F_INUSE) {
335                         cprintf("* %s (\\NoSelect) \"|\" ", cmd);
336                         imap_strout(fl->f_name);
337                         cprintf("\r\n");
338                 }
339         }
340 }
341
342
343
344 /*
345  * Back end for imap_lsub()
346  *
347  * IMAP "subscribed folder" is equivocated to Citadel "known rooms."  This
348  * may or may not be the desired behavior in the future.
349  */
350 void imap_lsub_listroom(struct quickroom *qrbuf, void *data) {
351         char buf[SIZ];
352         int ra;
353
354         /* Only list rooms to which the user has access!! */
355         ra = CtdlRoomAccess(qrbuf, &CC->usersupp);
356         if (ra & UA_KNOWN) {
357                 imap_mailboxname(buf, sizeof buf, qrbuf);
358                 cprintf("* LSUB () \"|\" ");
359                 imap_strout(buf);
360                 cprintf("\r\n");
361         }
362 }
363
364
365 /*
366  * Implements the LSUB command
367  *
368  * FIXME: Handle wildcards, please.
369  */
370 void imap_lsub(int num_parms, char *parms[]) {
371         imap_list_floors("LSUB");
372         ForEachRoom(imap_lsub_listroom, NULL);
373         cprintf("%s OK LSUB completed\r\n", parms[0]);
374 }
375
376
377
378 /*
379  * Back end for imap_list()
380  */
381 void imap_list_listroom(struct quickroom *qrbuf, void *data) {
382         char buf[SIZ];
383         int ra;
384
385         /* Only list rooms to which the user has access!! */
386         ra = CtdlRoomAccess(qrbuf, &CC->usersupp);
387         if ( (ra & UA_KNOWN) 
388           || ((ra & UA_GOTOALLOWED) && (ra & UA_ZAPPED))) {
389                 imap_mailboxname(buf, sizeof buf, qrbuf);
390                 cprintf("* LIST () \"|\" ");
391                 imap_strout(buf);
392                 cprintf("\r\n");
393         }
394 }
395
396
397 /*
398  * Implements the LIST command
399  *
400  * FIXME: Handle wildcards, please.
401  */
402 void imap_list(int num_parms, char *parms[]) {
403         imap_list_floors("LIST");
404         ForEachRoom(imap_list_listroom, NULL);
405         cprintf("%s OK LIST completed\r\n", parms[0]);
406 }
407
408
409
410 /*
411  * Implements the CREATE command (FIXME not finished yet)
412  *
413  */
414 void imap_create(int num_parms, char *parms[]) {
415         int ret;
416         char roomname[SIZ];
417         int floornum;
418         int flags;
419         int newroomtype;
420
421         ret = imap_roomname(roomname, sizeof roomname, parms[2]);
422         if (ret < 0) {
423                 cprintf("%s NO Invalid mailbox name or location\r\n",
424                         parms[0]);
425                 return;
426         }
427         floornum = ( ret & 0x00ff );    /* lower 8 bits = floor number */
428         flags =    ( ret & 0xff00 );    /* upper 8 bits = flags        */
429
430         if (flags & IR_MAILBOX) {
431                 newroomtype = 4;        /* private mailbox */
432         }
433         else {
434                 newroomtype = 0;        /* public folder */
435         }
436
437         lprintf(7, "Create new room <%s> on floor <%d> with type <%d>\n",
438                 roomname, floornum, newroomtype);
439
440         ret = create_room(roomname, newroomtype, "", floornum, 1);
441         if (ret == 0) {
442                 cprintf("%s NO Mailbox already exists, or create failed\r\n",
443                         parms[0]);
444         }
445         else {
446                 cprintf("%s OK CREATE completed\r\n", parms[0]);
447         }
448 }
449
450
451
452 /* 
453  * Main command loop for IMAP sessions.
454  */
455 void imap_command_loop(void) {
456         char cmdbuf[SIZ];
457         char *parms[SIZ];
458         int num_parms;
459
460         time(&CC->lastcmd);
461         memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
462         if (client_gets(cmdbuf) < 1) {
463                 lprintf(3, "IMAP socket is broken.  Ending session.\r\n");
464                 CC->kill_me = 1;
465                 return;
466         }
467
468         lprintf(5, "citserver[%3d]: %s\r\n", CC->cs_pid, cmdbuf);
469         while (strlen(cmdbuf) < 5) strcat(cmdbuf, " ");
470
471
472         /* strip off l/t whitespace and CRLF */
473         if (cmdbuf[strlen(cmdbuf)-1]=='\n') cmdbuf[strlen(cmdbuf)-1]=0;
474         if (cmdbuf[strlen(cmdbuf)-1]=='\r') cmdbuf[strlen(cmdbuf)-1]=0;
475         striplt(cmdbuf);
476
477         /* If we're in the middle of a multi-line command, handle that */
478         if (IMAP->authstate == imap_as_expecting_username) {
479                 imap_auth_login_user(cmdbuf);
480                 return;
481         }
482         if (IMAP->authstate == imap_as_expecting_password) {
483                 imap_auth_login_pass(cmdbuf);
484                 return;
485         }
486
487
488         /* Ok, at this point we're in normal command mode */
489
490         /* Grab the tag, command, and parameters.  Check syntax. */
491         num_parms = imap_parameterize(parms, cmdbuf);
492         if (num_parms < 2) {
493                 cprintf("BAD syntax error\r\n");
494         }
495
496         /* The commands below may be executed in any state */
497
498         else if ( (!strcasecmp(parms[1], "NOOP"))
499            || (!strcasecmp(parms[1], "CHECK")) ) {
500                 cprintf("%s OK This command successfully did nothing.\r\n",
501                         parms[0]);
502         }
503
504         else if (!strcasecmp(parms[1], "LOGOUT")) {
505                 cprintf("* BYE %s logging out\r\n", config.c_fqdn);
506                 cprintf("%s OK thank you for using Citadel IMAP\r\n", parms[0]);
507                 CC->kill_me = 1;
508                 return;
509         }
510
511         else if (!strcasecmp(parms[1], "LOGIN")) {
512                 imap_login(num_parms, parms);
513         }
514
515         else if (!strcasecmp(parms[1], "AUTHENTICATE")) {
516                 imap_authenticate(num_parms, parms);
517         }
518
519         else if (!strcasecmp(parms[1], "CAPABILITY")) {
520                 imap_capability(num_parms, parms);
521         }
522
523         else if (!CC->logged_in) {
524                 cprintf("%s BAD Not logged in.\r\n", parms[0]);
525         }
526
527         /* The commans below require a logged-in state */
528
529         else if (!strcasecmp(parms[1], "SELECT")) {
530                 imap_select(num_parms, parms);
531         }
532
533         else if (!strcasecmp(parms[1], "EXAMINE")) {
534                 imap_select(num_parms, parms);
535         }
536
537         else if (!strcasecmp(parms[1], "LSUB")) {
538                 imap_lsub(num_parms, parms);
539         }
540
541         else if (!strcasecmp(parms[1], "LIST")) {
542                 imap_list(num_parms, parms);
543         }
544
545         else if (!strcasecmp(parms[1], "CREATE")) {
546                 imap_create(num_parms, parms);
547         }
548
549         else if (IMAP->selected == 0) {
550                 cprintf("%s BAD no folder selected\r\n", parms[0]);
551         }
552
553         /* The commands below require the SELECT state on a mailbox */
554
555         else if (!strcasecmp(parms[1], "FETCH")) {
556                 imap_fetch(num_parms, parms);
557         }
558
559         else if ( (!strcasecmp(parms[1], "UID"))
560                 && (!strcasecmp(parms[2], "FETCH")) ) {
561                 imap_uidfetch(num_parms, parms);
562         }
563
564         else if (!strcasecmp(parms[1], "SEARCH")) {
565                 imap_search(num_parms, parms);
566         }
567
568         else if ( (!strcasecmp(parms[1], "UID"))
569                 && (!strcasecmp(parms[2], "SEARCH")) ) {
570                 imap_uidsearch(num_parms, parms);
571         }
572
573         else if (!strcasecmp(parms[1], "CLOSE")) {
574                 imap_close(num_parms, parms);
575         }
576
577         /* End of commands.  If we get here, the command is either invalid
578          * or unimplemented.
579          */
580
581         else {
582                 cprintf("%s BAD command unrecognized\r\n", parms[0]);
583         }
584
585 }
586
587
588
589 /*
590  * This function is called by dynloader.c to register the IMAP module
591  * with the Citadel server.
592  */
593 char *Dynamic_Module_Init(void)
594 {
595         SYM_IMAP = CtdlGetDynamicSymbol();
596         CtdlRegisterServiceHook(config.c_imap_port,
597                                 NULL,
598                                 imap_greeting,
599                                 imap_command_loop);
600         CtdlRegisterSessionHook(imap_cleanup_function, EVT_STOP);
601         return "$Id$";
602 }