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