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