]> code.citadel.org Git - citadel.git/blob - citadel/server/room_ops.c
749bcacb9130dbe8db1da339eade82c2cdd24787
[citadel.git] / citadel / server / room_ops.c
1 // Server functions which perform operations on room objects.
2 //
3 // Copyright (c) 1987-2023 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
216                 // is also allowed to delete
217                 if (roombuf->QRflags2 & QR2_COLLABDEL) {
218                         if (retval & UA_POSTALLOWED) {
219                                 retval = retval | UA_DELETEALLOWED;
220                         }
221                 }
222
223         }
224
225         // Check to see if the user has forgotten this room
226         if (vbuf.v_flags & V_FORGET) {
227                 retval = retval & ~UA_KNOWN;
228                 if (    ( ((roombuf->QRflags & QR_PRIVATE) == 0) 
229                         && ((roombuf->QRflags & QR_MAILBOX) == 0)
230                 ) || (  (roombuf->QRflags & QR_MAILBOX) 
231                         && (atol(roombuf->QRname) == CC->user.usernum))
232                 ) {
233                         retval = retval | UA_ZAPPED;
234                 }
235         }
236
237         // If user is explicitly locked out of this room, deny everything
238         if (vbuf.v_flags & V_LOCKOUT) {
239                 retval = retval & ~UA_KNOWN & ~UA_GOTOALLOWED & ~UA_POSTALLOWED & ~UA_REPLYALLOWED;
240         }
241
242         // Aides get access to all private rooms
243         if (    (userbuf->axlevel >= AxAideU)
244                 && ((roombuf->QRflags & QR_MAILBOX) == 0)
245         ) {
246                 if (vbuf.v_flags & V_FORGET) {
247                         retval = retval | UA_GOTOALLOWED | UA_POSTALLOWED | UA_REPLYALLOWED;
248                 }
249                 else {
250                         retval = retval | UA_KNOWN | UA_GOTOALLOWED | UA_POSTALLOWED | UA_REPLYALLOWED;
251                 }
252         }
253
254         // Aides can gain access to mailboxes as well, but they don't show by default.
255         if (    (userbuf->axlevel >= AxAideU)
256                 && (roombuf->QRflags & QR_MAILBOX)
257         ) {
258                 retval = retval | UA_GOTOALLOWED | UA_POSTALLOWED | UA_REPLYALLOWED;
259         }
260
261         // Aides and Room Aides have admin privileges
262         if (    (userbuf->axlevel >= AxAideU)
263                 || (userbuf->usernum == roombuf->QRroomaide)
264         ) {
265                 retval = retval | UA_ADMINALLOWED | UA_DELETEALLOWED | UA_POSTALLOWED | UA_REPLYALLOWED;
266         }
267
268 NEWMSG: // By the way, we also check for the presence of new messages
269         if (is_msg_in_sequence_set(vbuf.v_seen, roombuf->QRhighest) == 0) {
270                 retval = retval | UA_HASNEWMSGS;
271         }
272
273         // System rooms never show up in the list.
274         if (roombuf->QRflags2 & QR2_SYSTEM) {
275                 retval = retval & ~UA_KNOWN;
276         }
277
278 SKIP_EVERYTHING:
279         // Now give the caller the information it wants.
280         if (result != NULL) *result = retval;
281         if (view != NULL) *view = vbuf.v_view;
282 }
283
284
285 // Self-checking stuff for a room record read into memory
286 void room_sanity_check(struct ctdlroom *qrbuf) {
287         // Mailbox rooms are always on the lowest floor
288         if (qrbuf->QRflags & QR_MAILBOX) {
289                 qrbuf->QRfloor = 0;
290         }
291         // Listing order of 0 is illegal except for base rooms
292         if (qrbuf->QRorder == 0) {
293                 if (    !(qrbuf->QRflags & QR_MAILBOX)
294                         && strncasecmp(qrbuf->QRname, CtdlGetConfigStr("c_baseroom"), ROOMNAMELEN)
295                         && strncasecmp(qrbuf->QRname, CtdlGetConfigStr("c_aideroom"), ROOMNAMELEN)
296                 ) {
297                         qrbuf->QRorder = 64;
298                 }
299         }
300 }
301
302
303 // CtdlGetRoom()  -  retrieve room data from disk
304 int CtdlGetRoom(struct ctdlroom *qrbuf, const char *room_name) {
305         struct cdbdata *cdbqr;
306         char lowercase_name[ROOMNAMELEN];
307         char personal_lowercase_name[ROOMNAMELEN];
308         long len;
309
310         len = strlen(room_name);
311         for (int i=0; i<=len; ++i) {
312                 lowercase_name[i] = tolower(room_name[i]);
313         }
314
315         memset(qrbuf, 0, sizeof(struct ctdlroom));
316
317         if (IsEmptyStr(lowercase_name)) {
318                 return(1);                      // empty room name , not valid
319         }
320
321         // First, try the public namespace
322         cdbqr = cdb_fetch(CDB_ROOMS, lowercase_name, strlen(lowercase_name));
323
324         // If that didn't work, try the user's personal namespace
325         if (cdbqr == NULL) {
326                 snprintf(personal_lowercase_name, sizeof personal_lowercase_name, "%010ld.%s", CC->user.usernum, lowercase_name);
327                 cdbqr = cdb_fetch(CDB_ROOMS, personal_lowercase_name, strlen(personal_lowercase_name));
328         }
329         if (cdbqr != NULL) {
330                 memcpy(qrbuf, cdbqr->ptr, ((cdbqr->len > sizeof(struct ctdlroom)) ?  sizeof(struct ctdlroom) : cdbqr->len));
331                 cdb_free(cdbqr);
332                 room_sanity_check(qrbuf);
333                 return (0);
334         }
335         else {
336                 return (1);
337         }
338 }
339
340
341 // CtdlGetRoomLock()  -  same as getroom() but locks the record (if supported)
342 int CtdlGetRoomLock(struct ctdlroom *qrbuf, const char *room_name) {
343         register int retval;
344         retval = CtdlGetRoom(qrbuf, room_name);
345         if (retval == 0) begin_critical_section(S_ROOMS);
346         return(retval);
347 }
348
349
350 // b_putroom()  -  back end to putroom() and b_deleteroom()
351 // (if the supplied buffer is NULL, delete the room record)
352 void b_putroom(struct ctdlroom *qrbuf, char *room_name) {
353         char lowercase_name[ROOMNAMELEN];
354         long len;
355
356         len = strlen(room_name);
357         for (int i=0; i<=len; ++i) {
358                 lowercase_name[i] = tolower(room_name[i]);
359         }
360
361         if (qrbuf == NULL) {
362                 cdb_delete(CDB_ROOMS, lowercase_name, len);
363         }
364         else {
365                 time(&qrbuf->QRmtime);
366                 cdb_store(CDB_ROOMS, lowercase_name, len, qrbuf, sizeof(struct ctdlroom));
367         }
368 }
369
370
371 // CtdlPutRoom()  -  store room data to disk
372 void CtdlPutRoom(struct ctdlroom *qrbuf) {
373         b_putroom(qrbuf, qrbuf->QRname);
374 }
375
376
377 // b_deleteroom()  -  delete a room record from disk
378 void b_deleteroom(char *room_name) {
379         b_putroom(NULL, room_name);
380 }
381
382
383 // CtdlPutRoomLock()  -  same as CtdlPutRoom() but unlocks the record (if supported)
384 void CtdlPutRoomLock(struct ctdlroom *qrbuf) {
385         CtdlPutRoom(qrbuf);
386         end_critical_section(S_ROOMS);
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 != NULL) {
440                 memcpy(flbuf, cdbfl->ptr, ((cdbfl->len > sizeof(struct floor)) ?  sizeof(struct floor) : cdbfl->len));
441                 cdb_free(cdbfl);
442         }
443         else {
444                 if (floor_num == 0) {
445                         safestrncpy(flbuf->f_name, "Main Floor", sizeof flbuf->f_name);
446                         flbuf->f_flags = F_INUSE;
447                         flbuf->f_ref_count = 3;
448                 }
449         }
450 }
451
452
453 // lgetfloor()  -  same as CtdlGetFloor() but locks the record (if supported)
454 void lgetfloor(struct floor *flbuf, int floor_num) {
455         begin_critical_section(S_FLOORTAB);
456         CtdlGetFloor(flbuf, floor_num);
457 }
458
459
460 // CtdlGetCachedFloor()  -  Get floor record from *cache* (loads from disk if needed)
461 // This is strictly a performance hack.
462 struct floor *CtdlGetCachedFloor(int floor_num) {
463         static int initialized = 0;
464         int i;
465         int fetch_new = 0;
466         struct floor *fl = NULL;
467
468         begin_critical_section(S_FLOORCACHE);
469         if (initialized == 0) {
470                 for (i=0; i<MAXFLOORS; ++i) {
471                         floorcache[floor_num] = NULL;
472                 }
473         initialized = 1;
474         }
475         if (floorcache[floor_num] == NULL) {
476                 fetch_new = 1;
477         }
478         end_critical_section(S_FLOORCACHE);
479
480         if (fetch_new) {
481                 fl = malloc(sizeof(struct floor));
482                 CtdlGetFloor(fl, floor_num);
483                 begin_critical_section(S_FLOORCACHE);
484                 if (floorcache[floor_num] != NULL) {
485                         free(floorcache[floor_num]);
486                 }
487                 floorcache[floor_num] = fl;
488                 end_critical_section(S_FLOORCACHE);
489         }
490
491         return(floorcache[floor_num]);
492 }
493
494
495 // CtdlPutFloor()  -  store floor data on disk
496 void CtdlPutFloor(struct floor *flbuf, int floor_num) {
497         // If we've cached this, clear it out, 'cuz it's WRONG now!
498         begin_critical_section(S_FLOORCACHE);
499         if (floorcache[floor_num] != NULL) {
500                 free(floorcache[floor_num]);
501                 floorcache[floor_num] = malloc(sizeof(struct floor));
502                 memcpy(floorcache[floor_num], flbuf, sizeof(struct floor));
503         }
504         end_critical_section(S_FLOORCACHE);
505
506         cdb_store(CDB_FLOORTAB, &floor_num, sizeof(int),
507                   flbuf, sizeof(struct floor));
508 }
509
510
511 // CtdlPutFloorLock()  -  same as CtdlPutFloor() but unlocks the record (if supported)
512 void CtdlPutFloorLock(struct floor *flbuf, int floor_num) {
513         CtdlPutFloor(flbuf, floor_num);
514         end_critical_section(S_FLOORTAB);
515
516 }
517
518
519 // lputfloor()  -  same as CtdlPutFloor() but unlocks the record (if supported)
520 void lputfloor(struct floor *flbuf, int floor_num) {
521         CtdlPutFloorLock(flbuf, floor_num);
522 }
523
524
525 // Iterate through the room table, performing a callback for each room.
526 void CtdlForEachRoom(ForEachRoomCallBack callback_func, void *in_data) {
527         struct ctdlroom qrbuf;
528         struct cdbdata *cdbqr;
529
530         cdb_rewind(CDB_ROOMS);
531
532         while (cdbqr = cdb_next_item(CDB_ROOMS), cdbqr != NULL) {
533                 memset(&qrbuf, 0, sizeof(struct ctdlroom));
534                 memcpy(&qrbuf, cdbqr->ptr, ((cdbqr->len > sizeof(struct ctdlroom)) ?  sizeof(struct ctdlroom) : cdbqr->len) );
535                 cdb_free(cdbqr);
536                 room_sanity_check(&qrbuf);
537                 if (qrbuf.QRflags & QR_INUSE) {
538                         callback_func(&qrbuf, in_data);
539                 }
540         }
541 }
542
543
544 // delete_msglist()  -  delete room message pointers
545 void delete_msglist(struct ctdlroom *whichroom) {
546         struct cdbdata *cdbml;
547
548         // Make sure the msglist we're deleting actually exists, otherwise
549         // libdb will complain when we try to delete an invalid record
550         cdbml = cdb_fetch(CDB_MSGLISTS, &whichroom->QRnumber, sizeof(long));
551         if (cdbml != NULL) {
552                 cdb_free(cdbml);
553
554                 // Go ahead and delete it
555                 cdb_delete(CDB_MSGLISTS, &whichroom->QRnumber, sizeof(long));
556         }
557 }
558
559
560 // Message pointer compare function for sort_msglist()
561 int sort_msglist_cmp(const void *m1, const void *m2) {
562         if ((*(const long *)m1) > (*(const long *)m2)) return(1);
563         if ((*(const long *)m1) < (*(const long *)m2)) return(-1);
564         return(0);
565 }
566
567
568 // sort message pointers
569 // (returns new msg count)
570 int sort_msglist(long listptrs[], int oldcount) {
571         int numitems;
572         int i = 0;
573
574         numitems = oldcount;
575         if (numitems < 2) {                                                     // an empty or 1-item list needs no sorting
576                 return (oldcount);
577         }
578
579         qsort(listptrs, numitems, sizeof(long), sort_msglist_cmp);              // do the sort
580
581         while ((i < numitems) && (listptrs[i] == 0L)) i++;                      // yank out any nulls
582         if (i > 0) {
583                 memmove(&listptrs[0], &listptrs[i], (sizeof(long) * (numitems - i)));
584                 numitems-=i;
585         }
586
587         return (numitems);
588 }
589
590
591 // Determine whether a given room is non-editable.
592 int CtdlIsNonEditable(struct ctdlroom *qrbuf) {
593
594         // The inbox cannot be edited
595         if ( (qrbuf->QRflags & QR_MAILBOX) && (!strcasecmp(&qrbuf->QRname[11], MAILROOM)) ) {
596                 return (1);
597         }
598
599         // Everything else is editable
600         return (0);
601 }
602
603
604 // Retrieve a list of all messages (message numbers) in the specified room.
605 // Returns the number of messages in the room, allocates a pointer to the array and stuffs it in the supplied location.
606 // Caller must free that memory.
607 // If no messages in room, returns 0 and msgs is set to NULL.
608 int CtdlFetchMsgList(long roomnum, long **msgs) {
609         int num_msgs = 0;
610         struct cdbdata *cdbfr;
611
612         cdbfr = cdb_fetch(CDB_MSGLISTS, &roomnum, sizeof(long));
613         if (cdbfr == NULL) {
614                 syslog(LOG_ERR, "room_ops: no msglist for room %ld", roomnum);
615                 *msgs = NULL;
616                 return (0);
617         }
618
619         num_msgs = cdbfr->len / sizeof(long);
620         if (num_msgs > 0) {
621                 *msgs = malloc(cdbfr->len);
622                 memcpy(*msgs, cdbfr->ptr, cdbfr->len);
623         }
624         else {
625                 *msgs = NULL;
626         }
627         cdb_free(cdbfr);
628         // BEGIN diagnostic section remove this
629         syslog(LOG_DEBUG, "\033[7mCtdlFetchMsgList(%ld) %d messages\033[0m", roomnum, num_msgs);
630         int i;
631         long *p = *msgs;
632         long msgnum;
633         if (num_msgs>0) for (i=0; i<num_msgs; ++i) {
634                 memcpy(&msgnum, p, sizeof(long));
635                 p++;
636                 syslog(LOG_DEBUG, "\033[7m%ld\033[0m", msgnum);
637         }
638         // END diagnostic section remove this
639         return(num_msgs);
640 }
641
642
643 // Make the specified room the current room for this session.  No validation
644 // or access control is done here -- the caller should make sure that the
645 // specified room exists and is ok to access.
646 void CtdlUserGoto(char *where, int display_result, int transiently, int *retmsgs, int *retnew, long *retoldest, long *retnewest) {
647         int a;
648         int new_messages = 0;
649         int old_messages = 0;
650         int total_messages = 0;
651         long oldest_message = 0;
652         long newest_message = 0;
653         int info = 0;
654         int rmailflag;
655         int raideflag;
656         struct visit vbuf;
657         char truncated_roomname[ROOMNAMELEN];
658         long *msglist = NULL;
659         int num_msgs = 0;
660         unsigned int original_v_flags;
661         int num_sets;
662         int s;
663         char setstr[128], lostr[64], histr[64];
664         long lo, hi;
665         int is_trash = 0;
666
667         // If the supplied room name is NULL, the caller wants us to know that
668         // it has already copied the room record into CC->room, so
669         // we can skip the extra database fetch.
670         if (where != NULL) {
671                 safestrncpy(CC->room.QRname, where, sizeof CC->room.QRname);
672                 CtdlGetRoom(&CC->room, where);
673         }
674
675         // Take care of all the formalities.
676
677         begin_critical_section(S_USERS);
678         CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
679         original_v_flags = vbuf.v_flags;
680
681         // Know the room ... but not if it's the page log room, or if the
682         // caller specified that we're only entering this room transiently.
683         int add_room_to_known_list = 1;
684         if (transiently == 1) {
685                 add_room_to_known_list = 0;
686         }
687         char *c_logpages = CtdlGetConfigStr("c_logpages");
688         if ( (c_logpages != NULL) && (!strcasecmp(CC->room.QRname, c_logpages)) ) {
689                 add_room_to_known_list = 0;
690         }
691         if (add_room_to_known_list) {
692                 vbuf.v_flags = vbuf.v_flags & ~V_FORGET & ~V_LOCKOUT;
693                 vbuf.v_flags = vbuf.v_flags | V_ACCESS;
694         }
695         
696         // Only rewrite the database record if we changed something
697         if (vbuf.v_flags != original_v_flags) {
698                 CtdlSetRelationship(&vbuf, &CC->user, &CC->room);
699         }
700         end_critical_section(S_USERS);
701
702         // Set info to 1 if the room banner is new since our last visit.
703         // Some clients only want to display it when it changes.
704         if (CC->room.msgnum_info > vbuf.v_lastseen) {
705                 info = 1;
706         }
707
708         num_msgs = CtdlFetchMsgList(CC->room.QRnumber, &msglist);
709
710         total_messages = 0;
711         for (a=0; a<num_msgs; ++a) {
712                 if (msglist[a] > 0L) ++total_messages;
713         }
714
715         if (total_messages > 0) {
716                 oldest_message = msglist[0];
717                 newest_message = msglist[num_msgs - 1];
718         }
719
720         num_sets = num_tokens(vbuf.v_seen, ',');
721         for (s=0; s<num_sets; ++s) {
722                 extract_token(setstr, vbuf.v_seen, s, ',', sizeof setstr);
723
724                 extract_token(lostr, setstr, 0, ':', sizeof lostr);
725                 if (num_tokens(setstr, ':') >= 2) {
726                         extract_token(histr, setstr, 1, ':', sizeof histr);
727                         if (!strcmp(histr, "*")) {
728                                 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
729                         }
730                 } 
731                 else {
732                         strcpy(histr, lostr);
733                 }
734                 lo = atol(lostr);
735                 hi = atol(histr);
736
737                 for (a=0; a<num_msgs; ++a) if (msglist[a] > 0L) {
738                         if ((msglist[a] >= lo) && (msglist[a] <= hi)) {
739                                 ++old_messages;
740                                 msglist[a] = 0L;
741                         }
742                 }
743         }
744         new_messages = total_messages - old_messages;
745
746         if (msglist != NULL) free(msglist);
747
748         if (CC->room.QRflags & QR_MAILBOX)
749                 rmailflag = 1;
750         else
751                 rmailflag = 0;
752
753         if ((CC->room.QRroomaide == CC->user.usernum) || (CC->user.axlevel >= AxAideU))
754                 raideflag = 1;
755         else
756                 raideflag = 0;
757
758         safestrncpy(truncated_roomname, CC->room.QRname, sizeof truncated_roomname);
759         if ( (CC->room.QRflags & QR_MAILBOX) && (atol(CC->room.QRname) == CC->user.usernum) ) {
760                 safestrncpy(truncated_roomname, &truncated_roomname[11], sizeof truncated_roomname);
761         }
762
763         if (!strcasecmp(truncated_roomname, USERTRASHROOM)) {
764                 is_trash = 1;
765         }
766
767         if (retmsgs != NULL) *retmsgs = total_messages;
768         if (retnew != NULL) *retnew = new_messages;
769         if (retoldest != NULL) *retoldest = oldest_message;
770         if (retnewest != NULL) *retnewest = newest_message;
771         syslog(LOG_DEBUG, "room_ops: %s : %d new of %d total messages, oldest=%ld, newest=%ld",
772                    CC->room.QRname, new_messages, total_messages, oldest_message, newest_message
773         );
774
775         CC->curr_view = (int)vbuf.v_view;
776
777         if (display_result) {
778                 cprintf("%d%c%s|%d|%d|%d|%d|%ld|%ld|%d|%d|%d|%d|%d|%d|%d|%d|%ld|\n",
779                         CIT_OK, CtdlCheckExpress(),
780                         truncated_roomname,
781                         (int)new_messages,
782                         (int)total_messages,
783                         (int)info,
784                         (int)CC->room.QRflags,
785                         (long)CC->room.QRhighest,
786                         (long)vbuf.v_lastseen,
787                         (int)rmailflag,
788                         (int)raideflag,
789                         0,                                      // new mail is no longer counted here
790                         (int)CC->room.QRfloor,
791                         (int)vbuf.v_view,
792                         (int)CC->room.QRdefaultview,
793                         (int)is_trash,
794                         (int)CC->room.QRflags2,
795                         (long)CC->room.QRmtime
796                 );
797         }
798 }
799
800
801 // Handle some of the macro named rooms
802 void convert_room_name_macros(char *towhere, size_t maxlen) {
803         if (!strcasecmp(towhere, "_BASEROOM_")) {
804                 safestrncpy(towhere, CtdlGetConfigStr("c_baseroom"), maxlen);
805         }
806         else if (!strcasecmp(towhere, "_MAIL_")) {
807                 safestrncpy(towhere, MAILROOM, maxlen);
808         }
809         else if (!strcasecmp(towhere, "_TRASH_")) {
810                 safestrncpy(towhere, USERTRASHROOM, maxlen);
811         }
812         else if (!strcasecmp(towhere, "_DRAFTS_")) {
813                 safestrncpy(towhere, USERDRAFTROOM, maxlen);
814         }
815         else if (!strcasecmp(towhere, "_BITBUCKET_")) {
816                 safestrncpy(towhere, CtdlGetConfigStr("c_twitroom"), maxlen);
817         }
818         else if (!strcasecmp(towhere, "_CALENDAR_")) {
819                 safestrncpy(towhere, USERCALENDARROOM, maxlen);
820         }
821         else if (!strcasecmp(towhere, "_TASKS_")) {
822                 safestrncpy(towhere, USERTASKSROOM, maxlen);
823         }
824         else if (!strcasecmp(towhere, "_CONTACTS_")) {
825                 safestrncpy(towhere, USERCONTACTSROOM, maxlen);
826         }
827         else if (!strcasecmp(towhere, "_NOTES_")) {
828                 safestrncpy(towhere, USERNOTESROOM, maxlen);
829         }
830 }
831
832
833 // Back end function to rename a room.
834 // You can also specify which floor to move the room to, or specify -1 to
835 // keep the room on the same floor it was on.
836 //
837 // If you are renaming a mailbox room, you must supply the namespace prefix
838 // in *at least* the old name!
839 int CtdlRenameRoom(char *old_name, char *new_name, int new_floor) {
840         int old_floor = 0;
841         struct ctdlroom qrbuf;
842         struct ctdlroom qrtmp;
843         int ret = 0;
844         struct floor *fl;
845         struct floor flbuf;
846         long owner = 0L;
847         char actual_old_name[ROOMNAMELEN];
848
849         syslog(LOG_DEBUG, "room_ops: CtdlRenameRoom(%s, %s, %d)", old_name, new_name, new_floor);
850
851         if (new_floor >= 0) {
852                 fl = CtdlGetCachedFloor(new_floor);
853                 if ((fl->f_flags & F_INUSE) == 0) {
854                         return(crr_invalid_floor);
855                 }
856         }
857
858         begin_critical_section(S_ROOMS);
859
860         if ( (CtdlGetRoom(&qrtmp, new_name) == 0) && (strcasecmp(new_name, old_name)) ) {
861                 ret = crr_already_exists;
862         }
863
864         else if (CtdlGetRoom(&qrbuf, old_name) != 0) {
865                 ret = crr_room_not_found;
866         }
867
868         else if ( (CC->user.axlevel < AxAideU) && (!CC->internal_pgm)
869                   && (CC->user.usernum != qrbuf.QRroomaide)
870                   && ( (((qrbuf.QRflags & QR_MAILBOX) == 0) || (atol(qrbuf.QRname) != CC->user.usernum))) )  {
871                 ret = crr_access_denied;
872         }
873
874         else if (CtdlIsNonEditable(&qrbuf)) {
875                 ret = crr_noneditable;
876         }
877
878         else {
879                 // Rename it
880                 safestrncpy(actual_old_name, qrbuf.QRname, sizeof actual_old_name);
881                 if (qrbuf.QRflags & QR_MAILBOX) {
882                         owner = atol(qrbuf.QRname);
883                 }
884                 if ( (owner > 0L) && (atol(new_name) == 0L) ) {
885                         snprintf(qrbuf.QRname, sizeof(qrbuf.QRname),
886                                         "%010ld.%s", owner, new_name);
887                 }
888                 else {
889                         safestrncpy(qrbuf.QRname, new_name,
890                                                 sizeof(qrbuf.QRname));
891                 }
892
893                 // Reject change of floor for baseroom/aideroom
894                 if (!strncasecmp(old_name, CtdlGetConfigStr("c_baseroom"), ROOMNAMELEN) ||
895                     !strncasecmp(old_name, CtdlGetConfigStr("c_aideroom"), ROOMNAMELEN))
896                 {
897                         new_floor = 0;
898                 }
899
900                 // Take care of floor stuff
901                 old_floor = qrbuf.QRfloor;
902                 if (new_floor < 0) {
903                         new_floor = old_floor;
904                 }
905                 qrbuf.QRfloor = new_floor;
906                 CtdlPutRoom(&qrbuf);
907
908                 begin_critical_section(S_CONFIG);
909         
910                 // If baseroom/aideroom name changes, update config
911                 if (!strncasecmp(old_name, CtdlGetConfigStr("c_baseroom"), ROOMNAMELEN)) {
912                         CtdlSetConfigStr("c_baseroom", new_name);
913                 }
914                 if (!strncasecmp(old_name, CtdlGetConfigStr("c_aideroom"), ROOMNAMELEN)) {
915                         CtdlSetConfigStr("c_aideroom", new_name);
916                 }
917         
918                 end_critical_section(S_CONFIG);
919         
920                 // If the room name changed, then there are now two room
921                 // records, so we have to delete the old one.
922                 if (strcasecmp(new_name, old_name)) {
923                         b_deleteroom(actual_old_name);
924                 }
925
926                 ret = crr_ok;
927         }
928
929         end_critical_section(S_ROOMS);
930
931         // Adjust the floor reference counts if necessary
932         if (new_floor != old_floor) {
933                 lgetfloor(&flbuf, old_floor);
934                 --flbuf.f_ref_count;
935                 lputfloor(&flbuf, old_floor);
936                 syslog(LOG_DEBUG, "room_ops: reference count for floor %d is now %d", old_floor, flbuf.f_ref_count);
937                 lgetfloor(&flbuf, new_floor);
938                 ++flbuf.f_ref_count;
939                 lputfloor(&flbuf, new_floor);
940                 syslog(LOG_DEBUG, "room_ops: reference count for floor %d is now %d", new_floor, flbuf.f_ref_count);
941         }
942
943         // ...and everybody say "YATTA!"
944         return(ret);
945 }
946
947
948 // Asynchronously schedule a room for deletion.  By placing the room into an invalid private namespace,
949 // the room will appear deleted to the user(s), but the session doesn't need to block while waiting for
950 // database operations to complete.  Instead, the room gets purged when THE DREADED AUTO-PURGER makes
951 // its next run.  Aren't we so clever?!!
952 void CtdlScheduleRoomForDeletion(struct ctdlroom *qrbuf) {
953         char old_name[ROOMNAMELEN];
954         static int seq = 0;
955
956         syslog(LOG_NOTICE, "room_ops: scheduling room <%s> for deletion", qrbuf->QRname);
957
958         safestrncpy(old_name, qrbuf->QRname, sizeof old_name);
959         CtdlGetRoom(qrbuf, qrbuf->QRname);
960
961         // Move the room into a hidden namespace owned by a non-existent user.
962         // This will make the room invisible to everyone.
963         // It will also qualify it for removal during the next purge cycle.
964         snprintf(qrbuf->QRname, sizeof qrbuf->QRname, "9999999999.%08lx.%04d.%s",
965                 time(NULL),
966                 ++seq,
967                 old_name
968         );
969         qrbuf->QRflags |= QR_MAILBOX;
970         time(&qrbuf->QRgen);    // Use a timestamp as the new generation number
971         CtdlPutRoom(qrbuf);
972         b_deleteroom(old_name);
973 }
974
975
976 // Back end processing to delete a room and everything associated with it
977 // (This one is synchronous and should only get called by THE DREADED
978 // AUTO-PURGER in serv_expire.c.  All user-facing code should call
979 // the asynchronous schedule_room_for_deletion() instead.)
980 void CtdlDeleteRoom(struct ctdlroom *qrbuf) {
981         struct floor flbuf;
982         char configdbkeyname[25];
983
984         syslog(LOG_NOTICE, "room_ops: deleting room <%s>", qrbuf->QRname);
985
986         // Delete the room's network configdb entry
987         netcfg_keyname(configdbkeyname, qrbuf->QRnumber);
988         CtdlDelConfig(configdbkeyname);
989
990         // Delete the messages in the room
991         // (Careful: this opens an S_ROOMS critical section!)
992         CtdlDeleteMessages(qrbuf->QRname, NULL, 0, "");
993
994         // Flag the room record as not in use
995         CtdlGetRoomLock(qrbuf, qrbuf->QRname);
996         qrbuf->QRflags = 0;
997         CtdlPutRoomLock(qrbuf);
998
999         // then decrement the reference count for the floor
1000         lgetfloor(&flbuf, (int) (qrbuf->QRfloor));
1001         flbuf.f_ref_count = flbuf.f_ref_count - 1;
1002         lputfloor(&flbuf, (int) (qrbuf->QRfloor));
1003
1004         // Delete the room record from the database!
1005         b_deleteroom(qrbuf->QRname);
1006 }
1007
1008
1009 // Check access control for deleting a room
1010 int CtdlDoIHavePermissionToDeleteThisRoom(struct ctdlroom *qr) {
1011
1012         if ((!(CC->logged_in)) && (!(CC->internal_pgm))) {
1013                 return(0);
1014         }
1015
1016         if (CtdlIsNonEditable(qr)) {
1017                 return(0);
1018         }
1019
1020         // For mailboxes, check stuff
1021         if (qr->QRflags & QR_MAILBOX) {
1022
1023                 if (strlen(qr->QRname) < 12) return(0); // bad name
1024
1025                 if (atol(qr->QRname) != CC->user.usernum) {
1026                         return(0);                      // not my room
1027                 }
1028
1029                 // Can't delete your own inbox
1030                 if (!strcasecmp(&qr->QRname[11], MAILROOM)) return(0);
1031
1032                 // Otherwise it's ok
1033                 return(1);
1034         }
1035
1036         // For normal rooms, just check for admin or room admin status.
1037         return(is_room_aide());
1038 }
1039
1040
1041 // Internal code to create a new room (returns room flags)
1042 //
1043 // Room types:  0=public, 1=hidden, 2=passworded, 3=invitation-only,
1044 //              4=mailbox, 5=mailbox, but caller supplies namespace
1045 unsigned CtdlCreateRoom(char *new_room_name,
1046                      int new_room_type,
1047                      char *new_room_pass,
1048                      int new_room_floor,
1049                      int really_create,
1050                      int avoid_access,
1051                      int new_room_view)
1052 {
1053         struct ctdlroom qrbuf;
1054         struct floor flbuf;
1055         struct visit vbuf;
1056
1057         syslog(LOG_DEBUG, "room_ops: CtdlCreateRoom(name=%s, type=%d, view=%d)", new_room_name, new_room_type, new_room_view);
1058
1059         if (CtdlGetRoom(&qrbuf, new_room_name) == 0) {
1060                 syslog(LOG_DEBUG, "room_ops: cannot create room <%s> - already exists", new_room_name);
1061                 return(0);
1062         }
1063
1064         memset(&qrbuf, 0, sizeof(struct ctdlroom));
1065         safestrncpy(qrbuf.QRpasswd, new_room_pass, sizeof qrbuf.QRpasswd);
1066         qrbuf.QRflags = QR_INUSE;
1067         if (new_room_type > 0)
1068                 qrbuf.QRflags = (qrbuf.QRflags | QR_PRIVATE);
1069         if (new_room_type == 1)
1070                 qrbuf.QRflags = (qrbuf.QRflags | QR_GUESSNAME);
1071         if (new_room_type == 2)
1072                 qrbuf.QRflags = (qrbuf.QRflags | QR_PASSWORDED);
1073         if ( (new_room_type == 4) || (new_room_type == 5) ) {
1074                 qrbuf.QRflags = (qrbuf.QRflags | QR_MAILBOX);
1075                 // qrbuf.QRflags2 |= QR2_SUBJECTREQ;
1076         }
1077
1078         // If the user is requesting a personal room, set up the room
1079         // name accordingly (prepend the user number)
1080         if (new_room_type == 4) {
1081                 CtdlMailboxName(qrbuf.QRname, sizeof qrbuf.QRname, &CC->user, new_room_name);
1082         }
1083         else {
1084                 safestrncpy(qrbuf.QRname, new_room_name, sizeof qrbuf.QRname);
1085         }
1086
1087         // If the room is private, and the system administrator has elected
1088         // to automatically grant room admin privileges, do so now.
1089         if ((qrbuf.QRflags & QR_PRIVATE) && (CREATAIDE == 1)) {
1090                 qrbuf.QRroomaide = CC->user.usernum;
1091         }
1092
1093         // Blog owners automatically become room admins of their blogs.
1094         // (In the future we will offer a site-wide configuration setting to suppress this behavior.)
1095         else if (new_room_view == VIEW_BLOG) {
1096                 qrbuf.QRroomaide = CC->user.usernum;
1097         }
1098
1099         // Otherwise, set the room admin to undefined.
1100         else {
1101                 qrbuf.QRroomaide = (-1L);
1102         }
1103
1104         // If the caller is only interested in testing whether this will work,
1105         // return now without creating the room.
1106         if (!really_create) return (qrbuf.QRflags);
1107
1108         qrbuf.QRnumber = get_new_room_number();
1109         qrbuf.QRhighest = 0L;                   // No messages in this room yet
1110         time(&qrbuf.QRgen);                     // Use a timestamp as the generation number
1111         qrbuf.QRfloor = new_room_floor;
1112         qrbuf.QRdefaultview = new_room_view;
1113
1114         // save what we just did...
1115         CtdlPutRoom(&qrbuf);
1116
1117         // bump the reference count on whatever floor the room is on
1118         lgetfloor(&flbuf, (int) qrbuf.QRfloor);
1119         flbuf.f_ref_count = flbuf.f_ref_count + 1;
1120         lputfloor(&flbuf, (int) qrbuf.QRfloor);
1121
1122         // Grant the creator access to the room unless the avoid_access
1123         // parameter was specified.
1124         if ( (CC->logged_in) && (avoid_access == 0) ) {
1125                 CtdlGetRelationship(&vbuf, &CC->user, &qrbuf);
1126                 vbuf.v_flags = vbuf.v_flags & ~V_FORGET & ~V_LOCKOUT;
1127                 vbuf.v_flags = vbuf.v_flags | V_ACCESS;
1128                 CtdlSetRelationship(&vbuf, &CC->user, &qrbuf);
1129         }
1130
1131         // resume our happy day
1132         return(qrbuf.QRflags);
1133 }