3ab2f5dc103b5b636225b2f0be469a36e83b7ee2
[citadel.git] / webcit-ng / server / room_functions.c
1 // Room functions
2 //
3 // Copyright (c) 1996-2024 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 // Return an array of message numbers in the current room.
12 // Caller owns the memory and must free it.  Returns NULL if any problems.
13 Array *get_msglist(struct ctdlsession *c, char *which_msgs) {
14         char buf[1024];
15         Array *msglist = NULL;
16
17         msglist = array_new(sizeof(long));
18         if (msglist == NULL) {
19                 return(NULL);
20         }
21
22         ctdl_printf(c, "MSGS %s", which_msgs);
23         ctdl_readline(c, buf, sizeof(buf));
24         if (buf[0] == '1') {
25                 while (ctdl_readline(c, buf, sizeof(buf)), strcmp(buf, "000")) { 
26                         long m = atol(buf);
27                         array_append(msglist, &m);
28                 }
29         }
30
31         return msglist;
32 }
33
34
35 // Supplied with a list of potential matches from an If-Match: or If-None-Match: header, and
36 // a message number (which we always use as the entity tag in Citadel), return nonzero if the
37 // message number matches any of the supplied tags in the string.
38 int match_etags(char *taglist, long msgnum) {
39         int num_tags = num_tokens(taglist, ',');
40         int i = 0;
41         char tag[1024];
42
43         if (msgnum <= 0) {                                      // no msgnum?  no match.
44                 return (0);
45         }
46
47         for (i = 0; i < num_tags; ++i) {
48                 extract_token(tag, taglist, i, ',', sizeof tag);
49                 string_trim(tag);
50                 char *lq = (strchr(tag, '"'));
51                 char *rq = (strrchr(tag, '"'));
52                 if (lq < rq) {                                  // has two double quotes
53                         strcpy(rq, "");
54                         strcpy(tag, ++lq);
55                 }
56                 string_trim(tag);
57                 if (!strcmp(tag, "*")) {                        // wildcard match
58                         return (1);
59                 }
60                 long tagmsgnum = atol(tag);
61                 if ((tagmsgnum > 0) && (tagmsgnum == msgnum)) { // match
62                         return (1);
63                 }
64         }
65
66         return (0);                                             // no match
67 }
68
69
70 // Client is requesting a STAT (name and modification time) of the current room
71 void json_stat(struct http_transaction *h, struct ctdlsession *c) {
72         char buf[1024];
73         char field[1024];
74
75         ctdl_printf(c, "STAT");
76         ctdl_readline(c, buf, sizeof(buf));
77         if (buf[0] == '2') {
78                 JsonValue *j = NewJsonObject(HKEY("stat"));
79                 extract_token(field, &buf[4], 0, '|', sizeof field);
80                 JsonObjectAppend(j, NewJsonPlainString(HKEY("name"), field, -1));
81                 JsonObjectAppend(j, NewJsonNumber(HKEY("room_mtime"), extract_long(&buf[4], 1)));
82
83                 StrBuf *sj = NewStrBuf();
84                 SerializeJson(sj, j, 1);                                // '1' == free the source array
85                 add_response_header(h, strdup("Content-type"), strdup("application/json"));
86                 h->response_code = 200;
87                 h->response_string = strdup("OK");
88                 h->response_body_length = StrLength(sj);
89                 h->response_body = SmashStrBuf(&sj);
90         }
91         else {
92                 do_404(h);
93         }
94         return;
95 }
96
97
98 // Client is requesting a mailbox summary of the current room
99 void json_mailbox(struct http_transaction *h, struct ctdlsession *c) {
100         char buf[1024];
101         char field[1024];
102         JsonValue *j = NewJsonArray(HKEY("msgs"));
103
104         ctdl_printf(c, "MSGS ALL|||9");                         // "9" as the fourth parameter delivers a mailbox summary
105         ctdl_readline(c, buf, sizeof(buf));
106         if (buf[0] == '1') {
107                 while (ctdl_readline(c, buf, sizeof(buf)), (strcmp(buf, "000"))) {
108                         JsonValue *jmsg = NewJsonObject(HKEY("message"));
109                         JsonObjectAppend(jmsg, NewJsonNumber(HKEY("msgnum"), extract_long(buf, 0)));
110                         JsonObjectAppend(jmsg, NewJsonNumber(HKEY("time"), extract_long(buf, 1)));
111                         extract_token(field, buf, 2, '|', sizeof field);
112                         utf8ify_rfc822_string(field);
113                         JsonObjectAppend(jmsg, NewJsonPlainString(HKEY("author"), field, -1));
114                         extract_token(field, buf, 4, '|', sizeof field);
115                         utf8ify_rfc822_string(field);
116                         JsonObjectAppend(jmsg, NewJsonPlainString(HKEY("addr"), field, -1));
117                         extract_token(field, buf, 5, '|', sizeof field);
118                         utf8ify_rfc822_string(field);
119                         JsonObjectAppend(jmsg, NewJsonPlainString(HKEY("subject"), field, -1));
120                         JsonObjectAppend(jmsg, NewJsonNumber(HKEY("msgidhash"), extract_long(buf, 6)));
121                         extract_token(field, buf, 7, '|', sizeof field);
122                         utf8ify_rfc822_string(field);
123                         JsonObjectAppend(jmsg, NewJsonPlainString(HKEY("references"), field, -1));
124                         JsonArrayAppend(j, jmsg);               // add the message to the array
125                 }
126         }
127
128         StrBuf *sj = NewStrBuf();
129         SerializeJson(sj, j, 1);                                // '1' == free the source array
130
131         add_response_header(h, strdup("Content-type"), strdup("application/json"));
132         h->response_code = 200;
133         h->response_string = strdup("OK");
134         h->response_body_length = StrLength(sj);
135         h->response_body = SmashStrBuf(&sj);
136         return;
137 }
138
139
140 // Client is requesting a message list
141 void json_msglist(struct http_transaction *h, struct ctdlsession *c, char *which) {
142         int i = 0;
143         Array *msglist = get_msglist(c, which);
144         JsonValue *j = NewJsonArray(HKEY("msgs"));
145
146         if (msglist != NULL) {
147                 for (i = 0; i < array_len(msglist); ++i) {
148                         long m;
149                         memcpy(&m, array_get_element_at(msglist, i), sizeof(long));
150                         JsonArrayAppend(j, NewJsonNumber(HKEY("m"), m));
151                 }
152                 array_free(msglist);
153         }
154
155         StrBuf *sj = NewStrBuf();
156         SerializeJson(sj, j, 1);                                // '1' == free the source array
157
158         add_response_header(h, strdup("Content-type"), strdup("application/json"));
159         h->response_code = 200;
160         h->response_string = strdup("OK");
161         h->response_body_length = StrLength(sj);
162         h->response_body = SmashStrBuf(&sj);
163         return;
164 }
165
166
167 // Client is requesting the room info banner
168 void read_room_info_banner(struct http_transaction *h, struct ctdlsession *c) {
169         char buf[1024];
170
171         ctdl_printf(c, "RINF");
172         ctdl_readline(c, buf, sizeof(buf));
173         if (buf[0] == '1') {
174                 StrBuf *info = NewStrBuf();
175                 while (ctdl_readline(c, buf, sizeof(buf)), (strcmp(buf, "000"))){
176                         StrBufAppendPrintf(info, "%s\n", buf);
177                 }
178                 add_response_header(h, strdup("Content-type"), strdup("text/plain"));
179                 h->response_code = 200;
180                 h->response_string = strdup("OK");
181                 h->response_body_length = StrLength(info);
182                 h->response_body = SmashStrBuf(&info);
183                 return;
184         }
185         else {
186                 do_404(h);
187         }
188 }
189
190
191 // Client is setting the "Last Read Pointer" (marking all messages as "seen" up to this message)
192 void set_last_read_pointer(struct http_transaction *h, struct ctdlsession *c) {
193         char cbuf[1024];
194         ctdl_printf(c, "SLRP %d", atoi(get_url_param(h, "last")));
195         ctdl_readline(c, cbuf, sizeof(cbuf));
196         if (cbuf[0] == '2') {
197                 do_204(h);
198         }
199         else {
200                 do_404(h);
201         }
202 }
203
204
205 // Client requested an object in a room.
206 void object_in_room(struct http_transaction *h, struct ctdlsession *c) {
207         char buf[1024];
208         long msgnum = (-1);
209         char unescaped_euid[1024];
210
211         extract_token(buf, h->url, 4, '/', sizeof buf);
212
213         if (!strcasecmp(buf, "mailbox")) {              // Client is requesting a mailbox summary
214                 json_mailbox(h, c);
215                 return;
216         }
217
218         if (!strcasecmp(buf, "stat")) {                 // Client is requesting a stat command (name and modification time)
219                 json_stat(h, c);
220                 return;
221         }
222
223         if (!strncasecmp(buf, "msgs.", 5)) {            // Client is requesting a list of message numbers
224                 unescape_input(&buf[5]);
225                 json_msglist(h, c, &buf[5]);
226                 return;
227         }
228
229         if (!strcasecmp(buf, "info.txt")) {             // Client is requesting the room info banner
230                 read_room_info_banner(h, c);
231                 return;
232         }
233
234         if (!strcasecmp(buf, "slrp")) {                 // Set the Last Read Pointer
235                 set_last_read_pointer(h, c);
236                 return;
237         }
238
239         // If we get to this point, the client is requesting a specific object *in* the room.
240
241         if ((c->room_default_view == VIEW_CALENDAR)     // room types where objects are referenced by EUID
242            || (c->room_default_view == VIEW_TASKS)
243            || (c->room_default_view == VIEW_ADDRESSBOOK)
244            ) {
245                 safestrncpy(unescaped_euid, buf, sizeof unescaped_euid);
246                 unescape_input(unescaped_euid);
247                 msgnum = locate_message_by_uid(c, unescaped_euid);
248         }
249         else {                                          // otherwise the object is being referenced by message number
250                 msgnum = atol(buf);
251         }
252
253         // All methods except PUT require the message to already exist
254         if ((msgnum <= 0) && (strcasecmp(h->method, "PUT"))) {
255                 do_404(h);
256         }
257
258         // If we get to this point we have a valid message number in an accessible room.
259         syslog(LOG_DEBUG, "msgnum is %ld, method is %s", msgnum, h->method);
260
261         // A sixth component in the URL can be one of two things:
262         // (1) a MIME part specifier, in which case the client wants to download that component within the message
263         // (2) a content-type, in which ase the client wants us to try to render it a certain way
264         if (num_tokens(h->url, '/') >= 6) {
265                 extract_token(buf, h->url, 5, '/', sizeof buf);
266                 if (!IsEmptyStr(buf)) {
267                         if (!strcasecmp(buf, "json")) {
268                                 json_render_one_message(h, c, msgnum);
269                         }
270                         else {
271                                 download_mime_component(h, c, msgnum, buf);
272                         }
273                         return;
274                 }
275         }
276
277         // Ok, we want a full message, but first let's check for the if[-none]-match headers.
278         char *if_match = header_val(h, "If-Match");
279         if ((if_match != NULL) && (!match_etags(if_match, msgnum))) {
280                 do_412(h);
281                 return;
282         }
283
284         char *if_none_match = header_val(h, "If-None-Match");
285         if ((if_none_match != NULL) && (match_etags(if_none_match, msgnum))) {
286                 do_412(h);
287                 return;
288         }
289
290         // Now perform the requested operation.
291         if (!strcasecmp(h->method, "DELETE")) {
292                 dav_delete_message(h, c, msgnum);
293         }
294         else if (!strcasecmp(h->method, "GET")) {
295                 dav_get_message(h, c, msgnum);
296         }
297         else if (!strcasecmp(h->method, "PUT")) {
298                 dav_put_message(h, c, unescaped_euid, msgnum);
299         }
300         else if (!strcasecmp(h->method, "MOVE")) {
301                 dav_move_or_copy_message(h, c, msgnum, DAV_MOVE);
302         }
303         else if (!strcasecmp(h->method, "COPY")) {
304                 dav_move_or_copy_message(h, c, msgnum, DAV_COPY);
305         }
306         else {
307                 do_404(h);              // We should never get here, but if we do, a 404 error is clean.
308         }
309 }
310
311
312 // Called by the_room_itself() when the HTTP method is REPORT
313 void report_the_room_itself(struct http_transaction *h, struct ctdlsession *c) {
314         if (c->room_default_view == VIEW_CALENDAR) {
315                 caldav_report(h, c);    // CalDAV REPORTs ... fmgwac
316                 return;
317         }
318
319         do_404(h);                      // future implementations like CardDAV will require code paths here
320 }
321
322
323 // Called by the_room_itself() when the HTTP method is OPTIONS
324 void options_the_room_itself(struct http_transaction *h, struct ctdlsession *c) {
325         h->response_code = 200;
326         h->response_string = strdup("OK");
327         if (c->room_default_view == VIEW_CALENDAR) {
328                 add_response_header(h, strdup("DAV"), strdup("1, calendar-access"));    // offer CalDAV
329         }
330         else if (c->room_default_view == VIEW_ADDRESSBOOK) {
331                 add_response_header(h, strdup("DAV"), strdup("1, addressbook"));        // offer CardDAV
332         }
333         else {
334                 add_response_header(h, strdup("DAV"), strdup("1"));     // ordinary WebDAV for all other room types
335         }
336         add_response_header(h, strdup("Allow"), strdup("OPTIONS, PROPFIND, GET, PUT, REPORT, DELETE, MOVE, COPY"));
337 }
338
339
340 // Called by the_room_itself() when the HTTP method is PROPFIND
341 void propfind_the_room_itself(struct http_transaction *h, struct ctdlsession *c) {
342         char *e;
343         long timestamp;
344         int dav_depth = (header_val(h, "Depth") ? atoi(header_val(h, "Depth")) : INT_MAX);
345         syslog(LOG_DEBUG, "Client PROPFIND requested depth: %d", dav_depth);
346         StrBuf *Buf = NewStrBuf();
347
348         StrBufAppendPrintf(Buf,
349                 "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
350                 "<D:multistatus "
351                 "xmlns:D=\"DAV:\" "
352                 "xmlns:C=\"urn:ietf:params:xml:ns:caldav\""
353                 ">"
354         );
355
356         // Transmit the collection resource
357         StrBufAppendPrintf(Buf, "<D:response>");
358         StrBufAppendPrintf(Buf, "<D:href>");
359         StrBufXMLEscAppend(Buf, NULL, h->site_prefix, strlen(h->site_prefix), 0);
360         StrBufAppendPrintf(Buf, "/ctdl/r/");
361         StrBufXMLEscAppend(Buf, NULL, c->room, strlen(c->room), 0);
362         StrBufAppendPrintf(Buf, "</D:href>");
363
364         StrBufAppendPrintf(Buf, "<D:propstat>");
365         StrBufAppendPrintf(Buf, "<D:status>HTTP/1.1 200 OK</D:status>");
366         StrBufAppendPrintf(Buf, "<D:prop>");
367         StrBufAppendPrintf(Buf, "<D:displayname>");
368         StrBufXMLEscAppend(Buf, NULL, c->room, strlen(c->room), 0);
369         StrBufAppendPrintf(Buf, "</D:displayname>");
370
371         StrBufAppendPrintf(Buf, "<D:owner />"); // empty owner ought to be legal; see rfc3744 section 5.1
372
373         StrBufAppendPrintf(Buf, "<D:resourcetype><D:collection />");
374         switch (c->room_default_view) {
375         case VIEW_CALENDAR:
376                 StrBufAppendPrintf(Buf, "<C:calendar />");      // RFC4791 section 4.2
377                 break;
378         }
379         StrBufAppendPrintf(Buf, "</D:resourcetype>");
380
381         int enumerate_by_euid = 0;      // nonzero if messages will be retrieved by euid instead of msgnum
382         switch (c->room_default_view) {
383         case VIEW_CALENDAR:             // RFC4791 section 5.2
384                 StrBufAppendPrintf(Buf, "<C:supported-calendar-component-set><C:comp name=\"VEVENT\"/></C:supported-calendar-component-set>");
385                 StrBufAppendPrintf(Buf, "<C:supported-calendar-data>");
386                 StrBufAppendPrintf(Buf, "<C:calendar-data content-type=\"text/calendar\" version=\"2.0\"/>");
387                 StrBufAppendPrintf(Buf, "</C:supported-calendar-data>");
388                 enumerate_by_euid = 1;
389                 break;
390         case VIEW_TASKS:                // RFC4791 section 5.2
391                 StrBufAppendPrintf(Buf, "<C:supported-calendar-component-set><C:comp name=\"VTODO\"/></C:supported-calendar-component-set>");
392                 StrBufAppendPrintf(Buf, "<C:supported-calendar-data>");
393                 StrBufAppendPrintf(Buf, "<C:calendar-data content-type=\"text/calendar\" version=\"2.0\"/>");
394                 StrBufAppendPrintf(Buf, "</C:supported-calendar-data>");
395                 enumerate_by_euid = 1;
396                 break;
397         case VIEW_ADDRESSBOOK:          // FIXME put some sort of CardDAV crapola here when we implement it
398                 enumerate_by_euid = 1;
399                 break;
400         case VIEW_WIKI:                 // FIXME invent "WikiDAV" ?  The versioning stuff in DAV could be useful.
401                 enumerate_by_euid = 1;
402                 break;
403         }
404
405         // FIXME get the mtime
406         // StrBufAppendPrintf(Buf, "<D:getlastmodified>");
407         // escputs(datestring);
408         // StrBufAppendPrintf(Buf, "</D:getlastmodified>");
409
410         StrBufAppendPrintf(Buf, "</D:prop>");
411         StrBufAppendPrintf(Buf, "</D:propstat>");
412         StrBufAppendPrintf(Buf, "</D:response>\n");
413
414         // If a depth greater than zero was specified, transmit the collection listing
415         // BEGIN COLLECTION
416         if (dav_depth > 0) {
417                 Array *msglist = get_msglist(c, "ALL");
418                 if (msglist) {
419                         int i;
420                         for (i = 0; i < array_len(msglist); ++i) {
421                                 if ((i % 10) == 0) {
422                                         syslog(LOG_DEBUG, "PROPFIND enumerated %d messages", i);
423                                 }
424                                 e = NULL;               // EUID gets stored here
425                                 timestamp = 0;
426
427                                 long m;
428                                 memcpy(&m, array_get_element_at(msglist, i), sizeof(long));
429
430                                 char cbuf[1024];
431                                 ctdl_printf(c, "MSG0 %ld|3", m);
432                                 ctdl_readline(c, cbuf, sizeof(cbuf));
433                                 if (cbuf[0] == '1')
434                                         while (ctdl_readline(c, cbuf, sizeof(cbuf)), strcmp(cbuf, "000")) {
435                                                 if ((enumerate_by_euid) && (!strncasecmp(cbuf, "exti=", 5))) {
436                                                         // e = strdup(&cbuf[5]);
437                                                         int elen = (2 * strlen(&cbuf[5]));
438                                                         e = malloc(elen);
439                                                         urlesc(e, elen, &cbuf[5]);
440                                                 }
441                                                 if (!strncasecmp(cbuf, "time=", 5)) {
442                                                         timestamp = atol(&cbuf[5]);
443                                                 }
444                                         }
445                                 if (e == NULL) {
446                                         e = malloc(20);
447                                         sprintf(e, "%ld", m);
448                                 }
449                                 StrBufAppendPrintf(Buf, "<D:response>");
450
451                                 // Generate the 'href' tag for this message
452                                 StrBufAppendPrintf(Buf, "<D:href>");
453                                 StrBufXMLEscAppend(Buf, NULL, h->site_prefix, strlen(h->site_prefix), 0);
454                                 StrBufAppendPrintf(Buf, "/ctdl/r/");
455                                 StrBufXMLEscAppend(Buf, NULL, c->room, strlen(c->room), 0);
456                                 StrBufAppendPrintf(Buf, "/");
457                                 StrBufXMLEscAppend(Buf, NULL, e, strlen(e), 0);
458                                 StrBufAppendPrintf(Buf, "</D:href>");
459                                 StrBufAppendPrintf(Buf, "<D:propstat>");
460                                 StrBufAppendPrintf(Buf, "<D:status>HTTP/1.1 200 OK</D:status>");
461                                 StrBufAppendPrintf(Buf, "<D:prop>");
462
463                                 switch (c->room_default_view) {
464                                 case VIEW_CALENDAR:
465                                         StrBufAppendPrintf(Buf,
466                                                            "<D:getcontenttype>text/calendar; component=vevent</D:getcontenttype>");
467                                         break;
468                                 case VIEW_TASKS:
469                                         StrBufAppendPrintf(Buf,
470                                                            "<D:getcontenttype>text/calendar; component=vtodo</D:getcontenttype>");
471                                         break;
472                                 case VIEW_ADDRESSBOOK:
473                                         StrBufAppendPrintf(Buf, "<D:getcontenttype>text/x-vcard</D:getcontenttype>");
474                                         break;
475                                 }
476
477                                 if (timestamp > 0) {
478                                         char *datestring = http_datestring(timestamp);
479                                         if (datestring) {
480                                                 StrBufAppendPrintf(Buf, "<D:getlastmodified>");
481                                                 StrBufXMLEscAppend(Buf, NULL, datestring, strlen(datestring), 0);
482                                                 StrBufAppendPrintf(Buf, "</D:getlastmodified>");
483                                                 free(datestring);
484                                         }
485                                         if (enumerate_by_euid) {        // FIXME ajc 2017oct30 should this be inside the timestamp conditional?
486                                                 StrBufAppendPrintf(Buf, "<D:getetag>\"%ld\"</D:getetag>", m);
487                                         }
488                                 }
489                                 StrBufAppendPrintf(Buf, "</D:prop></D:propstat></D:response>\n");
490                                 free(e);
491                         }
492                         array_free(msglist);
493                 };
494         }
495         // END COLLECTION
496
497         StrBufAppendPrintf(Buf, "</D:multistatus>\n");
498
499         add_response_header(h, strdup("Content-type"), strdup("text/xml"));
500         h->response_code = 207;
501         h->response_string = strdup("Multi-Status");
502         h->response_body_length = StrLength(Buf);
503         h->response_body = SmashStrBuf(&Buf);
504 }
505
506 // some good examples here
507 // http://blogs.nologin.es/rickyepoderi/index.php?/archives/14-Introducing-CalDAV-Part-I.html
508
509
510 // Called by the_room_itself() when the HTTP method is PROPFIND
511 void get_the_room_itself(struct http_transaction *h, struct ctdlsession *c) {
512         JsonValue *j = NewJsonObject(HKEY("gotoroom"));
513
514         JsonObjectAppend(j, NewJsonPlainString(HKEY("name"), c->room, -1));
515         JsonObjectAppend(j, NewJsonNumber(HKEY("current_view"), c->room_current_view));
516         JsonObjectAppend(j, NewJsonNumber(HKEY("default_view"), c->room_default_view));
517         JsonObjectAppend(j, NewJsonNumber(HKEY("is_room_aide"), c->is_room_aide));
518         JsonObjectAppend(j, NewJsonNumber(HKEY("is_trash_folder"), c->is_trash_folder));
519         JsonObjectAppend(j, NewJsonNumber(HKEY("can_delete_messages"), c->can_delete_messages));
520         JsonObjectAppend(j, NewJsonNumber(HKEY("new_messages"), c->new_messages));
521         JsonObjectAppend(j, NewJsonNumber(HKEY("total_messages"), c->total_messages));
522         JsonObjectAppend(j, NewJsonNumber(HKEY("last_seen"), c->last_seen));
523         JsonObjectAppend(j, NewJsonNumber(HKEY("room_mtime"), c->room_mtime));
524
525         StrBuf *sj = NewStrBuf();
526         SerializeJson(sj, j, 1);        // '1' == free the source array
527
528         add_response_header(h, strdup("Content-type"), strdup("application/json"));
529         h->response_code = 200;
530         h->response_string = strdup("OK");
531         h->response_body_length = StrLength(sj);
532         h->response_body = SmashStrBuf(&sj);
533         return;
534 }
535
536
537 // Handle REST/DAV requests for the room itself (such as /ctdl/r/roomname
538 // or /ctdl/r/roomname/ but *not* specific objects within the room)
539 void the_room_itself(struct http_transaction *h, struct ctdlsession *c) {
540
541         // OPTIONS method on the room itself usually is a DAV client assessing what's here.
542         if (!strcasecmp(h->method, "OPTIONS")) {
543                 options_the_room_itself(h, c);
544                 return;
545         }
546
547         // PROPFIND method on the room itself could be looking for a directory
548         if (!strcasecmp(h->method, "PROPFIND")) {
549                 propfind_the_room_itself(h, c);
550                 return;
551         }
552
553         // REPORT method on the room itself is probably the dreaded CalDAV tower-of-crapola
554         if (!strcasecmp(h->method, "REPORT")) {
555                 report_the_room_itself(h, c);
556                 return;
557         }
558
559         // GET method on the room itself is an API call, possibly from our JavaScript front end
560         if (!strcasecmp(h->method, "get")) {
561                 get_the_room_itself(h, c);
562                 return;
563         }
564
565         // we probably want a "go to this room" for interactive access
566         do_404(h);
567 }
568
569
570 // Dispatcher for "/ctdl/r" and "/ctdl/r/" for the room list
571 void room_list(struct http_transaction *h, struct ctdlsession *c) {
572         char buf[1024];
573         char roomname[1024];
574
575         ctdl_printf(c, "LKRA");
576         ctdl_readline(c, buf, sizeof(buf));
577         if (buf[0] != '1') {
578                 do_502(h);
579                 return;
580         }
581
582         JsonValue *j = NewJsonArray(HKEY("lkra"));
583         while (ctdl_readline(c, buf, sizeof(buf)), strcmp(buf, "000")) {
584
585                 // 0   |1      |2      |3      |4       |5 |6           |7           |8
586                 // name|QRflags|QRfloor|QRorder|QRflags2|ra|current_view|default_view|mtime
587                 JsonValue *jr = NewJsonObject(HKEY("room"));
588
589                 extract_token(roomname, buf, 0, '|', sizeof roomname);
590                 JsonObjectAppend(jr, NewJsonPlainString(HKEY("name"), roomname, -1));
591
592                 JsonObjectAppend(jr, NewJsonNumber(HKEY("floor"), extract_int(buf, 2)));
593                 JsonObjectAppend(jr, NewJsonNumber(HKEY("rorder"), extract_int(buf, 3)));
594
595                 int ra = extract_int(buf, 5);
596                 JsonObjectAppend(jr, NewJsonBool(HKEY("known"), (ra & UA_KNOWN)));
597                 JsonObjectAppend(jr, NewJsonBool(HKEY("hasnewmsgs"), (ra & UA_HASNEWMSGS)));
598
599                 JsonObjectAppend(jr, NewJsonNumber(HKEY("current_view"), extract_int(buf, 6)));
600                 JsonObjectAppend(jr, NewJsonNumber(HKEY("default_view"), extract_int(buf, 7)));
601                 JsonObjectAppend(jr, NewJsonNumber(HKEY("mtime"), extract_int(buf, 8)));
602
603                 JsonArrayAppend(j, jr); // add the room to the array
604         }
605
606         StrBuf *sj = NewStrBuf();
607         SerializeJson(sj, j, 1);        // '1' == free the source array
608
609         add_response_header(h, strdup("Content-type"), strdup("application/json"));
610         h->response_code = 200;
611         h->response_string = strdup("OK");
612         h->response_body_length = StrLength(sj);
613         h->response_body = SmashStrBuf(&sj);
614 }
615
616
617 // Dispatcher for paths starting with /ctdl/r/
618 void ctdl_r(struct http_transaction *h, struct ctdlsession *c) {
619         char requested_roomname[128];
620         char buf[1024];
621         long room_flags = 0;
622         long room_flags2 = 0;
623
624         // All room-related functions require being "in" the room specified.  Are we in that room already?
625         extract_token(requested_roomname, h->url, 3, '/', sizeof requested_roomname);
626         unescape_input(requested_roomname);
627
628         if (IsEmptyStr(requested_roomname)) {   //      /ctdl/r/
629                 room_list(h, c);
630                 return;
631         }
632         // If not, try to go there.
633         if (strcasecmp(requested_roomname, c->room)) {
634                 ctdl_printf(c, "GOTO %s", requested_roomname);
635                 ctdl_readline(c, buf, sizeof(buf));
636                 if (buf[0] == '2') {
637                         // buf[3] will indicate whether any instant messages are waiting
638                         extract_token(c->room, &buf[4], 0, '|', sizeof c->room);
639                         c->new_messages = extract_int(&buf[4], 1);
640                         c->total_messages = extract_int(&buf[4], 2);
641                         //      3       (int)info                       Info flag: set to nonzero if the user needs to read this room's info file
642                         room_flags = extract_long(&buf[4], 3);          // Various flags associated with this room.
643                         //      5       (long)CC->room.QRhighest        The highest message number present in this room
644                         c->last_seen = extract_long(&buf[4], 6);        // The highest message number the user has read in this room
645                         //      7       (int)rmailflag                  Boolean flag: 1 if this is a Mail> room, 0 otherwise.
646                         c->is_room_aide = extract_int(&buf[4], 8);
647                         //      9                                       This position is no longer used
648                         //      10      (int)CC->room.QRfloor           The floor number this room resides on
649                         c->room_current_view = extract_int(&buf[4], 11);
650                         c->room_default_view = extract_int(&buf[4], 12);
651                         c->is_trash_folder  = extract_int(&buf[4], 13); // Boolean flag: 1 if this is the user's Trash folder, 0 otherwise.
652                         room_flags2 = extract_long(&buf[4], 14);        // More flags associated with this room.
653                         c->room_mtime = extract_long(&buf[4], 15);      // Timestamp of the last write activity in this room
654
655                         // If any of these three conditions are met, let the client know it has permission to delete messages.
656                         if ((c->is_room_aide) || (room_flags & QR_MAILBOX) || (room_flags2 & QR2_COLLABDEL)) {
657                                 c->can_delete_messages = 1;
658                         }
659                         else {
660                                 c->can_delete_messages = 0;
661                         }
662                 }
663                 else {
664                         do_404(h);
665                         return;
666                 }
667         }
668         // At this point our Citadel client session is "in" the specified room.
669
670         if (num_tokens(h->url, '/') == 4) {     //      /ctdl/r/roomname
671                 the_room_itself(h, c);
672                 return;
673         }
674
675         extract_token(buf, h->url, 4, '/', sizeof buf);
676         if (num_tokens(h->url, '/') == 5) {
677                 if (IsEmptyStr(buf)) {
678                         the_room_itself(h, c);  //      /ctdl/r/roomname/       ( same as /ctdl/r/roomname )
679                 }
680                 else {
681                         object_in_room(h, c);   //      /ctdl/r/roomname/object
682                 }
683                 return;
684         }
685         if (num_tokens(h->url, '/') >= 6) {
686                 object_in_room(h, c);   //      /ctdl/r/roomname/object/ or possibly /ctdl/r/roomname/object/component
687                 return;
688         }
689         // If we get to this point, the client specified a valid room but requested an action we don't know how to perform.
690         do_404(h);
691 }