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