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