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