Displaying incoming instant messages through an IMAP client
[citadel.git] / citadel / modules / imap / imap_misc.c
1 /*
2  * $Id$
3  *
4  *
5  */
6
7
8 #include "sysdep.h"
9 #include <stdlib.h>
10 #include <unistd.h>
11 #include <stdio.h>
12 #include <fcntl.h>
13 #include <signal.h>
14 #include <pwd.h>
15 #include <errno.h>
16 #include <sys/types.h>
17
18 #if TIME_WITH_SYS_TIME
19 # include <sys/time.h>
20 # include <time.h>
21 #else
22 # if HAVE_SYS_TIME_H
23 #  include <sys/time.h>
24 # else
25 #  include <time.h>
26 # endif
27 #endif
28
29 #include <sys/wait.h>
30 #include <ctype.h>
31 #include <string.h>
32 #include <limits.h>
33 #include <libcitadel.h>
34 #include "citadel.h"
35 #include "server.h"
36 #include "sysdep_decls.h"
37 #include "citserver.h"
38 #include "support.h"
39 #include "config.h"
40 #include "room_ops.h"
41 #include "user_ops.h"
42 #include "policy.h"
43 #include "database.h"
44 #include "msgbase.h"
45 #include "internet_addressing.h"
46 #include "serv_imap.h"
47 #include "imap_tools.h"
48 #include "imap_fetch.h"
49 #include "imap_misc.h"
50 #include "genstamp.h"
51 #include "ctdl_module.h"
52
53
54
55
56
57 /*
58  * imap_copy() calls imap_do_copy() to do its actual work, once it's
59  * validated and boiled down the request a bit.  (returns 0 on success)
60  */
61 int imap_do_copy(char *destination_folder) {
62         int i;
63         char roomname[ROOMNAMELEN];
64         struct ctdlroom qrbuf;
65         long *selected_msgs = NULL;
66         int num_selected = 0;
67
68         if (IMAP->num_msgs < 1) {
69                 return(0);
70         }
71
72         i = imap_grabroom(roomname, destination_folder, 0);
73         if (i != 0) return(i);
74
75         /*
76          * Copy all the message pointers in one shot.
77          */
78         selected_msgs = malloc(sizeof(long) * IMAP->num_msgs);
79         if (selected_msgs == NULL) return(-1);
80
81         for (i = 0; i < IMAP->num_msgs; ++i) {
82                 if (IMAP->flags[i] & IMAP_SELECTED) {
83                         selected_msgs[num_selected++] = IMAP->msgids[i];
84                 }
85         }
86
87         if (num_selected > 0) {
88                 CtdlCopyMsgsToRoom(selected_msgs, num_selected, roomname);
89         }
90         free(selected_msgs);
91
92         /* Don't bother wasting any more time if there were no messages. */
93         if (num_selected == 0) {
94                 return(0);
95         }
96
97         /* Enumerate lists of messages for which flags are toggled */
98         long *seen_yes = NULL;
99         int num_seen_yes = 0;
100         long *seen_no = NULL;
101         int num_seen_no = 0;
102         long *answ_yes = NULL;
103         int num_answ_yes = 0;
104         long *answ_no = NULL;
105         int num_answ_no = 0;
106
107         seen_yes = malloc(num_selected * sizeof(long));
108         seen_no = malloc(num_selected * sizeof(long));
109         answ_yes = malloc(num_selected * sizeof(long));
110         answ_no = malloc(num_selected * sizeof(long));
111
112         for (i = 0; i < IMAP->num_msgs; ++i) {
113                 if (IMAP->flags[i] & IMAP_SELECTED) {
114                         if (IMAP->flags[i] & IMAP_SEEN) {
115                                 seen_yes[num_seen_yes++] = IMAP->msgids[i];
116                         }
117                         if ((IMAP->flags[i] & IMAP_SEEN) == 0) {
118                                 seen_no[num_seen_no++] = IMAP->msgids[i];
119                         }
120                         if (IMAP->flags[i] & IMAP_ANSWERED) {
121                                 answ_yes[num_answ_yes++] = IMAP->msgids[i];
122                         }
123                         if ((IMAP->flags[i] & IMAP_ANSWERED) == 0) {
124                                 answ_no[num_answ_no++] = IMAP->msgids[i];
125                         }
126                 }
127         }
128
129         /* Set the flags... */
130         i = getroom(&qrbuf, roomname);
131         if (i == 0) {
132                 CtdlSetSeen(seen_yes, num_seen_yes, 1, ctdlsetseen_seen, NULL, &qrbuf);
133                 CtdlSetSeen(seen_no, num_seen_no, 0, ctdlsetseen_seen, NULL, &qrbuf);
134                 CtdlSetSeen(answ_yes, num_answ_yes, 1, ctdlsetseen_answered, NULL, &qrbuf);
135                 CtdlSetSeen(answ_no, num_answ_no, 0, ctdlsetseen_answered, NULL, &qrbuf);
136         }
137
138         free(seen_yes);
139         free(seen_no);
140         free(answ_yes);
141         free(answ_no);
142
143         return(0);
144 }
145
146
147 /*
148  * Output the [COPYUID xxx yyy] response code required by RFC2359
149  * to tell the client the UID's of the messages that were copied (if any).
150  * We are assuming that the IMAP_SELECTED flag is still set on any relevant
151  * messages in our source room.  Since the Citadel system uses UID's that
152  * are both globally unique and persistent across a room-to-room copy, we
153  * can get this done quite easily.
154  */
155 void imap_output_copyuid_response(void) {
156         int i;
157         int num_output = 0;
158   
159         for (i = 0; i < IMAP->num_msgs; ++i) {
160                 if (IMAP->flags[i] & IMAP_SELECTED) {
161                         ++num_output;
162                         if (num_output == 1) {
163                                 cprintf("[COPYUID ");
164                         }
165                         else if (num_output > 1) {
166                                 cprintf(",");
167                         }
168                         cprintf("%ld", IMAP->msgids[i]);
169                 }
170         }
171         if (num_output > 0) {
172                 cprintf("] ");
173         }
174 }
175
176
177 /*
178  * This function is called by the main command loop.
179  */
180 void imap_copy(int num_parms, char *parms[]) {
181         int ret;
182
183         if (num_parms != 4) {
184                 cprintf("%s BAD invalid parameters\r\n", parms[0]);
185                 return;
186         }
187
188         if (imap_is_message_set(parms[2])) {
189                 imap_pick_range(parms[2], 0);
190         }
191         else {
192                 cprintf("%s BAD invalid parameters\r\n", parms[0]);
193                 return;
194         }
195
196         ret = imap_do_copy(parms[3]);
197         if (!ret) {
198                 cprintf("%s OK ", parms[0]);
199                 imap_output_copyuid_response();
200                 cprintf("COPY completed\r\n");
201         }
202         else {
203                 cprintf("%s NO COPY failed (error %d)\r\n", parms[0], ret);
204         }
205 }
206
207 /*
208  * This function is called by the main command loop.
209  */
210 void imap_uidcopy(int num_parms, char *parms[]) {
211
212         if (num_parms != 5) {
213                 cprintf("%s BAD invalid parameters\r\n", parms[0]);
214                 return;
215         }
216
217         if (imap_is_message_set(parms[3])) {
218                 imap_pick_range(parms[3], 1);
219         }
220         else {
221                 cprintf("%s BAD invalid parameters\r\n", parms[0]);
222                 return;
223         }
224
225         if (imap_do_copy(parms[4]) == 0) {
226                 cprintf("%s OK ", parms[0]);
227                 imap_output_copyuid_response();
228                 cprintf("UID COPY completed\r\n");
229         }
230         else {
231                 cprintf("%s NO UID COPY failed\r\n", parms[0]);
232         }
233 }
234
235
236 /*
237  * imap_do_append_flags() is called by imap_append() to set any flags that
238  * the client specified at append time.
239  *
240  * FIXME find a way to do these in bulk so we don't max out our db journal
241  */
242 void imap_do_append_flags(long new_msgnum, char *new_message_flags) {
243         char flags[32];
244         char this_flag[sizeof flags];
245         int i;
246
247         if (new_message_flags == NULL) return;
248         if (IsEmptyStr(new_message_flags)) return;
249
250         safestrncpy(flags, new_message_flags, sizeof flags);
251
252         for (i=0; i<num_tokens(flags, ' '); ++i) {
253                 extract_token(this_flag, flags, i, ' ', sizeof this_flag);
254                 if (this_flag[0] == '\\') strcpy(this_flag, &this_flag[1]);
255                 if (!strcasecmp(this_flag, "Seen")) {
256                         CtdlSetSeen(&new_msgnum, 1, 1, ctdlsetseen_seen,
257                                 NULL, NULL);
258                 }
259                 if (!strcasecmp(this_flag, "Answered")) {
260                         CtdlSetSeen(&new_msgnum, 1, 1, ctdlsetseen_answered,
261                                 NULL, NULL);
262                 }
263         }
264 }
265
266
267 /*
268  * This function is called by the main command loop.
269  */
270 void imap_append(int num_parms, char *parms[]) {
271         long literal_length;
272         long bytes_transferred;
273         long stripped_length = 0;
274         struct CtdlMessage *msg = NULL;
275         long new_msgnum = (-1L);
276         int ret = 0;
277         char roomname[ROOMNAMELEN];
278         char buf[SIZ];
279         char savedroom[ROOMNAMELEN];
280         int msgs, new;
281         int i;
282         char new_message_flags[SIZ];
283         struct citimap *Imap;
284
285         if (num_parms < 4) {
286                 cprintf("%s BAD usage error\r\n", parms[0]);
287                 return;
288         }
289
290         if ( (parms[num_parms-1][0] != '{')
291            || (parms[num_parms-1][strlen(parms[num_parms-1])-1] != '}') )  {
292                 cprintf("%s BAD no message literal supplied\r\n", parms[0]);
293                 return;
294         }
295
296         strcpy(new_message_flags, "");
297         if (num_parms >= 5) {
298                 for (i=3; i<num_parms; ++i) {
299                         strcat(new_message_flags, parms[i]);
300                         strcat(new_message_flags, " ");
301                 }
302                 stripallbut(new_message_flags, '(', ')');
303         }
304
305         /* This is how we'd do this if it were relevant in our data store.
306          * if (num_parms >= 6) {
307          *  new_message_internaldate = parms[4];
308          * }
309          */
310
311         literal_length = atol(&parms[num_parms-1][1]);
312         if (literal_length < 1) {
313                 cprintf("%s BAD Message length must be at least 1.\r\n",
314                         parms[0]);
315                 return;
316         }
317
318         Imap = IMAP;
319         imap_free_transmitted_message();        /* just in case. */
320         Imap->transmitted_message = malloc(literal_length + 1);
321         if (Imap->transmitted_message == NULL) {
322                 cprintf("%s NO Cannot allocate memory.\r\n", parms[0]);
323                 return;
324         }
325         Imap->transmitted_length = literal_length;
326
327         cprintf("+ Transmit message now.\r\n");
328
329         bytes_transferred = 0;
330
331         ret = client_read(Imap->transmitted_message, literal_length);
332         Imap->transmitted_message[literal_length] = 0;
333
334         if (ret != 1) {
335                 cprintf("%s NO Read failed.\r\n", parms[0]);
336                 return;
337         }
338
339         /* Client will transmit a trailing CRLF after the literal (the message
340          * text) is received.  This call to client_getln() absorbs it.
341          */
342         flush_output();
343         client_getln(buf, sizeof buf);
344
345         /* Convert RFC822 newlines (CRLF) to Unix newlines (LF) */
346         CtdlLogPrintf(CTDL_DEBUG, "Converting CRLF to LF\n");
347         stripped_length = 0;
348         for (i=0; i<literal_length; ++i) {
349                 if (strncmp(&Imap->transmitted_message[i], "\r\n", 2)) {
350                         Imap->transmitted_message[stripped_length++] =
351                                 Imap->transmitted_message[i];
352                 }
353         }
354         literal_length = stripped_length;
355         Imap->transmitted_message[literal_length] = 0;  /* reterminate it */
356
357         CtdlLogPrintf(CTDL_DEBUG, "Converting message format\n");
358         msg = convert_internet_message(Imap->transmitted_message);
359         Imap->transmitted_message = NULL;
360         Imap->transmitted_length = 0;
361
362         ret = imap_grabroom(roomname, parms[2], 0);
363         if (ret != 0) {
364                 cprintf("%s NO Invalid mailbox name or access denied\r\n",
365                         parms[0]);
366                 return;
367         }
368
369         /*
370          * usergoto() formally takes us to the desired room.  (If another
371          * folder is selected, save its name so we can return there!!!!!)
372          */
373         if (Imap->selected) {
374                 strcpy(savedroom, CC->room.QRname);
375         }
376         usergoto(roomname, 0, 0, &msgs, &new);
377
378         /* If the user is locally authenticated, FORCE the From: header to
379          * show up as the real sender.  FIXME do we really want to do this?
380          * Probably should make it site-definable or even room-definable.
381          *
382          * For now, we allow "forgeries" if the room is one of the user's
383          * private mailboxes.
384          */
385         if (CC->logged_in) {
386            if ( ((CC->room.QRflags & QR_MAILBOX) == 0) && (config.c_imap_keep_from == 0)) {
387                 if (msg->cm_fields['A'] != NULL) free(msg->cm_fields['A']);
388                 if (msg->cm_fields['N'] != NULL) free(msg->cm_fields['N']);
389                 if (msg->cm_fields['H'] != NULL) free(msg->cm_fields['H']);
390                 msg->cm_fields['A'] = strdup(CC->user.fullname);
391                 msg->cm_fields['N'] = strdup(config.c_nodename);
392                 msg->cm_fields['H'] = strdup(config.c_humannode);
393             }
394         }
395
396         /* 
397          * Can we post here?
398          */
399         ret = CtdlDoIHavePermissionToPostInThisRoom(buf, sizeof buf, NULL, POST_LOGGED_IN);
400
401         if (ret) {
402                 /* Nope ... print an error message */
403                 cprintf("%s NO %s\r\n", parms[0], buf);
404         }
405
406         else {
407                 /* Yes ... go ahead and post! */
408                 if (msg != NULL) {
409                         new_msgnum = CtdlSubmitMsg(msg, NULL, "", 0);
410                 }
411                 if (new_msgnum >= 0L) {
412                         cprintf("%s OK [APPENDUID %ld %ld] APPEND completed\r\n",
413                                 parms[0], GLOBAL_UIDVALIDITY_VALUE, new_msgnum);
414                 }
415                 else {
416                         cprintf("%s BAD Error %ld saving message to disk.\r\n",
417                                 parms[0], new_msgnum);
418                 }
419         }
420
421         /*
422          * IMAP protocol response to client has already been sent by now.
423          *
424          * If another folder is selected, go back to that room so we can resume
425          * our happy day without violent explosions.
426          */
427         if (Imap->selected) {
428                 usergoto(savedroom, 0, 0, &msgs, &new);
429         }
430
431         /* We don't need this buffer anymore */
432         CtdlFreeMessage(msg);
433
434         if (new_message_flags != NULL) {
435                 imap_do_append_flags(new_msgnum, new_message_flags);
436         }
437 }