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