Grammar change in the license declaration.
[citadel.git] / webcit-ng / server / messages.c
1 // Message base functions
2 //
3 // Copyright (c) 1996-2023 by the citadel.org team
4 //
5 // This program is open source software.  Use, duplication, or
6 // disclosure is subject to the GNU General Public License v3.
7
8 #include "webcit.h"
9
10
11 // Given an encoded UID, translate that to an unencoded Citadel EUID and
12 // then search for it in the current room.  Return a message number or -1
13 // if not found.
14 long locate_message_by_uid(struct ctdlsession *c, char *uid) {
15         char buf[1024];
16
17         ctdl_printf(c, "EUID %s", uid);
18         ctdl_readline(c, buf, sizeof buf);
19         if (buf[0] == '2') {
20                 return (atol(&buf[4]));
21
22         }
23
24         // Ugly hack to handle Mozilla Thunderbird, try stripping ".ics" if present
25         if (!strcasecmp(&uid[strlen(uid) - 4], ".ics")) {
26                 safestrncpy(buf, uid, sizeof buf);
27                 buf[strlen(buf) - 4] = 0;
28                 ctdl_printf(c, "EUID %s", buf);
29                 ctdl_readline(c, buf, sizeof buf);
30                 if (buf[0] == '2') {
31                         return (atol(&buf[4]));
32
33                 }
34         }
35
36         return (-1);
37 }
38
39
40 // DAV delete an object in a room.
41 void dav_delete_message(struct http_transaction *h, struct ctdlsession *c, long msgnum) {
42         ctdl_delete_msgs(c, &msgnum, 1);
43         do_204(h);
44 }
45
46
47 // DAV move or copy an object in a room.
48 void dav_move_or_copy_message(struct http_transaction *h, struct ctdlsession *c, long msgnum, int move_or_copy) {
49         char target_room[ROOMNAMELEN];
50         char buf[1024];
51
52         // HTTP "Destination" header will tell us the target collection
53         char *target_collection = header_val(h, "Destination");
54         syslog(LOG_DEBUG, "dest coll: \"%s\"", target_collection);
55
56         // Translate the target WebDAV Collection name to a Citadel Room name.
57         // Note that some clients will supply a fully-qualified URL such as "http://example.com/ctdl/r/roomname/999"
58         // so we're just going to search for "/ctdl/r/" and work from there.
59         char *ctdlr = strstr(target_collection, "/ctdl/r/");
60         if (ctdlr == NULL) {    
61                 do_412(h);              // badly formed target collection; fail out.
62                 return;
63         }
64         safestrncpy(target_room, ctdlr+8, sizeof target_room);
65         char *slash = strchr(target_room, '/');
66         if (slash) {
67                 *slash = 0;             // lop off the "filename" we don't need it
68         }
69         unescape_input(target_room);
70         syslog(LOG_DEBUG, "dest room: \"%s\"", target_room);
71
72         // Perform the move or copy operation
73         ctdl_printf(c, "MOVE %ld|%s|%d", msgnum, target_room, move_or_copy);    // Citadel Server: 0=move, 1=copy
74         ctdl_readline(c, buf, sizeof buf);
75         if (buf[0] == '2') {
76                 do_204(h);              // succeed (no content)
77                 return;
78         }
79         do_412(h);                      // fail (precondition failed)
80 }
81
82
83 // GET method directly on a message in a room
84 void dav_get_message(struct http_transaction *h, struct ctdlsession *c, long msgnum) {
85         char buf[1024];
86         int in_body = 0;
87         int encoding = 0;
88         StrBuf *Body = NULL;
89
90         ctdl_printf(c, "MSG2 %ld", msgnum);
91         ctdl_readline(c, buf, sizeof buf);
92         if (buf[0] != '1') {
93                 do_404(h);
94                 return;
95         }
96
97         char *etag = malloc(20);
98         if (etag != NULL) {
99                 sprintf(etag, "%ld", msgnum);
100                 add_response_header(h, strdup("ETag"), etag);   // http_transaction now owns this memory
101         }
102
103         while (ctdl_readline(c, buf, sizeof buf), strcmp(buf, "000")) {
104                 if (IsEmptyStr(buf) && (in_body == 0)) {
105                         in_body = 1;
106                         Body = NewStrBuf();
107                 }
108                 else if (in_body == 0) {
109                         char *k = buf;
110                         char *v = strchr(buf, ':');
111                         if (v) {
112                                 *v = 0;
113                                 ++v;
114                                 string_trim(v);                         // we now have a key (k) and a value (v)
115                                 if ((!strcasecmp(k, "content-type"))    // fields which can be passed from RFC822 to HTTP as-is
116                                     || (!strcasecmp(k, "date"))
117                                 ) {
118                                         add_response_header(h, strdup(k), strdup(v));
119                                 }
120                                 else if (!strcasecmp(k, "content-transfer-encoding")) {
121                                         if (!strcasecmp(v, "base64")) {
122                                                 encoding = 'b';
123                                         }
124                                         else if (!strcasecmp(v, "quoted-printable")) {
125                                                 encoding = 'q';
126                                         }
127                                 }
128                         }
129                 }
130                 else if ((in_body == 1) && (Body != NULL)) {
131                         StrBufAppendPrintf(Body, "%s\n", buf);
132                 }
133         }
134
135         h->response_code = 200;
136         h->response_string = strdup("OK");
137
138         if (Body != NULL) {
139                 if (encoding == 'q') {
140                         h->response_body = malloc(StrLength(Body));
141                         if (h->response_body != NULL) {
142                                 h->response_body_length =
143                                     CtdlDecodeQuotedPrintable(h->response_body, (char *) ChrPtr(Body), StrLength(Body));
144                         }
145                         FreeStrBuf(&Body);
146                 }
147                 else if (encoding == 'b') {
148                         h->response_body = malloc(StrLength(Body));
149                         if (h->response_body != NULL) {
150                                 h->response_body_length = CtdlDecodeBase64(h->response_body, ChrPtr(Body), StrLength(Body));
151                         }
152                         FreeStrBuf(&Body);
153                 }
154                 else {
155                         h->response_body_length = StrLength(Body);
156                         h->response_body = SmashStrBuf(&Body);
157                 }
158         }
159 }
160
161
162 // PUT a message into a room
163 void dav_put_message(struct http_transaction *h, struct ctdlsession *c, char *euid, long old_msgnum) {
164         char buf[1024];
165         char *content_type = NULL;
166         char *content_transfer_encoding = NULL;
167         int n;
168         long new_msgnum;
169         char new_euid[1024];
170         char response_string[1024];
171         char mime_boundary[80];
172
173         if ((h->request_body == NULL) || (h->request_body_length < 1)) {
174                 do_404(h);                              // Refuse to post a null message
175                 return;
176         }
177
178         // Extract metadata from the URL
179         char *wefw = get_url_param(h, "wefw");          // References:
180         if (!wefw) wefw = "";
181         char *subj = get_url_param(h, "subj");          // Subject:
182         if (!subj) subj = "";
183         char *mailto = get_url_param(h, "mailto");      // To:
184         if (!mailto) mailto = "";
185         char *mailcc = get_url_param(h, "mailcc");      // Cc:
186         if (!mailcc) mailcc = "";
187         char *mailbcc = get_url_param(h, "mailbcc");    // Bcc:
188         if (!mailbcc) mailbcc = "";
189
190         // Mode 4 will give us metadata back after upload
191         ctdl_printf(c, "ENT0 1|%s||4|%s||1|%s|%s|||%s|", mailto, subj, mailcc, mailbcc, wefw);
192         ctdl_readline(c, buf, sizeof buf);
193         if (buf[0] != '8') {
194                 h->response_code = 502;
195                 h->response_string = strdup("bad gateway");
196                 add_response_header(h, strdup("Content-type"), strdup("text/plain"));
197                 h->response_body = strdup(buf);
198                 h->response_body_length = strlen(h->response_body);
199                 return;
200         }
201
202         // Remember, ctdl_printf() appends \n on its own, so when adding a CRLF newline, only use \r
203         // Or for a blank line, use ctdl_write() with \r\n
204
205         // If there are attachments, open up a multipart/mixed MIME container.
206         char *att = get_url_param(h, "att");
207         if (att) {
208                 snprintf(mime_boundary, sizeof(mime_boundary), "citadel-multipart-%x-%x", (unsigned int)time(NULL), rand());
209                 ctdl_printf(c, "MIME-Version: 1.0\r");
210                 ctdl_printf(c, "Content-Type: multipart/mixed; boundary=\"%s\"\r", mime_boundary);
211                 ctdl_write(c, HKEY("\r\n"));
212                 ctdl_printf(c, "--%s\r", mime_boundary);        // start of message body
213         }
214
215         // This section
216         content_type = header_val(h, "Content-type");
217         content_transfer_encoding = header_val(h, "Content-transfer-encoding");
218
219         // If the content is already encoded, pass it along as-is
220         if (!IsEmptyStr(content_transfer_encoding)) {
221                 ctdl_printf(c, "Content-type: %s\r", (content_type ? content_type : "application/octet-stream"));
222                 ctdl_write(c, HKEY("\r\n"));
223                 ctdl_write(c, h->request_body, h->request_body_length);
224         }
225
226         // But if it's raw, we ought to encode it so it's MIME-friendly.
227         else {
228                 ctdl_printf(c, "Content-type: %s\r", (content_type ? content_type : "application/octet-stream"));
229                 ctdl_printf(c, "Content-transfer-encoding: quoted-printable\r");
230                 ctdl_write(c, HKEY("\r\n"));
231                 h->request_body[h->request_body_length] = 0;            // make doubly sure it's null terminated.
232
233                 // Adapted from https://www.w3.org/Tools/Mail-Transcode/mail-transcode.c
234                 char *s = h->request_body;
235                 char strconv[8];
236                 int strconv_len;
237                 int n;
238                 for (n = 0; *s; s++) {
239                         if (n >= 73 && *s != 10 && *s != 13) {
240                                 ctdl_write(c, HKEY("=\r\n"));
241                                 n = 0;
242                         }
243                         if (*s == 10 || *s == 13) {
244                                 ctdl_write(c, s, 1);
245                                 n = 0;
246                         }
247                         else if (*s<32 || *s==61 || *s>126) {
248                                 strconv_len = sprintf(strconv, "=%02X", (unsigned char)*s);
249                                 ctdl_write(c, strconv, strconv_len);
250                                 n += strconv_len;
251                         }
252                         else if (*s != 32 || (*(s+1) != 10 && *(s+1) != 13)) {
253                                 ctdl_write(c, s, 1);
254                                 n++;
255                         }
256                         else {
257                                 ctdl_write(c, "=20", 3);
258                                 n += 3;
259                         }
260                 }
261         }
262
263         if (h->request_body[h->request_body_length] != '\n') {
264                 ctdl_write(c, HKEY("\r\n"));
265         }
266
267         // If there are attachments, add them now.
268         if (att) {
269                 int i;
270                 char attid[10];
271                 struct uploaded_file one_att;
272                 int num_attachments = num_tokens(att, ',');
273
274                 for (i=0; i<num_attachments; ++i) {
275                         extract_token(attid, att, i, ',', sizeof(attid));
276                         one_att = pop_upload(attid);
277
278                         // After calling pop_upload(), the attachment is no longer in the global list.
279                         // The file descriptor has zero links, so when we close it, the filesystem will remove it from disk.
280                         ctdl_printf(c, "--%s\r", mime_boundary);
281                         ctdl_printf(c, "Content-Type: %s; name=\"%s\"\r", one_att.content_type, one_att.filename);
282                         ctdl_printf(c, "Content-Disposition: attachment; filename=\"%s\"\r", one_att.filename);
283                         ctdl_printf(c, "Content-Transfer-Encoding: base64\r");
284                         ctdl_write(c, HKEY("\r\n"));
285
286                         char *raw_att = malloc(one_att.length);
287                         if (raw_att) {
288                                 rewind(one_att.fp);
289                                 if (fread(raw_att, one_att.length, 1, one_att.fp) != 1) {
290                                         syslog(LOG_ERR, "messages: %m");
291                                 }
292
293                                 // now encode it
294                                 char *encoded_att = malloc((one_att.length * 150) / 100);
295                                 if (encoded_att) {
296                                         size_t encoded_length = CtdlEncodeBase64(encoded_att, raw_att, one_att.length, BASE64_YES_LINEBREAKS);
297                                         ctdl_write(c, encoded_att, encoded_length);
298                                         syslog(LOG_DEBUG, "Encoded attachment: len=%ld", encoded_length);
299                                         free(encoded_att);
300                                 }
301                                 free(raw_att);
302                         }
303
304                         fclose(one_att.fp);
305                 }
306
307                 // Close the multipart/mixed MIME container.
308                 ctdl_printf(c, "--%s--\r", mime_boundary);
309         }
310
311         // Done writing to the Citadel Server.
312         ctdl_printf(c, "000");
313
314         // Now handle the response from the Citadel Server.
315         n = 0;
316         new_msgnum = 0;
317         strcpy(new_euid, "");
318         strcpy(response_string, "");
319
320         while (ctdl_readline(c, buf, sizeof buf), strcmp(buf, "000"))
321                 switch (n++) {
322                 case 0:
323                         new_msgnum = atol(buf);
324                         break;
325                 case 1:
326                         safestrncpy(response_string, buf, sizeof response_string);
327                         syslog(LOG_DEBUG, "new_msgnum=%ld (%s)\n", new_msgnum, buf);
328                         break;
329                 case 2:
330                         safestrncpy(new_euid, buf, sizeof new_euid);
331                         break;
332                 default:
333                         break;
334                 }
335
336         // Tell the client what happened.
337
338         // Citadel failed in some way?
339         char *new_location = malloc(1024);
340         if ((new_msgnum < 0L) || (new_location == NULL)) {
341                 h->response_code = 502;
342                 h->response_string = strdup("bad gateway");
343                 add_response_header(h, strdup("Content-type"), strdup("text/plain"));
344                 h->response_body = strdup(response_string);
345                 h->response_body_length = strlen(h->response_body);
346                 return;
347         }
348
349         char *etag = malloc(20);
350         if (etag != NULL) {
351                 sprintf(etag, "%ld", new_msgnum);
352                 add_response_header(h, strdup("ETag"), etag);   // http_transaction now owns this memory
353         }
354
355         char esc_room[1024];
356         char esc_euid[1024];
357         urlesc(esc_room, sizeof esc_room, c->room);
358         urlesc(esc_euid, sizeof esc_euid, new_euid);
359         snprintf(new_location, 1024, "/ctdl/r/%s/%s", esc_room, esc_euid);
360         add_response_header(h, strdup("Location"), new_location);       // http_transaction now owns this memory
361
362         if (old_msgnum <= 0) {
363                 h->response_code = 201; // We created this item for the first time.
364                 h->response_string = strdup("created");
365         }
366         else {
367                 h->response_code = 204; // We modified an existing item.
368                 h->response_string = strdup("no content");
369
370                 // The item we replaced has probably already been deleted by
371                 // the Citadel server, but we'll do this anyway, just in case.
372                 ctdl_delete_msgs(c, &old_msgnum, 1);
373         }
374
375 }
376
377
378 // Download a single component of a MIME-encoded message
379 void download_mime_component(struct http_transaction *h, struct ctdlsession *c, long msgnum, char *partnum) {
380         char buf[1024];
381         char content_type[1024];
382
383         ctdl_printf(c, "DLAT %ld|%s", msgnum, partnum);
384         ctdl_readline(c, buf, sizeof buf);
385         if (buf[0] != '6') {
386                 do_404(h);      // too bad, so sad, go away
387         }
388         // Server response is going to be: 6XX length|-1|filename|content-type|charset
389         h->response_body_length = extract_int(&buf[4], 0);
390         extract_token(content_type, buf, 3, '|', sizeof content_type);
391
392         h->response_body = malloc(h->response_body_length + 1);
393         int bytes = 0;
394         int thisblock;
395         do {
396                 thisblock = read(c->sock, &h->response_body[bytes], (h->response_body_length - bytes));
397                 bytes += thisblock;
398                 syslog(LOG_DEBUG, "Bytes read: %d of %d", (int) bytes, (int) h->response_body_length);
399         } while ((bytes < h->response_body_length) && (thisblock >= 0));
400         h->response_body[h->response_body_length] = 0;  // null terminate it just for good measure
401         syslog(LOG_DEBUG, "content type: %s", content_type);
402
403         add_response_header(h, strdup("Content-type"), strdup(content_type));
404         h->response_code = 200;
405         h->response_string = strdup("OK");
406 }