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