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