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