]> code.citadel.org Git - citadel.git/blob - citadel/serv_imap.c
* IMAP folder create and rename commands -- don't allow backslashes in
[citadel.git] / citadel / serv_imap.c
1 /*
2  * $Id$ 
3  *
4  * IMAP server for the Citadel/UX system
5  * Copyright (C) 2000-2002 by Art Cancro and others.
6  * This code is released under the terms of the GNU General Public License.
7  *
8  * WARNING: this is a workable implementation, but it could use some
9  * additional tweaking.  Some commands may be implemented incompletely.  The
10  * 'SEARCH' command is not implemented at all.
11  *
12  * WARNING: Mark Crispin is an idiot.  IMAP is the most brain-damaged protocol
13  * you will ever have the profound lack of pleasure to encounter.
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
26 #if TIME_WITH_SYS_TIME
27 # include <sys/time.h>
28 # include <time.h>
29 #else
30 # if HAVE_SYS_TIME_H
31 #  include <sys/time.h>
32 # else
33 #  include <time.h>
34 # endif
35 #endif
36
37 #include <sys/wait.h>
38 #include <ctype.h>
39 #include <string.h>
40 #include <limits.h>
41 #include "citadel.h"
42 #include "server.h"
43 #include "sysdep_decls.h"
44 #include "citserver.h"
45 #include "support.h"
46 #include "config.h"
47 #include "serv_extensions.h"
48 #include "room_ops.h"
49 #include "user_ops.h"
50 #include "policy.h"
51 #include "database.h"
52 #include "msgbase.h"
53 #include "tools.h"
54 #include "internet_addressing.h"
55 #include "serv_imap.h"
56 #include "imap_tools.h"
57 #include "imap_fetch.h"
58 #include "imap_search.h"
59 #include "imap_store.h"
60 #include "imap_misc.h"
61
62 /* imap_rename() uses this struct containing list of rooms to rename */
63 struct irl {
64         struct irl *next;
65         char irl_oldroom[ROOMNAMELEN];
66         char irl_newroom[ROOMNAMELEN];
67         int irl_newfloor;
68 };
69
70 /* Data which is passed between imap_rename() and imap_rename_backend() */
71 struct irlparms { 
72         char *oldname;
73         char *newname;
74         struct irl **irl;
75 };
76
77 long SYM_IMAP;
78
79
80 /*
81  * If there is a message ID map in memory, free it
82  */
83 void imap_free_msgids(void) {
84         if (IMAP->msgids != NULL) {
85                 phree(IMAP->msgids);
86                 IMAP->msgids = NULL;
87                 IMAP->num_msgs = 0;
88         }
89         if (IMAP->flags != NULL) {
90                 phree(IMAP->flags);
91                 IMAP->flags = NULL;
92         }
93 }
94
95
96 /*
97  * If there is a transmitted message in memory, free it
98  */
99 void imap_free_transmitted_message(void) {
100         if (IMAP->transmitted_message != NULL) {
101                 phree(IMAP->transmitted_message);
102                 IMAP->transmitted_message = NULL;
103                 IMAP->transmitted_length = 0;
104         }
105 }
106
107
108 /*
109  * Set the \\Seen flag for messages which aren't new
110  */
111 void imap_set_seen_flags(void) {
112         struct visit vbuf;
113         int i;
114
115         CtdlGetRelationship(&vbuf, &CC->usersupp, &CC->quickroom);
116         if (IMAP->num_msgs > 0) {
117                 for (i=0; i<IMAP->num_msgs; ++i) {
118                         if (is_msg_in_mset(vbuf.v_seen, IMAP->msgids[i])) {
119                                 IMAP->flags[i] |= IMAP_SEEN;
120                         }
121                 }
122         }
123 }
124
125
126
127
128 /*
129  * Back end for imap_load_msgids()
130  *
131  * Optimization: instead of calling realloc() to add each message, we
132  * allocate space in the list for REALLOC_INCREMENT messages at a time.  This
133  * allows the mapping to proceed much faster.
134  */
135 void imap_add_single_msgid(long msgnum, void *userdata) {
136         
137         IMAP->num_msgs = IMAP->num_msgs + 1;
138         if (IMAP->msgids == NULL) {
139                 IMAP->msgids = mallok(IMAP->num_msgs * sizeof(long)
140                                         * REALLOC_INCREMENT);
141         }
142         else if (IMAP->num_msgs % REALLOC_INCREMENT == 0) {
143                 IMAP->msgids = reallok(IMAP->msgids,
144                         (IMAP->num_msgs + REALLOC_INCREMENT) * sizeof(long));
145         }
146         if (IMAP->flags == NULL) {
147                 IMAP->flags = mallok(IMAP->num_msgs * sizeof(long)
148                                         * REALLOC_INCREMENT);
149         }
150         else if (IMAP->num_msgs % REALLOC_INCREMENT == 0) {
151                 IMAP->flags = reallok(IMAP->flags,
152                         (IMAP->num_msgs + REALLOC_INCREMENT) * sizeof(long));
153         }
154         IMAP->msgids[IMAP->num_msgs - 1] = msgnum;
155         IMAP->flags[IMAP->num_msgs - 1] = 0;
156 }
157
158
159
160 /*
161  * Set up a message ID map for the current room (folder)
162  */
163 void imap_load_msgids(void) {
164          
165         if (IMAP->selected == 0) {
166                 lprintf(5, "imap_load_msgids() can't run; no room selected\n");
167                 return;
168         }
169
170         imap_free_msgids();     /* If there was already a map, free it */
171
172         CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL,
173                 imap_add_single_msgid, NULL);
174
175         imap_set_seen_flags();
176         lprintf(9, "imap_load_msgids() mapped %d messages\n", IMAP->num_msgs);
177 }
178
179
180 /*
181  * Re-scan the selected room (folder) and see if it's been changed at all
182  */
183 void imap_rescan_msgids(void) {
184
185         int original_num_msgs = 0;
186         long original_highest = 0L;
187         int i, j;
188         int message_still_exists;
189         struct cdbdata *cdbfr;
190         long *msglist = NULL;
191         int num_msgs = 0;
192
193
194         if (IMAP->selected == 0) {
195                 lprintf(5, "imap_load_msgids() can't run; no room selected\n");
196                 return;
197         }
198
199         /* Load the *current* message list from disk, so we can compare it
200          * to what we have in memory.
201          */
202         cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->quickroom.QRnumber, sizeof(long));
203         if (cdbfr != NULL) {
204                 msglist = mallok(cdbfr->len);
205                 memcpy(msglist, cdbfr->ptr, cdbfr->len);
206                 num_msgs = cdbfr->len / sizeof(long);
207                 cdb_free(cdbfr);
208         }
209         else {
210                 num_msgs = 0;
211         }
212
213         /*
214          * Check to see if any of the messages we know about have been expunged
215          */
216         if (IMAP->num_msgs > 0)
217          for (i=0; i<IMAP->num_msgs; ++i) {
218
219                 message_still_exists = 0;
220                 if (num_msgs > 0) for (j = 0; j < num_msgs; ++j) {
221                         if (msglist[j] == IMAP->msgids[i]) {
222                                 message_still_exists = 1;
223                         }
224                 }
225
226                 if (message_still_exists == 0) {
227                         cprintf("* %d EXPUNGE\r\n", i+1);
228
229                         /* Here's some nice stupid nonsense.  When a message
230                          * is expunged, we have to slide all the existing
231                          * messages up in the message array.
232                          */
233                         --IMAP->num_msgs;
234                         memcpy(&IMAP->msgids[i], &IMAP->msgids[i+1],
235                                 (sizeof(long)*(IMAP->num_msgs-i)) );
236                         memcpy(&IMAP->flags[i], &IMAP->flags[i+1],
237                                 (sizeof(long)*(IMAP->num_msgs-i)) );
238
239                         --i;
240                 }
241
242         }
243
244         /*
245          * Remember how many messages were here before we re-scanned.
246          */
247         original_num_msgs = IMAP->num_msgs;
248         if (IMAP->num_msgs > 0) {
249                 original_highest = IMAP->msgids[IMAP->num_msgs - 1];
250         }
251         else {
252                 original_highest = 0L;
253         }
254
255         /*
256          * Now peruse the room for *new* messages only.
257          */
258         if (num_msgs > 0) for (j=0; j<num_msgs; ++j) {
259                 if (msglist[j] > original_highest) {
260                         imap_add_single_msgid(msglist[j], NULL);
261                 }
262         }
263         imap_set_seen_flags();
264
265         /*
266          * If new messages have arrived, tell the client about them.
267          */
268         if (IMAP->num_msgs > original_num_msgs) {
269                 cprintf("* %d EXISTS\r\n", IMAP->num_msgs);
270         }
271
272         if (num_msgs != 0) phree(msglist);
273 }
274
275
276
277
278
279
280
281 /*
282  * This cleanup function blows away the temporary memory and files used by
283  * the IMAP server.
284  */
285 void imap_cleanup_function(void) {
286
287         /* Don't do this stuff if this is not a IMAP session! */
288         if (CC->h_command_function != imap_command_loop) return;
289
290         lprintf(9, "Performing IMAP cleanup hook\n");
291         imap_free_msgids();
292         imap_free_transmitted_message();
293         lprintf(9, "Finished IMAP cleanup hook\n");
294 }
295
296
297
298 /*
299  * Here's where our IMAP session begins its happy day.
300  */
301 void imap_greeting(void) {
302
303         strcpy(CC->cs_clientname, "IMAP session");
304         CtdlAllocUserData(SYM_IMAP, sizeof(struct citimap));
305         IMAP->authstate = imap_as_normal;
306
307         cprintf("* OK %s Citadel/UX IMAP4rev1 server ready\r\n",
308                 config.c_fqdn);
309 }
310
311
312 /*
313  * implements the LOGIN command (ordinary username/password login)
314  */
315 void imap_login(int num_parms, char *parms[]) {
316         if (CtdlLoginExistingUser(parms[2]) == login_ok) {
317                 if (CtdlTryPassword(parms[3]) == pass_ok) {
318                         cprintf("%s OK login successful\r\n", parms[0]);
319                         return;
320                 }
321         }
322
323         cprintf("%s BAD Login incorrect\r\n", parms[0]);
324 }
325
326
327 /*
328  * Implements the AUTHENTICATE command
329  */
330 void imap_authenticate(int num_parms, char *parms[]) {
331         char buf[SIZ];
332
333         if (num_parms != 3) {
334                 cprintf("%s BAD incorrect number of parameters\r\n", parms[0]);
335                 return;
336         }
337
338         if (!strcasecmp(parms[2], "LOGIN")) {
339                 CtdlEncodeBase64(buf, "Username:", 9);
340                 cprintf("+ %s\r\n", buf);
341                 IMAP->authstate = imap_as_expecting_username;
342                 strcpy(IMAP->authseq, parms[0]);
343                 return;
344         }
345
346         else {
347                 cprintf("%s NO AUTHENTICATE %s failed\r\n",
348                         parms[0], parms[1]);
349         }
350 }
351
352 void imap_auth_login_user(char *cmd) {
353         char buf[SIZ];
354
355         CtdlDecodeBase64(buf, cmd, SIZ);
356         CtdlLoginExistingUser(buf);
357         CtdlEncodeBase64(buf, "Password:", 9);
358         cprintf("+ %s\r\n", buf);
359         IMAP->authstate = imap_as_expecting_password;
360         return;
361 }
362
363 void imap_auth_login_pass(char *cmd) {
364         char buf[SIZ];
365
366         CtdlDecodeBase64(buf, cmd, SIZ);
367         if (CtdlTryPassword(buf) == pass_ok) {
368                 cprintf("%s OK authentication succeeded\r\n", IMAP->authseq);
369         }
370         else {
371                 cprintf("%s NO authentication failed\r\n", IMAP->authseq);
372         }
373         IMAP->authstate = imap_as_normal;
374         return;
375 }
376
377
378
379 /*
380  * implements the CAPABILITY command
381  */
382 void imap_capability(int num_parms, char *parms[]) {
383         cprintf("* CAPABILITY IMAP4 IMAP4REV1 AUTH=LOGIN\r\n");
384         cprintf("%s OK CAPABILITY completed\r\n", parms[0]);
385 }
386
387
388
389
390
391 /*
392  * implements the SELECT command
393  */
394 void imap_select(int num_parms, char *parms[]) {
395         char towhere[SIZ];
396         char augmented_roomname[ROOMNAMELEN];
397         int c = 0;
398         int ok = 0;
399         int ra = 0;
400         struct quickroom QRscratch;
401         int msgs, new;
402         int floornum;
403         int roomflags;
404         int i;
405
406         /* Convert the supplied folder name to a roomname */
407         i = imap_roomname(towhere, sizeof towhere, parms[2]);
408         if (i < 0) {
409                 cprintf("%s NO Invalid mailbox name.\r\n", parms[0]);
410                 IMAP->selected = 0;
411                 return;
412         }
413         floornum = (i & 0x00ff);
414         roomflags = (i & 0xff00);
415
416         /* First try a regular match */
417         c = getroom(&QRscratch, towhere);
418
419         /* Then try a mailbox name match */
420         if (c != 0) {
421                 MailboxName(augmented_roomname, sizeof augmented_roomname,
422                             &CC->usersupp, towhere);
423                 c = getroom(&QRscratch, augmented_roomname);
424                 if (c == 0)
425                         strcpy(towhere, augmented_roomname);
426         }
427
428         /* If the room exists, check security/access */
429         if (c == 0) {
430                 /* See if there is an existing user/room relationship */
431                 ra = CtdlRoomAccess(&QRscratch, &CC->usersupp);
432
433                 /* normal clients have to pass through security */
434                 if (ra & UA_KNOWN) {
435                         ok = 1;
436                 }
437         }
438
439         /* Fail here if no such room */
440         if (!ok) {
441                 cprintf("%s NO ... no such room, or access denied\r\n",
442                         parms[0]);
443                 IMAP->selected = 0;
444                 return;
445         }
446
447         /*
448          * usergoto() formally takes us to the desired room, happily returning
449          * the number of messages and number of new messages.
450          */
451         memcpy(&CC->quickroom, &QRscratch, sizeof(struct quickroom));
452         usergoto(NULL, 0, 0, &msgs, &new);
453         IMAP->selected = 1;
454
455         if (!strcasecmp(parms[1], "EXAMINE")) {
456                 IMAP->readonly = 1;
457         }
458         else {
459                 IMAP->readonly = 0;
460         }
461
462         imap_load_msgids();
463
464         /* FIXME ... much more info needs to be supplied here */
465         cprintf("* %d EXISTS\r\n", msgs);
466         cprintf("* %d RECENT\r\n", new);
467         cprintf("* FLAGS (\\Deleted \\Seen)\r\n");
468         cprintf("* OK [PERMANENTFLAGS (\\Deleted \\Seen)] permanent flags\r\n");
469         cprintf("* OK [UIDVALIDITY 0] UIDs valid\r\n");
470         cprintf("%s OK [%s] %s completed\r\n",
471                 parms[0],
472                 (IMAP->readonly ? "READ-ONLY" : "READ-WRITE"),
473                 parms[1]);
474 }
475
476
477
478 /*
479  * does the real work for expunge
480  */
481 int imap_do_expunge(void) {
482         int i;
483         int num_expunged = 0;
484
485         if (IMAP->num_msgs > 0) for (i=0; i<IMAP->num_msgs; ++i) {
486                 if (IMAP->flags[i] & IMAP_DELETED) {
487                         CtdlDeleteMessages(CC->quickroom.QRname,
488                                         IMAP->msgids[i], "");
489                         ++num_expunged;
490                         lprintf(9, "%ld ... deleted\n", IMAP->msgids[i]);
491                 }
492                 else {
493                         lprintf(9, "%ld ... not deleted\n", IMAP->msgids[i]);
494                 }
495         }
496
497         if (num_expunged > 0) {
498                 imap_rescan_msgids();
499         }
500
501         return(num_expunged);
502 }
503
504
505 /*
506  * implements the EXPUNGE command syntax
507  */
508 void imap_expunge(int num_parms, char *parms[]) {
509         int num_expunged = 0;
510
511         num_expunged = imap_do_expunge();
512         cprintf("%s OK expunged %d messages.\r\n", parms[0], num_expunged);
513 }
514
515
516 /*
517  * implements the CLOSE command
518  */
519 void imap_close(int num_parms, char *parms[]) {
520
521         /* Yes, we always expunge on close. */
522         imap_do_expunge();
523
524         IMAP->selected = 0;
525         IMAP->readonly = 0;
526         imap_free_msgids();
527         cprintf("%s OK CLOSE completed\r\n", parms[0]);
528 }
529
530
531
532
533 /*
534  * Used by LIST and LSUB to show the floors in the listing
535  */
536 void imap_list_floors(char *cmd, char *pattern) {
537         int i;
538         struct floor *fl;
539
540         for (i=0; i<MAXFLOORS; ++i) {
541                 fl = cgetfloor(i);
542                 if (fl->f_flags & F_INUSE) {
543                         if (imap_mailbox_matches_pattern(pattern, fl->f_name)) {
544                                 cprintf("* %s (\\NoSelect) \"|\" ", cmd);
545                                 imap_strout(fl->f_name);
546                                 cprintf("\r\n");
547                         }
548                 }
549         }
550 }
551
552
553
554 /*
555  * Back end for imap_lsub()
556  *
557  * IMAP "subscribed folder" is equivocated to Citadel "known rooms."  This
558  * may or may not be the desired behavior in the future.
559  */
560 void imap_lsub_listroom(struct quickroom *qrbuf, void *data) {
561         char buf[SIZ];
562         int ra;
563         char *pattern;
564
565         pattern = (char *)data;
566
567         /* Only list rooms to which the user has access!! */
568         ra = CtdlRoomAccess(qrbuf, &CC->usersupp);
569         if (ra & UA_KNOWN) {
570                 imap_mailboxname(buf, sizeof buf, qrbuf);
571                 if (imap_mailbox_matches_pattern(pattern, buf)) {
572                         cprintf("* LSUB () \"|\" ");
573                         imap_strout(buf);
574                         cprintf("\r\n");
575                 }
576         }
577 }
578
579
580 /*
581  * Implements the LSUB command
582  */
583 void imap_lsub(int num_parms, char *parms[]) {
584         char pattern[SIZ];
585         if (num_parms < 4) {
586                 cprintf("%s BAD arguments invalid\r\n", parms[0]);
587                 return;
588         }
589         snprintf(pattern, sizeof pattern, "%s%s", parms[2], parms[3]);
590
591         if (strlen(parms[3])==0) {
592                 cprintf("* LIST (\\Noselect) \"|\" \"\"\r\n");
593         }
594
595         else {
596                 imap_list_floors("LSUB", pattern);
597                 ForEachRoom(imap_lsub_listroom, pattern);
598         }
599
600         cprintf("%s OK LSUB completed\r\n", parms[0]);
601 }
602
603
604
605 /*
606  * Back end for imap_list()
607  */
608 void imap_list_listroom(struct quickroom *qrbuf, void *data) {
609         char buf[SIZ];
610         int ra;
611         char *pattern;
612
613         pattern = (char *)data;
614
615         /* Only list rooms to which the user has access!! */
616         ra = CtdlRoomAccess(qrbuf, &CC->usersupp);
617         if ( (ra & UA_KNOWN) 
618           || ((ra & UA_GOTOALLOWED) && (ra & UA_ZAPPED))) {
619                 imap_mailboxname(buf, sizeof buf, qrbuf);
620                 if (imap_mailbox_matches_pattern(pattern, buf)) {
621                         cprintf("* LIST () \"|\" ");
622                         imap_strout(buf);
623                         cprintf("\r\n");
624                 }
625         }
626 }
627
628
629 /*
630  * Implements the LIST command
631  */
632 void imap_list(int num_parms, char *parms[]) {
633         char pattern[SIZ];
634         if (num_parms < 4) {
635                 cprintf("%s BAD arguments invalid\r\n", parms[0]);
636                 return;
637         }
638         snprintf(pattern, sizeof pattern, "%s%s", parms[2], parms[3]);
639
640         if (strlen(parms[3])==0) {
641                 cprintf("* LIST (\\Noselect) \"|\" \"\"\r\n");
642         }
643
644         else {
645                 imap_list_floors("LIST", pattern);
646                 ForEachRoom(imap_list_listroom, pattern);
647         }
648
649         cprintf("%s OK LIST completed\r\n", parms[0]);
650 }
651
652
653
654 /*
655  * Implements the CREATE command
656  *
657  */
658 void imap_create(int num_parms, char *parms[]) {
659         int ret;
660         char roomname[ROOMNAMELEN];
661         int floornum;
662         int flags;
663         int newroomtype;
664
665         if (strchr(parms[2], '\\') != NULL) {
666                 cprintf("%s NO Invalid character in folder name\r\n", parms[0]);
667                 return;
668         }
669
670         ret = imap_roomname(roomname, sizeof roomname, parms[2]);
671         if (ret < 0) {
672                 cprintf("%s NO Invalid mailbox name or location\r\n",
673                         parms[0]);
674                 return;
675         }
676         floornum = ( ret & 0x00ff );    /* lower 8 bits = floor number */
677         flags =    ( ret & 0xff00 );    /* upper 8 bits = flags        */
678
679         if (flags & IR_MAILBOX) {
680                 newroomtype = 4;        /* private mailbox */
681         }
682         else {
683                 newroomtype = 0;        /* public folder */
684         }
685
686         lprintf(7, "Create new room <%s> on floor <%d> with type <%d>\n",
687                 roomname, floornum, newroomtype);
688
689         ret = create_room(roomname, newroomtype, "", floornum, 1, 0);
690         if (ret == 0) {
691                 cprintf("%s NO Mailbox already exists, or create failed\r\n",
692                         parms[0]);
693         }
694         else {
695                 cprintf("%s OK CREATE completed\r\n", parms[0]);
696         }
697 }
698
699
700 /*
701  * Locate a room by its IMAP folder name, and check access to it
702  */
703 int imap_grabroom(char *returned_roomname, char *foldername) {
704         int ret;
705         char augmented_roomname[ROOMNAMELEN];
706         char roomname[ROOMNAMELEN];
707         int c;
708         struct quickroom QRscratch;
709         int ra;
710         int ok = 0;
711
712         ret = imap_roomname(roomname, sizeof roomname, foldername);
713         if (ret < 0) {
714                 return(1);
715         }
716
717         /* First try a regular match */
718         c = getroom(&QRscratch, roomname);
719
720         /* Then try a mailbox name match */
721         if (c != 0) {
722                 MailboxName(augmented_roomname, sizeof augmented_roomname,
723                             &CC->usersupp, roomname);
724                 c = getroom(&QRscratch, augmented_roomname);
725                 if (c == 0)
726                         strcpy(roomname, augmented_roomname);
727         }
728
729         /* If the room exists, check security/access */
730         if (c == 0) {
731                 /* See if there is an existing user/room relationship */
732                 ra = CtdlRoomAccess(&QRscratch, &CC->usersupp);
733
734                 /* normal clients have to pass through security */
735                 if (ra & UA_KNOWN) {
736                         ok = 1;
737                 }
738         }
739
740         /* Fail here if no such room */
741         if (!ok) {
742                 strcpy(returned_roomname, "");
743                 return(2);
744         }
745         else {
746                 strcpy(returned_roomname, QRscratch.QRname);
747                 return(0);
748         }
749 }
750
751
752 /*
753  * Implements the STATUS command (sort of)
754  *
755  */
756 void imap_status(int num_parms, char *parms[]) {
757         int ret;
758         char roomname[ROOMNAMELEN];
759         char buf[SIZ];
760         char savedroom[ROOMNAMELEN];
761         int msgs, new;
762
763         ret = imap_grabroom(roomname, parms[2]);
764         if (ret != 0) {
765                 cprintf("%s NO Invalid mailbox name or location, or access denied\r\n",
766                         parms[0]);
767                 return;
768         }
769
770         /*
771          * usergoto() formally takes us to the desired room, happily returning
772          * the number of messages and number of new messages.  (If another
773          * folder is selected, save its name so we can return there!!!!!)
774          */
775         if (IMAP->selected) {
776                 strcpy(savedroom, CC->quickroom.QRname);
777         }
778         usergoto(roomname, 0, 0, &msgs, &new);
779
780         /*
781          * Tell the client what it wants to know.  In fact, tell it *more* than
782          * it wants to know.  We happily IGnore the supplied status data item
783          * names and simply spew all possible data items.  It's far easier to
784          * code and probably saves us some processing time too.
785          */
786         imap_mailboxname(buf, sizeof buf, &CC->quickroom);
787         cprintf("* STATUS ");
788         imap_strout(buf);
789         cprintf(" (MESSAGES %d ", msgs);
790         cprintf("RECENT 0 ");   /* FIXME we need to implement this */
791         cprintf("UIDNEXT %ld ", CitControl.MMhighest + 1);
792         cprintf("UNSEEN %d)\r\n", new);
793
794         /*
795          * If another folder is selected, go back to that room so we can resume
796          * our happy day without violent explosions.
797          */
798         if (IMAP->selected) {
799                 usergoto(savedroom, 0, 0, &msgs, &new);
800         }
801
802         /*
803          * Oooh, look, we're done!
804          */
805         cprintf("%s OK STATUS completed\r\n", parms[0]);
806 }
807
808
809
810 /*
811  * Implements the SUBSCRIBE command
812  *
813  */
814 void imap_subscribe(int num_parms, char *parms[]) {
815         int ret;
816         char roomname[ROOMNAMELEN];
817         char savedroom[ROOMNAMELEN];
818         int msgs, new;
819
820         ret = imap_grabroom(roomname, parms[2]);
821         if (ret != 0) {
822                 cprintf("%s NO Invalid mailbox name or location, or access denied\r\n",
823                         parms[0]);
824                 return;
825         }
826
827         /*
828          * usergoto() formally takes us to the desired room, which has the side
829          * effect of marking the room as not-zapped ... exactly the effect
830          * we're looking for.
831          */
832         if (IMAP->selected) {
833                 strcpy(savedroom, CC->quickroom.QRname);
834         }
835         usergoto(roomname, 0, 0, &msgs, &new);
836
837         /*
838          * If another folder is selected, go back to that room so we can resume
839          * our happy day without violent explosions.
840          */
841         if (IMAP->selected) {
842                 usergoto(savedroom, 0, 0, &msgs, &new);
843         }
844
845         cprintf("%s OK SUBSCRIBE completed\r\n", parms[0]);
846 }
847
848
849 /*
850  * Implements the UNSUBSCRIBE command
851  *
852  */
853 void imap_unsubscribe(int num_parms, char *parms[]) {
854         int ret;
855         char roomname[ROOMNAMELEN];
856         char savedroom[ROOMNAMELEN];
857         int msgs, new;
858
859         ret = imap_grabroom(roomname, parms[2]);
860         if (ret != 0) {
861                 cprintf("%s NO Invalid mailbox name or location, or access denied\r\n",
862                         parms[0]);
863                 return;
864         }
865
866         /*
867          * usergoto() formally takes us to the desired room.
868          */
869         if (IMAP->selected) {
870                 strcpy(savedroom, CC->quickroom.QRname);
871         }
872         usergoto(roomname, 0, 0, &msgs, &new);
873
874         /* 
875          * Now make the API call to zap the room
876          */
877         if (CtdlForgetThisRoom() == 0) {
878                 cprintf("%s OK UNSUBSCRIBE completed\r\n", parms[0]);
879         }
880         else {
881                 cprintf("%s NO You may not unsubscribe from this folder.\r\n",
882                         parms[0]);
883         }
884
885         /*
886          * If another folder is selected, go back to that room so we can resume
887          * our happy day without violent explosions.
888          */
889         if (IMAP->selected) {
890                 usergoto(savedroom, 0, 0, &msgs, &new);
891         }
892 }
893
894
895
896 /*
897  * Implements the DELETE command
898  *
899  */
900 void imap_delete(int num_parms, char *parms[]) {
901         int ret;
902         char roomname[ROOMNAMELEN];
903         char savedroom[ROOMNAMELEN];
904         int msgs, new;
905
906         ret = imap_grabroom(roomname, parms[2]);
907         if (ret != 0) {
908                 cprintf("%s NO Invalid mailbox name, or access denied\r\n",
909                         parms[0]);
910                 return;
911         }
912
913         /*
914          * usergoto() formally takes us to the desired room, happily returning
915          * the number of messages and number of new messages.  (If another
916          * folder is selected, save its name so we can return there!!!!!)
917          */
918         if (IMAP->selected) {
919                 strcpy(savedroom, CC->quickroom.QRname);
920         }
921         usergoto(roomname, 0, 0, &msgs, &new);
922
923         /*
924          * Now delete the room.
925          */
926         if (CtdlDoIHavePermissionToDeleteThisRoom(&CC->quickroom)) {
927                 cprintf("%s OK DELETE completed\r\n", parms[0]);
928                 delete_room(&CC->quickroom);
929         }
930         else {
931                 cprintf("%s NO Can't delete this folder.\r\n", parms[0]);
932         }
933
934         /*
935          * If another folder is selected, go back to that room so we can resume
936          * our happy day without violent explosions.
937          */
938         if (IMAP->selected) {
939                 usergoto(savedroom, 0, 0, &msgs, &new);
940         }
941 }
942
943
944 /*
945  * Back end function for imap_rename()
946  */
947 void imap_rename_backend(struct quickroom *qrbuf, void *data) {
948         char foldername[SIZ];
949         char newfoldername[SIZ];
950         char newroomname[ROOMNAMELEN];
951         int newfloor = 0;
952         struct irl *irlp = NULL;        /* scratch pointer */
953         struct irlparms *irlparms;
954
955         irlparms = (struct irlparms *)data;
956         imap_mailboxname(foldername, sizeof foldername, qrbuf);
957
958         /* Rename subfolders */
959         if ( (!strncasecmp(foldername, irlparms->oldname,
960            strlen(irlparms->oldname))
961            && (foldername[strlen(irlparms->oldname)] == '|')) ) {
962
963                 sprintf(newfoldername, "%s|%s",
964                         irlparms->newname,
965                         &foldername[strlen(irlparms->oldname)+1]
966                 );
967
968                 newfloor = imap_roomname(newroomname,
969                         sizeof newroomname, newfoldername) & 0xFF;
970
971                 irlp = (struct irl *) mallok(sizeof(struct irl));
972                 strcpy(irlp->irl_newroom, newroomname);
973                 strcpy(irlp->irl_oldroom, qrbuf->QRname);
974                 irlp->irl_newfloor = newfloor;
975                 irlp->next = *(irlparms->irl);
976                 *(irlparms->irl) = irlp;
977         }
978 }
979         
980
981 /*
982  * Implements the RENAME command
983  *
984  */
985 void imap_rename(int num_parms, char *parms[]) {
986         char old_room[ROOMNAMELEN];
987         char new_room[ROOMNAMELEN];
988         int oldr, newr;
989         int new_floor;
990         int r;
991         struct irl *irl = NULL;         /* the list */
992         struct irl *irlp = NULL;        /* scratch pointer */
993         struct irlparms irlparms;
994
995         if (strchr(parms[3], '\\') != NULL) {
996                 cprintf("%s NO Invalid character in folder name\r\n", parms[0]);
997                 return;
998         }
999
1000         oldr = imap_roomname(old_room, sizeof old_room, parms[2]);
1001         newr = imap_roomname(new_room, sizeof new_room, parms[3]);
1002         new_floor = (newr & 0xFF);
1003
1004         r = CtdlRenameRoom(old_room, new_room, new_floor);
1005
1006         if (r == crr_room_not_found) {
1007                 cprintf("%s NO Could not locate this folder\r\n", parms[0]);
1008                 return;
1009         }
1010         if (r == crr_already_exists) {
1011                 cprintf("%s '%s' already exists.\r\n", parms[0], parms[2]);
1012                 return;
1013         }
1014         if (r == crr_noneditable) {
1015                 cprintf("%s This folder is not editable.\r\n", parms[0]);
1016                 return;
1017         }
1018         if (r == crr_invalid_floor) {
1019                 cprintf("%s Folder root does not exist.\r\n", parms[0]);
1020                 return;
1021         }
1022         if (r == crr_access_denied) {
1023                 cprintf("%s You do not have permission to edit "
1024                         "this folder.\r\n", parms[0]);
1025                 return;
1026         }
1027         if (r != crr_ok) {
1028                 cprintf("%s NO Rename failed - undefined error %d\r\n",
1029                         parms[0], r);
1030                 return;
1031         }
1032
1033
1034         /* If this is the INBOX, then RFC2060 says we have to just move the
1035          * contents.  In a Citadel environment it's easier to rename the room
1036          * (already did that) and create a new inbox.
1037          */
1038         if (!strcasecmp(parms[2], "INBOX")) {
1039                 create_room(MAILROOM, 4, "", 0, 1, 0);
1040         }
1041
1042         /* Otherwise, do the subfolders.  Build a list of rooms to rename... */
1043         else {
1044                 irlparms.oldname = parms[2];
1045                 irlparms.newname = parms[3];
1046                 irlparms.irl = &irl;
1047                 ForEachRoom(imap_rename_backend, (void *)&irlparms);
1048
1049                 /* ... and now rename them. */
1050                 while (irl != NULL) {
1051                         r = CtdlRenameRoom(irl->irl_oldroom,
1052                                 irl->irl_newroom, irl->irl_newfloor);
1053                         if (r != crr_ok) {
1054                                 /* FIXME handle error returns better */
1055                                 lprintf(5, "CtdlRenameRoom() error %d\n", r);
1056                         }
1057                         irlp = irl;
1058                         irl = irl->next;
1059                         phree(irlp);
1060                 }
1061         }
1062
1063         cprintf("%s OK RENAME completed\r\n", parms[0]);
1064 }
1065
1066
1067
1068
1069 /* 
1070  * Main command loop for IMAP sessions.
1071  */
1072 void imap_command_loop(void) {
1073         char cmdbuf[SIZ];
1074         char *parms[SIZ];
1075         int num_parms;
1076
1077         time(&CC->lastcmd);
1078         memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
1079         if (client_gets(cmdbuf) < 1) {
1080                 lprintf(3, "IMAP socket is broken.  Ending session.\r\n");
1081                 CC->kill_me = 1;
1082                 return;
1083         }
1084
1085         lprintf(5, "IMAP: %s\r\n", cmdbuf);
1086         while (strlen(cmdbuf) < 5) strcat(cmdbuf, " ");
1087
1088
1089         /* strip off l/t whitespace and CRLF */
1090         if (cmdbuf[strlen(cmdbuf)-1]=='\n') cmdbuf[strlen(cmdbuf)-1]=0;
1091         if (cmdbuf[strlen(cmdbuf)-1]=='\r') cmdbuf[strlen(cmdbuf)-1]=0;
1092         striplt(cmdbuf);
1093
1094         /* If we're in the middle of a multi-line command, handle that */
1095         if (IMAP->authstate == imap_as_expecting_username) {
1096                 imap_auth_login_user(cmdbuf);
1097                 return;
1098         }
1099         if (IMAP->authstate == imap_as_expecting_password) {
1100                 imap_auth_login_pass(cmdbuf);
1101                 return;
1102         }
1103
1104
1105         /* Ok, at this point we're in normal command mode.  The first thing
1106          * we do is print any incoming pages (yeah! we really do!)
1107          */
1108         imap_print_express_messages();
1109
1110         /*
1111          * Before processing the command that was just entered... if we happen
1112          * to have a folder selected, we'd like to rescan that folder for new
1113          * messages, and for deletions/changes of existing messages.  This
1114          * could probably be optimized somehow, but IMAP sucks...
1115          */
1116         if (IMAP->selected) {
1117                 imap_rescan_msgids();
1118         }
1119
1120         /* Now for the command set. */
1121
1122         /* Grab the tag, command, and parameters.  Check syntax. */
1123         num_parms = imap_parameterize(parms, cmdbuf);
1124         if (num_parms < 2) {
1125                 cprintf("BAD syntax error\r\n");
1126         }
1127
1128         /* The commands below may be executed in any state */
1129
1130         else if ( (!strcasecmp(parms[1], "NOOP"))
1131            || (!strcasecmp(parms[1], "CHECK")) ) {
1132                 cprintf("%s OK This command successfully did nothing.\r\n",
1133                         parms[0]);
1134         }
1135
1136         else if (!strcasecmp(parms[1], "LOGOUT")) {
1137                 cprintf("* BYE %s logging out\r\n", config.c_fqdn);
1138                 cprintf("%s OK thank you for using Citadel IMAP\r\n", parms[0]);
1139                 CC->kill_me = 1;
1140                 return;
1141         }
1142
1143         else if (!strcasecmp(parms[1], "LOGIN")) {
1144                 imap_login(num_parms, parms);
1145         }
1146
1147         else if (!strcasecmp(parms[1], "AUTHENTICATE")) {
1148                 imap_authenticate(num_parms, parms);
1149         }
1150
1151         else if (!strcasecmp(parms[1], "CAPABILITY")) {
1152                 imap_capability(num_parms, parms);
1153         }
1154
1155         else if (!CC->logged_in) {
1156                 cprintf("%s BAD Not logged in.\r\n", parms[0]);
1157         }
1158
1159         /* The commans below require a logged-in state */
1160
1161         else if (!strcasecmp(parms[1], "SELECT")) {
1162                 imap_select(num_parms, parms);
1163         }
1164
1165         else if (!strcasecmp(parms[1], "EXAMINE")) {
1166                 imap_select(num_parms, parms);
1167         }
1168
1169         else if (!strcasecmp(parms[1], "LSUB")) {
1170                 imap_lsub(num_parms, parms);
1171         }
1172
1173         else if (!strcasecmp(parms[1], "LIST")) {
1174                 imap_list(num_parms, parms);
1175         }
1176
1177         else if (!strcasecmp(parms[1], "CREATE")) {
1178                 imap_create(num_parms, parms);
1179         }
1180
1181         else if (!strcasecmp(parms[1], "DELETE")) {
1182                 imap_delete(num_parms, parms);
1183         }
1184
1185         else if (!strcasecmp(parms[1], "RENAME")) {
1186                 imap_rename(num_parms, parms);
1187         }
1188
1189         else if (!strcasecmp(parms[1], "STATUS")) {
1190                 imap_status(num_parms, parms);
1191         }
1192
1193         else if (!strcasecmp(parms[1], "SUBSCRIBE")) {
1194                 imap_subscribe(num_parms, parms);
1195         }
1196
1197         else if (!strcasecmp(parms[1], "UNSUBSCRIBE")) {
1198                 imap_unsubscribe(num_parms, parms);
1199         }
1200
1201         else if (!strcasecmp(parms[1], "APPEND")) {
1202                 imap_append(num_parms, parms);
1203         }
1204
1205         else if (IMAP->selected == 0) {
1206                 cprintf("%s BAD no folder selected\r\n", parms[0]);
1207         }
1208
1209         /* The commands below require the SELECT state on a mailbox */
1210
1211         else if (!strcasecmp(parms[1], "FETCH")) {
1212                 imap_fetch(num_parms, parms);
1213         }
1214
1215         else if ( (!strcasecmp(parms[1], "UID"))
1216                 && (!strcasecmp(parms[2], "FETCH")) ) {
1217                 imap_uidfetch(num_parms, parms);
1218         }
1219
1220         else if (!strcasecmp(parms[1], "SEARCH")) {
1221                 imap_search(num_parms, parms);
1222         }
1223
1224         else if ( (!strcasecmp(parms[1], "UID"))
1225                 && (!strcasecmp(parms[2], "SEARCH")) ) {
1226                 imap_uidsearch(num_parms, parms);
1227         }
1228
1229         else if (!strcasecmp(parms[1], "STORE")) {
1230                 imap_store(num_parms, parms);
1231         }
1232
1233         else if ( (!strcasecmp(parms[1], "UID"))
1234                 && (!strcasecmp(parms[2], "STORE")) ) {
1235                 imap_uidstore(num_parms, parms);
1236         }
1237
1238         else if (!strcasecmp(parms[1], "COPY")) {
1239                 imap_copy(num_parms, parms);
1240         }
1241
1242         else if ( (!strcasecmp(parms[1], "UID"))
1243                 && (!strcasecmp(parms[2], "COPY")) ) {
1244                 imap_uidcopy(num_parms, parms);
1245         }
1246
1247         else if (!strcasecmp(parms[1], "EXPUNGE")) {
1248                 imap_expunge(num_parms, parms);
1249         }
1250
1251         else if (!strcasecmp(parms[1], "CLOSE")) {
1252                 imap_close(num_parms, parms);
1253         }
1254
1255         /* End of commands.  If we get here, the command is either invalid
1256          * or unimplemented.
1257          */
1258
1259         else {
1260                 cprintf("%s BAD command unrecognized\r\n", parms[0]);
1261         }
1262
1263         /* If the client transmitted a message we can free it now */
1264         imap_free_transmitted_message();
1265 }
1266
1267
1268
1269 /*
1270  * This function is called to register the IMAP extension with Citadel.
1271  */
1272 char *serv_imap_init(void)
1273 {
1274         SYM_IMAP = CtdlGetDynamicSymbol();
1275         CtdlRegisterServiceHook(config.c_imap_port,
1276                                 NULL,
1277                                 imap_greeting,
1278                                 imap_command_loop);
1279         CtdlRegisterSessionHook(imap_cleanup_function, EVT_STOP);
1280         return "$Id$";
1281 }