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