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