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