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