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