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