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