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