00c652f277dfd4a7d4c2acd9883956d384874ab2
[citadel.git] / citadel / 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 "citadel.h"
34 #include "server.h"
35 #include "sysdep_decls.h"
36 #include "citserver.h"
37 #include "support.h"
38 #include "config.h"
39 #include "serv_extensions.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 "tools.h"
46 #include "internet_addressing.h"
47 #include "serv_imap.h"
48 #include "imap_tools.h"
49 #include "imap_fetch.h"
50 #include "imap_misc.h"
51 #include "genstamp.h"
52
53
54
55
56
57
58 /*
59  * imap_copy() calls imap_do_copy() to do its actual work, once it's
60  * validated and boiled down the request a bit.  (returns 0 on success)
61  */
62 int imap_do_copy(char *destination_folder) {
63         int i;
64         char roomname[ROOMNAMELEN];
65         struct ctdlroom qrbuf;
66
67         if (IMAP->num_msgs < 1) {
68                 return(0);
69         }
70
71         i = imap_grabroom(roomname, destination_folder, 0);
72         if (i != 0) return(i);
73
74         for (i = 0; i < IMAP->num_msgs; ++i) {
75                 if (IMAP->flags[i] & IMAP_SELECTED) {
76                         CtdlCopyMsgToRoom(IMAP->msgids[i], roomname);
77                 }
78         }
79
80         /* Set the flags... */
81         i = getroom(&qrbuf, roomname);
82         if (i != 0) return(i);
83
84         for (i = 0; i < IMAP->num_msgs; ++i) {
85                 if (IMAP->flags[i] & IMAP_SELECTED) {
86                         CtdlSetSeen(IMAP->msgids[i],
87                                 ((IMAP->flags[i] & IMAP_SEEN) ? 1 : 0),
88                                 ctdlsetseen_seen,
89                                 NULL, &qrbuf
90                         );
91                         CtdlSetSeen(IMAP->msgids[i],
92                                 ((IMAP->flags[i] & IMAP_ANSWERED) ? 1 : 0),
93                                 ctdlsetseen_answered,
94                                 NULL, &qrbuf
95                         );
96                 }
97         }
98
99         return(0);
100 }
101
102
103
104 /*
105  * This function is called by the main command loop.
106  */
107 void imap_copy(int num_parms, char *parms[]) {
108         int ret;
109
110         if (num_parms != 4) {
111                 cprintf("%s BAD invalid parameters\r\n", parms[0]);
112                 return;
113         }
114
115         if (imap_is_message_set(parms[2])) {
116                 imap_pick_range(parms[2], 0);
117         }
118         else {
119                 cprintf("%s BAD invalid parameters\r\n", parms[0]);
120                 return;
121         }
122
123         ret = imap_do_copy(parms[3]);
124         if (!ret) {
125                 cprintf("%s OK COPY completed\r\n", parms[0]);
126         }
127         else {
128                 cprintf("%s NO COPY failed (error %d)\r\n", parms[0], ret);
129         }
130 }
131
132 /*
133  * This function is called by the main command loop.
134  */
135 void imap_uidcopy(int num_parms, char *parms[]) {
136
137         if (num_parms != 5) {
138                 cprintf("%s BAD invalid parameters\r\n", parms[0]);
139                 return;
140         }
141
142         if (imap_is_message_set(parms[3])) {
143                 imap_pick_range(parms[3], 1);
144         }
145         else {
146                 cprintf("%s BAD invalid parameters\r\n", parms[0]);
147                 return;
148         }
149
150         if (imap_do_copy(parms[4]) == 0) {
151                 cprintf("%s OK UID COPY completed\r\n", parms[0]);
152         }
153         else {
154                 cprintf("%s NO UID COPY failed\r\n", parms[0]);
155         }
156 }
157
158
159 /*
160  * Poll for instant messages (yeah, we can do this in IMAP ... I think)
161  */
162 void imap_print_instant_messages(void) {
163         struct ExpressMessage *ptr, *holdptr;
164         char *dumpomatic = NULL;
165         char tmp[SIZ];
166         int i;
167         size_t size, size2;
168         struct tm stamp;
169
170         if (CC->FirstExpressMessage == NULL) {
171                 return;
172         }
173         begin_critical_section(S_SESSION_TABLE);
174         ptr = CC->FirstExpressMessage;
175         CC->FirstExpressMessage = NULL;
176         end_critical_section(S_SESSION_TABLE);
177
178         while (ptr != NULL) {
179                 localtime_r(&(ptr->timestamp), &stamp);
180                 size = strlen(ptr->text) + SIZ;
181                 dumpomatic = malloc(size);
182                 strcpy(dumpomatic, "");
183                 if (ptr->flags && EM_BROADCAST)
184                         strcat(dumpomatic, "Broadcast message ");
185                 else if (ptr->flags && EM_CHAT)
186                         strcat(dumpomatic, "Chat request ");
187                 else if (ptr->flags && EM_GO_AWAY)
188                         strcat(dumpomatic, "Please logoff now, as requested ");
189                 else
190                         strcat(dumpomatic, "Message ");
191
192                 /* Timestamp.  Can this be improved? */
193                 if (stamp.tm_hour == 0 || stamp.tm_hour == 12)
194                         sprintf(tmp, "at 12:%02d%cm",
195                                 stamp.tm_min, 
196                                 stamp.tm_hour ? 'p' : 'a');
197                 else if (stamp.tm_hour > 12)            /* pm */
198                         sprintf(tmp, "at %d:%02dpm",
199                                 stamp.tm_hour - 12,
200                                 stamp.tm_min);
201                 else                                    /* am */
202                         sprintf(tmp, "at %d:%02dam",
203                                 stamp.tm_hour, stamp.tm_min);
204                 strcat(dumpomatic, tmp);
205
206                 size2 = strlen(dumpomatic);
207                 snprintf(&dumpomatic[size2], size - size2,
208                         " from %s:\n", ptr->sender);
209                 if (ptr->text != NULL)
210                         strcat(dumpomatic, ptr->text);
211
212                 holdptr = ptr->next;
213                 if (ptr->text != NULL) free(ptr->text);
214                 free(ptr);
215                 ptr = holdptr;
216
217                 for (i=0; i<strlen(dumpomatic); ++i) {
218                         if (!isprint(dumpomatic[i])) dumpomatic[i] = ' ';
219                         if (dumpomatic[i]=='\\') dumpomatic[i]='/';
220                         if (dumpomatic[i]=='\"') dumpomatic[i]='\'';
221                 }
222
223                 cprintf("* OK [ALERT] %s\r\n", dumpomatic);
224                 free(dumpomatic);
225         }
226         cprintf("000\n");
227 }
228
229
230 /*
231  * imap_do_append_flags() is called by imap_append() to set any flags that
232  * the client specified at append time.
233  *
234  * FIXME find a way to do these in bulk so we don't max out our db journal
235  */
236 void imap_do_append_flags(long new_msgnum, char *new_message_flags) {
237         char flags[32];
238         char this_flag[sizeof flags];
239         int i;
240
241         if (new_message_flags == NULL) return;
242         if (strlen(new_message_flags) == 0) return;
243
244         safestrncpy(flags, new_message_flags, sizeof flags);
245
246         for (i=0; i<num_tokens(flags, ' '); ++i) {
247                 extract_token(this_flag, flags, i, ' ', sizeof this_flag);
248                 if (this_flag[0] == '\\') strcpy(this_flag, &this_flag[1]);
249                 if (!strcasecmp(this_flag, "Seen")) {
250                         CtdlSetSeen(new_msgnum, 1, ctdlsetseen_seen,
251                                 NULL, NULL);
252                 }
253                 if (!strcasecmp(this_flag, "Answered")) {
254                         CtdlSetSeen(new_msgnum, 1, ctdlsetseen_answered,
255                                 NULL, NULL);
256                 }
257         }
258 }
259
260
261 /*
262  * This function is called by the main command loop.
263  */
264 void imap_append(int num_parms, char *parms[]) {
265         long literal_length;
266         long bytes_transferred;
267         long stripped_length = 0;
268         struct CtdlMessage *msg;
269         long new_msgnum = (-1L);
270         int ret = 0;
271         char roomname[ROOMNAMELEN];
272         char buf[SIZ];
273         char savedroom[ROOMNAMELEN];
274         int msgs, new;
275         int i;
276         char new_message_flags[SIZ];
277
278         if (num_parms < 4) {
279                 cprintf("%s BAD usage error\r\n", parms[0]);
280                 return;
281         }
282
283         if ( (parms[num_parms-1][0] != '{')
284            || (parms[num_parms-1][strlen(parms[num_parms-1])-1] != '}') )  {
285                 cprintf("%s BAD no message literal supplied\r\n", parms[0]);
286                 return;
287         }
288
289         strcpy(new_message_flags, "");
290         if (num_parms >= 5) {
291                 for (i=3; i<num_parms; ++i) {
292                         strcat(new_message_flags, parms[i]);
293                         strcat(new_message_flags, " ");
294                 }
295                 stripallbut(new_message_flags, '(', ')');
296         }
297
298         /* This is how we'd do this if it were relevant in our data store.
299          * if (num_parms >= 6) {
300          *  new_message_internaldate = parms[4];
301          * }
302          */
303
304         literal_length = atol(&parms[num_parms-1][1]);
305         if (literal_length < 1) {
306                 cprintf("%s BAD Message length must be at least 1.\r\n",
307                         parms[0]);
308                 return;
309         }
310
311         imap_free_transmitted_message();        /* just in case. */
312         IMAP->transmitted_message = malloc(literal_length + 1);
313         if (IMAP->transmitted_message == NULL) {
314                 cprintf("%s NO Cannot allocate memory.\r\n", parms[0]);
315                 return;
316         }
317         IMAP->transmitted_length = literal_length;
318
319         cprintf("+ Transmit message now.\r\n");
320
321         bytes_transferred = 0;
322
323         ret = client_read(IMAP->transmitted_message, literal_length);
324         IMAP->transmitted_message[literal_length] = 0;
325
326         if (ret != 1) {
327                 cprintf("%s NO Read failed.\r\n", parms[0]);
328                 return;
329         }
330
331         /* Client will transmit a trailing CRLF after the literal (the message
332          * text) is received.  This call to client_getln() absorbs it.
333          */
334         flush_output();
335         client_getln(buf, sizeof buf);
336
337         /* Convert RFC822 newlines (CRLF) to Unix newlines (LF) */
338         lprintf(CTDL_DEBUG, "Converting CRLF to LF\n");
339         stripped_length = 0;
340         for (i=0; i<literal_length; ++i) {
341                 if (strncmp(&IMAP->transmitted_message[i], "\r\n", 2)) {
342                         IMAP->transmitted_message[stripped_length++] =
343                                 IMAP->transmitted_message[i];
344                 }
345         }
346         literal_length = stripped_length;
347         IMAP->transmitted_message[literal_length] = 0;  /* reterminate it */
348
349         lprintf(CTDL_DEBUG, "Converting message format\n");
350         msg = convert_internet_message(IMAP->transmitted_message);
351         IMAP->transmitted_message = NULL;
352         IMAP->transmitted_length = 0;
353
354         ret = imap_grabroom(roomname, parms[2], 0);
355         if (ret != 0) {
356                 cprintf("%s NO Invalid mailbox name or access denied\r\n",
357                         parms[0]);
358                 return;
359         }
360
361         /*
362          * usergoto() formally takes us to the desired room.  (If another
363          * folder is selected, save its name so we can return there!!!!!)
364          */
365         if (IMAP->selected) {
366                 strcpy(savedroom, CC->room.QRname);
367         }
368         usergoto(roomname, 0, 0, &msgs, &new);
369
370         /* If the user is locally authenticated, FORCE the From: header to
371          * show up as the real sender.  FIXME do we really want to do this?
372          * Probably should make it site-definable or even room-definable.
373          *
374          * For now, we allow "forgeries" if the room is one of the user's
375          * private mailboxes.
376          */
377         if (CC->logged_in) {
378            if ( (CC->room.QRflags & QR_MAILBOX) == 0) {
379                 if (msg->cm_fields['A'] != NULL) free(msg->cm_fields['A']);
380                 if (msg->cm_fields['N'] != NULL) free(msg->cm_fields['N']);
381                 if (msg->cm_fields['H'] != NULL) free(msg->cm_fields['H']);
382                 msg->cm_fields['A'] = strdup(CC->user.fullname);
383                 msg->cm_fields['N'] = strdup(config.c_nodename);
384                 msg->cm_fields['H'] = strdup(config.c_humannode);
385             }
386         }
387
388         /* 
389          * Can we post here?
390          */
391         ret = CtdlDoIHavePermissionToPostInThisRoom(buf, sizeof buf);
392
393         if (ret) {
394                 /* Nope ... print an error message */
395                 cprintf("%s NO %s\r\n", parms[0], buf);
396         }
397
398         else {
399                 /* Yes ... go ahead and post! */
400                 if (msg != NULL) {
401                         new_msgnum = CtdlSubmitMsg(msg, NULL, "");
402                 }
403                 if (new_msgnum >= 0L) {
404                         cprintf("%s OK APPEND completed\r\n", parms[0]);
405                 }
406                 else {
407                         cprintf("%s BAD Error %ld saving message to disk.\r\n",
408                                 parms[0], new_msgnum);
409                 }
410         }
411
412         /*
413          * IMAP protocol response to client has already been sent by now.
414          *
415          * If another folder is selected, go back to that room so we can resume
416          * our happy day without violent explosions.
417          */
418         if (IMAP->selected) {
419                 usergoto(savedroom, 0, 0, &msgs, &new);
420         }
421
422         /* We don't need this buffer anymore */
423         CtdlFreeMessage(msg);
424
425         if (new_message_flags != NULL) {
426                 imap_do_append_flags(new_msgnum, new_message_flags);
427         }
428 }