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