* strcpy() --> safestrncpy() in a few other random places
[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
749         /* If the supplied room name is NULL, the caller wants us to know that
750          * it has already copied the room record into CC->room, so
751          * we can skip the extra database fetch.
752          */
753         if (where != NULL) {
754                 safestrncpy(CC->room.QRname, where, sizeof CC->room.QRname);
755                 getroom(&CC->room, where);
756         }
757
758         /* Take care of all the formalities. */
759
760         begin_critical_section(S_USERS);
761         CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
762
763         /* Know the room ... but not if it's the page log room, or if the
764          * caller specified that we're only entering this room transiently.
765          */
766         if ((strcasecmp(CC->room.QRname, config.c_logpages))
767            && (transiently == 0) ) {
768                 vbuf.v_flags = vbuf.v_flags & ~V_FORGET & ~V_LOCKOUT;
769                 vbuf.v_flags = vbuf.v_flags | V_ACCESS;
770         }
771         CtdlSetRelationship(&vbuf, &CC->user, &CC->room);
772         end_critical_section(S_USERS);
773
774         /* Check for new mail */
775         newmailcount = NewMailCount();
776
777         /* set info to 1 if the user needs to read the room's info file */
778         if (CC->room.QRinfo > vbuf.v_lastseen) {
779                 info = 1;
780         }
781
782         get_mm();
783         cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
784         if (cdbfr != NULL) {
785                 msglist = mallok(cdbfr->len);
786                 memcpy(msglist, cdbfr->ptr, cdbfr->len);
787                 num_msgs = cdbfr->len / sizeof(long);
788                 cdb_free(cdbfr);
789         }
790
791         if (num_msgs > 0) for (a = 0; a < num_msgs; ++a) {
792                 if (msglist[a] > 0L) {
793                         ++total_messages;
794                         if (is_msg_in_mset(vbuf.v_seen, msglist[a]) == 0) {
795                                 ++new_messages;
796                         }
797                 }
798         }
799
800         if (msglist != NULL) phree(msglist);
801
802         if (CC->room.QRflags & QR_MAILBOX)
803                 rmailflag = 1;
804         else
805                 rmailflag = 0;
806
807         if ((CC->room.QRroomaide == CC->user.usernum)
808             || (CC->user.axlevel >= 6))
809                 raideflag = 1;
810         else
811                 raideflag = 0;
812
813         strcpy(truncated_roomname, CC->room.QRname);
814         if ( (CC->room.QRflags & QR_MAILBOX)
815            && (atol(CC->room.QRname) == CC->user.usernum) ) {
816                 strcpy(truncated_roomname, &truncated_roomname[11]);
817         }
818
819         if (retmsgs != NULL) *retmsgs = total_messages;
820         if (retnew != NULL) *retnew = new_messages;
821         lprintf(9, "<%s> %d new of %d total messages\n",
822                 CC->room.QRname,
823                 new_messages, total_messages
824         );
825
826         if (display_result) {
827                 cprintf("%d%c%s|%d|%d|%d|%d|%ld|%ld|%d|%d|%d|%d|%d|%d|\n",
828                         CIT_OK, CtdlCheckExpress(),
829                         truncated_roomname,
830                         (int)new_messages,
831                         (int)total_messages,
832                         (int)info,
833                         (int)CC->room.QRflags,
834                         (long)CC->room.QRhighest,
835                         (long)vbuf.v_lastseen,
836                         (int)rmailflag,
837                         (int)raideflag,
838                         (int)newmailcount,
839                         (int)CC->room.QRfloor,
840                         (int)vbuf.v_view,
841                         (int)CC->room.QRdefaultview
842                 );
843         }
844 }
845
846
847 /* 
848  * cmd_goto()  -  goto a new room
849  */
850 void cmd_goto(char *gargs)
851 {
852         struct ctdlroom QRscratch;
853         int c;
854         int ok = 0;
855         int ra;
856         char augmented_roomname[SIZ];
857         char towhere[SIZ];
858         char password[SIZ];
859         int transiently = 0;
860
861         if (CtdlAccessCheck(ac_logged_in)) return;
862
863         extract(towhere, gargs, 0);
864         extract(password, gargs, 1);
865         transiently = extract_int(gargs, 2);
866
867         getuser(&CC->user, CC->curr_user);
868
869         if (!strcasecmp(towhere, "_BASEROOM_"))
870                 strcpy(towhere, config.c_baseroom);
871
872         if (!strcasecmp(towhere, "_MAIL_"))
873                 strcpy(towhere, MAILROOM);
874
875         if (!strcasecmp(towhere, "_BITBUCKET_"))
876                 strcpy(towhere, config.c_twitroom);
877
878
879         /* First try a regular match */
880         c = getroom(&QRscratch, towhere);
881
882         /* Then try a mailbox name match */
883         if (c != 0) {
884                 MailboxName(augmented_roomname, sizeof augmented_roomname,
885                             &CC->user, towhere);
886                 c = getroom(&QRscratch, augmented_roomname);
887                 if (c == 0)
888                         strcpy(towhere, augmented_roomname);
889         }
890
891         /* And if the room was found... */
892         if (c == 0) {
893
894                 /* Let internal programs go directly to any room. */
895                 if (CC->internal_pgm) {
896                         memcpy(&CC->room, &QRscratch,
897                                 sizeof(struct ctdlroom));
898                         usergoto(NULL, 1, transiently, NULL, NULL);
899                         return;
900                 }
901
902                 /* See if there is an existing user/room relationship */
903                 ra = CtdlRoomAccess(&QRscratch, &CC->user);
904
905                 /* normal clients have to pass through security */
906                 if (ra & UA_GOTOALLOWED) {
907                         ok = 1;
908                 }
909
910                 if (ok == 1) {
911                         if ((QRscratch.QRflags & QR_MAILBOX) &&
912                             ((ra & UA_GOTOALLOWED))) {
913                                 memcpy(&CC->room, &QRscratch,
914                                         sizeof(struct ctdlroom));
915                                 usergoto(NULL, 1, transiently, NULL, NULL);
916                                 return;
917                         } else if ((QRscratch.QRflags & QR_PASSWORDED) &&
918                             ((ra & UA_KNOWN) == 0) &&
919                             (strcasecmp(QRscratch.QRpasswd, password)) &&
920                             (CC->user.axlevel < 6)
921                             ) {
922                                 cprintf("%d wrong or missing passwd\n",
923                                         ERROR + PASSWORD_REQUIRED);
924                                 return;
925                         } else if ((QRscratch.QRflags & QR_PRIVATE) &&
926                                    ((QRscratch.QRflags & QR_PASSWORDED) == 0) &&
927                                    ((QRscratch.QRflags & QR_GUESSNAME) == 0) &&
928                                    ((ra & UA_KNOWN) == 0) &&
929                                    (CC->user.axlevel < 6)
930                                   ) {
931                                 lprintf(9, "Failed to acquire private room\n");
932                                 goto NOPE;
933                         } else {
934                                 memcpy(&CC->room, &QRscratch,
935                                         sizeof(struct ctdlroom));
936                                 usergoto(NULL, 1, transiently, NULL, NULL);
937                                 return;
938                         }
939                 }
940         }
941
942 NOPE:   cprintf("%d room '%s' not found\n", ERROR + ROOM_NOT_FOUND, towhere);
943 }
944
945
946 void cmd_whok(void)
947 {
948         struct ctdluser temp;
949         struct cdbdata *cdbus;
950
951         getuser(&CC->user, CC->curr_user);
952
953         /*
954          * This command is only allowed by aides, room aides,
955          * and room namespace owners
956          */
957         if (is_room_aide()
958            || (atol(CC->room.QRname) == CC->user.usernum) ) {
959                 /* access granted */
960         }
961         else {
962                 /* access denied */
963                 cprintf("%d Higher access or room ownership required.\n",
964                         ERROR + HIGHER_ACCESS_REQUIRED);
965                 return;
966         }
967
968         cprintf("%d Who knows room:\n", LISTING_FOLLOWS);
969         cdb_rewind(CDB_USERS);
970         while (cdbus = cdb_next_item(CDB_USERS), cdbus != NULL) {
971                 memset(&temp, 0, sizeof temp);
972                 memcpy(&temp, cdbus->ptr, sizeof temp);
973                 cdb_free(cdbus);
974
975                 if ((CC->room.QRflags & QR_INUSE)
976                     && (CtdlRoomAccess(&CC->room, &temp) & UA_KNOWN)
977                     )
978                         cprintf("%s\n", temp.fullname);
979         }
980         cprintf("000\n");
981 }
982
983
984 /*
985  * RDIR command for room directory
986  */
987 void cmd_rdir(void)
988 {
989         char buf[SIZ];
990         char flnm[SIZ];
991         char comment[SIZ];
992         FILE *ls, *fd;
993         struct stat statbuf;
994
995         if (CtdlAccessCheck(ac_logged_in)) return;
996         
997         getroom(&CC->room, CC->room.QRname);
998         getuser(&CC->user, CC->curr_user);
999
1000         if ((CC->room.QRflags & QR_DIRECTORY) == 0) {
1001                 cprintf("%d not here.\n", ERROR + NOT_HERE);
1002                 return;
1003         }
1004         if (((CC->room.QRflags & QR_VISDIR) == 0)
1005             && (CC->user.axlevel < 6)
1006             && (CC->user.usernum != CC->room.QRroomaide)) {
1007                 cprintf("%d not here.\n", ERROR + HIGHER_ACCESS_REQUIRED);
1008                 return;
1009         }
1010         cprintf("%d %s|%s/files/%s\n",
1011         LISTING_FOLLOWS, config.c_fqdn, BBSDIR, CC->room.QRdirname);
1012
1013         snprintf(buf, sizeof buf, "ls %s/files/%s  >%s 2> /dev/null",
1014                 BBSDIR, CC->room.QRdirname, CC->temp);
1015         system(buf);
1016
1017         snprintf(buf, sizeof buf, "%s/files/%s/filedir", BBSDIR, CC->room.QRdirname);
1018         fd = fopen(buf, "r");
1019         if (fd == NULL)
1020                 fd = fopen("/dev/null", "r");
1021
1022         ls = fopen(CC->temp, "r");
1023         while (fgets(flnm, sizeof flnm, ls) != NULL) {
1024                 flnm[strlen(flnm) - 1] = 0;
1025                 if (strcasecmp(flnm, "filedir")) {
1026                         snprintf(buf, sizeof buf, "%s/files/%s/%s",
1027                                 BBSDIR, CC->room.QRdirname, flnm);
1028                         stat(buf, &statbuf);
1029                         strcpy(comment, "");
1030                         fseek(fd, 0L, 0);
1031                         while ((fgets(buf, sizeof buf, fd) != NULL)
1032                                && (strlen(comment) == 0)) {
1033                                 buf[strlen(buf) - 1] = 0;
1034                                 if ((!strncasecmp(buf, flnm, strlen(flnm)))
1035                                     && (buf[strlen(flnm)] == ' '))
1036                                         safestrncpy(comment,
1037                                             &buf[strlen(flnm) + 1],
1038                                             sizeof comment);
1039                         }
1040                         cprintf("%s|%ld|%s\n", flnm, (long)statbuf.st_size, comment);
1041                 }
1042         }
1043         fclose(ls);
1044         fclose(fd);
1045         unlink(CC->temp);
1046
1047         cprintf("000\n");
1048 }
1049
1050 /*
1051  * get room parameters (aide or room aide command)
1052  */
1053 void cmd_getr(void)
1054 {
1055         if (CtdlAccessCheck(ac_room_aide)) return;
1056
1057         getroom(&CC->room, CC->room.QRname);
1058         cprintf("%d%c%s|%s|%s|%d|%d|%d|%d|%d|\n",
1059                 CIT_OK,
1060                 CtdlCheckExpress(),
1061
1062                 ((CC->room.QRflags & QR_MAILBOX) ?
1063                         &CC->room.QRname[11] : CC->room.QRname),
1064
1065                 ((CC->room.QRflags & QR_PASSWORDED) ?
1066                         CC->room.QRpasswd : ""),
1067
1068                 ((CC->room.QRflags & QR_DIRECTORY) ?
1069                         CC->room.QRdirname : ""),
1070
1071                 CC->room.QRflags,
1072                 (int) CC->room.QRfloor,
1073                 (int) CC->room.QRorder,
1074
1075                 CC->room.QRdefaultview,
1076                 CC->room.QRflags2
1077                 );
1078 }
1079
1080
1081 /*
1082  * Back end function to rename a room.
1083  * You can also specify which floor to move the room to, or specify -1 to
1084  * keep the room on the same floor it was on.
1085  *
1086  * If you are renaming a mailbox room, you must supply the namespace prefix
1087  * in *at least* the old name!
1088  */
1089 int CtdlRenameRoom(char *old_name, char *new_name, int new_floor) {
1090         int old_floor = 0;
1091         struct ctdlroom qrbuf;
1092         struct ctdlroom qrtmp;
1093         int ret = 0;
1094         struct floor *fl;
1095         struct floor flbuf;
1096         long owner = 0L;
1097         char actual_old_name[SIZ];
1098
1099         lprintf(9, "CtdlRenameRoom(%s, %s, %d)\n",
1100                 old_name, new_name, new_floor);
1101
1102         if (new_floor >= 0) {
1103                 fl = cgetfloor(new_floor);
1104                 if ((fl->f_flags & F_INUSE) == 0) {
1105                         return(crr_invalid_floor);
1106                 }
1107         }
1108
1109         begin_critical_section(S_ROOMS);
1110
1111         if ( (getroom(&qrtmp, new_name) == 0) 
1112            && (strcasecmp(new_name, old_name)) ) {
1113                 ret = crr_already_exists;
1114         }
1115
1116         else if (getroom(&qrbuf, old_name) != 0) {
1117                 ret = crr_room_not_found;
1118         }
1119
1120         else if ( (CC->user.axlevel < 6)
1121                   && (CC->user.usernum != qrbuf.QRroomaide)
1122                   && ( (((qrbuf.QRflags & QR_MAILBOX) == 0) || (atol(qrbuf.QRname) != CC->user.usernum))) )  {
1123                 ret = crr_access_denied;
1124         }
1125
1126         else if (is_noneditable(&qrbuf)) {
1127                 ret = crr_noneditable;
1128         }
1129
1130         else {
1131                 /* Rename it */
1132                 strcpy(actual_old_name, qrbuf.QRname);
1133                 if (qrbuf.QRflags & QR_MAILBOX) {
1134                         owner = atol(qrbuf.QRname);
1135                 }
1136                 if ( (owner > 0L) && (atol(new_name) == 0L) ) {
1137                         snprintf(qrbuf.QRname, sizeof(qrbuf.QRname),
1138                                         "%010ld.%s", owner, new_name);
1139                 }
1140                 else {
1141                         safestrncpy(qrbuf.QRname, new_name,
1142                                                 sizeof(qrbuf.QRname));
1143                 }
1144
1145                 /* Reject change of floor for baseroom/aideroom */
1146                 if (!strncasecmp(old_name, config.c_baseroom, ROOMNAMELEN) ||
1147                     !strncasecmp(old_name, config.c_aideroom, ROOMNAMELEN)) {
1148                         new_floor = 0;
1149                 }
1150
1151                 /* Take care of floor stuff */
1152                 old_floor = qrbuf.QRfloor;
1153                 if (new_floor < 0) {
1154                         new_floor = old_floor;
1155                 }
1156                 qrbuf.QRfloor = new_floor;
1157                 putroom(&qrbuf);
1158
1159                 begin_critical_section(S_CONFIG);
1160         
1161                 /* If baseroom/aideroom name changes, update config */
1162                 if (!strncasecmp(old_name, config.c_baseroom, ROOMNAMELEN)) {
1163                         safestrncpy(config.c_baseroom, new_name, ROOMNAMELEN);
1164                         put_config();
1165                 }
1166                 if (!strncasecmp(old_name, config.c_aideroom, ROOMNAMELEN)) {
1167                         safestrncpy(config.c_aideroom, new_name, ROOMNAMELEN);
1168                         put_config();
1169                 }
1170         
1171                 end_critical_section(S_CONFIG);
1172         
1173                 /* If the room name changed, then there are now two room
1174                  * records, so we have to delete the old one.
1175                  */
1176                 if (strcasecmp(new_name, old_name)) {
1177                         b_deleteroom(actual_old_name);
1178                 }
1179
1180                 ret = crr_ok;
1181         }
1182
1183         end_critical_section(S_ROOMS);
1184
1185         /* Adjust the floor reference counts if necessary */
1186         if (new_floor != old_floor) {
1187                 lgetfloor(&flbuf, old_floor);
1188                 --flbuf.f_ref_count;
1189                 lputfloor(&flbuf, old_floor);
1190                 lgetfloor(&flbuf, CC->room.QRfloor);
1191                 ++flbuf.f_ref_count;
1192                 lputfloor(&flbuf, CC->room.QRfloor);
1193         }
1194
1195         /* ...and everybody say "YATTA!" */     
1196         return(ret);
1197 }
1198
1199
1200 /*
1201  * set room parameters (aide or room aide command)
1202  */
1203 void cmd_setr(char *args)
1204 {
1205         char buf[SIZ];
1206         int new_order = 0;
1207         int r;
1208         int new_floor;
1209         char new_name[ROOMNAMELEN];
1210
1211         if (CtdlAccessCheck(ac_logged_in)) return;
1212
1213         if (num_parms(args) >= 6) {
1214                 new_floor = extract_int(args, 5);
1215         } else {
1216                 new_floor = (-1);       /* don't change the floor */
1217         }
1218
1219         /* When is a new name more than just a new name?  When the old name
1220          * has a namespace prefix.
1221          */
1222         if (CC->room.QRflags & QR_MAILBOX) {
1223                 sprintf(new_name, "%010ld.", atol(CC->room.QRname) );
1224         } else {
1225                 strcpy(new_name, "");
1226         }
1227         extract(&new_name[strlen(new_name)], args, 0);
1228
1229         r = CtdlRenameRoom(CC->room.QRname, new_name, new_floor);
1230
1231         if (r == crr_room_not_found) {
1232                 cprintf("%d Internal error - room not found?\n", ERROR);
1233         } else if (r == crr_already_exists) {
1234                 cprintf("%d '%s' already exists.\n",
1235                         ERROR + ALREADY_EXISTS, new_name);
1236         } else if (r == crr_noneditable) {
1237                 cprintf("%d Cannot edit this room.\n", ERROR);
1238         } else if (r == crr_invalid_floor) {
1239                 cprintf("%d Target floor does not exist.\n",
1240                         ERROR + INVALID_FLOOR_OPERATION);
1241         } else if (r == crr_access_denied) {
1242                 cprintf("%d You do not have permission to edit '%s'\n",
1243                         ERROR + HIGHER_ACCESS_REQUIRED,
1244                         CC->room.QRname);
1245         } else if (r != crr_ok) {
1246                 cprintf("%d Error: CtdlRenameRoom() returned %d\n",
1247                         ERROR, r);
1248         }
1249
1250         if (r != crr_ok) {
1251                 return;
1252         }
1253
1254         getroom(&CC->room, new_name);
1255
1256         /* Now we have to do a bunch of other stuff */
1257
1258         if (num_parms(args) >= 7) {
1259                 new_order = extract_int(args, 6);
1260                 if (new_order < 1)
1261                         new_order = 1;
1262                 if (new_order > 127)
1263                         new_order = 127;
1264         }
1265
1266         lgetroom(&CC->room, CC->room.QRname);
1267
1268         /* Directory room */
1269         extract(buf, args, 2);
1270         buf[15] = 0;
1271         safestrncpy(CC->room.QRdirname, buf,
1272                 sizeof CC->room.QRdirname);
1273
1274         /* Default view */
1275         if (num_parms(args) >= 8) {
1276                 CC->room.QRdefaultview = extract_int(args, 7);
1277         }
1278
1279         /* Second set of flags */
1280         if (num_parms(args) >= 9) {
1281                 CC->room.QRflags2 = extract_int(args, 8);
1282         }
1283
1284         /* Misc. flags */
1285         CC->room.QRflags = (extract_int(args, 3) | QR_INUSE);
1286         /* Clean up a client boo-boo: if the client set the room to
1287          * guess-name or passworded, ensure that the private flag is
1288          * also set.
1289          */
1290         if ((CC->room.QRflags & QR_GUESSNAME)
1291             || (CC->room.QRflags & QR_PASSWORDED))
1292                 CC->room.QRflags |= QR_PRIVATE;
1293
1294         /* Some changes can't apply to BASEROOM */
1295         if (!strncasecmp(CC->room.QRname, config.c_baseroom,
1296                          ROOMNAMELEN)) {
1297                 CC->room.QRorder = 0;
1298                 CC->room.QRpasswd[0] = '\0';
1299                 CC->room.QRflags &= ~(QR_PRIVATE & QR_PASSWORDED &
1300                         QR_GUESSNAME & QR_PREFONLY & QR_MAILBOX);
1301                 CC->room.QRflags |= QR_PERMANENT;
1302         } else {        
1303                 /* March order (doesn't apply to AIDEROOM) */
1304                 if (num_parms(args) >= 7)
1305                         CC->room.QRorder = (char) new_order;
1306                 /* Room password */
1307                 extract(buf, args, 1);
1308                 buf[10] = 0;
1309                 safestrncpy(CC->room.QRpasswd, buf,
1310                             sizeof CC->room.QRpasswd);
1311                 /* Kick everyone out if the client requested it
1312                  * (by changing the room's generation number)
1313                  */
1314                 if (extract_int(args, 4)) {
1315                         time(&CC->room.QRgen);
1316                 }
1317         }
1318         /* Some changes can't apply to AIDEROOM */
1319         if (!strncasecmp(CC->room.QRname, config.c_baseroom,
1320                          ROOMNAMELEN)) {
1321                 CC->room.QRorder = 0;
1322                 CC->room.QRflags &= ~QR_MAILBOX;
1323                 CC->room.QRflags |= QR_PERMANENT;
1324         }
1325
1326         /* Write the room record back to disk */
1327         lputroom(&CC->room);
1328
1329         /* Create a room directory if necessary */
1330         if (CC->room.QRflags & QR_DIRECTORY) {
1331                 snprintf(buf, sizeof buf, "./files/%s",
1332                         CC->room.QRdirname);
1333                 mkdir(buf, 0755);
1334         }
1335         snprintf(buf, sizeof buf, "%s> edited by %s\n", CC->room.QRname, CC->curr_user);
1336         aide_message(buf);
1337         cprintf("%d Ok\n", CIT_OK);
1338 }
1339
1340
1341
1342 /* 
1343  * get the name of the room aide for this room
1344  */
1345 void cmd_geta(void)
1346 {
1347         struct ctdluser usbuf;
1348
1349         if (CtdlAccessCheck(ac_logged_in)) return;
1350
1351         if (getuserbynumber(&usbuf, CC->room.QRroomaide) == 0) {
1352                 cprintf("%d %s\n", CIT_OK, usbuf.fullname);
1353         } else {
1354                 cprintf("%d \n", CIT_OK);
1355         }
1356 }
1357
1358
1359 /* 
1360  * set the room aide for this room
1361  */
1362 void cmd_seta(char *new_ra)
1363 {
1364         struct ctdluser usbuf;
1365         long newu;
1366         char buf[SIZ];
1367         int post_notice;
1368
1369         if (CtdlAccessCheck(ac_room_aide)) return;
1370
1371         if (getuser(&usbuf, new_ra) != 0) {
1372                 newu = (-1L);
1373         } else {
1374                 newu = usbuf.usernum;
1375         }
1376
1377         lgetroom(&CC->room, CC->room.QRname);
1378         post_notice = 0;
1379         if (CC->room.QRroomaide != newu) {
1380                 post_notice = 1;
1381         }
1382         CC->room.QRroomaide = newu;
1383         lputroom(&CC->room);
1384
1385         /*
1386          * We have to post the change notice _after_ writing changes to 
1387          * the room table, otherwise it would deadlock!
1388          */
1389         if (post_notice == 1) {
1390                 if (strlen(usbuf.fullname) > 0)
1391                         snprintf(buf, sizeof buf,
1392                                 "%s is now room aide for %s>\n",
1393                                 usbuf.fullname, CC->room.QRname);
1394                 else
1395                         snprintf(buf, sizeof buf,
1396                                 "There is now no room aide for %s>\n",
1397                                 CC->room.QRname);
1398                 aide_message(buf);
1399         }
1400         cprintf("%d Ok\n", CIT_OK);
1401 }
1402
1403 /*
1404  * Generate an associated file name for a room
1405  */
1406 void assoc_file_name(char *buf, size_t n,
1407                      struct ctdlroom *qrbuf, const char *prefix)
1408 {
1409         snprintf(buf, n, "./%s/%ld", prefix, qrbuf->QRnumber);
1410 }
1411
1412 /* 
1413  * retrieve info file for this room
1414  */
1415 void cmd_rinf(void)
1416 {
1417         char filename[128];
1418         char buf[SIZ];
1419         FILE *info_fp;
1420
1421         assoc_file_name(filename, sizeof filename, &CC->room, "info");
1422         info_fp = fopen(filename, "r");
1423
1424         if (info_fp == NULL) {
1425                 cprintf("%d No info file.\n", ERROR);
1426                 return;
1427         }
1428         cprintf("%d Info:\n", LISTING_FOLLOWS);
1429         while (fgets(buf, sizeof buf, info_fp) != NULL) {
1430                 if (strlen(buf) > 0)
1431                         buf[strlen(buf) - 1] = 0;
1432                 cprintf("%s\n", buf);
1433         }
1434         cprintf("000\n");
1435         fclose(info_fp);
1436 }
1437
1438 /*
1439  * Back end processing to delete a room and everything associated with it
1440  */
1441 void delete_room(struct ctdlroom *qrbuf)
1442 {
1443         struct floor flbuf;
1444         char filename[100];
1445
1446         lprintf(9, "Deleting room <%s>\n", qrbuf->QRname);
1447
1448         /* Delete the info file */
1449         assoc_file_name(filename, sizeof filename, qrbuf, "info");
1450         unlink(filename);
1451
1452         /* Delete the image file */
1453         assoc_file_name(filename, sizeof filename, qrbuf, "images");
1454         unlink(filename);
1455
1456         /* Delete the room's network config file */
1457         assoc_file_name(filename, sizeof filename, qrbuf, "netconfigs");
1458         unlink(filename);
1459
1460         /* Delete the messages in the room
1461          * (Careful: this opens an S_ROOMS critical section!)
1462          */
1463         CtdlDeleteMessages(qrbuf->QRname, 0L, "");
1464
1465         /* Flag the room record as not in use */
1466         lgetroom(qrbuf, qrbuf->QRname);
1467         qrbuf->QRflags = 0;
1468         lputroom(qrbuf);
1469
1470         /* then decrement the reference count for the floor */
1471         lgetfloor(&flbuf, (int) (qrbuf->QRfloor));
1472         flbuf.f_ref_count = flbuf.f_ref_count - 1;
1473         lputfloor(&flbuf, (int) (qrbuf->QRfloor));
1474
1475         /* Delete the room record from the database! */
1476         b_deleteroom(qrbuf->QRname);
1477 }
1478
1479
1480
1481 /*
1482  * Check access control for deleting a room
1483  */
1484 int CtdlDoIHavePermissionToDeleteThisRoom(struct ctdlroom *qr) {
1485
1486         if ((!(CC->logged_in)) && (!(CC->internal_pgm))) {
1487                 return(0);
1488         }
1489
1490         if (is_noneditable(qr)) {
1491                 return(0);
1492         }
1493
1494         /*
1495          * For mailboxes, check stuff
1496          */
1497         if (qr->QRflags & QR_MAILBOX) {
1498
1499                 if (strlen(qr->QRname) < 12) return(0); /* bad name */
1500
1501                 if (atol(qr->QRname) != CC->user.usernum) {
1502                         return(0);      /* not my room */
1503                 }
1504
1505                 /* Can't delete your Mail> room */
1506                 if (!strcasecmp(&qr->QRname[12], MAILROOM)) return(0);
1507
1508                 /* Otherwise it's ok */
1509                 return(1);
1510         }
1511
1512         /*
1513          * For normal rooms, just check for aide or room aide status.
1514          */
1515         return(is_room_aide());
1516 }
1517
1518 /*
1519  * aide command: kill the current room
1520  */
1521 void cmd_kill(char *argbuf)
1522 {
1523         char deleted_room_name[ROOMNAMELEN];
1524         char msg[SIZ];
1525         int kill_ok;
1526
1527         kill_ok = extract_int(argbuf, 0);
1528
1529         if (CtdlDoIHavePermissionToDeleteThisRoom(&CC->room) == 0) {
1530                 cprintf("%d Can't delete this room.\n", ERROR + NOT_HERE);
1531                 return;
1532         }
1533         if (kill_ok) {
1534                 if (CC->room.QRflags & QR_MAILBOX) {
1535                         strcpy(deleted_room_name, &CC->room.QRname[11]);
1536                 }
1537                 else {
1538                         strcpy(deleted_room_name, CC->room.QRname);
1539                 }
1540
1541                 /* Do the dirty work */
1542                 delete_room(&CC->room);
1543
1544                 /* Return to the Lobby */
1545                 usergoto(config.c_baseroom, 0, 0, NULL, NULL);
1546
1547                 /* tell the world what we did */
1548                 snprintf(msg, sizeof msg, "%s> killed by %s\n",
1549                          deleted_room_name, CC->curr_user);
1550                 aide_message(msg);
1551                 cprintf("%d '%s' deleted.\n", CIT_OK, deleted_room_name);
1552         } else {
1553                 cprintf("%d ok to delete.\n", CIT_OK);
1554         }
1555 }
1556
1557
1558 /*
1559  * Internal code to create a new room (returns room flags)
1560  *
1561  * Room types:  0=public, 1=guessname, 2=passworded, 3=inv-only,
1562  *              4=mailbox, 5=mailbox, but caller supplies namespace
1563  */
1564 unsigned create_room(char *new_room_name,
1565                      int new_room_type,
1566                      char *new_room_pass,
1567                      int new_room_floor,
1568                      int really_create,
1569                      int avoid_access)
1570 {
1571
1572         struct ctdlroom qrbuf;
1573         struct floor flbuf;
1574         struct visit vbuf;
1575
1576         lprintf(9, "create_room(%s)\n", new_room_name);
1577         if (getroom(&qrbuf, new_room_name) == 0) {
1578                 lprintf(9, "%s already exists.\n", new_room_name);
1579                 return (0);     /* already exists */
1580         }
1581
1582
1583         memset(&qrbuf, 0, sizeof(struct ctdlroom));
1584         safestrncpy(qrbuf.QRpasswd, new_room_pass, sizeof qrbuf.QRpasswd);
1585         qrbuf.QRflags = QR_INUSE;
1586         if (new_room_type > 0)
1587                 qrbuf.QRflags = (qrbuf.QRflags | QR_PRIVATE);
1588         if (new_room_type == 1)
1589                 qrbuf.QRflags = (qrbuf.QRflags | QR_GUESSNAME);
1590         if (new_room_type == 2)
1591                 qrbuf.QRflags = (qrbuf.QRflags | QR_PASSWORDED);
1592         if ( (new_room_type == 4) || (new_room_type == 5) )
1593                 qrbuf.QRflags = (qrbuf.QRflags | QR_MAILBOX);
1594
1595         /* If the user is requesting a personal room, set up the room
1596          * name accordingly (prepend the user number)
1597          */
1598         if (new_room_type == 4) {
1599                 MailboxName(qrbuf.QRname, sizeof qrbuf.QRname, &CC->user, new_room_name);
1600         }
1601         else {
1602                 safestrncpy(qrbuf.QRname, new_room_name, sizeof qrbuf.QRname);
1603         }
1604
1605         /* If the room is private, and the system administrator has elected
1606          * to automatically grant room aide privileges, do so now; otherwise,
1607          * set the room aide to undefined.
1608          */
1609         if ((qrbuf.QRflags & QR_PRIVATE) && (CREATAIDE == 1)) {
1610                 qrbuf.QRroomaide = CC->user.usernum;
1611         } else {
1612                 qrbuf.QRroomaide = (-1L);
1613         }
1614
1615         /* 
1616          * If the caller is only interested in testing whether this will work,
1617          * return now without creating the room.
1618          */
1619         if (!really_create) return (qrbuf.QRflags);
1620
1621         qrbuf.QRnumber = get_new_room_number();
1622         qrbuf.QRhighest = 0L;   /* No messages in this room yet */
1623         time(&qrbuf.QRgen);     /* Use a timestamp as the generation number */
1624         qrbuf.QRfloor = new_room_floor;
1625
1626         /* save what we just did... */
1627         putroom(&qrbuf);
1628
1629         /* bump the reference count on whatever floor the room is on */
1630         lgetfloor(&flbuf, (int) qrbuf.QRfloor);
1631         flbuf.f_ref_count = flbuf.f_ref_count + 1;
1632         lputfloor(&flbuf, (int) qrbuf.QRfloor);
1633
1634         /* Grant the creator access to the room unless the avoid_access
1635          * parameter was specified.
1636          */
1637         if (avoid_access == 0) {
1638                 lgetuser(&CC->user, CC->curr_user);
1639                 CtdlGetRelationship(&vbuf, &CC->user, &qrbuf);
1640                 vbuf.v_flags = vbuf.v_flags & ~V_FORGET & ~V_LOCKOUT;
1641                 vbuf.v_flags = vbuf.v_flags | V_ACCESS;
1642                 CtdlSetRelationship(&vbuf, &CC->user, &qrbuf);
1643                 lputuser(&CC->user);
1644         }
1645
1646         /* resume our happy day */
1647         return (qrbuf.QRflags);
1648 }
1649
1650
1651 /*
1652  * create a new room
1653  */
1654 void cmd_cre8(char *args)
1655 {
1656         int cre8_ok;
1657         char new_room_name[SIZ];
1658         int new_room_type;
1659         char new_room_pass[SIZ];
1660         int new_room_floor;
1661         char aaa[SIZ];
1662         unsigned newflags;
1663         struct floor *fl;
1664         int avoid_access = 0;
1665
1666         cre8_ok = extract_int(args, 0);
1667         extract(new_room_name, args, 1);
1668         new_room_name[ROOMNAMELEN - 1] = 0;
1669         new_room_type = extract_int(args, 2);
1670         extract(new_room_pass, args, 3);
1671         avoid_access = extract_int(args, 5);
1672         new_room_pass[9] = 0;
1673         new_room_floor = 0;
1674
1675         if ((strlen(new_room_name) == 0) && (cre8_ok == 1)) {
1676                 cprintf("%d Invalid room name.\n", ERROR);
1677                 return;
1678         }
1679
1680         if (!strcasecmp(new_room_name, MAILROOM)) {
1681                 cprintf("%d '%s' already exists.\n",
1682                         ERROR + ALREADY_EXISTS, new_room_name);
1683                 return;
1684         }
1685
1686         if (num_parms(args) >= 5) {
1687                 fl = cgetfloor(extract_int(args, 4));
1688                 if ((fl->f_flags & F_INUSE) == 0) {
1689                         cprintf("%d Invalid floor number.\n",
1690                                 ERROR + INVALID_FLOOR_OPERATION);
1691                         return;
1692                 } else {
1693                         new_room_floor = extract_int(args, 4);
1694                 }
1695         }
1696
1697         if (CtdlAccessCheck(ac_logged_in)) return;
1698
1699         if (CC->user.axlevel < config.c_createax) {
1700                 cprintf("%d You need higher access to create rooms.\n",
1701                         ERROR + HIGHER_ACCESS_REQUIRED);
1702                 return;
1703         }
1704
1705         if ((strlen(new_room_name) == 0) && (cre8_ok == 0)) {
1706                 cprintf("%d Ok to create rooms.\n", CIT_OK);
1707                 return;
1708         }
1709
1710         if ((new_room_type < 0) || (new_room_type > 5)) {
1711                 cprintf("%d Invalid room type.\n", ERROR);
1712                 return;
1713         }
1714
1715         if (new_room_type == 5) {
1716                 if ((config.c_aide_mailboxes == 0)
1717                    || (CC->user.axlevel < 6)) {
1718                         cprintf("%d Higher access required\n", 
1719                                 ERROR+HIGHER_ACCESS_REQUIRED);
1720                         return;
1721                 }
1722         }
1723
1724         /* Check to make sure the requested room name doesn't already exist */
1725         newflags = create_room(new_room_name,
1726                                 new_room_type, new_room_pass, new_room_floor,
1727                                 0, avoid_access);
1728         if (newflags == 0) {
1729                 cprintf("%d '%s' already exists.\n",
1730                         ERROR + ALREADY_EXISTS, new_room_name);
1731                 return;
1732         }
1733
1734         if (cre8_ok == 0) {
1735                 cprintf("%d OK to create '%s'\n", CIT_OK, new_room_name);
1736                 return;
1737         }
1738
1739         /* If we reach this point, the room needs to be created. */
1740
1741         newflags = create_room(new_room_name,
1742                            new_room_type, new_room_pass, new_room_floor, 1, 0);
1743
1744         /* post a message in Aide> describing the new room */
1745         safestrncpy(aaa, new_room_name, sizeof aaa);
1746         strcat(aaa, "> created by ");
1747         strcat(aaa, CC->user.fullname);
1748         if (newflags & QR_MAILBOX)
1749                 strcat(aaa, " [personal]");
1750         else if (newflags & QR_PRIVATE)
1751                 strcat(aaa, " [private]");
1752         if (newflags & QR_GUESSNAME)
1753                 strcat(aaa, "[guessname] ");
1754         if (newflags & QR_PASSWORDED) {
1755                 strcat(aaa, "\n Password: ");
1756                 strcat(aaa, new_room_pass);
1757         }
1758         strcat(aaa, "\n");
1759         aide_message(aaa);
1760
1761         cprintf("%d '%s' has been created.\n", CIT_OK, new_room_name);
1762 }
1763
1764
1765
1766 void cmd_einf(char *ok)
1767 {                               /* enter info file for current room */
1768         FILE *fp;
1769         char infofilename[SIZ];
1770         char buf[SIZ];
1771
1772         if (CtdlAccessCheck(ac_room_aide)) return;
1773
1774         if (atoi(ok) == 0) {
1775                 cprintf("%d Ok.\n", CIT_OK);
1776                 return;
1777         }
1778         assoc_file_name(infofilename, sizeof infofilename, &CC->room, "info");
1779         lprintf(9, "opening\n");
1780         fp = fopen(infofilename, "w");
1781         lprintf(9, "checking\n");
1782         if (fp == NULL) {
1783                 cprintf("%d Cannot open %s: %s\n",
1784                   ERROR + INTERNAL_ERROR, infofilename, strerror(errno));
1785                 return;
1786         }
1787         cprintf("%d Send info...\n", SEND_LISTING);
1788
1789         do {
1790                 client_gets(buf);
1791                 if (strcmp(buf, "000"))
1792                         fprintf(fp, "%s\n", buf);
1793         } while (strcmp(buf, "000"));
1794         fclose(fp);
1795
1796         /* now update the room index so people will see our new info */
1797         lgetroom(&CC->room, CC->room.QRname);           /* lock so no one steps on us */
1798         CC->room.QRinfo = CC->room.QRhighest + 1L;
1799         lputroom(&CC->room);
1800 }
1801
1802
1803 /* 
1804  * cmd_lflr()   -  List all known floors
1805  */
1806 void cmd_lflr(void)
1807 {
1808         int a;
1809         struct floor flbuf;
1810
1811         if (CtdlAccessCheck(ac_logged_in)) return;
1812
1813         cprintf("%d Known floors:\n", LISTING_FOLLOWS);
1814
1815         for (a = 0; a < MAXFLOORS; ++a) {
1816                 getfloor(&flbuf, a);
1817                 if (flbuf.f_flags & F_INUSE) {
1818                         cprintf("%d|%s|%d\n",
1819                                 a,
1820                                 flbuf.f_name,
1821                                 flbuf.f_ref_count);
1822                 }
1823         }
1824         cprintf("000\n");
1825 }
1826
1827
1828
1829 /*
1830  * create a new floor
1831  */
1832 void cmd_cflr(char *argbuf)
1833 {
1834         char new_floor_name[SIZ];
1835         struct floor flbuf;
1836         int cflr_ok;
1837         int free_slot = (-1);
1838         int a;
1839
1840         extract(new_floor_name, argbuf, 0);
1841         cflr_ok = extract_int(argbuf, 1);
1842
1843         if (CtdlAccessCheck(ac_aide)) return;
1844
1845         if (strlen(new_floor_name) == 0) {
1846                 cprintf("%d Blank floor name not allowed.\n",
1847                         ERROR+ILLEGAL_VALUE);
1848                 return;
1849         }
1850
1851         for (a = 0; a < MAXFLOORS; ++a) {
1852                 getfloor(&flbuf, a);
1853
1854                 /* note any free slots while we're scanning... */
1855                 if (((flbuf.f_flags & F_INUSE) == 0)
1856                     && (free_slot < 0))
1857                         free_slot = a;
1858
1859                 /* check to see if it already exists */
1860                 if ((!strcasecmp(flbuf.f_name, new_floor_name))
1861                     && (flbuf.f_flags & F_INUSE)) {
1862                         cprintf("%d Floor '%s' already exists.\n",
1863                                 ERROR + ALREADY_EXISTS,
1864                                 flbuf.f_name);
1865                         return;
1866                 }
1867         }
1868
1869         if (free_slot < 0) {
1870                 cprintf("%d There is no space available for a new floor.\n",
1871                         ERROR + INVALID_FLOOR_OPERATION);
1872                 return;
1873         }
1874         if (cflr_ok == 0) {
1875                 cprintf("%d ok to create...\n", CIT_OK);
1876                 return;
1877         }
1878         lgetfloor(&flbuf, free_slot);
1879         flbuf.f_flags = F_INUSE;
1880         flbuf.f_ref_count = 0;
1881         safestrncpy(flbuf.f_name, new_floor_name, sizeof flbuf.f_name);
1882         lputfloor(&flbuf, free_slot);
1883         cprintf("%d %d\n", CIT_OK, free_slot);
1884 }
1885
1886
1887
1888 /*
1889  * delete a floor
1890  */
1891 void cmd_kflr(char *argbuf)
1892 {
1893         struct floor flbuf;
1894         int floor_to_delete;
1895         int kflr_ok;
1896         int delete_ok;
1897
1898         floor_to_delete = extract_int(argbuf, 0);
1899         kflr_ok = extract_int(argbuf, 1);
1900
1901         if (CtdlAccessCheck(ac_aide)) return;
1902
1903         lgetfloor(&flbuf, floor_to_delete);
1904
1905         delete_ok = 1;
1906         if ((flbuf.f_flags & F_INUSE) == 0) {
1907                 cprintf("%d Floor %d not in use.\n",
1908                         ERROR + INVALID_FLOOR_OPERATION, floor_to_delete);
1909                 delete_ok = 0;
1910         } else {
1911                 if (flbuf.f_ref_count != 0) {
1912                         cprintf("%d Cannot delete; floor contains %d rooms.\n",
1913                                 ERROR + INVALID_FLOOR_OPERATION,
1914                                 flbuf.f_ref_count);
1915                         delete_ok = 0;
1916                 } else {
1917                         if (kflr_ok == 1) {
1918                                 cprintf("%d Ok\n", CIT_OK);
1919                         } else {
1920                                 cprintf("%d Ok to delete...\n", CIT_OK);
1921                         }
1922
1923                 }
1924
1925         }
1926
1927         if ((delete_ok == 1) && (kflr_ok == 1))
1928                 flbuf.f_flags = 0;
1929         lputfloor(&flbuf, floor_to_delete);
1930 }
1931
1932 /*
1933  * edit a floor
1934  */
1935 void cmd_eflr(char *argbuf)
1936 {
1937         struct floor flbuf;
1938         int floor_num;
1939         int np;
1940
1941         np = num_parms(argbuf);
1942         if (np < 1) {
1943                 cprintf("%d Usage error.\n", ERROR);
1944                 return;
1945         }
1946
1947         if (CtdlAccessCheck(ac_aide)) return;
1948
1949         floor_num = extract_int(argbuf, 0);
1950         lgetfloor(&flbuf, floor_num);
1951         if ((flbuf.f_flags & F_INUSE) == 0) {
1952                 lputfloor(&flbuf, floor_num);
1953                 cprintf("%d Floor %d is not in use.\n",
1954                         ERROR + INVALID_FLOOR_OPERATION, floor_num);
1955                 return;
1956         }
1957         if (np >= 2)
1958                 extract(flbuf.f_name, argbuf, 1);
1959         lputfloor(&flbuf, floor_num);
1960
1961         cprintf("%d Ok\n", CIT_OK);
1962 }