Move user privileges functions to user_ops.c, room access check functions to room_ops.c
[citadel.git] / citadel / room_ops.c
1 /* 
2  * Server functions which perform operations on room objects.
3  *
4  * Copyright (c) 1987-2012 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 "sysdep.h"
16 #include <stdlib.h>
17 #include <unistd.h>
18 #include <stdio.h>
19 #include <sys/stat.h>
20 #include <ctype.h>
21 #include <string.h>
22 #include <dirent.h>     /* for cmd_rdir to read contents of the directory */
23
24 #if TIME_WITH_SYS_TIME
25 # include <sys/time.h>
26 # include <time.h>
27 #else
28 # if HAVE_SYS_TIME_H
29 #  include <sys/time.h>
30 # else
31 #  include <time.h>
32 # endif
33 #endif
34
35 #include <limits.h>
36 #include <errno.h>
37 #include "citadel.h"
38 #include <libcitadel.h>
39 #include "server.h"
40 #include "database.h"
41 #include "config.h"
42 #include "room_ops.h"
43 #include "sysdep_decls.h"
44 #include "support.h"
45 #include "msgbase.h"
46 #include "citserver.h"
47 #include "control.h"
48 #include "citadel_dirs.h"
49 #include "threads.h"
50
51 #include "ctdl_module.h"
52 #include "user_ops.h"
53
54 struct floor *floorcache[MAXFLOORS];
55
56 /* 
57  * Determine whether the currently logged in session has permission to read
58  * messages in the current room.
59  */
60 int CtdlDoIHavePermissionToReadMessagesInThisRoom(void) {
61         if (    (!(CC->logged_in))
62                 && (!(CC->internal_pgm))
63                 && (!config.c_guest_logins)
64         ) {
65                 return(om_not_logged_in);
66         }
67         return(om_ok);
68 }
69
70 /*
71  * Check to see whether we have permission to post a message in the current
72  * room.  Returns a *CITADEL ERROR CODE* and puts a message in errmsgbuf, or
73  * returns 0 on success.
74  */
75 int CtdlDoIHavePermissionToPostInThisRoom(
76         char *errmsgbuf, 
77         size_t n, 
78         const char* RemoteIdentifier,
79         PostType PostPublic,
80         int is_reply
81         ) {
82         int ra;
83
84         if (!(CC->logged_in) && 
85             (PostPublic == POST_LOGGED_IN)) {
86                 snprintf(errmsgbuf, n, "Not logged in.");
87                 return (ERROR + NOT_LOGGED_IN);
88         }
89         else if (PostPublic == CHECK_EXISTANCE) {
90                 return (0); // We're Evaling whether a recipient exists
91         }
92         else if (!(CC->logged_in)) {
93                 
94                 if ((CC->room.QRflags & QR_READONLY)) {
95                         snprintf(errmsgbuf, n, "Not logged in.");
96                         return (ERROR + NOT_LOGGED_IN);
97                 }
98                 if (CC->room.QRflags2 & QR2_MODERATED) {
99                         snprintf(errmsgbuf, n, "Not logged in Moderation feature not yet implemented!");
100                         return (ERROR + NOT_LOGGED_IN);
101                 }
102                 if ((PostPublic!=POST_LMTP) &&(CC->room.QRflags2 & QR2_SMTP_PUBLIC) == 0) {
103
104                         return CtdlNetconfigCheckRoomaccess(errmsgbuf, n, RemoteIdentifier);
105                 }
106                 return (0);
107
108         }
109
110         if ((CC->user.axlevel < AxProbU)
111             && ((CC->room.QRflags & QR_MAILBOX) == 0)) {
112                 snprintf(errmsgbuf, n, "Need to be validated to enter (except in %s> to sysop)", MAILROOM);
113                 return (ERROR + HIGHER_ACCESS_REQUIRED);
114         }
115
116         CtdlRoomAccess(&CC->room, &CC->user, &ra, NULL);
117
118         if (ra & UA_POSTALLOWED) {
119                 strcpy(errmsgbuf, "OK to post or reply here");
120                 return(0);
121         }
122
123         if ( (ra & UA_REPLYALLOWED) && (is_reply) ) {
124                 /*
125                  * To be thorough, we ought to check to see if the message they are
126                  * replying to is actually a valid one in this room, but unless this
127                  * actually becomes a problem we'll go with high performance instead.
128                  */
129                 strcpy(errmsgbuf, "OK to reply here");
130                 return(0);
131         }
132
133         if ( (ra & UA_REPLYALLOWED) && (!is_reply) ) {
134                 /* Clarify what happened with a better error message */
135                 snprintf(errmsgbuf, n, "You may only reply to existing messages here.");
136                 return (ERROR + HIGHER_ACCESS_REQUIRED);
137         }
138
139         snprintf(errmsgbuf, n, "Higher access is required to post in this room.");
140         return (ERROR + HIGHER_ACCESS_REQUIRED);
141
142 }
143
144 /*
145  * Check whether the current user has permission to delete messages from
146  * the current room (returns 1 for yes, 0 for no)
147  */
148 int CtdlDoIHavePermissionToDeleteMessagesFromThisRoom(void) {
149         int ra;
150         CtdlRoomAccess(&CC->room, &CC->user, &ra, NULL);
151         if (ra & UA_DELETEALLOWED) return(1);
152         return(0);
153 }
154
155 /*
156  * Retrieve access control information for any user/room pair
157  */
158 void CtdlRoomAccess(struct ctdlroom *roombuf, struct ctdluser *userbuf,
159                 int *result, int *view)
160 {
161         int retval = 0;
162         visit vbuf;
163         int is_me = 0;
164         int is_guest = 0;
165
166         if (userbuf == &CC->user) {
167                 is_me = 1;
168         }
169
170         if ((is_me) && (config.c_guest_logins) && (!CC->logged_in)) {
171                 is_guest = 1;
172         }
173
174         /* for internal programs, always do everything */
175         if (((CC->internal_pgm)) && (roombuf->QRflags & QR_INUSE)) {
176                 retval = (UA_KNOWN | UA_GOTOALLOWED | UA_POSTALLOWED | UA_DELETEALLOWED | UA_REPLYALLOWED);
177                 vbuf.v_view = 0;
178                 goto SKIP_EVERYTHING;
179         }
180
181         /* If guest mode is enabled, always grant access to the Lobby */
182         if ((is_guest) && (!strcasecmp(roombuf->QRname, BASEROOM))) {
183                 retval = (UA_KNOWN | UA_GOTOALLOWED);
184                 vbuf.v_view = 0;
185                 goto SKIP_EVERYTHING;
186         }
187
188         /* Locate any applicable user/room relationships */
189         if (is_guest) {
190                 memset(&vbuf, 0, sizeof vbuf);
191         }
192         else {
193                 CtdlGetRelationship(&vbuf, userbuf, roombuf);
194         }
195
196         /* Force the properties of the Aide room */
197         if (!strcasecmp(roombuf->QRname, config.c_aideroom)) {
198                 if (userbuf->axlevel >= AxAideU) {
199                         retval = UA_KNOWN | UA_GOTOALLOWED | UA_POSTALLOWED | UA_DELETEALLOWED | UA_REPLYALLOWED;
200                 } else {
201                         retval = 0;
202                 }
203                 goto NEWMSG;
204         }
205
206         /* If this is a public room, it's accessible... */
207         if (    ((roombuf->QRflags & QR_PRIVATE) == 0) 
208                 && ((roombuf->QRflags & QR_MAILBOX) == 0)
209         ) {
210                 retval = retval | UA_KNOWN | UA_GOTOALLOWED;
211         }
212
213         /* If this is a preferred users only room, check access level */
214         if (roombuf->QRflags & QR_PREFONLY) {
215                 if (userbuf->axlevel < AxPrefU) {
216                         retval = retval & ~UA_KNOWN & ~UA_GOTOALLOWED;
217                 }
218         }
219
220         /* For private rooms, check the generation number matchups */
221         if (    (roombuf->QRflags & QR_PRIVATE) 
222                 && ((roombuf->QRflags & QR_MAILBOX) == 0)
223         ) {
224
225                 /* An explicit match means the user belongs in this room */
226                 if (vbuf.v_flags & V_ACCESS) {
227                         retval = retval | UA_KNOWN | UA_GOTOALLOWED;
228                 }
229                 /* Otherwise, check if this is a guess-name or passworded
230                  * room.  If it is, a goto may at least be attempted
231                  */
232                 else if (       (roombuf->QRflags & QR_PRIVATE)
233                                 || (roombuf->QRflags & QR_PASSWORDED)
234                 ) {
235                         retval = retval & ~UA_KNOWN;
236                         retval = retval | UA_GOTOALLOWED;
237                 }
238         }
239
240         /* For mailbox rooms, also check the namespace */
241         /* Also, mailbox owners can delete their messages */
242         if ( (roombuf->QRflags & QR_MAILBOX) && (atol(roombuf->QRname) != 0)) {
243                 if (userbuf->usernum == atol(roombuf->QRname)) {
244                         retval = retval | UA_KNOWN | UA_GOTOALLOWED | UA_POSTALLOWED | UA_DELETEALLOWED | UA_REPLYALLOWED;
245                 }
246                 /* An explicit match means the user belongs in this room */
247                 if (vbuf.v_flags & V_ACCESS) {
248                         retval = retval | UA_KNOWN | UA_GOTOALLOWED | UA_POSTALLOWED | UA_DELETEALLOWED | UA_REPLYALLOWED;
249                 }
250         }
251
252         /* For non-mailbox rooms... */
253         else {
254
255                 /* User is allowed to post in the room unless:
256                  * - User is not validated
257                  * - User has no net privileges and it is a shared network room
258                  * - It is a read-only room
259                  * - It is a blog room (in which case we only allow replies to existing messages)
260                  */
261                 int post_allowed = 1;
262                 int reply_allowed = 1;
263                 if (userbuf->axlevel < AxProbU) {
264                         post_allowed = 0;
265                         reply_allowed = 0;
266                 }
267                 if ((userbuf->axlevel < AxNetU) && (roombuf->QRflags & QR_NETWORK)) {
268                         post_allowed = 0;
269                         reply_allowed = 0;
270                 }
271                 if (roombuf->QRflags & QR_READONLY) {
272                         post_allowed = 0;
273                         reply_allowed = 0;
274                 }
275                 if (roombuf->QRdefaultview == VIEW_BLOG) {
276                         post_allowed = 0;
277                 }
278                 if (post_allowed) {
279                         retval = retval | UA_POSTALLOWED | UA_REPLYALLOWED;
280                 }
281                 if (reply_allowed) {
282                         retval = retval | UA_REPLYALLOWED;
283                 }
284
285                 /* If "collaborative deletion" is active for this room, any user who can post
286                  * is also allowed to delete
287                  */
288                 if (roombuf->QRflags2 & QR2_COLLABDEL) {
289                         if (retval & UA_POSTALLOWED) {
290                                 retval = retval | UA_DELETEALLOWED;
291                         }
292                 }
293
294         }
295
296         /* Check to see if the user has forgotten this room */
297         if (vbuf.v_flags & V_FORGET) {
298                 retval = retval & ~UA_KNOWN;
299                 if (    ( ((roombuf->QRflags & QR_PRIVATE) == 0) 
300                         && ((roombuf->QRflags & QR_MAILBOX) == 0)
301                 ) || (  (roombuf->QRflags & QR_MAILBOX) 
302                         && (atol(roombuf->QRname) == CC->user.usernum))
303                 ) {
304                         retval = retval | UA_ZAPPED;
305                 }
306         }
307
308         /* If user is explicitly locked out of this room, deny everything */
309         if (vbuf.v_flags & V_LOCKOUT) {
310                 retval = retval & ~UA_KNOWN & ~UA_GOTOALLOWED & ~UA_POSTALLOWED & ~UA_REPLYALLOWED;
311         }
312
313         /* Aides get access to all private rooms */
314         if (    (userbuf->axlevel >= AxAideU)
315                 && ((roombuf->QRflags & QR_MAILBOX) == 0)
316         ) {
317                 if (vbuf.v_flags & V_FORGET) {
318                         retval = retval | UA_GOTOALLOWED | UA_POSTALLOWED | UA_REPLYALLOWED;
319                 }
320                 else {
321                         retval = retval | UA_KNOWN | UA_GOTOALLOWED | UA_POSTALLOWED | UA_REPLYALLOWED;
322                 }
323         }
324
325         /* Aides can gain access to mailboxes as well, but they don't show
326          * by default.
327          */
328         if (    (userbuf->axlevel >= AxAideU)
329                 && (roombuf->QRflags & QR_MAILBOX)
330         ) {
331                 retval = retval | UA_GOTOALLOWED | UA_POSTALLOWED | UA_REPLYALLOWED;
332         }
333
334         /* Aides and Room Aides have admin privileges */
335         if (    (userbuf->axlevel >= AxAideU)
336                 || (userbuf->usernum == roombuf->QRroomaide)
337         ) {
338                 retval = retval | UA_ADMINALLOWED | UA_DELETEALLOWED | UA_POSTALLOWED | UA_REPLYALLOWED;
339         }
340
341 NEWMSG: /* By the way, we also check for the presence of new messages */
342         if (is_msg_in_sequence_set(vbuf.v_seen, roombuf->QRhighest) == 0) {
343                 retval = retval | UA_HASNEWMSGS;
344         }
345
346         /* System rooms never show up in the list. */
347         if (roombuf->QRflags2 & QR2_SYSTEM) {
348                 retval = retval & ~UA_KNOWN;
349         }
350
351 SKIP_EVERYTHING:
352         /* Now give the caller the information it wants. */
353         if (result != NULL) *result = retval;
354         if (view != NULL) *view = vbuf.v_view;
355 }
356
357
358 /*
359  * Self-checking stuff for a room record read into memory
360  */
361 void room_sanity_check(struct ctdlroom *qrbuf)
362 {
363         /* Mailbox rooms are always on the lowest floor */
364         if (qrbuf->QRflags & QR_MAILBOX) {
365                 qrbuf->QRfloor = 0;
366         }
367         /* Listing order of 0 is illegal except for base rooms */
368         if (qrbuf->QRorder == 0)
369                 if (!(qrbuf->QRflags & QR_MAILBOX) &&
370                     strncasecmp(qrbuf->QRname, config.c_baseroom, ROOMNAMELEN)
371                     &&
372                     strncasecmp(qrbuf->QRname, config.c_aideroom, ROOMNAMELEN))
373                         qrbuf->QRorder = 64;
374 }
375
376
377 /*
378  * CtdlGetRoom()  -  retrieve room data from disk
379  */
380 int CtdlGetRoom(struct ctdlroom *qrbuf, const char *room_name)
381 {
382         struct cdbdata *cdbqr;
383         char lowercase_name[ROOMNAMELEN];
384         char personal_lowercase_name[ROOMNAMELEN];
385         const char *sptr;
386         char *dptr, *eptr;
387
388         dptr = lowercase_name;
389         sptr = room_name;
390         eptr = (dptr + (sizeof lowercase_name - 1));
391         while (!IsEmptyStr(sptr) && (dptr < eptr)){
392                 *dptr = tolower(*sptr);
393                 sptr++; dptr++;
394         }
395         *dptr = '\0';
396
397         memset(qrbuf, 0, sizeof(struct ctdlroom));
398
399         /* First, try the public namespace */
400         cdbqr = cdb_fetch(CDB_ROOMS,
401                           lowercase_name, strlen(lowercase_name));
402
403         /* If that didn't work, try the user's personal namespace */
404         if (cdbqr == NULL) {
405                 snprintf(personal_lowercase_name,
406                          sizeof personal_lowercase_name, "%010ld.%s",
407                          CC->user.usernum, lowercase_name);
408                 cdbqr = cdb_fetch(CDB_ROOMS,
409                                   personal_lowercase_name,
410                                   strlen(personal_lowercase_name));
411         }
412         if (cdbqr != NULL) {
413                 memcpy(qrbuf, cdbqr->ptr,
414                        ((cdbqr->len > sizeof(struct ctdlroom)) ?
415                         sizeof(struct ctdlroom) : cdbqr->len));
416                 cdb_free(cdbqr);
417
418                 room_sanity_check(qrbuf);
419
420                 return (0);
421         } else {
422                 return (1);
423         }
424 }
425
426 /*
427  * CtdlGetRoomLock()  -  same as getroom() but locks the record (if supported)
428  */
429 int CtdlGetRoomLock(struct ctdlroom *qrbuf, char *room_name)
430 {
431         register int retval;
432         retval = CtdlGetRoom(qrbuf, room_name);
433         if (retval == 0) begin_critical_section(S_ROOMS);
434         return(retval);
435 }
436
437
438 /*
439  * b_putroom()  -  back end to putroom() and b_deleteroom()
440  *              (if the supplied buffer is NULL, delete the room record)
441  */
442 void b_putroom(struct ctdlroom *qrbuf, char *room_name)
443 {
444         char lowercase_name[ROOMNAMELEN];
445         char *aptr, *bptr;
446         long len;
447
448         aptr = room_name;
449         bptr = lowercase_name;
450         while (!IsEmptyStr(aptr))
451         {
452                 *bptr = tolower(*aptr);
453                 aptr++;
454                 bptr++;
455         }
456         *bptr='\0';
457
458         len = bptr - lowercase_name;
459         if (qrbuf == NULL) {
460                 cdb_delete(CDB_ROOMS, lowercase_name, len);
461         } else {
462                 time(&qrbuf->QRmtime);
463                 cdb_store(CDB_ROOMS, lowercase_name, len, qrbuf, sizeof(struct ctdlroom));
464         }
465 }
466
467
468 /* 
469  * CtdlPutRoom()  -  store room data to disk
470  */
471 void CtdlPutRoom(struct ctdlroom *qrbuf) {
472         b_putroom(qrbuf, qrbuf->QRname);
473 }
474
475
476 /*
477  * b_deleteroom()  -  delete a room record from disk
478  */
479 void b_deleteroom(char *room_name) {
480         b_putroom(NULL, room_name);
481 }
482
483
484 /*
485  * CtdlPutRoomLock()  -  same as CtdlPutRoom() but unlocks the record (if supported)
486  */
487 void CtdlPutRoomLock(struct ctdlroom *qrbuf)
488 {
489
490         CtdlPutRoom(qrbuf);
491         end_critical_section(S_ROOMS);
492
493 }
494
495
496 /*
497  * CtdlGetFloorByName()  -  retrieve the number of the named floor
498  * return < 0 if not found else return floor number
499  */
500 int CtdlGetFloorByName(const char *floor_name)
501 {
502         int a;
503         struct floor *flbuf = NULL;
504
505         for (a = 0; a < MAXFLOORS; ++a) {
506                 flbuf = CtdlGetCachedFloor(a);
507
508                 /* check to see if it already exists */
509                 if ((!strcasecmp(flbuf->f_name, floor_name))
510                     && (flbuf->f_flags & F_INUSE)) {
511                         return a;
512                 }
513         }
514         return -1;
515 }
516
517
518 /*
519  * CtdlGetFloorByNameLock()  -  retrieve floor number for given floor and lock the floor list.
520  */
521 int CtdlGetFloorByNameLock(const char *floor_name)
522 {
523         begin_critical_section(S_FLOORTAB);
524         return CtdlGetFloorByName(floor_name);
525 }
526
527
528
529 /*
530  * CtdlGetAvailableFloor()  -  Return number of first unused floor
531  * return < 0 if none available
532  */
533 int CtdlGetAvailableFloor(void)
534 {
535         int a;
536         struct floor *flbuf = NULL;
537
538         for (a = 0; a < MAXFLOORS; a++) {
539                 flbuf = CtdlGetCachedFloor(a);
540
541                 /* check to see if it already exists */
542                 if ((flbuf->f_flags & F_INUSE) == 0) {
543                         return a;
544                 }
545         }
546         return -1;
547 }
548
549
550 /*
551  * CtdlGetFloor()  -  retrieve floor data from disk
552  */
553 void CtdlGetFloor(struct floor *flbuf, int floor_num)
554 {
555         struct cdbdata *cdbfl;
556
557         memset(flbuf, 0, sizeof(struct floor));
558         cdbfl = cdb_fetch(CDB_FLOORTAB, &floor_num, sizeof(int));
559         if (cdbfl != NULL) {
560                 memcpy(flbuf, cdbfl->ptr,
561                        ((cdbfl->len > sizeof(struct floor)) ?
562                         sizeof(struct floor) : cdbfl->len));
563                 cdb_free(cdbfl);
564         } else {
565                 if (floor_num == 0) {
566                         safestrncpy(flbuf->f_name, "Main Floor", 
567                                 sizeof flbuf->f_name);
568                         flbuf->f_flags = F_INUSE;
569                         flbuf->f_ref_count = 3;
570                 }
571         }
572
573 }
574
575
576 /*
577  * lgetfloor()  -  same as CtdlGetFloor() but locks the record (if supported)
578  */
579 void lgetfloor(struct floor *flbuf, int floor_num)
580 {
581
582         begin_critical_section(S_FLOORTAB);
583         CtdlGetFloor(flbuf, floor_num);
584 }
585
586
587 /*
588  * CtdlGetCachedFloor()  -  Get floor record from *cache* (loads from disk if needed)
589  *    
590  * This is strictly a performance hack.
591  */
592 struct floor *CtdlGetCachedFloor(int floor_num) {
593         static int initialized = 0;
594         int i;
595         int fetch_new = 0;
596         struct floor *fl = NULL;
597
598         begin_critical_section(S_FLOORCACHE);
599         if (initialized == 0) {
600                 for (i=0; i<MAXFLOORS; ++i) {
601                         floorcache[floor_num] = NULL;
602                 }
603         initialized = 1;
604         }
605         if (floorcache[floor_num] == NULL) {
606                 fetch_new = 1;
607         }
608         end_critical_section(S_FLOORCACHE);
609
610         if (fetch_new) {
611                 fl = malloc(sizeof(struct floor));
612                 CtdlGetFloor(fl, floor_num);
613                 begin_critical_section(S_FLOORCACHE);
614                 if (floorcache[floor_num] != NULL) {
615                         free(floorcache[floor_num]);
616                 }
617                 floorcache[floor_num] = fl;
618                 end_critical_section(S_FLOORCACHE);
619         }
620
621         return(floorcache[floor_num]);
622 }
623
624
625 /*
626  * CtdlPutFloor()  -  store floor data on disk
627  */
628 void CtdlPutFloor(struct floor *flbuf, int floor_num)
629 {
630         /* If we've cached this, clear it out, 'cuz it's WRONG now! */
631         begin_critical_section(S_FLOORCACHE);
632         if (floorcache[floor_num] != NULL) {
633                 free(floorcache[floor_num]);
634                 floorcache[floor_num] = malloc(sizeof(struct floor));
635                 memcpy(floorcache[floor_num], flbuf, sizeof(struct floor));
636         }
637         end_critical_section(S_FLOORCACHE);
638
639         cdb_store(CDB_FLOORTAB, &floor_num, sizeof(int),
640                   flbuf, sizeof(struct floor));
641 }
642
643
644 /*
645  * CtdlPutFloorLock()  -  same as CtdlPutFloor() but unlocks the record (if supported)
646  */
647 void CtdlPutFloorLock(struct floor *flbuf, int floor_num)
648 {
649
650         CtdlPutFloor(flbuf, floor_num);
651         end_critical_section(S_FLOORTAB);
652
653 }
654
655
656 /*
657  * lputfloor()  -  same as CtdlPutFloor() but unlocks the record (if supported)
658  */
659 void lputfloor(struct floor *flbuf, int floor_num)
660 {
661         CtdlPutFloorLock(flbuf, floor_num);
662 }
663
664
665 /* 
666  *  Traverse the room file...
667  */
668 void CtdlForEachRoom(ForEachRoomCallBack CB, void *in_data)
669 {
670         struct ctdlroom qrbuf;
671         struct cdbdata *cdbqr;
672
673         cdb_rewind(CDB_ROOMS);
674
675         while (cdbqr = cdb_next_item(CDB_ROOMS), cdbqr != NULL) {
676                 memset(&qrbuf, 0, sizeof(struct ctdlroom));
677                 memcpy(&qrbuf, cdbqr->ptr,
678                        ((cdbqr->len > sizeof(struct ctdlroom)) ?
679                         sizeof(struct ctdlroom) : cdbqr->len)
680                 );
681                 cdb_free(cdbqr);
682                 room_sanity_check(&qrbuf);
683                 if (qrbuf.QRflags & QR_INUSE) {
684                         CB(&qrbuf, in_data);
685                 }
686         }
687 }
688
689 /* 
690  *  Traverse the room file...
691  */
692 void CtdlForEachNetCfgRoom(ForEachRoomNetCfgCallBack CB,
693                            void *in_data,
694                            RoomNetCfg filter)
695 {
696         struct ctdlroom qrbuf;
697         struct cdbdata *cdbqr;
698
699         cdb_rewind(CDB_ROOMS);
700
701         while (cdbqr = cdb_next_item(CDB_ROOMS), cdbqr != NULL) {
702                 memset(&qrbuf, 0, sizeof(struct ctdlroom));
703                 memcpy(&qrbuf, cdbqr->ptr,
704                        ((cdbqr->len > sizeof(struct ctdlroom)) ?
705                         sizeof(struct ctdlroom) : cdbqr->len)
706                 );
707                 cdb_free(cdbqr);
708                 room_sanity_check(&qrbuf);
709                 if (qrbuf.QRflags & QR_INUSE)
710                 {
711                         OneRoomNetCfg* RNCfg;
712                         RNCfg = CtdlGetNetCfgForRoom(qrbuf.QRnumber);
713                         if ((RNCfg != NULL) &&
714                             ((filter == maxRoomNetCfg) ||
715                              (RNCfg->NetConfigs[filter] != NULL)))
716                         {
717                                 CB(&qrbuf, in_data, RNCfg);
718                         }
719                 }
720         }
721 }
722
723
724 /*
725  * delete_msglist()  -  delete room message pointers
726  */
727 void delete_msglist(struct ctdlroom *whichroom)
728 {
729         struct cdbdata *cdbml;
730
731         /* Make sure the msglist we're deleting actually exists, otherwise
732          * libdb will complain when we try to delete an invalid record
733          */
734         cdbml = cdb_fetch(CDB_MSGLISTS, &whichroom->QRnumber, sizeof(long));
735         if (cdbml != NULL) {
736                 cdb_free(cdbml);
737
738                 /* Go ahead and delete it */
739                 cdb_delete(CDB_MSGLISTS, &whichroom->QRnumber, sizeof(long));
740         }
741 }
742
743
744 /*
745  * Message pointer compare function for sort_msglist()
746  */
747 int sort_msglist_cmp(const void *m1, const void *m2) {
748         if ((*(const long *)m1) > (*(const long *)m2)) return(1);
749         if ((*(const long *)m1) < (*(const long *)m2)) return(-1);
750         return(0);
751 }
752
753
754 /*
755  * sort message pointers
756  * (returns new msg count)
757  */
758 int sort_msglist(long listptrs[], int oldcount)
759 {
760         int numitems;
761         int i = 0;
762
763         numitems = oldcount;
764         if (numitems < 2) {
765                 return (oldcount);
766         }
767
768         /* do the sort */
769         qsort(listptrs, numitems, sizeof(long), sort_msglist_cmp);
770
771         /* and yank any nulls */
772         while ((i < numitems) && (listptrs[i] == 0L)) i++;
773
774         if (i > 0)
775         {
776                 memmove(&listptrs[0], &listptrs[i], (sizeof(long) * (numitems - i)));
777                 numitems-=i;
778         }
779
780         return (numitems);
781 }
782
783
784 /*
785  * Determine whether a given room is non-editable.
786  */
787 int CtdlIsNonEditable(struct ctdlroom *qrbuf)
788 {
789
790         /* Mail> rooms are non-editable */
791         if ( (qrbuf->QRflags & QR_MAILBOX)
792              && (!strcasecmp(&qrbuf->QRname[11], MAILROOM)) )
793                 return (1);
794
795         /* Everything else is editable */
796         return (0);
797 }
798
799
800 /*
801  * Back-back-end for all room listing commands
802  */
803 void list_roomname(struct ctdlroom *qrbuf, int ra, int current_view, int default_view)
804 {
805         char truncated_roomname[ROOMNAMELEN];
806
807         /* For my own mailbox rooms, chop off the owner prefix */
808         if ( (qrbuf->QRflags & QR_MAILBOX)
809              && (atol(qrbuf->QRname) == CC->user.usernum) ) {
810                 safestrncpy(truncated_roomname, qrbuf->QRname, sizeof truncated_roomname);
811                 safestrncpy(truncated_roomname, &truncated_roomname[11], sizeof truncated_roomname);
812                 cprintf("%s", truncated_roomname);
813         }
814         /* For all other rooms, just display the name in its entirety */
815         else {
816                 cprintf("%s", qrbuf->QRname);
817         }
818
819         /* ...and now the other parameters */
820         cprintf("|%u|%d|%d|%d|%d|%d|%d|%ld|\n",
821                 qrbuf->QRflags,
822                 (int) qrbuf->QRfloor,
823                 (int) qrbuf->QRorder,
824                 (int) qrbuf->QRflags2,
825                 ra,
826                 current_view,
827                 default_view,
828                 qrbuf->QRmtime
829         );
830 }
831
832
833 /* 
834  * cmd_lrms()   -  List all accessible rooms, known or forgotten
835  */
836 void cmd_lrms_backend(struct ctdlroom *qrbuf, void *data)
837 {
838         int FloorBeingSearched = (-1);
839         int ra;
840         int view;
841
842         FloorBeingSearched = *(int *)data;
843         CtdlRoomAccess(qrbuf, &CC->user, &ra, &view);
844
845         if ((( ra & (UA_KNOWN | UA_ZAPPED)))
846             && ((qrbuf->QRfloor == (FloorBeingSearched))
847                 || ((FloorBeingSearched) < 0)))
848                 list_roomname(qrbuf, ra, view, qrbuf->QRdefaultview);
849 }
850
851 void cmd_lrms(char *argbuf)
852 {
853         int FloorBeingSearched = (-1);
854         if (!IsEmptyStr(argbuf))
855                 FloorBeingSearched = extract_int(argbuf, 0);
856
857         if (CtdlAccessCheck(ac_logged_in_or_guest)) return;
858
859         CtdlGetUser(&CC->user, CC->curr_user);
860         cprintf("%d Accessible rooms:\n", LISTING_FOLLOWS);
861
862         CtdlForEachRoom(cmd_lrms_backend, &FloorBeingSearched);
863         cprintf("000\n");
864 }
865
866
867
868 /* 
869  * cmd_lkra()   -  List all known rooms
870  */
871 void cmd_lkra_backend(struct ctdlroom *qrbuf, void *data)
872 {
873         int FloorBeingSearched = (-1);
874         int ra;
875         int view;
876
877         FloorBeingSearched = *(int *)data;
878         CtdlRoomAccess(qrbuf, &CC->user, &ra, &view);
879
880         if ((( ra & (UA_KNOWN)))
881             && ((qrbuf->QRfloor == (FloorBeingSearched))
882                 || ((FloorBeingSearched) < 0)))
883                 list_roomname(qrbuf, ra, view, qrbuf->QRdefaultview);
884 }
885
886 void cmd_lkra(char *argbuf)
887 {
888         int FloorBeingSearched = (-1);
889         if (!IsEmptyStr(argbuf))
890                 FloorBeingSearched = extract_int(argbuf, 0);
891
892         if (CtdlAccessCheck(ac_logged_in_or_guest)) return;
893         
894         CtdlGetUser(&CC->user, CC->curr_user);
895         cprintf("%d Known rooms:\n", LISTING_FOLLOWS);
896
897         CtdlForEachRoom(cmd_lkra_backend, &FloorBeingSearched);
898         cprintf("000\n");
899 }
900
901
902
903 void cmd_lprm_backend(struct ctdlroom *qrbuf, void *data)
904 {
905         int FloorBeingSearched = (-1);
906         int ra;
907         int view;
908
909         FloorBeingSearched = *(int *)data;
910         CtdlRoomAccess(qrbuf, &CC->user, &ra, &view);
911
912         if (   ((qrbuf->QRflags & QR_PRIVATE) == 0)
913                 && ((qrbuf->QRflags & QR_MAILBOX) == 0)
914             && ((qrbuf->QRfloor == (FloorBeingSearched))
915                 || ((FloorBeingSearched) < 0)))
916                 list_roomname(qrbuf, ra, view, qrbuf->QRdefaultview);
917 }
918
919 void cmd_lprm(char *argbuf)
920 {
921         int FloorBeingSearched = (-1);
922         if (!IsEmptyStr(argbuf))
923                 FloorBeingSearched = extract_int(argbuf, 0);
924
925         cprintf("%d Public rooms:\n", LISTING_FOLLOWS);
926
927         CtdlForEachRoom(cmd_lprm_backend, &FloorBeingSearched);
928         cprintf("000\n");
929 }
930
931
932
933 /* 
934  * cmd_lkrn()   -  List all known rooms with new messages
935  */
936 void cmd_lkrn_backend(struct ctdlroom *qrbuf, void *data)
937 {
938         int FloorBeingSearched = (-1);
939         int ra;
940         int view;
941
942         FloorBeingSearched = *(int *)data;
943         CtdlRoomAccess(qrbuf, &CC->user, &ra, &view);
944
945         if ((ra & UA_KNOWN)
946             && (ra & UA_HASNEWMSGS)
947             && ((qrbuf->QRfloor == (FloorBeingSearched))
948                 || ((FloorBeingSearched) < 0)))
949                 list_roomname(qrbuf, ra, view, qrbuf->QRdefaultview);
950 }
951
952 void cmd_lkrn(char *argbuf)
953 {
954         int FloorBeingSearched = (-1);
955         if (!IsEmptyStr(argbuf))
956                 FloorBeingSearched = extract_int(argbuf, 0);
957
958         if (CtdlAccessCheck(ac_logged_in_or_guest)) return;
959         
960         CtdlGetUser(&CC->user, CC->curr_user);
961         cprintf("%d Rooms w/ new msgs:\n", LISTING_FOLLOWS);
962
963         CtdlForEachRoom(cmd_lkrn_backend, &FloorBeingSearched);
964         cprintf("000\n");
965 }
966
967
968
969 /* 
970  * cmd_lkro()   -  List all known rooms
971  */
972 void cmd_lkro_backend(struct ctdlroom *qrbuf, void *data)
973 {
974         int FloorBeingSearched = (-1);
975         int ra;
976         int view;
977
978         FloorBeingSearched = *(int *)data;
979         CtdlRoomAccess(qrbuf, &CC->user, &ra, &view);
980
981         if ((ra & UA_KNOWN)
982             && ((ra & UA_HASNEWMSGS) == 0)
983             && ((qrbuf->QRfloor == (FloorBeingSearched))
984                 || ((FloorBeingSearched) < 0)))
985                 list_roomname(qrbuf, ra, view, qrbuf->QRdefaultview);
986 }
987
988 void cmd_lkro(char *argbuf)
989 {
990         int FloorBeingSearched = (-1);
991         if (!IsEmptyStr(argbuf))
992                 FloorBeingSearched = extract_int(argbuf, 0);
993
994         if (CtdlAccessCheck(ac_logged_in_or_guest)) return;
995         
996         CtdlGetUser(&CC->user, CC->curr_user);
997         cprintf("%d Rooms w/o new msgs:\n", LISTING_FOLLOWS);
998
999         CtdlForEachRoom(cmd_lkro_backend, &FloorBeingSearched);
1000         cprintf("000\n");
1001 }
1002
1003
1004
1005 /* 
1006  * cmd_lzrm()   -  List all forgotten rooms
1007  */
1008 void cmd_lzrm_backend(struct ctdlroom *qrbuf, void *data)
1009 {
1010         int FloorBeingSearched = (-1);
1011         int ra;
1012         int view;
1013
1014         FloorBeingSearched = *(int *)data;
1015         CtdlRoomAccess(qrbuf, &CC->user, &ra, &view);
1016
1017         if ((ra & UA_GOTOALLOWED)
1018             && (ra & UA_ZAPPED)
1019             && ((qrbuf->QRfloor == (FloorBeingSearched))
1020                 || ((FloorBeingSearched) < 0)))
1021                 list_roomname(qrbuf, ra, view, qrbuf->QRdefaultview);
1022 }
1023
1024 void cmd_lzrm(char *argbuf)
1025 {
1026         int FloorBeingSearched = (-1);
1027         if (!IsEmptyStr(argbuf))
1028                 FloorBeingSearched = extract_int(argbuf, 0);
1029
1030         if (CtdlAccessCheck(ac_logged_in_or_guest)) return;
1031         
1032         CtdlGetUser(&CC->user, CC->curr_user);
1033         cprintf("%d Zapped rooms:\n", LISTING_FOLLOWS);
1034
1035         CtdlForEachRoom(cmd_lzrm_backend, &FloorBeingSearched);
1036         cprintf("000\n");
1037 }
1038
1039
1040 /*
1041  * Make the specified room the current room for this session.  No validation
1042  * or access control is done here -- the caller should make sure that the
1043  * specified room exists and is ok to access.
1044  */
1045 void CtdlUserGoto(char *where, int display_result, int transiently,
1046                 int *retmsgs, int *retnew)
1047 {
1048         struct CitContext *CCC = CC;
1049         int a;
1050         int new_messages = 0;
1051         int old_messages = 0;
1052         int total_messages = 0;
1053         int info = 0;
1054         int rmailflag;
1055         int raideflag;
1056         int newmailcount = 0;
1057         visit vbuf;
1058         char truncated_roomname[ROOMNAMELEN];
1059         struct cdbdata *cdbfr;
1060         long *msglist = NULL;
1061         int num_msgs = 0;
1062         unsigned int original_v_flags;
1063         int num_sets;
1064         int s;
1065         char setstr[128], lostr[64], histr[64];
1066         long lo, hi;
1067         int is_trash = 0;
1068
1069         /* If the supplied room name is NULL, the caller wants us to know that
1070          * it has already copied the room record into CC->room, so
1071          * we can skip the extra database fetch.
1072          */
1073         if (where != NULL) {
1074                 safestrncpy(CCC->room.QRname, where, sizeof CCC->room.QRname);
1075                 CtdlGetRoom(&CCC->room, where);
1076         }
1077
1078         /* Take care of all the formalities. */
1079
1080         begin_critical_section(S_USERS);
1081         CtdlGetRelationship(&vbuf, &CCC->user, &CCC->room);
1082         original_v_flags = vbuf.v_flags;
1083
1084         /* Know the room ... but not if it's the page log room, or if the
1085          * caller specified that we're only entering this room transiently.
1086          */
1087         if ((strcasecmp(CCC->room.QRname, config.c_logpages))
1088            && (transiently == 0) ) {
1089                 vbuf.v_flags = vbuf.v_flags & ~V_FORGET & ~V_LOCKOUT;
1090                 vbuf.v_flags = vbuf.v_flags | V_ACCESS;
1091         }
1092         
1093         /* Only rewrite the database record if we changed something */
1094         if (vbuf.v_flags != original_v_flags) {
1095                 CtdlSetRelationship(&vbuf, &CCC->user, &CCC->room);
1096         }
1097         end_critical_section(S_USERS);
1098
1099         /* Check for new mail */
1100         newmailcount = NewMailCount();
1101
1102         /* set info to 1 if the user needs to read the room's info file */
1103         if (CCC->room.QRinfo > vbuf.v_lastseen) {
1104                 info = 1;
1105         }
1106
1107         cdbfr = cdb_fetch(CDB_MSGLISTS, &CCC->room.QRnumber, sizeof(long));
1108         if (cdbfr != NULL) {
1109                 msglist = (long *) cdbfr->ptr;
1110                 cdbfr->ptr = NULL;      /* CtdlUserGoto() now owns this memory */
1111                 num_msgs = cdbfr->len / sizeof(long);
1112                 cdb_free(cdbfr);
1113         }
1114
1115         total_messages = 0;
1116         for (a=0; a<num_msgs; ++a) {
1117                 if (msglist[a] > 0L) ++total_messages;
1118         }
1119
1120         num_sets = num_tokens(vbuf.v_seen, ',');
1121         for (s=0; s<num_sets; ++s) {
1122                 extract_token(setstr, vbuf.v_seen, s, ',', sizeof setstr);
1123
1124                 extract_token(lostr, setstr, 0, ':', sizeof lostr);
1125                 if (num_tokens(setstr, ':') >= 2) {
1126                         extract_token(histr, setstr, 1, ':', sizeof histr);
1127                         if (!strcmp(histr, "*")) {
1128                                 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
1129                         }
1130                 } 
1131                 else {
1132                         strcpy(histr, lostr);
1133                 }
1134                 lo = atol(lostr);
1135                 hi = atol(histr);
1136
1137                 for (a=0; a<num_msgs; ++a) if (msglist[a] > 0L) {
1138                         if ((msglist[a] >= lo) && (msglist[a] <= hi)) {
1139                                 ++old_messages;
1140                                 msglist[a] = 0L;
1141                         }
1142                 }
1143         }
1144         new_messages = total_messages - old_messages;
1145
1146         if (msglist != NULL) free(msglist);
1147
1148         if (CCC->room.QRflags & QR_MAILBOX)
1149                 rmailflag = 1;
1150         else
1151                 rmailflag = 0;
1152
1153         if ((CCC->room.QRroomaide == CCC->user.usernum)
1154             || (CCC->user.axlevel >= AxAideU))
1155                 raideflag = 1;
1156         else
1157                 raideflag = 0;
1158
1159         safestrncpy(truncated_roomname, CCC->room.QRname, sizeof truncated_roomname);
1160         if ( (CCC->room.QRflags & QR_MAILBOX)
1161            && (atol(CCC->room.QRname) == CCC->user.usernum) ) {
1162                 safestrncpy(truncated_roomname, &truncated_roomname[11], sizeof truncated_roomname);
1163         }
1164
1165         if (!strcasecmp(truncated_roomname, USERTRASHROOM)) {
1166                 is_trash = 1;
1167         }
1168
1169         if (retmsgs != NULL) *retmsgs = total_messages;
1170         if (retnew != NULL) *retnew = new_messages;
1171         MSG_syslog(LOG_INFO, "<%s> %d new of %d total messages\n",
1172                    CCC->room.QRname,
1173                    new_messages, total_messages
1174                 );
1175
1176         CCC->curr_view = (int)vbuf.v_view;
1177
1178         if (display_result) {
1179                 cprintf("%d%c%s|%d|%d|%d|%d|%ld|%ld|%d|%d|%d|%d|%d|%d|%d|%d|%ld|\n",
1180                         CIT_OK, CtdlCheckExpress(),
1181                         truncated_roomname,
1182                         (int)new_messages,
1183                         (int)total_messages,
1184                         (int)info,
1185                         (int)CCC->room.QRflags,
1186                         (long)CCC->room.QRhighest,
1187                         (long)vbuf.v_lastseen,
1188                         (int)rmailflag,
1189                         (int)raideflag,
1190                         (int)newmailcount,
1191                         (int)CCC->room.QRfloor,
1192                         (int)vbuf.v_view,
1193                         (int)CCC->room.QRdefaultview,
1194                         (int)is_trash,
1195                         (int)CCC->room.QRflags2,
1196                         (long)CCC->room.QRmtime
1197                 );
1198         }
1199 }
1200
1201
1202 /*
1203  * Handle some of the macro named rooms
1204  */
1205 void convert_room_name_macros(char *towhere, size_t maxlen) {
1206         if (!strcasecmp(towhere, "_BASEROOM_")) {
1207                 safestrncpy(towhere, config.c_baseroom, maxlen);
1208         }
1209         else if (!strcasecmp(towhere, "_MAIL_")) {
1210                 safestrncpy(towhere, MAILROOM, maxlen);
1211         }
1212         else if (!strcasecmp(towhere, "_TRASH_")) {
1213                 safestrncpy(towhere, USERTRASHROOM, maxlen);
1214         }
1215         else if (!strcasecmp(towhere, "_DRAFTS_")) {
1216                 safestrncpy(towhere, USERDRAFTROOM, maxlen);
1217         }
1218         else if (!strcasecmp(towhere, "_BITBUCKET_")) {
1219                 safestrncpy(towhere, config.c_twitroom, maxlen);
1220         }
1221         else if (!strcasecmp(towhere, "_CALENDAR_")) {
1222                 safestrncpy(towhere, USERCALENDARROOM, maxlen);
1223         }
1224         else if (!strcasecmp(towhere, "_TASKS_")) {
1225                 safestrncpy(towhere, USERTASKSROOM, maxlen);
1226         }
1227         else if (!strcasecmp(towhere, "_CONTACTS_")) {
1228                 safestrncpy(towhere, USERCONTACTSROOM, maxlen);
1229         }
1230         else if (!strcasecmp(towhere, "_NOTES_")) {
1231                 safestrncpy(towhere, USERNOTESROOM, maxlen);
1232         }
1233 }
1234
1235
1236 /* 
1237  * cmd_goto()  -  goto a new room
1238  */
1239 void cmd_goto(char *gargs)
1240 {
1241         struct ctdlroom QRscratch;
1242         int c;
1243         int ok = 0;
1244         int ra;
1245         char augmented_roomname[ROOMNAMELEN];
1246         char towhere[ROOMNAMELEN];
1247         char password[32];
1248         int transiently = 0;
1249
1250         if (CtdlAccessCheck(ac_logged_in_or_guest)) return;
1251
1252         extract_token(towhere, gargs, 0, '|', sizeof towhere);
1253         extract_token(password, gargs, 1, '|', sizeof password);
1254         transiently = extract_int(gargs, 2);
1255
1256         CtdlGetUser(&CC->user, CC->curr_user);
1257
1258         /*
1259          * Handle some of the macro named rooms
1260          */
1261         convert_room_name_macros(towhere, sizeof towhere);
1262
1263         /* First try a regular match */
1264         c = CtdlGetRoom(&QRscratch, towhere);
1265
1266         /* Then try a mailbox name match */
1267         if (c != 0) {
1268                 CtdlMailboxName(augmented_roomname, sizeof augmented_roomname,
1269                             &CC->user, towhere);
1270                 c = CtdlGetRoom(&QRscratch, augmented_roomname);
1271                 if (c == 0)
1272                         safestrncpy(towhere, augmented_roomname, sizeof towhere);
1273         }
1274
1275         /* And if the room was found... */
1276         if (c == 0) {
1277
1278                 /* Let internal programs go directly to any room. */
1279                 if (CC->internal_pgm) {
1280                         memcpy(&CC->room, &QRscratch,
1281                                 sizeof(struct ctdlroom));
1282                         CtdlUserGoto(NULL, 1, transiently, NULL, NULL);
1283                         return;
1284                 }
1285
1286                 /* See if there is an existing user/room relationship */
1287                 CtdlRoomAccess(&QRscratch, &CC->user, &ra, NULL);
1288
1289                 /* normal clients have to pass through security */
1290                 if (ra & UA_GOTOALLOWED) {
1291                         ok = 1;
1292                 }
1293
1294                 if (ok == 1) {
1295                         if ((QRscratch.QRflags & QR_MAILBOX) &&
1296                             ((ra & UA_GOTOALLOWED))) {
1297                                 memcpy(&CC->room, &QRscratch,
1298                                         sizeof(struct ctdlroom));
1299                                 CtdlUserGoto(NULL, 1, transiently, NULL, NULL);
1300                                 return;
1301                         } else if ((QRscratch.QRflags & QR_PASSWORDED) &&
1302                             ((ra & UA_KNOWN) == 0) &&
1303                             (strcasecmp(QRscratch.QRpasswd, password)) &&
1304                             (CC->user.axlevel < AxAideU)
1305                             ) {
1306                                 cprintf("%d wrong or missing passwd\n",
1307                                         ERROR + PASSWORD_REQUIRED);
1308                                 return;
1309                         } else if ((QRscratch.QRflags & QR_PRIVATE) &&
1310                                    ((QRscratch.QRflags & QR_PASSWORDED) == 0) &&
1311                                    ((QRscratch.QRflags & QR_GUESSNAME) == 0) &&
1312                                    ((ra & UA_KNOWN) == 0) &&
1313                                    (CC->user.axlevel < AxAideU)
1314                                   ) {
1315                                 syslog(LOG_DEBUG, "Failed to acquire private room\n");
1316                         } else {
1317                                 memcpy(&CC->room, &QRscratch,
1318                                         sizeof(struct ctdlroom));
1319                                 CtdlUserGoto(NULL, 1, transiently, NULL, NULL);
1320                                 return;
1321                         }
1322                 }
1323         }
1324
1325         cprintf("%d room '%s' not found\n", ERROR + ROOM_NOT_FOUND, towhere);
1326 }
1327
1328
1329 void cmd_whok(char *cmdbuf)
1330 {
1331         struct ctdluser temp;
1332         struct cdbdata *cdbus;
1333         int ra;
1334
1335         cprintf("%d Who knows room:\n", LISTING_FOLLOWS);
1336         cdb_rewind(CDB_USERS);
1337         while (cdbus = cdb_next_item(CDB_USERS), cdbus != NULL) {
1338                 memset(&temp, 0, sizeof temp);
1339                 memcpy(&temp, cdbus->ptr, sizeof temp);
1340                 cdb_free(cdbus);
1341
1342                 CtdlRoomAccess(&CC->room, &temp, &ra, NULL);
1343                 if ((!IsEmptyStr(temp.fullname)) && 
1344                     (CC->room.QRflags & QR_INUSE) &&
1345                     (ra & UA_KNOWN)
1346                         )
1347                         cprintf("%s\n", temp.fullname);
1348         }
1349         cprintf("000\n");
1350 }
1351
1352
1353 /*
1354  * RDIR command for room directory
1355  */
1356 void cmd_rdir(char *cmdbuf)
1357 {
1358         char buf[256];
1359         char comment[256];
1360         FILE *fd;
1361         struct stat statbuf;
1362         DIR *filedir = NULL;
1363         struct dirent *filedir_entry;
1364         int d_namelen;
1365         char buf2[SIZ];
1366         char mimebuf[64];
1367         long len;
1368         
1369         if (CtdlAccessCheck(ac_logged_in)) return;
1370         
1371         CtdlGetRoom(&CC->room, CC->room.QRname);
1372         CtdlGetUser(&CC->user, CC->curr_user);
1373
1374         if ((CC->room.QRflags & QR_DIRECTORY) == 0) {
1375                 cprintf("%d not here.\n", ERROR + NOT_HERE);
1376                 return;
1377         }
1378         if (((CC->room.QRflags & QR_VISDIR) == 0)
1379             && (CC->user.axlevel < AxAideU)
1380             && (CC->user.usernum != CC->room.QRroomaide)) {
1381                 cprintf("%d not here.\n", ERROR + HIGHER_ACCESS_REQUIRED);
1382                 return;
1383         }
1384
1385         snprintf(buf, sizeof buf, "%s/%s", ctdl_file_dir, CC->room.QRdirname);
1386         filedir = opendir (buf);
1387         
1388         if (filedir == NULL) {
1389                 cprintf("%d not here.\n", ERROR + HIGHER_ACCESS_REQUIRED);
1390                 return;
1391         }
1392         cprintf("%d %s|%s/%s\n", LISTING_FOLLOWS, config.c_fqdn, ctdl_file_dir, CC->room.QRdirname);
1393         
1394         snprintf(buf, sizeof buf, "%s/%s/filedir", ctdl_file_dir, CC->room.QRdirname);
1395         fd = fopen(buf, "r");
1396         if (fd == NULL)
1397                 fd = fopen("/dev/null", "r");
1398         while ((filedir_entry = readdir(filedir)))
1399         {
1400                 if (strcasecmp(filedir_entry->d_name, "filedir") && filedir_entry->d_name[0] != '.')
1401                 {
1402 #ifdef _DIRENT_HAVE_D_NAMELEN
1403                         d_namelen = filedir_entry->d_namelen;
1404 #else
1405                         d_namelen = strlen(filedir_entry->d_name);
1406 #endif
1407                         snprintf(buf, sizeof buf, "%s/%s/%s", ctdl_file_dir, CC->room.QRdirname, filedir_entry->d_name);
1408                         stat(buf, &statbuf);    /* stat the file */
1409                         if (!(statbuf.st_mode & S_IFREG))
1410                         {
1411                                 snprintf(buf2, sizeof buf2,
1412                                         "\"%s\" appears in the file directory for room \"%s\" but is not a regular file.  Directories, named pipes, sockets, etc. are not usable in Citadel room directories.\n",
1413                                         buf, CC->room.QRname
1414                                 );
1415                                 CtdlAideMessage(buf2, "Unusable data found in room directory");
1416                                 continue;       /* not a useable file type so don't show it */
1417                         }
1418                         safestrncpy(comment, "", sizeof comment);
1419                         fseek(fd, 0L, 0);       /* rewind descriptions file */
1420                         /* Get the description from the descriptions file */
1421                         while ((fgets(buf, sizeof buf, fd) != NULL) && (IsEmptyStr(comment))) 
1422                         {
1423                                 buf[strlen(buf) - 1] = 0;
1424                                 if ((!strncasecmp(buf, filedir_entry->d_name, d_namelen)) && (buf[d_namelen] == ' '))
1425                                         safestrncpy(comment, &buf[d_namelen + 1], sizeof comment);
1426                         }
1427                         len = extract_token (mimebuf, comment, 0,' ', 64);
1428                         if ((len <0) || strchr(mimebuf, '/') == NULL)
1429                         {
1430                                 snprintf (mimebuf, 64, "application/octetstream");
1431                                 len = 0;
1432                         }
1433                         cprintf("%s|%ld|%s|%s\n", 
1434                                 filedir_entry->d_name, 
1435                                 (long)statbuf.st_size, 
1436                                 mimebuf, 
1437                                 &comment[len]);
1438                 }
1439         }
1440         fclose(fd);
1441         closedir(filedir);
1442         
1443         cprintf("000\n");
1444 }
1445
1446 /*
1447  * get room parameters (admin or room admin command)
1448  */
1449 void cmd_getr(char *cmdbuf)
1450 {
1451         if (CtdlAccessCheck(ac_room_aide)) return;
1452
1453         CtdlGetRoom(&CC->room, CC->room.QRname);
1454         cprintf("%d%c%s|%s|%s|%d|%d|%d|%d|%d|\n",
1455                 CIT_OK,
1456                 CtdlCheckExpress(),
1457
1458                 ((CC->room.QRflags & QR_MAILBOX) ?
1459                         &CC->room.QRname[11] : CC->room.QRname),
1460
1461                 ((CC->room.QRflags & QR_PASSWORDED) ?
1462                         CC->room.QRpasswd : ""),
1463
1464                 ((CC->room.QRflags & QR_DIRECTORY) ?
1465                         CC->room.QRdirname : ""),
1466
1467                 CC->room.QRflags,
1468                 (int) CC->room.QRfloor,
1469                 (int) CC->room.QRorder,
1470
1471                 CC->room.QRdefaultview,
1472                 CC->room.QRflags2
1473                 );
1474 }
1475
1476
1477 /*
1478  * Back end function to rename a room.
1479  * You can also specify which floor to move the room to, or specify -1 to
1480  * keep the room on the same floor it was on.
1481  *
1482  * If you are renaming a mailbox room, you must supply the namespace prefix
1483  * in *at least* the old name!
1484  */
1485 int CtdlRenameRoom(char *old_name, char *new_name, int new_floor) {
1486         int old_floor = 0;
1487         struct ctdlroom qrbuf;
1488         struct ctdlroom qrtmp;
1489         int ret = 0;
1490         struct floor *fl;
1491         struct floor flbuf;
1492         long owner = 0L;
1493         char actual_old_name[ROOMNAMELEN];
1494
1495         syslog(LOG_DEBUG, "CtdlRenameRoom(%s, %s, %d)\n",
1496                 old_name, new_name, new_floor);
1497
1498         if (new_floor >= 0) {
1499                 fl = CtdlGetCachedFloor(new_floor);
1500                 if ((fl->f_flags & F_INUSE) == 0) {
1501                         return(crr_invalid_floor);
1502                 }
1503         }
1504
1505         begin_critical_section(S_ROOMS);
1506
1507         if ( (CtdlGetRoom(&qrtmp, new_name) == 0) 
1508            && (strcasecmp(new_name, old_name)) ) {
1509                 ret = crr_already_exists;
1510         }
1511
1512         else if (CtdlGetRoom(&qrbuf, old_name) != 0) {
1513                 ret = crr_room_not_found;
1514         }
1515
1516         else if ( (CC->user.axlevel < AxAideU) && (!CC->internal_pgm)
1517                   && (CC->user.usernum != qrbuf.QRroomaide)
1518                   && ( (((qrbuf.QRflags & QR_MAILBOX) == 0) || (atol(qrbuf.QRname) != CC->user.usernum))) )  {
1519                 ret = crr_access_denied;
1520         }
1521
1522         else if (CtdlIsNonEditable(&qrbuf)) {
1523                 ret = crr_noneditable;
1524         }
1525
1526         else {
1527                 /* Rename it */
1528                 safestrncpy(actual_old_name, qrbuf.QRname, sizeof actual_old_name);
1529                 if (qrbuf.QRflags & QR_MAILBOX) {
1530                         owner = atol(qrbuf.QRname);
1531                 }
1532                 if ( (owner > 0L) && (atol(new_name) == 0L) ) {
1533                         snprintf(qrbuf.QRname, sizeof(qrbuf.QRname),
1534                                         "%010ld.%s", owner, new_name);
1535                 }
1536                 else {
1537                         safestrncpy(qrbuf.QRname, new_name,
1538                                                 sizeof(qrbuf.QRname));
1539                 }
1540
1541                 /* Reject change of floor for baseroom/aideroom */
1542                 if (!strncasecmp(old_name, config.c_baseroom, ROOMNAMELEN) ||
1543                     !strncasecmp(old_name, config.c_aideroom, ROOMNAMELEN)) {
1544                         new_floor = 0;
1545                 }
1546
1547                 /* Take care of floor stuff */
1548                 old_floor = qrbuf.QRfloor;
1549                 if (new_floor < 0) {
1550                         new_floor = old_floor;
1551                 }
1552                 qrbuf.QRfloor = new_floor;
1553                 CtdlPutRoom(&qrbuf);
1554
1555                 begin_critical_section(S_CONFIG);
1556         
1557                 /* If baseroom/aideroom name changes, update config */
1558                 if (!strncasecmp(old_name, config.c_baseroom, ROOMNAMELEN)) {
1559                         safestrncpy(config.c_baseroom, new_name, ROOMNAMELEN);
1560                         put_config();
1561                 }
1562                 if (!strncasecmp(old_name, config.c_aideroom, ROOMNAMELEN)) {
1563                         safestrncpy(config.c_aideroom, new_name, ROOMNAMELEN);
1564                         put_config();
1565                 }
1566         
1567                 end_critical_section(S_CONFIG);
1568         
1569                 /* If the room name changed, then there are now two room
1570                  * records, so we have to delete the old one.
1571                  */
1572                 if (strcasecmp(new_name, old_name)) {
1573                         b_deleteroom(actual_old_name);
1574                 }
1575
1576                 ret = crr_ok;
1577         }
1578
1579         end_critical_section(S_ROOMS);
1580
1581         /* Adjust the floor reference counts if necessary */
1582         if (new_floor != old_floor) {
1583                 lgetfloor(&flbuf, old_floor);
1584                 --flbuf.f_ref_count;
1585                 lputfloor(&flbuf, old_floor);
1586                 syslog(LOG_DEBUG, "Reference count for floor %d is now %d\n", old_floor, flbuf.f_ref_count);
1587                 lgetfloor(&flbuf, new_floor);
1588                 ++flbuf.f_ref_count;
1589                 lputfloor(&flbuf, new_floor);
1590                 syslog(LOG_DEBUG, "Reference count for floor %d is now %d\n", new_floor, flbuf.f_ref_count);
1591         }
1592
1593         /* ...and everybody say "YATTA!" */     
1594         return(ret);
1595 }
1596
1597
1598 /*
1599  * set room parameters (admin or room admin command)
1600  */
1601 void cmd_setr(char *args)
1602 {
1603         char buf[256];
1604         int new_order = 0;
1605         int r;
1606         int new_floor;
1607         char new_name[ROOMNAMELEN];
1608
1609         if (CtdlAccessCheck(ac_logged_in)) return;
1610
1611         if (num_parms(args) >= 6) {
1612                 new_floor = extract_int(args, 5);
1613         } else {
1614                 new_floor = (-1);       /* don't change the floor */
1615         }
1616
1617         /* When is a new name more than just a new name?  When the old name
1618          * has a namespace prefix.
1619          */
1620         if (CC->room.QRflags & QR_MAILBOX) {
1621                 sprintf(new_name, "%010ld.", atol(CC->room.QRname) );
1622         } else {
1623                 safestrncpy(new_name, "", sizeof new_name);
1624         }
1625         extract_token(&new_name[strlen(new_name)], args, 0, '|', (sizeof new_name - strlen(new_name)));
1626
1627         r = CtdlRenameRoom(CC->room.QRname, new_name, new_floor);
1628
1629         if (r == crr_room_not_found) {
1630                 cprintf("%d Internal error - room not found?\n", ERROR + INTERNAL_ERROR);
1631         } else if (r == crr_already_exists) {
1632                 cprintf("%d '%s' already exists.\n",
1633                         ERROR + ALREADY_EXISTS, new_name);
1634         } else if (r == crr_noneditable) {
1635                 cprintf("%d Cannot edit this room.\n", ERROR + NOT_HERE);
1636         } else if (r == crr_invalid_floor) {
1637                 cprintf("%d Target floor does not exist.\n",
1638                         ERROR + INVALID_FLOOR_OPERATION);
1639         } else if (r == crr_access_denied) {
1640                 cprintf("%d You do not have permission to edit '%s'\n",
1641                         ERROR + HIGHER_ACCESS_REQUIRED,
1642                         CC->room.QRname);
1643         } else if (r != crr_ok) {
1644                 cprintf("%d Error: CtdlRenameRoom() returned %d\n",
1645                         ERROR + INTERNAL_ERROR, r);
1646         }
1647
1648         if (r != crr_ok) {
1649                 return;
1650         }
1651
1652         CtdlGetRoom(&CC->room, new_name);
1653
1654         /* Now we have to do a bunch of other stuff */
1655
1656         if (num_parms(args) >= 7) {
1657                 new_order = extract_int(args, 6);
1658                 if (new_order < 1)
1659                         new_order = 1;
1660                 if (new_order > 127)
1661                         new_order = 127;
1662         }
1663
1664         CtdlGetRoomLock(&CC->room, CC->room.QRname);
1665
1666         /* Directory room */
1667         extract_token(buf, args, 2, '|', sizeof buf);
1668         buf[15] = 0;
1669         safestrncpy(CC->room.QRdirname, buf,
1670                 sizeof CC->room.QRdirname);
1671
1672         /* Default view */
1673         if (num_parms(args) >= 8) {
1674                 CC->room.QRdefaultview = extract_int(args, 7);
1675         }
1676
1677         /* Second set of flags */
1678         if (num_parms(args) >= 9) {
1679                 CC->room.QRflags2 = extract_int(args, 8);
1680         }
1681
1682         /* Misc. flags */
1683         CC->room.QRflags = (extract_int(args, 3) | QR_INUSE);
1684         /* Clean up a client boo-boo: if the client set the room to
1685          * guess-name or passworded, ensure that the private flag is
1686          * also set.
1687          */
1688         if ((CC->room.QRflags & QR_GUESSNAME)
1689             || (CC->room.QRflags & QR_PASSWORDED))
1690                 CC->room.QRflags |= QR_PRIVATE;
1691
1692         /* Some changes can't apply to BASEROOM */
1693         if (!strncasecmp(CC->room.QRname, config.c_baseroom,
1694                          ROOMNAMELEN)) {
1695                 CC->room.QRorder = 0;
1696                 CC->room.QRpasswd[0] = '\0';
1697                 CC->room.QRflags &= ~(QR_PRIVATE & QR_PASSWORDED &
1698                         QR_GUESSNAME & QR_PREFONLY & QR_MAILBOX);
1699                 CC->room.QRflags |= QR_PERMANENT;
1700         } else {        
1701                 /* March order (doesn't apply to AIDEROOM) */
1702                 if (num_parms(args) >= 7)
1703                         CC->room.QRorder = (char) new_order;
1704                 /* Room password */
1705                 extract_token(buf, args, 1, '|', sizeof buf);
1706                 buf[10] = 0;
1707                 safestrncpy(CC->room.QRpasswd, buf,
1708                             sizeof CC->room.QRpasswd);
1709                 /* Kick everyone out if the client requested it
1710                  * (by changing the room's generation number)
1711                  */
1712                 if (extract_int(args, 4)) {
1713                         time(&CC->room.QRgen);
1714                 }
1715         }
1716         /* Some changes can't apply to AIDEROOM */
1717         if (!strncasecmp(CC->room.QRname, config.c_baseroom,
1718                          ROOMNAMELEN)) {
1719                 CC->room.QRorder = 0;
1720                 CC->room.QRflags &= ~QR_MAILBOX;
1721                 CC->room.QRflags |= QR_PERMANENT;
1722         }
1723
1724         /* Write the room record back to disk */
1725         CtdlPutRoomLock(&CC->room);
1726
1727         /* Create a room directory if necessary */
1728         if (CC->room.QRflags & QR_DIRECTORY) {
1729                 snprintf(buf, sizeof buf,"%s/%s",
1730                                  ctdl_file_dir,
1731                                  CC->room.QRdirname);
1732                 mkdir(buf, 0755);
1733         }
1734         snprintf(buf, sizeof buf, "The room \"%s\" has been edited by %s.\n",
1735                 CC->room.QRname,
1736                 (CC->logged_in ? CC->curr_user : "an administrator")
1737         );
1738         CtdlAideMessage(buf, "Room modification Message");
1739         cprintf("%d Ok\n", CIT_OK);
1740 }
1741
1742
1743
1744 /* 
1745  * get the name of the room admin for this room
1746  */
1747 void cmd_geta(char *cmdbuf)
1748 {
1749         struct ctdluser usbuf;
1750
1751         if (CtdlAccessCheck(ac_logged_in)) return;
1752
1753         if (CtdlGetUserByNumber(&usbuf, CC->room.QRroomaide) == 0) {
1754                 cprintf("%d %s\n", CIT_OK, usbuf.fullname);
1755         } else {
1756                 cprintf("%d \n", CIT_OK);
1757         }
1758 }
1759
1760
1761 /* 
1762  * set the room admin for this room
1763  */
1764 void cmd_seta(char *new_ra)
1765 {
1766         struct ctdluser usbuf;
1767         long newu;
1768         char buf[SIZ];
1769         int post_notice;
1770
1771         if (CtdlAccessCheck(ac_room_aide)) return;
1772
1773         if (CtdlGetUser(&usbuf, new_ra) != 0) {
1774                 newu = (-1L);
1775         } else {
1776                 newu = usbuf.usernum;
1777         }
1778
1779         CtdlGetRoomLock(&CC->room, CC->room.QRname);
1780         post_notice = 0;
1781         if (CC->room.QRroomaide != newu) {
1782                 post_notice = 1;
1783         }
1784         CC->room.QRroomaide = newu;
1785         CtdlPutRoomLock(&CC->room);
1786
1787         /*
1788          * We have to post the change notice _after_ writing changes to 
1789          * the room table, otherwise it would deadlock!
1790          */
1791         if (post_notice == 1) {
1792                 if (!IsEmptyStr(usbuf.fullname))
1793                         snprintf(buf, sizeof buf,
1794                                 "%s is now the room admin for \"%s\".\n",
1795                                 usbuf.fullname, CC->room.QRname);
1796                 else
1797                         snprintf(buf, sizeof buf,
1798                                 "There is now no room admin for \"%s\".\n",
1799                                 CC->room.QRname);
1800                 CtdlAideMessage(buf, "Admin Room Modification");
1801         }
1802         cprintf("%d Ok\n", CIT_OK);
1803 }
1804
1805 /* 
1806  * retrieve info file for this room
1807  */
1808 void cmd_rinf(char *gargs)
1809 {
1810         char filename[PATH_MAX];
1811         char buf[SIZ];
1812         FILE *info_fp;
1813
1814         assoc_file_name(filename, sizeof filename, &CC->room, ctdl_info_dir);
1815         info_fp = fopen(filename, "r");
1816
1817         if (info_fp == NULL) {
1818                 cprintf("%d No info file.\n", ERROR + FILE_NOT_FOUND);
1819                 return;
1820         }
1821         cprintf("%d Info:\n", LISTING_FOLLOWS);
1822         while (fgets(buf, sizeof buf, info_fp) != NULL) {
1823                 if (!IsEmptyStr(buf))
1824                         buf[strlen(buf) - 1] = 0;
1825                 cprintf("%s\n", buf);
1826         }
1827         cprintf("000\n");
1828         fclose(info_fp);
1829 }
1830
1831 /*
1832  * Asynchronously schedule a room for deletion.  The room will appear
1833  * deleted to the user(s), but it won't actually get purged from the
1834  * database until THE DREADED AUTO-PURGER makes its next run.
1835  */
1836 void CtdlScheduleRoomForDeletion(struct ctdlroom *qrbuf)
1837 {
1838         char old_name[ROOMNAMELEN];
1839         static int seq = 0;
1840
1841         syslog(LOG_NOTICE, "Scheduling room <%s> for deletion\n",
1842                 qrbuf->QRname);
1843
1844         safestrncpy(old_name, qrbuf->QRname, sizeof old_name);
1845
1846         CtdlGetRoom(qrbuf, qrbuf->QRname);
1847
1848         /* Turn the room into a private mailbox owned by a user who doesn't
1849          * exist.  This will immediately make the room invisible to everyone,
1850          * and qualify the room for purging.
1851          */
1852         snprintf(qrbuf->QRname, sizeof qrbuf->QRname, "9999999999.%08lx.%04d.%s",
1853                 time(NULL),
1854                 ++seq,
1855                 old_name
1856         );
1857         qrbuf->QRflags |= QR_MAILBOX;
1858         time(&qrbuf->QRgen);    /* Use a timestamp as the new generation number  */
1859
1860         CtdlPutRoom(qrbuf);
1861
1862         b_deleteroom(old_name);
1863 }
1864
1865
1866
1867 /*
1868  * Back end processing to delete a room and everything associated with it
1869  * (This one is synchronous and should only get called by THE DREADED
1870  * AUTO-PURGER in serv_expire.c.  All user-facing code should call
1871  * the asynchronous schedule_room_for_deletion() instead.)
1872  */
1873 void CtdlDeleteRoom(struct ctdlroom *qrbuf)
1874 {
1875         struct floor flbuf;
1876         char filename[100];
1877         /* TODO: filename magic? does this realy work? */
1878
1879         syslog(LOG_NOTICE, "Deleting room <%s>\n", qrbuf->QRname);
1880
1881         /* Delete the info file */
1882         assoc_file_name(filename, sizeof filename, qrbuf, ctdl_info_dir);
1883         unlink(filename);
1884
1885         /* Delete the image file */
1886         assoc_file_name(filename, sizeof filename, qrbuf, ctdl_image_dir);
1887         unlink(filename);
1888
1889         /* Delete the room's network config file */
1890         assoc_file_name(filename, sizeof filename, qrbuf, ctdl_netcfg_dir);
1891         unlink(filename);
1892
1893         /* Delete the messages in the room
1894          * (Careful: this opens an S_ROOMS critical section!)
1895          */
1896         CtdlDeleteMessages(qrbuf->QRname, NULL, 0, "");
1897
1898         /* Flag the room record as not in use */
1899         CtdlGetRoomLock(qrbuf, qrbuf->QRname);
1900         qrbuf->QRflags = 0;
1901         CtdlPutRoomLock(qrbuf);
1902
1903         /* then decrement the reference count for the floor */
1904         lgetfloor(&flbuf, (int) (qrbuf->QRfloor));
1905         flbuf.f_ref_count = flbuf.f_ref_count - 1;
1906         lputfloor(&flbuf, (int) (qrbuf->QRfloor));
1907
1908         /* Delete the room record from the database! */
1909         b_deleteroom(qrbuf->QRname);
1910 }
1911
1912
1913
1914 /*
1915  * Check access control for deleting a room
1916  */
1917 int CtdlDoIHavePermissionToDeleteThisRoom(struct ctdlroom *qr) {
1918
1919         if ((!(CC->logged_in)) && (!(CC->internal_pgm))) {
1920                 return(0);
1921         }
1922
1923         if (CtdlIsNonEditable(qr)) {
1924                 return(0);
1925         }
1926
1927         /*
1928          * For mailboxes, check stuff
1929          */
1930         if (qr->QRflags & QR_MAILBOX) {
1931
1932                 if (strlen(qr->QRname) < 12) return(0); /* bad name */
1933
1934                 if (atol(qr->QRname) != CC->user.usernum) {
1935                         return(0);      /* not my room */
1936                 }
1937
1938                 /* Can't delete your Mail> room */
1939                 if (!strcasecmp(&qr->QRname[11], MAILROOM)) return(0);
1940
1941                 /* Otherwise it's ok */
1942                 return(1);
1943         }
1944
1945         /*
1946          * For normal rooms, just check for admin or room admin status.
1947          */
1948         return(is_room_aide());
1949 }
1950
1951 /*
1952  * admin command: kill the current room
1953  */
1954 void cmd_kill(char *argbuf)
1955 {
1956         char deleted_room_name[ROOMNAMELEN];
1957         char msg[SIZ];
1958         int kill_ok;
1959
1960         kill_ok = extract_int(argbuf, 0);
1961
1962         if (CtdlDoIHavePermissionToDeleteThisRoom(&CC->room) == 0) {
1963                 cprintf("%d Can't delete this room.\n", ERROR + NOT_HERE);
1964                 return;
1965         }
1966         if (kill_ok) {
1967                 if (CC->room.QRflags & QR_MAILBOX) {
1968                         safestrncpy(deleted_room_name, &CC->room.QRname[11], sizeof deleted_room_name);
1969                 }
1970                 else {
1971                         safestrncpy(deleted_room_name, CC->room.QRname, sizeof deleted_room_name);
1972                 }
1973
1974                 /* Do the dirty work */
1975                 CtdlScheduleRoomForDeletion(&CC->room);
1976
1977                 /* Return to the Lobby */
1978                 CtdlUserGoto(config.c_baseroom, 0, 0, NULL, NULL);
1979
1980                 /* tell the world what we did */
1981                 snprintf(msg, sizeof msg, "The room \"%s\" has been deleted by %s.\n",
1982                          deleted_room_name,
1983                         (CC->logged_in ? CC->curr_user : "an administrator")
1984                 );
1985                 CtdlAideMessage(msg, "Room Purger Message");
1986                 cprintf("%d '%s' deleted.\n", CIT_OK, deleted_room_name);
1987         } else {
1988                 cprintf("%d ok to delete.\n", CIT_OK);
1989         }
1990 }
1991
1992
1993 /*
1994  * Internal code to create a new room (returns room flags)
1995  *
1996  * Room types:  0=public, 1=hidden, 2=passworded, 3=invitation-only,
1997  *              4=mailbox, 5=mailbox, but caller supplies namespace
1998  */
1999 unsigned CtdlCreateRoom(char *new_room_name,
2000                      int new_room_type,
2001                      char *new_room_pass,
2002                      int new_room_floor,
2003                      int really_create,
2004                      int avoid_access,
2005                      int new_room_view)
2006 {
2007
2008         struct ctdlroom qrbuf;
2009         struct floor flbuf;
2010         visit vbuf;
2011
2012         syslog(LOG_DEBUG, "CtdlCreateRoom(name=%s, type=%d, view=%d)\n",
2013                 new_room_name, new_room_type, new_room_view);
2014
2015         if (CtdlGetRoom(&qrbuf, new_room_name) == 0) {
2016                 syslog(LOG_DEBUG, "%s already exists.\n", new_room_name);
2017                 return(0);
2018         }
2019
2020         memset(&qrbuf, 0, sizeof(struct ctdlroom));
2021         safestrncpy(qrbuf.QRpasswd, new_room_pass, sizeof qrbuf.QRpasswd);
2022         qrbuf.QRflags = QR_INUSE;
2023         if (new_room_type > 0)
2024                 qrbuf.QRflags = (qrbuf.QRflags | QR_PRIVATE);
2025         if (new_room_type == 1)
2026                 qrbuf.QRflags = (qrbuf.QRflags | QR_GUESSNAME);
2027         if (new_room_type == 2)
2028                 qrbuf.QRflags = (qrbuf.QRflags | QR_PASSWORDED);
2029         if ( (new_room_type == 4) || (new_room_type == 5) ) {
2030                 qrbuf.QRflags = (qrbuf.QRflags | QR_MAILBOX);
2031                 /* qrbuf.QRflags2 |= QR2_SUBJECTREQ; */
2032         }
2033
2034         /* If the user is requesting a personal room, set up the room
2035          * name accordingly (prepend the user number)
2036          */
2037         if (new_room_type == 4) {
2038                 CtdlMailboxName(qrbuf.QRname, sizeof qrbuf.QRname, &CC->user, new_room_name);
2039         }
2040         else {
2041                 safestrncpy(qrbuf.QRname, new_room_name, sizeof qrbuf.QRname);
2042         }
2043
2044         /* If the room is private, and the system administrator has elected
2045          * to automatically grant room admin privileges, do so now.
2046          */
2047         if ((qrbuf.QRflags & QR_PRIVATE) && (CREATAIDE == 1)) {
2048                 qrbuf.QRroomaide = CC->user.usernum;
2049         }
2050         /* Blog owners automatically become room admins of their blogs.
2051          * (In the future we will offer a site-wide configuration setting to suppress this behavior.)
2052          */
2053         else if (new_room_view == VIEW_BLOG) {
2054                 qrbuf.QRroomaide = CC->user.usernum;
2055         }
2056         /* Otherwise, set the room admin to undefined.
2057          */
2058         else {
2059                 qrbuf.QRroomaide = (-1L);
2060         }
2061
2062         /* 
2063          * If the caller is only interested in testing whether this will work,
2064          * return now without creating the room.
2065          */
2066         if (!really_create) return (qrbuf.QRflags);
2067
2068         qrbuf.QRnumber = get_new_room_number();
2069         qrbuf.QRhighest = 0L;   /* No messages in this room yet */
2070         time(&qrbuf.QRgen);     /* Use a timestamp as the generation number */
2071         qrbuf.QRfloor = new_room_floor;
2072         qrbuf.QRdefaultview = new_room_view;
2073
2074         /* save what we just did... */
2075         CtdlPutRoom(&qrbuf);
2076
2077         /* bump the reference count on whatever floor the room is on */
2078         lgetfloor(&flbuf, (int) qrbuf.QRfloor);
2079         flbuf.f_ref_count = flbuf.f_ref_count + 1;
2080         lputfloor(&flbuf, (int) qrbuf.QRfloor);
2081
2082         /* Grant the creator access to the room unless the avoid_access
2083          * parameter was specified.
2084          */
2085         if ( (CC->logged_in) && (avoid_access == 0) ) {
2086                 CtdlGetRelationship(&vbuf, &CC->user, &qrbuf);
2087                 vbuf.v_flags = vbuf.v_flags & ~V_FORGET & ~V_LOCKOUT;
2088                 vbuf.v_flags = vbuf.v_flags | V_ACCESS;
2089                 CtdlSetRelationship(&vbuf, &CC->user, &qrbuf);
2090         }
2091
2092         /* resume our happy day */
2093         return (qrbuf.QRflags);
2094 }
2095
2096
2097 /*
2098  * create a new room
2099  */
2100 void cmd_cre8(char *args)
2101 {
2102         int cre8_ok;
2103         char new_room_name[ROOMNAMELEN];
2104         int new_room_type;
2105         char new_room_pass[32];
2106         int new_room_floor;
2107         int new_room_view;
2108         char *notification_message = NULL;
2109         unsigned newflags;
2110         struct floor *fl;
2111         int avoid_access = 0;
2112
2113         cre8_ok = extract_int(args, 0);
2114         extract_token(new_room_name, args, 1, '|', sizeof new_room_name);
2115         new_room_name[ROOMNAMELEN - 1] = 0;
2116         new_room_type = extract_int(args, 2);
2117         extract_token(new_room_pass, args, 3, '|', sizeof new_room_pass);
2118         avoid_access = extract_int(args, 5);
2119         new_room_view = extract_int(args, 6);
2120         new_room_pass[9] = 0;
2121         new_room_floor = 0;
2122
2123         if ((IsEmptyStr(new_room_name)) && (cre8_ok == 1)) {
2124                 cprintf("%d Invalid room name.\n", ERROR + ILLEGAL_VALUE);
2125                 return;
2126         }
2127
2128         if (!strcasecmp(new_room_name, MAILROOM)) {
2129                 cprintf("%d '%s' already exists.\n",
2130                         ERROR + ALREADY_EXISTS, new_room_name);
2131                 return;
2132         }
2133
2134         if (num_parms(args) >= 5) {
2135                 fl = CtdlGetCachedFloor(extract_int(args, 4));
2136                 if (fl == NULL) {
2137                         cprintf("%d Invalid floor number.\n",
2138                                 ERROR + INVALID_FLOOR_OPERATION);
2139                         return;
2140                 }
2141                 else if ((fl->f_flags & F_INUSE) == 0) {
2142                         cprintf("%d Invalid floor number.\n",
2143                                 ERROR + INVALID_FLOOR_OPERATION);
2144                         return;
2145                 } else {
2146                         new_room_floor = extract_int(args, 4);
2147                 }
2148         }
2149
2150         if (CtdlAccessCheck(ac_logged_in)) return;
2151
2152         if (CC->user.axlevel < config.c_createax && !CC->internal_pgm) {
2153                 cprintf("%d You need higher access to create rooms.\n",
2154                         ERROR + HIGHER_ACCESS_REQUIRED);
2155                 return;
2156         }
2157
2158         if ((IsEmptyStr(new_room_name)) && (cre8_ok == 0)) {
2159                 cprintf("%d Ok to create rooms.\n", CIT_OK);
2160                 return;
2161         }
2162
2163         if ((new_room_type < 0) || (new_room_type > 5)) {
2164                 cprintf("%d Invalid room type.\n", ERROR + ILLEGAL_VALUE);
2165                 return;
2166         }
2167
2168         if (new_room_type == 5) {
2169                 if (CC->user.axlevel < AxAideU) {
2170                         cprintf("%d Higher access required\n", 
2171                                 ERROR + HIGHER_ACCESS_REQUIRED);
2172                         return;
2173                 }
2174         }
2175
2176         /* Check to make sure the requested room name doesn't already exist */
2177         newflags = CtdlCreateRoom(new_room_name,
2178                                 new_room_type, new_room_pass, new_room_floor,
2179                                 0, avoid_access, new_room_view);
2180         if (newflags == 0) {
2181                 cprintf("%d '%s' already exists.\n",
2182                         ERROR + ALREADY_EXISTS, new_room_name);
2183                 return;
2184         }
2185
2186         if (cre8_ok == 0) {
2187                 cprintf("%d OK to create '%s'\n", CIT_OK, new_room_name);
2188                 return;
2189         }
2190
2191         /* If we reach this point, the room needs to be created. */
2192
2193         newflags = CtdlCreateRoom(new_room_name,
2194                            new_room_type, new_room_pass, new_room_floor, 1, 0,
2195                            new_room_view);
2196
2197         /* post a message in Aide> describing the new room */
2198         notification_message = malloc(1024);
2199         snprintf(notification_message, 1024,
2200                 "A new room called \"%s\" has been created by %s%s%s%s%s%s\n",
2201                 new_room_name,
2202                 (CC->logged_in ? CC->curr_user : "an administrator"),
2203                 ((newflags & QR_MAILBOX) ? " [personal]" : ""),
2204                 ((newflags & QR_PRIVATE) ? " [private]" : ""),
2205                 ((newflags & QR_GUESSNAME) ? " [hidden]" : ""),
2206                 ((newflags & QR_PASSWORDED) ? " Password: " : ""),
2207                 ((newflags & QR_PASSWORDED) ? new_room_pass : "")
2208         );
2209         CtdlAideMessage(notification_message, "Room Creation Message");
2210         free(notification_message);
2211
2212         cprintf("%d '%s' has been created.\n", CIT_OK, new_room_name);
2213 }
2214
2215
2216
2217 void cmd_einf(char *ok)
2218 {                               /* enter info file for current room */
2219         FILE *fp;
2220         char infofilename[SIZ];
2221         char buf[SIZ];
2222
2223         unbuffer_output();
2224
2225         if (CtdlAccessCheck(ac_room_aide)) return;
2226
2227         if (atoi(ok) == 0) {
2228                 cprintf("%d Ok.\n", CIT_OK);
2229                 return;
2230         }
2231         assoc_file_name(infofilename, sizeof infofilename, &CC->room, ctdl_info_dir);
2232         syslog(LOG_DEBUG, "opening\n");
2233         fp = fopen(infofilename, "w");
2234         syslog(LOG_DEBUG, "checking\n");
2235         if (fp == NULL) {
2236                 cprintf("%d Cannot open %s: %s\n",
2237                   ERROR + INTERNAL_ERROR, infofilename, strerror(errno));
2238                 return;
2239         }
2240         cprintf("%d Send info...\n", SEND_LISTING);
2241
2242         do {
2243                 client_getln(buf, sizeof buf);
2244                 if (strcmp(buf, "000"))
2245                         fprintf(fp, "%s\n", buf);
2246         } while (strcmp(buf, "000"));
2247         fclose(fp);
2248
2249         /* now update the room index so people will see our new info */
2250         CtdlGetRoomLock(&CC->room, CC->room.QRname);            /* lock so no one steps on us */
2251         CC->room.QRinfo = CC->room.QRhighest + 1L;
2252         CtdlPutRoomLock(&CC->room);
2253 }
2254
2255
2256 /* 
2257  * cmd_lflr()   -  List all known floors
2258  */
2259 void cmd_lflr(char *gargs)
2260 {
2261         int a;
2262         struct floor flbuf;
2263
2264         if (CtdlAccessCheck(ac_logged_in_or_guest)) return;
2265
2266         cprintf("%d Known floors:\n", LISTING_FOLLOWS);
2267
2268         for (a = 0; a < MAXFLOORS; ++a) {
2269                 CtdlGetFloor(&flbuf, a);
2270                 if (flbuf.f_flags & F_INUSE) {
2271                         cprintf("%d|%s|%d\n",
2272                                 a,
2273                                 flbuf.f_name,
2274                                 flbuf.f_ref_count);
2275                 }
2276         }
2277         cprintf("000\n");
2278 }
2279
2280
2281
2282 /*
2283  * create a new floor
2284  */
2285 void cmd_cflr(char *argbuf)
2286 {
2287         char new_floor_name[256];
2288         struct floor flbuf;
2289         int cflr_ok;
2290         int free_slot = (-1);
2291         int a;
2292
2293         extract_token(new_floor_name, argbuf, 0, '|', sizeof new_floor_name);
2294         cflr_ok = extract_int(argbuf, 1);
2295
2296         if (CtdlAccessCheck(ac_aide)) return;
2297
2298         if (IsEmptyStr(new_floor_name)) {
2299                 cprintf("%d Blank floor name not allowed.\n",
2300                         ERROR + ILLEGAL_VALUE);
2301                 return;
2302         }
2303
2304         for (a = 0; a < MAXFLOORS; ++a) {
2305                 CtdlGetFloor(&flbuf, a);
2306
2307                 /* note any free slots while we're scanning... */
2308                 if (((flbuf.f_flags & F_INUSE) == 0)
2309                     && (free_slot < 0))
2310                         free_slot = a;
2311
2312                 /* check to see if it already exists */
2313                 if ((!strcasecmp(flbuf.f_name, new_floor_name))
2314                     && (flbuf.f_flags & F_INUSE)) {
2315                         cprintf("%d Floor '%s' already exists.\n",
2316                                 ERROR + ALREADY_EXISTS,
2317                                 flbuf.f_name);
2318                         return;
2319                 }
2320         }
2321
2322         if (free_slot < 0) {
2323                 cprintf("%d There is no space available for a new floor.\n",
2324                         ERROR + INVALID_FLOOR_OPERATION);
2325                 return;
2326         }
2327         if (cflr_ok == 0) {
2328                 cprintf("%d ok to create...\n", CIT_OK);
2329                 return;
2330         }
2331         lgetfloor(&flbuf, free_slot);
2332         flbuf.f_flags = F_INUSE;
2333         flbuf.f_ref_count = 0;
2334         safestrncpy(flbuf.f_name, new_floor_name, sizeof flbuf.f_name);
2335         lputfloor(&flbuf, free_slot);
2336         cprintf("%d %d\n", CIT_OK, free_slot);
2337 }
2338
2339
2340
2341 /*
2342  * delete a floor
2343  */
2344 void cmd_kflr(char *argbuf)
2345 {
2346         struct floor flbuf;
2347         int floor_to_delete;
2348         int kflr_ok;
2349         int delete_ok;
2350
2351         floor_to_delete = extract_int(argbuf, 0);
2352         kflr_ok = extract_int(argbuf, 1);
2353
2354         if (CtdlAccessCheck(ac_aide)) return;
2355
2356         lgetfloor(&flbuf, floor_to_delete);
2357
2358         delete_ok = 1;
2359         if ((flbuf.f_flags & F_INUSE) == 0) {
2360                 cprintf("%d Floor %d not in use.\n",
2361                         ERROR + INVALID_FLOOR_OPERATION, floor_to_delete);
2362                 delete_ok = 0;
2363         } else {
2364                 if (flbuf.f_ref_count != 0) {
2365                         cprintf("%d Cannot delete; floor contains %d rooms.\n",
2366                                 ERROR + INVALID_FLOOR_OPERATION,
2367                                 flbuf.f_ref_count);
2368                         delete_ok = 0;
2369                 } else {
2370                         if (kflr_ok == 1) {
2371                                 cprintf("%d Ok\n", CIT_OK);
2372                         } else {
2373                                 cprintf("%d Ok to delete...\n", CIT_OK);
2374                         }
2375
2376                 }
2377
2378         }
2379
2380         if ((delete_ok == 1) && (kflr_ok == 1))
2381                 flbuf.f_flags = 0;
2382         lputfloor(&flbuf, floor_to_delete);
2383 }
2384
2385 /*
2386  * edit a floor
2387  */
2388 void cmd_eflr(char *argbuf)
2389 {
2390         struct floor flbuf;
2391         int floor_num;
2392         int np;
2393
2394         np = num_parms(argbuf);
2395         if (np < 1) {
2396                 cprintf("%d Usage error.\n", ERROR + ILLEGAL_VALUE);
2397                 return;
2398         }
2399
2400         if (CtdlAccessCheck(ac_aide)) return;
2401
2402         floor_num = extract_int(argbuf, 0);
2403         lgetfloor(&flbuf, floor_num);
2404         if ((flbuf.f_flags & F_INUSE) == 0) {
2405                 lputfloor(&flbuf, floor_num);
2406                 cprintf("%d Floor %d is not in use.\n",
2407                         ERROR + INVALID_FLOOR_OPERATION, floor_num);
2408                 return;
2409         }
2410         if (np >= 2)
2411                 extract_token(flbuf.f_name, argbuf, 1, '|', sizeof flbuf.f_name);
2412         lputfloor(&flbuf, floor_num);
2413
2414         cprintf("%d Ok\n", CIT_OK);
2415 }
2416
2417
2418
2419 /* 
2420  * cmd_stat()  -  return the modification time of the current room (maybe other things in the future)
2421  */
2422 void cmd_stat(char *gargs)
2423 {
2424         if (CtdlAccessCheck(ac_logged_in_or_guest)) return;
2425         CtdlGetRoom(&CC->room, CC->room.QRname);
2426         cprintf("%d %s|%ld|\n", CIT_OK, CC->room.QRname, CC->room.QRmtime);
2427 }
2428
2429
2430
2431 /*****************************************************************************/
2432 /*                      MODULE INITIALIZATION STUFF                          */
2433 /*****************************************************************************/
2434
2435 CTDL_MODULE_INIT(room_ops)
2436 {
2437         if (!threading) {
2438                 CtdlRegisterProtoHook(cmd_lrms, "LRMS", "List rooms");
2439                 CtdlRegisterProtoHook(cmd_lkra, "LKRA", "List all known rooms");
2440                 CtdlRegisterProtoHook(cmd_lkrn, "LKRN", "List known rooms with new messages");
2441                 CtdlRegisterProtoHook(cmd_lkro, "LKRO", "List known rooms without new messages");
2442                 CtdlRegisterProtoHook(cmd_lzrm, "LZRM", "List zapped rooms");
2443                 CtdlRegisterProtoHook(cmd_lprm, "LPRM", "List public rooms");
2444                 CtdlRegisterProtoHook(cmd_goto, "GOTO", "Goto a named room");
2445                 CtdlRegisterProtoHook(cmd_stat, "STAT", "Get mtime of the current room");
2446                 CtdlRegisterProtoHook(cmd_whok, "WHOK", "List users who know this room");
2447                 CtdlRegisterProtoHook(cmd_rdir, "RDIR", "List files in room directory");
2448                 CtdlRegisterProtoHook(cmd_getr, "GETR", "Get room parameters");
2449                 CtdlRegisterProtoHook(cmd_setr, "SETR", "Set room parameters");
2450                 CtdlRegisterProtoHook(cmd_geta, "GETA", "Get the room admin name");
2451                 CtdlRegisterProtoHook(cmd_seta, "SETA", "Set the room admin for this room");
2452                 CtdlRegisterProtoHook(cmd_rinf, "RINF", "Fetch room info file");
2453                 CtdlRegisterProtoHook(cmd_kill, "KILL", "Kill (delete) the current room");
2454                 CtdlRegisterProtoHook(cmd_cre8, "CRE8", "Create a new room");
2455                 CtdlRegisterProtoHook(cmd_einf, "EINF", "Enter info file for the current room");
2456                 CtdlRegisterProtoHook(cmd_lflr, "LFLR", "List all known floors");
2457                 CtdlRegisterProtoHook(cmd_cflr, "CFLR", "Create a new floor");
2458                 CtdlRegisterProtoHook(cmd_kflr, "KFLR", "Kill a floor");
2459                 CtdlRegisterProtoHook(cmd_eflr, "EFLR", "Edit a floor");
2460         }
2461         /* return our Subversion id for the Log */
2462         return "room_ops";
2463 }