CtdlCheckExpress() now accepts a session context.
[citadel.git] / citadel / server / room_ops.c
1 // Server functions which perform operations on room objects.
2 //
3 // Copyright (c) 1987-2024 by the citadel.org team
4 //
5 // This program is open source software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License, version 3.
7
8 #include <stdio.h>
9 #include <libcitadel.h>
10
11 #include "citserver.h"
12 #include "ctdl_module.h"
13 #include "config.h"
14 #include "control.h"
15 #include "user_ops.h"
16 #include "room_ops.h"
17
18 struct floor *floorcache[MAXFLOORS];
19
20 // Determine whether the currently logged in session has permission to read
21 // messages in the current room.
22 int CtdlDoIHavePermissionToReadMessagesInThisRoom(void) {
23         if (    (!(CC->logged_in))
24                 && (!(CC->internal_pgm))
25                 && (!CtdlGetConfigInt("c_guest_logins"))
26         ) {
27                 return(om_not_logged_in);
28         }
29         return(om_ok);
30 }
31
32
33 // Check to see whether we have permission to post a message in the current
34 // room.  Returns a *CITADEL ERROR CODE* and puts a message in errmsgbuf, or
35 // returns 0 on success.
36 int CtdlDoIHavePermissionToPostInThisRoom(char *errmsgbuf, size_t n, PostType PostPublic, int is_reply) {
37         int ra;
38
39         if (!(CC->logged_in) && (PostPublic == POST_LOGGED_IN)) {
40                 snprintf(errmsgbuf, n, "Not logged in.");
41                 return (ERROR + NOT_LOGGED_IN);
42         }
43         else if (PostPublic == CHECK_EXIST) {
44                 return (0);                                     // evaluate whether a recipient exists
45         }
46         else if (!(CC->logged_in)) {
47                 if ((CC->room.QRflags & QR_READONLY)) {
48                         snprintf(errmsgbuf, n, "Not logged in.");
49                         return (ERROR + NOT_LOGGED_IN);
50                 }
51                 return (0);
52         }
53
54         if ((CC->user.axlevel < AxProbU) && ((CC->room.QRflags & QR_MAILBOX) == 0)) {
55                 snprintf(errmsgbuf, n, "Need to be validated to enter (except in %s> to sysop)", MAILROOM);
56                 return (ERROR + HIGHER_ACCESS_REQUIRED);
57         }
58
59         CtdlRoomAccess(&CC->room, &CC->user, &ra, NULL);
60
61         if (ra & UA_POSTALLOWED) {
62                 strcpy(errmsgbuf, "OK to post or reply here");
63                 return(0);
64         }
65
66         if ( (ra & UA_REPLYALLOWED) && (is_reply) ) {
67                 // To be thorough, we ought to check to see if the message they are
68                 // replying to is actually a valid one in this room, but unless this
69                 // actually becomes a problem we'll go with high performance instead.
70                 strcpy(errmsgbuf, "OK to reply here");
71                 return(0);
72         }
73
74         if ( (ra & UA_REPLYALLOWED) && (!is_reply) ) {
75                 // Clarify what happened with a better error message
76                 snprintf(errmsgbuf, n, "You may only reply to existing messages here.");
77                 return (ERROR + HIGHER_ACCESS_REQUIRED);
78         }
79
80         snprintf(errmsgbuf, n, "Higher access is required to post in this room.");
81         return (ERROR + HIGHER_ACCESS_REQUIRED);
82
83 }
84
85
86 // Check whether the current user has permission to delete messages from
87 // the current room (returns 1 for yes, 0 for no)
88 int CtdlDoIHavePermissionToDeleteMessagesFromThisRoom(void) {
89         int ra;
90         CtdlRoomAccess(&CC->room, &CC->user, &ra, NULL);
91         if (ra & UA_DELETEALLOWED) return(1);
92         return(0);
93 }
94
95
96 // This is the main access control function for any user/room pair.
97 // Yes, it has a couple of gotos.  If you don't like that, go die in a car fire.
98 void CtdlRoomAccess(struct ctdlroom *roombuf, struct ctdluser *userbuf, int *result, int *view) {
99         int retval = 0;
100         struct visit vbuf;
101         int is_me = 0;
102         int is_guest = 0;
103
104         if (userbuf == &CC->user) {
105                 is_me = 1;
106         }
107
108         if ((is_me) && (CtdlGetConfigInt("c_guest_logins")) && (!CC->logged_in)) {
109                 is_guest = 1;
110         }
111
112         // for internal programs, always do everything
113         if (((CC->internal_pgm)) && (roombuf->QRflags & QR_INUSE)) {
114                 retval = (UA_KNOWN | UA_GOTOALLOWED | UA_POSTALLOWED | UA_DELETEALLOWED | UA_REPLYALLOWED);
115                 vbuf.v_view = 0;
116                 goto SKIP_EVERYTHING;
117         }
118
119         // If guest mode is enabled, always grant access to the Lobby
120         if ((is_guest) && (!strcasecmp(roombuf->QRname, BASEROOM))) {
121                 retval = (UA_KNOWN | UA_GOTOALLOWED);
122                 vbuf.v_view = 0;
123                 goto SKIP_EVERYTHING;
124         }
125
126         // Locate any applicable user/room relationships
127         if (is_guest) {
128                 memset(&vbuf, 0, sizeof vbuf);
129         }
130         else {
131                 CtdlGetRelationship(&vbuf, userbuf, roombuf);
132         }
133
134         // Force the properties of the Aide room
135         if (!strcasecmp(roombuf->QRname, CtdlGetConfigStr("c_aideroom"))) {
136                 if (userbuf->axlevel >= AxAideU) {
137                         retval = UA_KNOWN | UA_GOTOALLOWED | UA_POSTALLOWED | UA_DELETEALLOWED | UA_REPLYALLOWED;
138                 }
139                 else {
140                         retval = 0;
141                 }
142                 goto NEWMSG;
143         }
144
145         // If this is a public room, it's accessible...
146         if (    ((roombuf->QRflags & QR_PRIVATE) == 0) 
147                 && ((roombuf->QRflags & QR_MAILBOX) == 0)
148         ) {
149                 retval = retval | UA_KNOWN | UA_GOTOALLOWED;
150         }
151
152         // If this is a preferred users only room, check access level
153         if (roombuf->QRflags & QR_PREFONLY) {
154                 if (userbuf->axlevel < AxPrefU) {
155                         retval = retval & ~UA_KNOWN & ~UA_GOTOALLOWED;
156                 }
157         }
158
159         // For private rooms, check the generation number matchups
160         if (    (roombuf->QRflags & QR_PRIVATE) 
161                 && ((roombuf->QRflags & QR_MAILBOX) == 0)
162         ) {
163
164                 // An explicit match means the user belongs in this room
165                 if (vbuf.v_flags & V_ACCESS) {
166                         retval = retval | UA_KNOWN | UA_GOTOALLOWED;
167                 }
168                 // Otherwise, check if this is a guess-name or passworded
169                 // room.  If it is, a goto may at least be attempted
170                 else if (       (roombuf->QRflags & QR_PRIVATE)
171                                 || (roombuf->QRflags & QR_PASSWORDED)
172                 ) {
173                         retval = retval & ~UA_KNOWN;
174                         retval = retval | UA_GOTOALLOWED;
175                 }
176         }
177
178         // For mailbox rooms, also check the namespace.   Also, mailbox owners can delete their messages
179         if ( (roombuf->QRflags & QR_MAILBOX) && (atol(roombuf->QRname) != 0)) {
180                 if (userbuf->usernum == atol(roombuf->QRname)) {
181                         retval = retval | UA_KNOWN | UA_GOTOALLOWED | UA_POSTALLOWED | UA_DELETEALLOWED | UA_REPLYALLOWED;
182                 }
183                 // An explicit match means the user belongs in this room
184                 if (vbuf.v_flags & V_ACCESS) {
185                         retval = retval | UA_KNOWN | UA_GOTOALLOWED | UA_POSTALLOWED | UA_DELETEALLOWED | UA_REPLYALLOWED;
186                 }
187         }
188
189         // For non-mailbox rooms...
190         else {
191                 // User is allowed to post in the room unless:
192                 // - User is not validated
193                 // - It is a read-only room
194                 // - It is a blog room (in which case we only allow replies to existing messages)
195                 int post_allowed = 1;
196                 int reply_allowed = 1;
197                 if (userbuf->axlevel < AxProbU) {
198                         post_allowed = 0;
199                         reply_allowed = 0;
200                 }
201                 if (roombuf->QRflags & QR_READONLY) {
202                         post_allowed = 0;
203                         reply_allowed = 0;
204                 }
205                 if (roombuf->QRdefaultview == VIEW_BLOG) {
206                         post_allowed = 0;
207                 }
208                 if (post_allowed) {
209                         retval = retval | UA_POSTALLOWED | UA_REPLYALLOWED;
210                 }
211                 if (reply_allowed) {
212                         retval = retval | UA_REPLYALLOWED;
213                 }
214
215                 // If "collaborative deletion" is active for this room, any user who can post is also allowed to delete
216                 if (roombuf->QRflags2 & QR2_COLLABDEL) {
217                         if (retval & UA_POSTALLOWED) {
218                                 retval = retval | UA_DELETEALLOWED;
219                         }
220                 }
221         }
222
223         // Check to see if the user has forgotten this room
224         if (vbuf.v_flags & V_FORGET) {
225                 retval = retval & ~UA_KNOWN;
226                 if (    ( ((roombuf->QRflags & QR_PRIVATE) == 0) 
227                         && ((roombuf->QRflags & QR_MAILBOX) == 0)
228                 ) || (  (roombuf->QRflags & QR_MAILBOX) 
229                         && (atol(roombuf->QRname) == CC->user.usernum))
230                 ) {
231                         retval = retval | UA_ZAPPED;
232                 }
233         }
234
235         // If user is explicitly locked out of this room, deny everything
236         if (vbuf.v_flags & V_LOCKOUT) {
237                 retval = retval & ~UA_KNOWN & ~UA_GOTOALLOWED & ~UA_POSTALLOWED & ~UA_REPLYALLOWED;
238         }
239
240         // Aides get access to all private rooms
241         if (    (userbuf->axlevel >= AxAideU)
242                 && ((roombuf->QRflags & QR_MAILBOX) == 0)
243         ) {
244                 if (vbuf.v_flags & V_FORGET) {
245                         retval = retval | UA_GOTOALLOWED | UA_POSTALLOWED | UA_REPLYALLOWED;
246                 }
247                 else {
248                         retval = retval | UA_KNOWN | UA_GOTOALLOWED | UA_POSTALLOWED | UA_REPLYALLOWED;
249                 }
250         }
251
252         // Aides can gain access to mailboxes as well, but they don't show by default.
253         if (    (userbuf->axlevel >= AxAideU)
254                 && (roombuf->QRflags & QR_MAILBOX)
255         ) {
256                 retval = retval | UA_GOTOALLOWED | UA_POSTALLOWED | UA_REPLYALLOWED;
257         }
258
259         // Aides and Room Aides have admin privileges
260         if (    (userbuf->axlevel >= AxAideU)
261                 || (userbuf->usernum == roombuf->QRroomaide)
262         ) {
263                 retval = retval | UA_ADMINALLOWED | UA_DELETEALLOWED | UA_POSTALLOWED | UA_REPLYALLOWED;
264         }
265
266 NEWMSG: // By the way, we also check for the presence of new messages
267         if (is_msg_in_sequence_set(vbuf.v_seen, roombuf->QRhighest) == 0) {
268                 retval = retval | UA_HASNEWMSGS;
269         }
270
271         // System rooms never show up in the list.
272         if (roombuf->QRflags2 & QR2_SYSTEM) {
273                 retval = retval & ~UA_KNOWN;
274         }
275
276 SKIP_EVERYTHING:
277         // Now give the caller the information it wants.
278         if (result != NULL) *result = retval;
279         if (view != NULL) *view = vbuf.v_view;
280 }
281
282
283 // Self-checking stuff for a room record read into memory
284 void room_sanity_check(struct ctdlroom *qrbuf) {
285         // Mailbox rooms are always on the lowest floor
286         if (qrbuf->QRflags & QR_MAILBOX) {
287                 qrbuf->QRfloor = 0;
288         }
289         // Listing order of 0 is illegal except for base rooms
290         if (qrbuf->QRorder == 0) {
291                 if (    !(qrbuf->QRflags & QR_MAILBOX)
292                         && strncasecmp(qrbuf->QRname, CtdlGetConfigStr("c_baseroom"), ROOMNAMELEN)
293                         && strncasecmp(qrbuf->QRname, CtdlGetConfigStr("c_aideroom"), ROOMNAMELEN)
294                 ) {
295                         qrbuf->QRorder = 64;
296                 }
297         }
298 }
299
300
301 // CtdlGetRoom()  -  retrieve room data from disk
302 int CtdlGetRoom(struct ctdlroom *qrbuf, const char *room_name) {
303         struct cdbdata cdbqr;
304         char lowercase_name[ROOMNAMELEN];
305         char personal_lowercase_name[ROOMNAMELEN];
306         long len;
307
308         len = strlen(room_name);
309         for (int i=0; i<=len; ++i) {
310                 lowercase_name[i] = tolower(room_name[i]);
311         }
312
313         memset(qrbuf, 0, sizeof(struct ctdlroom));
314
315         if (IsEmptyStr(lowercase_name)) {
316                 return(1);                      // empty room name , not valid
317         }
318
319         // First, try the public namespace
320         cdbqr = cdb_fetch(CDB_ROOMS, lowercase_name, strlen(lowercase_name));
321
322         // If that didn't work, try the user's personal namespace
323         if (cdbqr.ptr == NULL) {
324                 snprintf(personal_lowercase_name, sizeof personal_lowercase_name, "%010ld.%s", CC->user.usernum, lowercase_name);
325                 cdbqr = cdb_fetch(CDB_ROOMS, personal_lowercase_name, strlen(personal_lowercase_name));
326         }
327         if (cdbqr.ptr != NULL) {
328                 memcpy(qrbuf, cdbqr.ptr, ((cdbqr.len > sizeof(struct ctdlroom)) ?  sizeof(struct ctdlroom) : cdbqr.len));
329                 room_sanity_check(qrbuf);
330                 return (0);
331         }
332         else {
333                 return (1);
334         }
335 }
336
337
338 // CtdlGetRoomLock()  -  same as getroom() but locks the record (if supported)
339 int CtdlGetRoomLock(struct ctdlroom *qrbuf, const char *room_name) {
340         register int retval;
341         retval = CtdlGetRoom(qrbuf, room_name);
342         if (retval == 0) {
343                 begin_critical_section(S_ROOMS);
344         }
345         return(retval);
346 }
347
348
349 // b_putroom()  -  back end to putroom() and b_deleteroom()
350 // (if the supplied buffer is NULL, delete the room record)
351 void b_putroom(struct ctdlroom *qrbuf, char *room_name) {
352         char lowercase_name[ROOMNAMELEN];
353         long len;
354
355         len = strlen(room_name);
356         for (int i=0; i<=len; ++i) {
357                 lowercase_name[i] = tolower(room_name[i]);
358         }
359
360         if (qrbuf == NULL) {
361                 cdb_delete(CDB_ROOMS, lowercase_name, len);
362         }
363         else {
364                 time(&qrbuf->QRmtime);
365                 cdb_store(CDB_ROOMS, lowercase_name, len, qrbuf, sizeof(struct ctdlroom));
366         }
367 }
368
369
370 // CtdlPutRoom()  -  store room data to disk
371 void CtdlPutRoom(struct ctdlroom *qrbuf) {
372         b_putroom(qrbuf, qrbuf->QRname);
373 }
374
375
376 // b_deleteroom()  -  delete a room record from disk
377 void b_deleteroom(char *room_name) {
378         b_putroom(NULL, room_name);
379 }
380
381
382 // CtdlPutRoomLock()  -  same as CtdlPutRoom() but unlocks the record (if supported)
383 void CtdlPutRoomLock(struct ctdlroom *qrbuf) {
384         CtdlPutRoom(qrbuf);
385         end_critical_section(S_ROOMS);
386         //syslog(LOG_ERR, "\033[32mCtdlGetRoomLock(%p) released\033[0m", CC);
387 }
388
389
390 // CtdlGetFloorByName()  -  retrieve the number of the named floor
391 // return < 0 if not found else return floor number
392 int CtdlGetFloorByName(const char *floor_name) {
393         int a;
394         struct floor *flbuf = NULL;
395
396         for (a = 0; a < MAXFLOORS; ++a) {
397                 flbuf = CtdlGetCachedFloor(a);
398
399                 // check to see if it already exists
400                 if ((!strcasecmp(flbuf->f_name, floor_name)) && (flbuf->f_flags & F_INUSE)) {
401                         return a;
402                 }
403         }
404         return -1;
405 }
406
407
408 // CtdlGetFloorByNameLock()  -  retrieve floor number for given floor and lock the floor list.
409 int CtdlGetFloorByNameLock(const char *floor_name) {
410         begin_critical_section(S_FLOORTAB);
411         return CtdlGetFloorByName(floor_name);
412 }
413
414
415 // CtdlGetAvailableFloor()  -  Return number of first unused floor
416 // return < 0 if none available
417 int CtdlGetAvailableFloor(void) {
418         int a;
419         struct floor *flbuf = NULL;
420
421         for (a = 0; a < MAXFLOORS; a++) {
422                 flbuf = CtdlGetCachedFloor(a);
423
424                 // check to see if it already exists
425                 if ((flbuf->f_flags & F_INUSE) == 0) {
426                         return a;
427                 }
428         }
429         return -1;
430 }
431
432
433 // CtdlGetFloor()  -  retrieve floor data from disk
434 void CtdlGetFloor(struct floor *flbuf, int floor_num) {
435         struct cdbdata cdbfl;
436
437         memset(flbuf, 0, sizeof(struct floor));
438         cdbfl = cdb_fetch(CDB_FLOORTAB, &floor_num, sizeof(int));
439         if (cdbfl.ptr != NULL) {
440                 memcpy(flbuf, cdbfl.ptr, ((cdbfl.len > sizeof(struct floor)) ?  sizeof(struct floor) : cdbfl.len));
441         }
442         else {
443                 if (floor_num == 0) {
444                         safestrncpy(flbuf->f_name, "Main Floor", sizeof flbuf->f_name);
445                         flbuf->f_flags = F_INUSE;
446                         flbuf->f_ref_count = 3;
447                 }
448         }
449 }
450
451
452 // lgetfloor()  -  same as CtdlGetFloor() but locks the record (if supported)
453 void lgetfloor(struct floor *flbuf, int floor_num) {
454         begin_critical_section(S_FLOORTAB);
455         CtdlGetFloor(flbuf, floor_num);
456 }
457
458
459 // CtdlGetCachedFloor()  -  Get floor record from *cache* (loads from disk if needed)
460 // This is strictly a performance hack.
461 struct floor *CtdlGetCachedFloor(int floor_num) {
462         static int initialized = 0;
463         int i;
464         int fetch_new = 0;
465         struct floor *fl = NULL;
466
467         begin_critical_section(S_FLOORCACHE);
468         if (initialized == 0) {
469                 for (i=0; i<MAXFLOORS; ++i) {
470                         floorcache[floor_num] = NULL;
471                 }
472                 initialized = 1;
473         }
474         if (floorcache[floor_num] == NULL) {
475                 fetch_new = 1;
476         }
477         end_critical_section(S_FLOORCACHE);
478
479         if (fetch_new) {
480                 fl = malloc(sizeof(struct floor));
481                 CtdlGetFloor(fl, floor_num);
482                 begin_critical_section(S_FLOORCACHE);
483                 if (floorcache[floor_num] != NULL) {
484                         free(floorcache[floor_num]);
485                 }
486                 floorcache[floor_num] = fl;
487                 end_critical_section(S_FLOORCACHE);
488         }
489
490         return(floorcache[floor_num]);
491 }
492
493
494 // CtdlPutFloor()  -  store floor data on disk
495 void CtdlPutFloor(struct floor *flbuf, int floor_num) {
496         // If we've cached this, clear it out, 'cuz it's WRONG now!
497         begin_critical_section(S_FLOORCACHE);
498         if (floorcache[floor_num] != NULL) {
499                 free(floorcache[floor_num]);
500                 floorcache[floor_num] = malloc(sizeof(struct floor));
501                 memcpy(floorcache[floor_num], flbuf, sizeof(struct floor));
502         }
503         end_critical_section(S_FLOORCACHE);
504         cdb_store(CDB_FLOORTAB, &floor_num, sizeof(int), flbuf, sizeof(struct floor));
505 }
506
507
508 // CtdlPutFloorLock()  -  same as CtdlPutFloor() but unlocks the record (if supported)
509 void CtdlPutFloorLock(struct floor *flbuf, int floor_num) {
510         CtdlPutFloor(flbuf, floor_num);
511         end_critical_section(S_FLOORTAB);
512
513 }
514
515
516 // lputfloor()  -  same as CtdlPutFloor() but unlocks the record (if supported)
517 void lputfloor(struct floor *flbuf, int floor_num) {
518         CtdlPutFloorLock(flbuf, floor_num);
519 }
520
521
522 // Iterate through the room table, performing a callback for each room.
523 void CtdlForEachRoom(ForEachRoomCallBack callback_func, void *in_data) {
524         struct ctdlroom qrbuf;
525         struct cdbkeyval cdbqr;
526
527         cdb_rewind(CDB_ROOMS);
528         while (cdbqr = cdb_next_item(CDB_ROOMS), cdbqr.val.ptr!=NULL) {         // always read through to the end
529                 memset(&qrbuf, 0, sizeof(struct ctdlroom));
530                 memcpy(&qrbuf, cdbqr.val.ptr, ((cdbqr.val.len > sizeof(struct ctdlroom)) ? sizeof(struct ctdlroom) : cdbqr.val.len) );
531                 room_sanity_check(&qrbuf);
532                 if (qrbuf.QRflags & QR_INUSE) {
533                         callback_func(&qrbuf, in_data);
534                 }
535         }
536 }
537
538
539 // delete_msglist()  -  delete room message pointers
540 void delete_msglist(struct ctdlroom *whichroom) {
541         struct cdbdata cdbml;
542
543         // Make sure the msglist we're deleting actually exists; don't try to delete an invalid record
544         cdbml = cdb_fetch(CDB_MSGLISTS, &whichroom->QRnumber, sizeof(long));
545         if (cdbml.ptr != NULL) {
546                 // ok it exists, go ahead and delete it
547                 cdb_delete(CDB_MSGLISTS, &whichroom->QRnumber, sizeof(long));
548         }
549 }
550
551
552 // Message pointer compare function for sort_msglist()
553 int sort_msglist_cmp(const void *m1, const void *m2) {
554         if ((*(const long *)m1) > (*(const long *)m2)) return(1);
555         if ((*(const long *)m1) < (*(const long *)m2)) return(-1);
556         return(0);
557 }
558
559
560 // sort message pointers
561 // (returns new msg count)
562 int sort_msglist(long listptrs[], int oldcount) {
563         int numitems;
564         int i = 0;
565
566         numitems = oldcount;
567         if (numitems < 2) {                                                     // an empty or 1-item list needs no sorting
568                 return (oldcount);
569         }
570
571         qsort(listptrs, numitems, sizeof(long), sort_msglist_cmp);              // do the sort
572
573         while ((i < numitems) && (listptrs[i] == 0L)) i++;                      // yank out any nulls
574         if (i > 0) {
575                 memmove(&listptrs[0], &listptrs[i], (sizeof(long) * (numitems - i)));
576                 numitems-=i;
577         }
578
579         return (numitems);
580 }
581
582
583 // Determine whether a given room is non-editable.
584 int CtdlIsNonEditable(struct ctdlroom *qrbuf) {
585
586         // The inbox cannot be edited
587         if ( (qrbuf->QRflags & QR_MAILBOX) && (!strcasecmp(&qrbuf->QRname[11], MAILROOM)) ) {
588                 return (1);
589         }
590
591         // Everything else is editable
592         return (0);
593 }
594
595
596 // Retrieve a list of all messages (message numbers) in the specified room.
597 // Returns the number of messages in the room, allocates a pointer to the array and stuffs it in the supplied location.
598 // Caller must free that memory.
599 // If no messages in room, returns 0 and msgs is set to NULL.
600 int CtdlFetchMsgList(long roomnum, long **msgs) {
601         int num_msgs = 0;
602         struct cdbdata cdbfr;
603
604         cdbfr = cdb_fetch(CDB_MSGLISTS, &roomnum, sizeof(long));
605         if (cdbfr.ptr == NULL) {
606                 *msgs = malloc(sizeof(long));   // dummy buffer
607                 *msgs[0] = 0;
608                 return (0);
609         }
610
611         num_msgs = cdbfr.len / sizeof(long);
612         if (num_msgs > 0) {
613                 *msgs = malloc(cdbfr.len);
614                 memcpy(*msgs, cdbfr.ptr, cdbfr.len);
615         }
616         else {
617                 *msgs = NULL;
618         }
619         return(num_msgs);
620 }
621
622
623 // Make the specified room the current room for this session.  No validation
624 // or access control is done here -- the caller should make sure that the
625 // specified room exists and is ok to access.
626 void CtdlUserGoto(char *where, int display_result, int transiently, int *retmsgs, int *retnew, long *retoldest, long *retnewest) {
627         int a;
628         int new_messages = 0;
629         int old_messages = 0;
630         int total_messages = 0;
631         long oldest_message = 0;
632         long newest_message = 0;
633         int info = 0;
634         int rmailflag;
635         int raideflag;
636         struct visit vbuf;
637         char truncated_roomname[ROOMNAMELEN];
638         long *msglist = NULL;
639         int num_msgs = 0;
640         unsigned int original_v_flags;
641         int num_sets;
642         int s;
643         char setstr[128], lostr[64], histr[64];
644         long lo, hi;
645         int is_trash = 0;
646
647         // If the supplied room name is NULL, the caller wants us to know that
648         // it has already copied the room record into CC->room, so
649         // we can skip the extra database fetch.
650         if (where != NULL) {
651                 safestrncpy(CC->room.QRname, where, sizeof CC->room.QRname);
652                 CtdlGetRoom(&CC->room, where);
653         }
654
655         // Take care of all the formalities.
656
657         begin_critical_section(S_USERS);
658         CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
659         original_v_flags = vbuf.v_flags;
660
661         // Know the room ... but not if it's the page log room, or if the
662         // caller specified that we're only entering this room transiently.
663         int add_room_to_known_list = 1;
664         if (transiently == 1) {
665                 add_room_to_known_list = 0;
666         }
667         char *c_logpages = CtdlGetConfigStr("c_logpages");
668         if ( (c_logpages != NULL) && (!strcasecmp(CC->room.QRname, c_logpages)) ) {
669                 add_room_to_known_list = 0;
670         }
671         if (add_room_to_known_list) {
672                 vbuf.v_flags = vbuf.v_flags & ~V_FORGET & ~V_LOCKOUT;
673                 vbuf.v_flags = vbuf.v_flags | V_ACCESS;
674         }
675         
676         // Only rewrite the database record if we changed something
677         if (vbuf.v_flags != original_v_flags) {
678                 CtdlSetRelationship(&vbuf, &CC->user, &CC->room);
679         }
680         end_critical_section(S_USERS);
681
682         // Set info to 1 if the room banner is new since our last visit.
683         // Some clients only want to display it when it changes.
684         if (CC->room.msgnum_info > vbuf.v_lastseen) {
685                 info = 1;
686         }
687
688         num_msgs = CtdlFetchMsgList(CC->room.QRnumber, &msglist);
689
690         total_messages = 0;
691         for (a=0; a<num_msgs; ++a) {
692                 if (msglist[a] > 0L) ++total_messages;
693         }
694
695         if (total_messages > 0) {
696                 oldest_message = msglist[0];
697                 newest_message = msglist[num_msgs - 1];
698         }
699
700         num_sets = num_tokens(vbuf.v_seen, ',');
701         for (s=0; s<num_sets; ++s) {
702                 extract_token(setstr, vbuf.v_seen, s, ',', sizeof setstr);
703
704                 extract_token(lostr, setstr, 0, ':', sizeof lostr);
705                 if (num_tokens(setstr, ':') >= 2) {
706                         extract_token(histr, setstr, 1, ':', sizeof histr);
707                         if (!strcmp(histr, "*")) {
708                                 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
709                         }
710                 } 
711                 else {
712                         strcpy(histr, lostr);
713                 }
714                 lo = atol(lostr);
715                 hi = atol(histr);
716
717                 for (a=0; a<num_msgs; ++a) if (msglist[a] > 0L) {
718                         if ((msglist[a] >= lo) && (msglist[a] <= hi)) {
719                                 ++old_messages;
720                                 msglist[a] = 0L;
721                         }
722                 }
723         }
724         new_messages = total_messages - old_messages;
725
726         if (msglist != NULL) free(msglist);
727
728         if (CC->room.QRflags & QR_MAILBOX)
729                 rmailflag = 1;
730         else
731                 rmailflag = 0;
732
733         if ((CC->room.QRroomaide == CC->user.usernum) || (CC->user.axlevel >= AxAideU))
734                 raideflag = 1;
735         else
736                 raideflag = 0;
737
738         safestrncpy(truncated_roomname, CC->room.QRname, sizeof truncated_roomname);
739         if ( (CC->room.QRflags & QR_MAILBOX) && (atol(CC->room.QRname) == CC->user.usernum) ) {
740                 safestrncpy(truncated_roomname, &truncated_roomname[11], sizeof truncated_roomname);
741         }
742
743         if (!strcasecmp(truncated_roomname, USERTRASHROOM)) {
744                 is_trash = 1;
745         }
746
747         if (retmsgs != NULL) *retmsgs = total_messages;
748         if (retnew != NULL) *retnew = new_messages;
749         if (retoldest != NULL) *retoldest = oldest_message;
750         if (retnewest != NULL) *retnewest = newest_message;
751         syslog(LOG_DEBUG, "room_ops: %s : %d new of %d total messages, oldest=%ld, newest=%ld",
752                    CC->room.QRname, new_messages, total_messages, oldest_message, newest_message
753         );
754
755         CC->curr_view = (int)vbuf.v_view;
756
757         if (display_result) {
758                 cprintf("%d%c%s|%d|%d|%d|%d|%ld|%ld|%d|%d|%d|%d|%d|%d|%d|%d|%ld|\n",
759                         CIT_OK, CtdlCheckExpress(CC),
760                         truncated_roomname,
761                         (int)new_messages,
762                         (int)total_messages,
763                         (int)info,
764                         (int)CC->room.QRflags,
765                         (long)CC->room.QRhighest,
766                         (long)vbuf.v_lastseen,
767                         (int)rmailflag,
768                         (int)raideflag,
769                         0,                                      // new mail is no longer counted here
770                         (int)CC->room.QRfloor,
771                         (int)vbuf.v_view,
772                         (int)CC->room.QRdefaultview,
773                         (int)is_trash,
774                         (int)CC->room.QRflags2,
775                         (long)CC->room.QRmtime
776                 );
777         }
778 }
779
780
781 // Handle some of the macro named rooms
782 void convert_room_name_macros(char *towhere, size_t maxlen) {
783         if (!strcasecmp(towhere, "_BASEROOM_")) {
784                 safestrncpy(towhere, CtdlGetConfigStr("c_baseroom"), maxlen);
785         }
786         else if (!strcasecmp(towhere, "_MAIL_")) {
787                 safestrncpy(towhere, MAILROOM, maxlen);
788         }
789         else if (!strcasecmp(towhere, "_TRASH_")) {
790                 safestrncpy(towhere, USERTRASHROOM, maxlen);
791         }
792         else if (!strcasecmp(towhere, "_DRAFTS_")) {
793                 safestrncpy(towhere, USERDRAFTROOM, maxlen);
794         }
795         else if (!strcasecmp(towhere, "_BITBUCKET_")) {
796                 safestrncpy(towhere, CtdlGetConfigStr("c_twitroom"), maxlen);
797         }
798         else if (!strcasecmp(towhere, "_CALENDAR_")) {
799                 safestrncpy(towhere, USERCALENDARROOM, maxlen);
800         }
801         else if (!strcasecmp(towhere, "_TASKS_")) {
802                 safestrncpy(towhere, USERTASKSROOM, maxlen);
803         }
804         else if (!strcasecmp(towhere, "_CONTACTS_")) {
805                 safestrncpy(towhere, USERCONTACTSROOM, maxlen);
806         }
807         else if (!strcasecmp(towhere, "_NOTES_")) {
808                 safestrncpy(towhere, USERNOTESROOM, maxlen);
809         }
810 }
811
812
813 // Back end function to rename a room.
814 // You can also specify which floor to move the room to, or specify -1 to
815 // keep the room on the same floor it was on.
816 //
817 // If you are renaming a mailbox room, you must supply the namespace prefix
818 // in *at least* the old name!
819 int CtdlRenameRoom(char *old_name, char *new_name, int new_floor) {
820         int old_floor = 0;
821         struct ctdlroom qrbuf;
822         struct ctdlroom qrtmp;
823         int ret = 0;
824         struct floor *fl;
825         struct floor flbuf;
826         long owner = 0L;
827         char actual_old_name[ROOMNAMELEN];
828
829         syslog(LOG_DEBUG, "room_ops: CtdlRenameRoom(%s, %s, %d)", old_name, new_name, new_floor);
830
831         if (new_floor >= 0) {
832                 fl = CtdlGetCachedFloor(new_floor);
833                 if ((fl->f_flags & F_INUSE) == 0) {
834                         return(crr_invalid_floor);
835                 }
836         }
837
838         begin_critical_section(S_ROOMS);
839
840         if ( (CtdlGetRoom(&qrtmp, new_name) == 0) && (strcasecmp(new_name, old_name)) ) {
841                 ret = crr_already_exists;
842         }
843
844         else if (CtdlGetRoom(&qrbuf, old_name) != 0) {
845                 ret = crr_room_not_found;
846         }
847
848         else if ( (CC->user.axlevel < AxAideU) && (!CC->internal_pgm)
849                   && (CC->user.usernum != qrbuf.QRroomaide)
850                   && ( (((qrbuf.QRflags & QR_MAILBOX) == 0) || (atol(qrbuf.QRname) != CC->user.usernum))) )  {
851                 ret = crr_access_denied;
852         }
853
854         else if (CtdlIsNonEditable(&qrbuf)) {
855                 ret = crr_noneditable;
856         }
857
858         else {
859                 // Rename it
860                 safestrncpy(actual_old_name, qrbuf.QRname, sizeof actual_old_name);
861                 if (qrbuf.QRflags & QR_MAILBOX) {
862                         owner = atol(qrbuf.QRname);
863                 }
864                 if ( (owner > 0L) && (atol(new_name) == 0L) ) {
865                         snprintf(qrbuf.QRname, sizeof(qrbuf.QRname),
866                                         "%010ld.%s", owner, new_name);
867                 }
868                 else {
869                         safestrncpy(qrbuf.QRname, new_name,
870                                                 sizeof(qrbuf.QRname));
871                 }
872
873                 // Reject change of floor for baseroom/aideroom
874                 if (!strncasecmp(old_name, CtdlGetConfigStr("c_baseroom"), ROOMNAMELEN) ||
875                     !strncasecmp(old_name, CtdlGetConfigStr("c_aideroom"), ROOMNAMELEN))
876                 {
877                         new_floor = 0;
878                 }
879
880                 // Take care of floor stuff
881                 old_floor = qrbuf.QRfloor;
882                 if (new_floor < 0) {
883                         new_floor = old_floor;
884                 }
885                 qrbuf.QRfloor = new_floor;
886                 CtdlPutRoom(&qrbuf);
887
888         
889                 // If the room name changed, then there are now two room
890                 // records, so we have to delete the old one.
891                 if (strcasecmp(new_name, old_name)) {
892                         b_deleteroom(actual_old_name);
893                 }
894
895                 ret = crr_ok;
896         }
897
898         end_critical_section(S_ROOMS);
899
900         // If baseroom/aideroom name changes, update config
901         begin_critical_section(S_CONFIG);
902         if (!strncasecmp(old_name, CtdlGetConfigStr("c_baseroom"), ROOMNAMELEN)) {
903                 CtdlSetConfigStr("c_baseroom", new_name);
904         }
905         if (!strncasecmp(old_name, CtdlGetConfigStr("c_aideroom"), ROOMNAMELEN)) {
906                 CtdlSetConfigStr("c_aideroom", new_name);
907         }
908         end_critical_section(S_CONFIG);
909
910         // Adjust the floor reference counts if necessary
911         if (new_floor != old_floor) {
912                 lgetfloor(&flbuf, old_floor);
913                 --flbuf.f_ref_count;
914                 lputfloor(&flbuf, old_floor);
915                 syslog(LOG_DEBUG, "room_ops: reference count for floor %d is now %d", old_floor, flbuf.f_ref_count);
916                 lgetfloor(&flbuf, new_floor);
917                 ++flbuf.f_ref_count;
918                 lputfloor(&flbuf, new_floor);
919                 syslog(LOG_DEBUG, "room_ops: reference count for floor %d is now %d", new_floor, flbuf.f_ref_count);
920         }
921
922         // ...and everybody say "YATTA!"
923         return(ret);
924 }
925
926
927 // Asynchronously schedule a room for deletion.  By placing the room into an invalid private namespace,
928 // the room will appear deleted to the user(s), but the session doesn't need to block while waiting for
929 // database operations to complete.  Instead, the room gets purged when THE DREADED AUTO-PURGER makes
930 // its next run.  Aren't we so clever?!!
931 void CtdlScheduleRoomForDeletion(struct ctdlroom *qrbuf) {
932         char old_name[ROOMNAMELEN];
933         static int seq = 0;
934
935         syslog(LOG_NOTICE, "room_ops: scheduling room <%s> for deletion", qrbuf->QRname);
936
937         safestrncpy(old_name, qrbuf->QRname, sizeof old_name);
938         CtdlGetRoom(qrbuf, qrbuf->QRname);
939
940         // Move the room into a hidden namespace owned by a non-existent user.
941         // This will make the room invisible to everyone.
942         // It will also qualify it for removal during the next purge cycle.
943         snprintf(qrbuf->QRname, sizeof qrbuf->QRname, "9999999999.%08lx.%04d.%s",
944                 time(NULL),
945                 ++seq,
946                 old_name
947         );
948         qrbuf->QRflags |= QR_MAILBOX;
949         time(&qrbuf->QRgen);    // Use a timestamp as the new generation number
950         CtdlPutRoom(qrbuf);
951         b_deleteroom(old_name);
952 }
953
954
955 // Back end processing to delete a room and everything associated with it
956 // (This one is synchronous and should only get called by THE DREADED
957 // AUTO-PURGER in serv_expire.c.  All user-facing code should call
958 // the asynchronous schedule_room_for_deletion() instead.)
959 void CtdlDeleteRoom(struct ctdlroom *qrbuf) {
960         struct floor flbuf;
961         char configdbkeyname[25];
962
963         syslog(LOG_NOTICE, "room_ops: deleting room <%s>", qrbuf->QRname);
964
965         // Delete the room's network configdb entry
966         netcfg_keyname(configdbkeyname, qrbuf->QRnumber);
967         CtdlDelConfig(configdbkeyname);
968
969         // Delete the messages in the room
970         // (Careful: this opens an S_ROOMS critical section!)
971         CtdlDeleteMessages(qrbuf->QRname, NULL, 0, "");
972
973         // Flag the room record as not in use
974         CtdlGetRoomLock(qrbuf, qrbuf->QRname);
975         qrbuf->QRflags = 0;
976         CtdlPutRoomLock(qrbuf);
977
978         // then decrement the reference count for the floor
979         lgetfloor(&flbuf, (int) (qrbuf->QRfloor));
980         flbuf.f_ref_count = flbuf.f_ref_count - 1;
981         lputfloor(&flbuf, (int) (qrbuf->QRfloor));
982
983         // Delete the room record from the database!
984         b_deleteroom(qrbuf->QRname);
985 }
986
987
988 // Check access control for deleting a room
989 int CtdlDoIHavePermissionToDeleteThisRoom(struct ctdlroom *qr) {
990
991         if ((!(CC->logged_in)) && (!(CC->internal_pgm))) {
992                 return(0);
993         }
994
995         if (CtdlIsNonEditable(qr)) {
996                 return(0);
997         }
998
999         // For mailboxes, check stuff
1000         if (qr->QRflags & QR_MAILBOX) {
1001
1002                 if (strlen(qr->QRname) < 12) return(0); // bad name
1003
1004                 if (atol(qr->QRname) != CC->user.usernum) {
1005                         return(0);                      // not my room
1006                 }
1007
1008                 // Can't delete your own inbox
1009                 if (!strcasecmp(&qr->QRname[11], MAILROOM)) return(0);
1010
1011                 // Otherwise it's ok
1012                 return(1);
1013         }
1014
1015         // For normal rooms, just check for admin or room admin status.
1016         return(is_room_aide());
1017 }
1018
1019
1020 // Internal code to create a new room (returns room flags)
1021 //
1022 // Room types:  0=public, 1=hidden, 2=passworded, 3=invitation-only,
1023 //              4=mailbox, 5=mailbox, but caller supplies namespace
1024 unsigned CtdlCreateRoom(char *new_room_name,
1025                      int new_room_type,
1026                      char *new_room_pass,
1027                      int new_room_floor,
1028                      int really_create,
1029                      int avoid_access,
1030                      int new_room_view)
1031 {
1032         struct ctdlroom qrbuf;
1033         struct floor flbuf;
1034         struct visit vbuf;
1035
1036         syslog(LOG_DEBUG, "room_ops: CtdlCreateRoom(name=%s, type=%d, view=%d)", new_room_name, new_room_type, new_room_view);
1037
1038         if (CtdlGetRoom(&qrbuf, new_room_name) == 0) {
1039                 syslog(LOG_DEBUG, "room_ops: cannot create room <%s> - already exists", new_room_name);
1040                 return(0);
1041         }
1042
1043         memset(&qrbuf, 0, sizeof(struct ctdlroom));
1044         safestrncpy(qrbuf.QRpasswd, new_room_pass, sizeof qrbuf.QRpasswd);
1045         qrbuf.QRflags = QR_INUSE;
1046         if (new_room_type > 0)
1047                 qrbuf.QRflags = (qrbuf.QRflags | QR_PRIVATE);
1048         if (new_room_type == 1)
1049                 qrbuf.QRflags = (qrbuf.QRflags | QR_GUESSNAME);
1050         if (new_room_type == 2)
1051                 qrbuf.QRflags = (qrbuf.QRflags | QR_PASSWORDED);
1052         if ( (new_room_type == 4) || (new_room_type == 5) ) {
1053                 qrbuf.QRflags = (qrbuf.QRflags | QR_MAILBOX);
1054                 // qrbuf.QRflags2 |= QR2_SUBJECTREQ;
1055         }
1056
1057         // If the user is requesting a personal room, set up the room
1058         // name accordingly (prepend the user number)
1059         if (new_room_type == 4) {
1060                 CtdlMailboxName(qrbuf.QRname, sizeof qrbuf.QRname, &CC->user, new_room_name);
1061         }
1062         else {
1063                 safestrncpy(qrbuf.QRname, new_room_name, sizeof qrbuf.QRname);
1064         }
1065
1066         // If the room is private, and the system administrator has elected
1067         // to automatically grant room admin privileges, do so now.
1068         if ((qrbuf.QRflags & QR_PRIVATE) && (CREATAIDE == 1)) {
1069                 qrbuf.QRroomaide = CC->user.usernum;
1070         }
1071
1072         // Blog owners automatically become room admins of their blogs.
1073         // (In the future we will offer a site-wide configuration setting to suppress this behavior.)
1074         else if (new_room_view == VIEW_BLOG) {
1075                 qrbuf.QRroomaide = CC->user.usernum;
1076         }
1077
1078         // Otherwise, set the room admin to undefined.
1079         else {
1080                 qrbuf.QRroomaide = (-1L);
1081         }
1082
1083         // If the caller is only interested in testing whether this will work,
1084         // return now without creating the room.
1085         if (!really_create) return (qrbuf.QRflags);
1086
1087         qrbuf.QRnumber = get_new_room_number();
1088         qrbuf.QRhighest = 0L;                   // No messages in this room yet
1089         time(&qrbuf.QRgen);                     // Use a timestamp as the generation number
1090         qrbuf.QRfloor = new_room_floor;
1091         qrbuf.QRdefaultview = new_room_view;
1092
1093         // save what we just did...
1094         CtdlPutRoom(&qrbuf);
1095
1096         // bump the reference count on whatever floor the room is on
1097         lgetfloor(&flbuf, (int) qrbuf.QRfloor);
1098         flbuf.f_ref_count = flbuf.f_ref_count + 1;
1099         lputfloor(&flbuf, (int) qrbuf.QRfloor);
1100
1101         // Grant the creator access to the room unless the avoid_access
1102         // parameter was specified.
1103         if ( (CC->logged_in) && (avoid_access == 0) ) {
1104                 CtdlGetRelationship(&vbuf, &CC->user, &qrbuf);
1105                 vbuf.v_flags = vbuf.v_flags & ~V_FORGET & ~V_LOCKOUT;
1106                 vbuf.v_flags = vbuf.v_flags | V_ACCESS;
1107                 CtdlSetRelationship(&vbuf, &CC->user, &qrbuf);
1108         }
1109
1110         // resume our happy day
1111         return(qrbuf.QRflags);
1112 }