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