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