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