* When sending a page that results in the receiver's Sent/Received Pages>
[citadel.git] / citadel / user_ops.c
1 /* 
2  * $Id$
3  *
4  * Server functions which perform operations on user objects.
5  *
6  */
7
8 #ifdef DLL_EXPORT
9 #define IN_LIBCIT
10 #endif
11
12 #include "sysdep.h"
13 #include <errno.h>
14 #include <stdlib.h>
15 #include <unistd.h>
16 #include <stdio.h>
17 #include <fcntl.h>
18 #include <signal.h>
19 #include <pwd.h>
20 #include <sys/types.h>
21 #include <sys/wait.h>
22
23 #if TIME_WITH_SYS_TIME
24 # include <sys/time.h>
25 # include <time.h>
26 #else
27 # if HAVE_SYS_TIME_H
28 #  include <sys/time.h>
29 # else
30 #  include <time.h>
31 # endif
32 #endif
33
34 #include <string.h>
35 #include <syslog.h>
36 #include <limits.h>
37 #ifndef ENABLE_CHKPWD
38 #include "auth.h"
39 #endif
40 #include "citadel.h"
41 #include "server.h"
42 #include "database.h"
43 #include "user_ops.h"
44 #include "dynloader.h"
45 #include "sysdep_decls.h"
46 #include "support.h"
47 #include "room_ops.h"
48 #include "logging.h"
49 #include "file_ops.h"
50 #include "control.h"
51 #include "msgbase.h"
52 #include "config.h"
53 #include "tools.h"
54 #include "citserver.h"
55
56
57 /*
58  * getuser()  -  retrieve named user into supplied buffer.
59  *               returns 0 on success
60  */
61 int getuser(struct usersupp *usbuf, char name[])
62 {
63
64         char lowercase_name[32];
65         int a;
66         struct cdbdata *cdbus;
67
68         memset(usbuf, 0, sizeof(struct usersupp));
69         for (a = 0; a <= strlen(name); ++a) {
70                 if (a < sizeof(lowercase_name))
71                         lowercase_name[a] = tolower(name[a]);
72         }
73         lowercase_name[sizeof(lowercase_name) - 1] = 0;
74
75         cdbus = cdb_fetch(CDB_USERSUPP, lowercase_name, strlen(lowercase_name));
76         if (cdbus == NULL) {
77                 return (1);     /* user not found */
78         }
79         memcpy(usbuf, cdbus->ptr,
80                ((cdbus->len > sizeof(struct usersupp)) ?
81                 sizeof(struct usersupp) : cdbus->len));
82         cdb_free(cdbus);
83
84         if (usbuf->version < 573) {
85                 CC->usersupp.moderation_filter = config.c_default_filter;
86         }
87         return (0);
88 }
89
90
91 /*
92  * lgetuser()  -  same as getuser() but locks the record
93  */
94 int lgetuser(struct usersupp *usbuf, char *name)
95 {
96         int retcode;
97
98         retcode = getuser(usbuf, name);
99         if (retcode == 0) {
100                 begin_critical_section(S_USERSUPP);
101         }
102         return (retcode);
103 }
104
105
106 /*
107  * putuser()  -  write user buffer into the correct place on disk
108  */
109 void putuser(struct usersupp *usbuf)
110 {
111         char lowercase_name[32];
112         int a;
113
114         for (a = 0; a <= strlen(usbuf->fullname); ++a) {
115                 if (a < sizeof(lowercase_name))
116                         lowercase_name[a] = tolower(usbuf->fullname[a]);
117         }
118         lowercase_name[sizeof(lowercase_name) - 1] = 0;
119
120         usbuf->version = REV_LEVEL;
121         cdb_store(CDB_USERSUPP,
122                   lowercase_name, strlen(lowercase_name),
123                   usbuf, sizeof(struct usersupp));
124
125 }
126
127
128 /*
129  * lputuser()  -  same as putuser() but locks the record
130  */
131 void lputuser(struct usersupp *usbuf)
132 {
133         putuser(usbuf);
134         end_critical_section(S_USERSUPP);
135 }
136
137 /*
138  * Index-generating function used by Ctdl[Get|Set]Relationship
139  */
140 int GenerateRelationshipIndex(char *IndexBuf,
141                               long RoomID,
142                               long RoomGen,
143                               long UserID)
144 {
145
146         struct {
147                 long iRoomID;
148                 long iRoomGen;
149                 long iUserID;
150         } TheIndex;
151
152         TheIndex.iRoomID = RoomID;
153         TheIndex.iRoomGen = RoomGen;
154         TheIndex.iUserID = UserID;
155
156         memcpy(IndexBuf, &TheIndex, sizeof(TheIndex));
157         return (sizeof(TheIndex));
158 }
159
160
161
162 /*
163  * Back end for CtdlSetRelationship()
164  */
165 void put_visit(struct visit *newvisit)
166 {
167         char IndexBuf[32];
168         int IndexLen;
169
170         /* Generate an index */
171         IndexLen = GenerateRelationshipIndex(IndexBuf,
172                                              newvisit->v_roomnum,
173                                              newvisit->v_roomgen,
174                                              newvisit->v_usernum);
175
176         /* Store the record */
177         cdb_store(CDB_VISIT, IndexBuf, IndexLen,
178                   newvisit, sizeof(struct visit)
179         );
180 }
181
182
183
184
185 /*
186  * Define a relationship between a user and a room
187  */
188 void CtdlSetRelationship(struct visit *newvisit,
189                          struct usersupp *rel_user,
190                          struct quickroom *rel_room)
191 {
192
193
194         /* We don't use these in Citadel because they're implicit by the
195          * index, but they must be present if the database is exported.
196          */
197         newvisit->v_roomnum = rel_room->QRnumber;
198         newvisit->v_roomgen = rel_room->QRgen;
199         newvisit->v_usernum = rel_user->usernum;
200
201         put_visit(newvisit);
202 }
203
204 /*
205  * Locate a relationship between a user and a room
206  */
207 void CtdlGetRelationship(struct visit *vbuf,
208                          struct usersupp *rel_user,
209                          struct quickroom *rel_room)
210 {
211
212         char IndexBuf[32];
213         int IndexLen;
214         struct cdbdata *cdbvisit;
215
216         /* Generate an index */
217         IndexLen = GenerateRelationshipIndex(IndexBuf,
218                                              rel_room->QRnumber,
219                                              rel_room->QRgen,
220                                              rel_user->usernum);
221
222         /* Clear out the buffer */
223         memset(vbuf, 0, sizeof(struct visit));
224
225         cdbvisit = cdb_fetch(CDB_VISIT, IndexBuf, IndexLen);
226         if (cdbvisit != NULL) {
227                 memcpy(vbuf, cdbvisit->ptr,
228                        ((cdbvisit->len > sizeof(struct visit)) ?
229                         sizeof(struct visit) : cdbvisit->len));
230                 cdb_free(cdbvisit);
231         }
232         else {
233                 /* If this is the first time the user has seen this room,
234                  * set the view to be the default for the room.
235                  */
236                 vbuf->v_view = rel_room->QRdefaultview;
237         }
238
239         /* Set v_seen if necessary */
240         if (vbuf->v_seen[0] == 0) {
241                 snprintf(vbuf->v_seen, sizeof vbuf->v_seen, "*:%ld", vbuf->v_lastseen);
242         }
243 }
244
245
246 void MailboxName(char *buf, size_t n, const struct usersupp *who, const char *prefix)
247 {
248         snprintf(buf, n, "%010ld.%s", who->usernum, prefix);
249 }
250
251
252 /*
253  * Is the user currently logged in an Aide?
254  */
255 int is_aide(void)
256 {
257         if (CC->usersupp.axlevel >= 6)
258                 return (1);
259         else
260                 return (0);
261 }
262
263
264 /*
265  * Is the user currently logged in an Aide *or* the room aide for this room?
266  */
267 int is_room_aide(void)
268 {
269
270         if (!CC->logged_in) {
271                 return (0);
272         }
273
274         if ((CC->usersupp.axlevel >= 6)
275             || (CC->quickroom.QRroomaide == CC->usersupp.usernum)) {
276                 return (1);
277         } else {
278                 return (0);
279         }
280 }
281
282 /*
283  * getuserbynumber()  -  get user by number
284  *                       returns 0 if user was found
285  *
286  * WARNING: don't use this function unless you absolutely have to.  It does
287  *          a sequential search and therefore is computationally expensive.
288  */
289 int getuserbynumber(struct usersupp *usbuf, long int number)
290 {
291         struct cdbdata *cdbus;
292
293         cdb_rewind(CDB_USERSUPP);
294
295         while (cdbus = cdb_next_item(CDB_USERSUPP), cdbus != NULL) {
296                 memset(usbuf, 0, sizeof(struct usersupp));
297                 memcpy(usbuf, cdbus->ptr,
298                        ((cdbus->len > sizeof(struct usersupp)) ?
299                         sizeof(struct usersupp) : cdbus->len));
300                 cdb_free(cdbus);
301                 if (usbuf->usernum == number) {
302                         cdb_close_cursor(CDB_USERSUPP);
303                         return (0);
304                 }
305         }
306         return (-1);
307 }
308
309
310 /*
311  * Back end for cmd_user() and its ilk
312  */
313 int CtdlLoginExistingUser(char *trythisname)
314 {
315         char username[SIZ];
316         char autoname[SIZ];
317         int found_user = 0;
318         struct passwd *p;
319         int a;
320
321         if (trythisname == NULL) return login_not_found;
322         safestrncpy(username, trythisname, sizeof username);
323         strproc(username);
324
325         if ((CC->logged_in)) {
326                 return login_already_logged_in;
327         }
328         found_user = getuser(&CC->usersupp, username);
329         if (found_user != 0) {
330                 p = (struct passwd *) getpwnam(username);
331                 if (p != NULL) {
332                         strcpy(autoname, p->pw_gecos);
333                         for (a = 0; a < strlen(autoname); ++a)
334                                 if (autoname[a] == ',')
335                                         autoname[a] = 0;
336                         found_user = getuser(&CC->usersupp, autoname);
337                 }
338         }
339         if (found_user == 0) {
340                 if (((CC->nologin)) && (CC->usersupp.axlevel < 6)) {
341                         return login_too_many_users;
342                 } else {
343                         strcpy(CC->curr_user, CC->usersupp.fullname);
344                         return login_ok;
345                 }
346         }
347         return login_not_found;
348 }
349
350
351
352 /*
353  * USER cmd
354  */
355 void cmd_user(char *cmdbuf)
356 {
357         char username[SIZ];
358         int a;
359
360         extract(username, cmdbuf, 0);
361         username[25] = 0;
362         strproc(username);
363
364         a = CtdlLoginExistingUser(username);
365         switch (a) {
366         case login_already_logged_in:
367                 cprintf("%d Already logged in.\n", ERROR);
368                 return;
369         case login_too_many_users:
370                 cprintf("%d %s: "
371                         "Too many users are already online "
372                         "(maximum is %d)\n",
373                         ERROR + MAX_SESSIONS_EXCEEDED,
374                         config.c_nodename, config.c_maxsessions);
375                 return;
376         case login_ok:
377                 cprintf("%d Password required for %s\n",
378                         MORE_DATA, CC->curr_user);
379                 return;
380         case login_not_found:
381                 cprintf("%d %s not found.\n", ERROR, username);
382                 return;
383                 cprintf("%d Internal error\n", ERROR);
384         }
385 }
386
387
388
389 /*
390  * session startup code which is common to both cmd_pass() and cmd_newu()
391  */
392 void session_startup(void)
393 {
394         syslog(LOG_NOTICE, "session %d: user <%s> logged in",
395                CC->cs_pid, CC->curr_user);
396
397         lgetuser(&CC->usersupp, CC->curr_user);
398         ++(CC->usersupp.timescalled);
399         time(&CC->usersupp.lastcall);
400
401         /* If this user's name is the name of the system administrator
402          * (as specified in setup), automatically assign access level 6.
403          */
404         if (!strcasecmp(CC->usersupp.fullname, config.c_sysadm)) {
405                 CC->usersupp.axlevel = 6;
406         }
407         lputuser(&CC->usersupp);
408
409         /* Run any startup routines registered by loadable modules */
410         PerformSessionHooks(EVT_LOGIN);
411
412         /* Create any personal rooms required by the system */
413         create_room(SENTITEMS, 4, "", 0, 1, 0);
414
415         /* Enter the lobby */
416         usergoto(BASEROOM, 0, NULL, NULL);
417
418         /* Record this login in the Citadel log */
419         rec_log(CL_LOGIN, CC->curr_user);
420 }
421
422
423 void logged_in_response(void)
424 {
425         cprintf("%d %s|%d|%ld|%ld|%u|%ld|%ld\n",
426                 CIT_OK, CC->usersupp.fullname, CC->usersupp.axlevel,
427                 CC->usersupp.timescalled, CC->usersupp.posted,
428                 CC->usersupp.flags, CC->usersupp.usernum,
429                 CC->usersupp.lastcall);
430 }
431
432
433
434 /* 
435  * misc things to be taken care of when a user is logged out
436  */
437 void logout(struct CitContext *who)
438 {
439         who->logged_in = 0;
440
441         /*
442          * If there is a download in progress, abort it.
443          */
444         if (who->download_fp != NULL) {
445                 fclose(who->download_fp);
446                 who->download_fp = NULL;
447         }
448
449         /*
450          * If there is an upload in progress, abort it.
451          */
452         if (who->upload_fp != NULL) {
453                 abort_upl(who);
454         }
455
456         /*
457          * If we were talking to a network node, we're not anymore...
458          */
459         if (strlen(who->net_node) > 0) {
460                 network_talking_to(who->net_node, NTT_REMOVE);
461         }
462
463         /*
464          * Yes, we really need to free EVERY LAST BYTE we allocated.
465          */
466         if (who->cs_inet_email != NULL) {
467                 phree(who->cs_inet_email);
468                 who->cs_inet_email = NULL;
469         }
470
471         /* Do modular stuff... */
472         PerformSessionHooks(EVT_LOGOUT);
473 }
474
475 #ifdef ENABLE_CHKPWD
476 /*
477  * an alternate version of validpw() which executes `chkpwd' instead of
478  * verifying the password directly
479  */
480 static int validpw(uid_t uid, const char *pass)
481 {
482         pid_t pid;
483         int status, pipev[2];
484         char buf[24];
485
486         if (pipe(pipev)) {
487                 lprintf(1, "pipe failed (%s): denying autologin access for "
488                         "uid %ld\n", strerror(errno), (long)uid);
489                 return 0;
490         }
491         switch (pid = fork()) {
492         case -1:
493                 lprintf(1, "fork failed (%s): denying autologin access for "
494                         "uid %ld\n", strerror(errno), (long)uid);
495                 close(pipev[0]);
496                 close(pipev[1]);
497                 return 0;
498
499         case 0:
500                 close(pipev[1]);
501                 if (dup2(pipev[0], 0) == -1) {
502                         perror("dup2");
503                         exit(1);
504                 }
505                 close(pipev[0]);
506
507                 execl(BBSDIR "/chkpwd", BBSDIR "/chkpwd", NULL);
508                 perror(BBSDIR "/chkpwd");
509                 exit(1);
510         }
511
512         close(pipev[0]);
513         write(pipev[1], buf,
514               snprintf(buf, sizeof buf, "%lu\n", (unsigned long) uid));
515         write(pipev[1], pass, strlen(pass));
516         write(pipev[1], "\n", 1);
517         close(pipev[1]);
518
519         while (waitpid(pid, &status, 0) == -1)
520                 if (errno != EINTR) {
521                         lprintf(1, "waitpid failed (%s): denying autologin "
522                                 "access for uid %ld\n",
523                                 strerror(errno), (long)uid);
524                         return 0;
525                 }
526         if (WIFEXITED(status) && !WEXITSTATUS(status))
527                 return 1;
528
529         return 0;
530 }
531 #endif
532
533 void do_login()
534 {
535         (CC->logged_in) = 1;
536         session_startup();
537 }
538
539
540 int CtdlTryPassword(char *password)
541 {
542         int code;
543
544         if ((CC->logged_in)) {
545                 lprintf(5, "CtdlTryPassword: already logged in\n");
546                 return pass_already_logged_in;
547         }
548         if (!strcmp(CC->curr_user, NLI)) {
549                 lprintf(5, "CtdlTryPassword: no user selected\n");
550                 return pass_no_user;
551         }
552         if (getuser(&CC->usersupp, CC->curr_user)) {
553                 lprintf(5, "CtdlTryPassword: internal error\n");
554                 return pass_internal_error;
555         }
556         if (password == NULL) {
557                 lprintf(5, "CtdlTryPassword: NULL password string supplied\n");
558                 return pass_wrong_password;
559         }
560         code = (-1);
561         if (CC->usersupp.uid == BBSUID) {
562                 strproc(password);
563                 strproc(CC->usersupp.password);
564                 code = strcasecmp(CC->usersupp.password, password);
565         }
566 #ifdef ENABLE_AUTOLOGIN
567         else {
568                 if (validpw(CC->usersupp.uid, password)) {
569                         code = 0;
570                         lgetuser(&CC->usersupp, CC->curr_user);
571                         safestrncpy(CC->usersupp.password, password,
572                                     sizeof CC->usersupp.password);
573                         lputuser(&CC->usersupp);
574                 }
575         }
576 #endif
577
578         if (!code) {
579                 do_login();
580                 return pass_ok;
581         } else {
582                 rec_log(CL_BADPW, CC->curr_user);
583                 return pass_wrong_password;
584         }
585 }
586
587
588 void cmd_pass(char *buf)
589 {
590         char password[SIZ];
591         int a;
592
593         extract(password, buf, 0);
594         a = CtdlTryPassword(password);
595
596         switch (a) {
597         case pass_already_logged_in:
598                 cprintf("%d Already logged in.\n", ERROR);
599                 return;
600         case pass_no_user:
601                 cprintf("%d You must send a name with USER first.\n",
602                         ERROR);
603                 return;
604         case pass_wrong_password:
605                 cprintf("%d Wrong password.\n", ERROR);
606                 return;
607         case pass_ok:
608                 logged_in_response();
609                 return;
610                 cprintf("%d Can't find user record!\n",
611                         ERROR + INTERNAL_ERROR);
612         }
613 }
614
615
616
617 /*
618  * Delete a user record *and* all of its related resources.
619  */
620 int purge_user(char pname[])
621 {
622         char filename[64];
623         struct usersupp usbuf;
624         char lowercase_name[32];
625         int a;
626         struct CitContext *ccptr;
627         int user_is_logged_in = 0;
628
629         for (a = 0; a <= strlen(pname); ++a) {
630                 lowercase_name[a] = tolower(pname[a]);
631         }
632
633         if (getuser(&usbuf, pname) != 0) {
634                 lprintf(5, "Cannot purge user <%s> - not found\n", pname);
635                 return (ERROR + NO_SUCH_USER);
636         }
637         /* Don't delete a user who is currently logged in.  Instead, just
638          * set the access level to 0, and let the account get swept up
639          * during the next purge.
640          */
641         user_is_logged_in = 0;
642         begin_critical_section(S_SESSION_TABLE);
643         for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
644                 if (ccptr->usersupp.usernum == usbuf.usernum) {
645                         user_is_logged_in = 1;
646                 }
647         }
648         end_critical_section(S_SESSION_TABLE);
649         if (user_is_logged_in == 1) {
650                 lprintf(5, "User <%s> is logged in; not deleting.\n", pname);
651                 usbuf.axlevel = 0;
652                 putuser(&usbuf);
653                 return (1);
654         }
655         lprintf(5, "Deleting user <%s>\n", pname);
656
657         /* Perform any purge functions registered by server extensions */
658         PerformUserHooks(usbuf.fullname, usbuf.usernum, EVT_PURGEUSER);
659
660         /* delete any existing user/room relationships */
661         cdb_delete(CDB_VISIT, &usbuf.usernum, sizeof(long));
662
663         /* delete the userlog entry */
664         cdb_delete(CDB_USERSUPP, lowercase_name, strlen(lowercase_name));
665
666         /* remove the user's bio file */
667         snprintf(filename, sizeof filename, "./bio/%ld", usbuf.usernum);
668         unlink(filename);
669
670         /* remove the user's picture */
671         snprintf(filename, sizeof filename, "./userpics/%ld.gif", usbuf.usernum);
672         unlink(filename);
673
674         return (0);
675 }
676
677
678 /*
679  * create_user()  -  back end processing to create a new user
680  *
681  * Set 'newusername' to the desired account name.
682  * Set 'become_user' to nonzero if this is self-service account creation and we want
683  * to actually log in as the user we just created, otherwise set it to 0.
684  */
685 int create_user(char *newusername, int become_user)
686 {
687         struct usersupp usbuf;
688         struct passwd *p = NULL;
689         char username[SIZ];
690         char mailboxname[ROOMNAMELEN];
691         uid_t uid;
692
693         strcpy(username, newusername);
694         strproc(username);
695
696 #ifdef ENABLE_AUTOLOGIN
697         p = (struct passwd *) getpwnam(username);
698 #endif
699         if (p != NULL) {
700                 extract_token(username, p->pw_gecos, 0, ',');
701                 uid = p->pw_uid;
702         } else {
703                 uid = BBSUID;
704         }
705
706         if (!getuser(&usbuf, username)) {
707                 return (ERROR + ALREADY_EXISTS);
708         }
709
710         /* Go ahead and initialize a new user record */
711         memset(&usbuf, 0, sizeof(struct usersupp));
712         strcpy(usbuf.fullname, username);
713         strcpy(usbuf.password, "");
714         usbuf.uid = uid;
715
716         /* These are the default flags on new accounts */
717         usbuf.flags = US_LASTOLD | US_DISAPPEAR | US_PAGINATOR | US_FLOORS;
718
719         usbuf.timescalled = 0;
720         usbuf.posted = 0;
721         usbuf.axlevel = config.c_initax;
722         usbuf.USscreenwidth = 80;
723         usbuf.USscreenheight = 24;
724         usbuf.lastcall = time(NULL);
725         usbuf.moderation_filter = config.c_default_filter;
726
727         /* fetch a new user number */
728         usbuf.usernum = get_new_user_number();
729
730         /* The very first user created on the system will always be an Aide */
731         if (usbuf.usernum == 1L) {
732                 usbuf.axlevel = 6;
733         }
734
735         /* add user to userlog */
736         putuser(&usbuf);
737
738         /* give the user a private mailbox and a configuration room */
739         MailboxName(mailboxname, sizeof mailboxname, &usbuf, MAILROOM);
740         create_room(mailboxname, 5, "", 0, 1, 1);
741         MailboxName(mailboxname, sizeof mailboxname, &usbuf, USERCONFIGROOM);
742         create_room(mailboxname, 5, "", 0, 1, 1);
743
744         /* Everything below this line can be bypassed if administratively
745            creating a user, instead of doing self-service account creation
746          */
747
748         if (become_user) {
749                 /* Now become the user we just created */
750                 memcpy(&CC->usersupp, &usbuf, sizeof(struct usersupp));
751                 strcpy(CC->curr_user, username);
752                 CC->logged_in = 1;
753         
754                 /* Check to make sure we're still who we think we are */
755                 if (getuser(&CC->usersupp, CC->curr_user)) {
756                         return (ERROR + INTERNAL_ERROR);
757                 }
758         
759                 rec_log(CL_NEWUSER, CC->curr_user);
760         }
761
762         return (0);
763 }
764
765
766
767
768 /*
769  * cmd_newu()  -  create a new user account and log in as that user
770  */
771 void cmd_newu(char *cmdbuf)
772 {
773         int a;
774         char username[SIZ];
775
776         if (config.c_disable_newu) {
777                 cprintf("%d Self-service user account creation "
778                         "is disabled on this system.\n", ERROR);
779                 return;
780         }
781
782         if (CC->logged_in) {
783                 cprintf("%d Already logged in.\n", ERROR);
784                 return;
785         }
786         if (CC->nologin) {
787                 cprintf("%d %s: Too many users are already online (maximum is %d)\n",
788                         ERROR + MAX_SESSIONS_EXCEEDED,
789                         config.c_nodename, config.c_maxsessions);
790         }
791         extract(username, cmdbuf, 0);
792         username[25] = 0;
793         strproc(username);
794
795         if (strlen(username) == 0) {
796                 cprintf("%d You must supply a user name.\n", ERROR);
797                 return;
798         }
799
800         if ((!strcasecmp(username, "bbs")) ||
801             (!strcasecmp(username, "new")) ||
802             (!strcasecmp(username, "."))) {
803                 cprintf("%d '%s' is an invalid login name.\n", ERROR, username);
804                 return;
805         }
806
807         a = create_user(username, 1);
808
809         if (a == 0) {
810                 session_startup();
811                 logged_in_response();
812         } else if (a == ERROR + ALREADY_EXISTS) {
813                 cprintf("%d '%s' already exists.\n",
814                         ERROR + ALREADY_EXISTS, username);
815                 return;
816         } else if (a == ERROR + INTERNAL_ERROR) {
817                 cprintf("%d Internal error - user record disappeared?\n",
818                         ERROR + INTERNAL_ERROR);
819                 return;
820         } else {
821                 cprintf("%d unknown error\n", ERROR);
822         }
823         rec_log(CL_NEWUSER, CC->curr_user);
824 }
825
826
827
828 /*
829  * set password
830  */
831 void cmd_setp(char *new_pw)
832 {
833         if (CtdlAccessCheck(ac_logged_in)) {
834                 return;
835         }
836
837         if (CC->usersupp.uid != BBSUID) {
838                 cprintf("%d Not allowed.  Use the 'passwd' command.\n", ERROR);
839                 return;
840         }
841         strproc(new_pw);
842         if (strlen(new_pw) == 0) {
843                 cprintf("%d Password unchanged.\n", CIT_OK);
844                 return;
845         }
846         lgetuser(&CC->usersupp, CC->curr_user);
847         strcpy(CC->usersupp.password, new_pw);
848         lputuser(&CC->usersupp);
849         cprintf("%d Password changed.\n", CIT_OK);
850         rec_log(CL_PWCHANGE, CC->curr_user);
851         PerformSessionHooks(EVT_SETPASS);
852 }
853
854
855 /*
856  * cmd_creu()  -  administratively create a new user account (do not log in to it)
857  */
858 void cmd_creu(char *cmdbuf)
859 {
860         int a;
861         char username[SIZ];
862
863         if (CtdlAccessCheck(ac_aide)) {
864                 return;
865         }
866
867         extract(username, cmdbuf, 0);
868         username[25] = 0;
869         strproc(username);
870
871         if (strlen(username) == 0) {
872                 cprintf("%d You must supply a user name.\n", ERROR);
873                 return;
874         }
875
876         a = create_user(username, 0);
877
878         if (a == 0) {
879                 cprintf("%d ok\n", CIT_OK);
880                 return;
881         } else if (a == ERROR + ALREADY_EXISTS) {
882                 cprintf("%d '%s' already exists.\n",
883                         ERROR + ALREADY_EXISTS, username);
884                 return;
885         } else {
886                 cprintf("%d An error occured creating the user account.\n", ERROR);
887         }
888         rec_log(CL_NEWUSER, username);
889 }
890
891
892
893 /*
894  * get user parameters
895  */
896 void cmd_getu(void)
897 {
898
899         if (CtdlAccessCheck(ac_logged_in))
900                 return;
901
902         getuser(&CC->usersupp, CC->curr_user);
903         cprintf("%d %d|%d|%d|%d\n",
904                 CIT_OK,
905                 CC->usersupp.USscreenwidth,
906                 CC->usersupp.USscreenheight,
907                 (CC->usersupp.flags & US_USER_SET),
908                 CC->usersupp.moderation_filter
909             );
910 }
911
912 /*
913  * set user parameters
914  */
915 void cmd_setu(char *new_parms)
916 {
917         int new_mod;
918
919         if (CtdlAccessCheck(ac_logged_in))
920                 return;
921
922         if (num_parms(new_parms) < 3) {
923                 cprintf("%d Usage error.\n", ERROR);
924                 return;
925         }
926         lgetuser(&CC->usersupp, CC->curr_user);
927         CC->usersupp.USscreenwidth = extract_int(new_parms, 0);
928         CC->usersupp.USscreenheight = extract_int(new_parms, 1);
929         CC->usersupp.flags = CC->usersupp.flags & (~US_USER_SET);
930         CC->usersupp.flags = CC->usersupp.flags |
931             (extract_int(new_parms, 2) & US_USER_SET);
932
933         if (num_parms(new_parms) >= 4) {
934                 new_mod = extract_int(new_parms, 3);
935                 lprintf(9, "new_mod extracted to %d\n", new_mod);
936
937                 /* Aides cannot set the filter level lower than -100 */
938                 if (new_mod < (-100))
939                         new_mod = -100;
940
941                 /* Normal users cannot set the filter level lower than -63 */
942                 if ((new_mod < (-63)) && (CC->usersupp.axlevel < 6))
943                         new_mod = -63;
944
945                 /* Nobody can set the filter level higher than +63 */
946                 if (new_mod > 63)
947                         new_mod = 63;
948
949                 CC->usersupp.moderation_filter = new_mod;
950                 lprintf(9, "new_mod processed to %d\n", new_mod);
951         }
952         lputuser(&CC->usersupp);
953         cprintf("%d Ok\n", CIT_OK);
954 }
955
956 /*
957  * set last read pointer
958  */
959 void cmd_slrp(char *new_ptr)
960 {
961         long newlr;
962         struct visit vbuf;
963
964         if (CtdlAccessCheck(ac_logged_in)) {
965                 return;
966         }
967
968         if (!strncasecmp(new_ptr, "highest", 7)) {
969                 newlr = CC->quickroom.QRhighest;
970         } else {
971                 newlr = atol(new_ptr);
972         }
973
974         lgetuser(&CC->usersupp, CC->curr_user);
975
976         CtdlGetRelationship(&vbuf, &CC->usersupp, &CC->quickroom);
977         vbuf.v_lastseen = newlr;
978         snprintf(vbuf.v_seen, sizeof vbuf.v_seen, "*:%ld", newlr);
979         CtdlSetRelationship(&vbuf, &CC->usersupp, &CC->quickroom);
980
981         lputuser(&CC->usersupp);
982         cprintf("%d %ld\n", CIT_OK, newlr);
983 }
984
985
986 void cmd_seen(char *argbuf) {
987         long target_msgnum = 0L;
988         int target_setting = 0;
989
990         if (CtdlAccessCheck(ac_logged_in)) {
991                 return;
992         }
993
994         if (num_parms(argbuf) != 2) {
995                 cprintf("%d Invalid parameters\n", ERROR);
996                 return;
997         }
998
999         target_msgnum = extract_long(argbuf, 0);
1000         target_setting = extract_int(argbuf, 1);
1001
1002         CtdlSetSeen(target_msgnum, target_setting);
1003         cprintf("%d OK\n", CIT_OK);
1004 }
1005
1006
1007 /*
1008  * INVT and KICK commands
1009  */
1010 void cmd_invt_kick(char *iuser, int op)
1011                         /* user name */
1012 {                               /* 1 = invite, 0 = kick out */
1013         struct usersupp USscratch;
1014         char bbb[SIZ];
1015         struct visit vbuf;
1016
1017         /*
1018          * These commands are only allowed by aides, room aides,
1019          * and room namespace owners
1020          */
1021         if (is_room_aide()
1022            || (atol(CC->quickroom.QRname) == CC->usersupp.usernum) ) {
1023                 /* access granted */
1024         }
1025         else {
1026                 /* access denied */
1027                 cprintf("%d Higher access or room ownership required.\n",
1028                         ERROR + HIGHER_ACCESS_REQUIRED);
1029                 return;
1030         }
1031
1032         if (lgetuser(&USscratch, iuser) != 0) {
1033                 cprintf("%d No such user.\n", ERROR);
1034                 return;
1035         }
1036         CtdlGetRelationship(&vbuf, &USscratch, &CC->quickroom);
1037
1038         if (op == 1) {
1039                 vbuf.v_flags = vbuf.v_flags & ~V_FORGET & ~V_LOCKOUT;
1040                 vbuf.v_flags = vbuf.v_flags | V_ACCESS;
1041         }
1042         if (op == 0) {
1043                 vbuf.v_flags = vbuf.v_flags & ~V_ACCESS;
1044                 vbuf.v_flags = vbuf.v_flags | V_FORGET | V_LOCKOUT;
1045         }
1046         CtdlSetRelationship(&vbuf, &USscratch, &CC->quickroom);
1047
1048         lputuser(&USscratch);
1049
1050         /* post a message in Aide> saying what we just did */
1051         snprintf(bbb, sizeof bbb, "%s %s %s> by %s\n",
1052                 iuser,
1053                 ((op == 1) ? "invited to" : "kicked out of"),
1054                 CC->quickroom.QRname,
1055                 CC->usersupp.fullname);
1056         aide_message(bbb);
1057
1058         cprintf("%d %s %s %s.\n",
1059                 CIT_OK, iuser,
1060                 ((op == 1) ? "invited to" : "kicked out of"),
1061                 CC->quickroom.QRname);
1062         return;
1063 }
1064
1065
1066 /*
1067  * Forget (Zap) the current room (API call)
1068  * Returns 0 on success
1069  */
1070 int CtdlForgetThisRoom(void) {
1071         struct visit vbuf;
1072
1073         /* On some systems, Aides are not allowed to forget rooms */
1074         if (is_aide() && (config.c_aide_zap == 0)
1075            && ((CC->quickroom.QRflags & QR_MAILBOX) == 0)  ) {
1076                 return(1);
1077         }
1078
1079         lgetuser(&CC->usersupp, CC->curr_user);
1080         CtdlGetRelationship(&vbuf, &CC->usersupp, &CC->quickroom);
1081
1082         vbuf.v_flags = vbuf.v_flags | V_FORGET;
1083         vbuf.v_flags = vbuf.v_flags & ~V_ACCESS;
1084
1085         CtdlSetRelationship(&vbuf, &CC->usersupp, &CC->quickroom);
1086         lputuser(&CC->usersupp);
1087
1088         /* Return to the Lobby, so we don't end up in an undefined room */
1089         usergoto(BASEROOM, 0, NULL, NULL);
1090         return(0);
1091
1092 }
1093
1094
1095 /*
1096  * forget (Zap) the current room
1097  */
1098 void cmd_forg(void)
1099 {
1100
1101         if (CtdlAccessCheck(ac_logged_in)) {
1102                 return;
1103         }
1104
1105         if (CtdlForgetThisRoom() == 0) {
1106                 cprintf("%d Ok\n", CIT_OK);
1107         }
1108         else {
1109                 cprintf("%d You may not forget this room.\n", ERROR);
1110         }
1111 }
1112
1113 /*
1114  * Get Next Unregistered User
1115  */
1116 void cmd_gnur(void)
1117 {
1118         struct cdbdata *cdbus;
1119         struct usersupp usbuf;
1120
1121         if (CtdlAccessCheck(ac_aide)) {
1122                 return;
1123         }
1124
1125         if ((CitControl.MMflags & MM_VALID) == 0) {
1126                 cprintf("%d There are no unvalidated users.\n", CIT_OK);
1127                 return;
1128         }
1129
1130         /* There are unvalidated users.  Traverse the usersupp database,
1131          * and return the first user we find that needs validation.
1132          */
1133         cdb_rewind(CDB_USERSUPP);
1134         while (cdbus = cdb_next_item(CDB_USERSUPP), cdbus != NULL) {
1135                 memset(&usbuf, 0, sizeof(struct usersupp));
1136                 memcpy(&usbuf, cdbus->ptr,
1137                        ((cdbus->len > sizeof(struct usersupp)) ?
1138                         sizeof(struct usersupp) : cdbus->len));
1139                 cdb_free(cdbus);
1140                 if ((usbuf.flags & US_NEEDVALID)
1141                     && (usbuf.axlevel > 0)) {
1142                         cprintf("%d %s\n", MORE_DATA, usbuf.fullname);
1143                         cdb_close_cursor(CDB_USERSUPP);
1144                         return;
1145                 }
1146         }
1147
1148         /* If we get to this point, there are no more unvalidated users.
1149          * Therefore we clear the "users need validation" flag.
1150          */
1151
1152         begin_critical_section(S_CONTROL);
1153         get_control();
1154         CitControl.MMflags = CitControl.MMflags & (~MM_VALID);
1155         put_control();
1156         end_critical_section(S_CONTROL);
1157         cprintf("%d *** End of registration.\n", CIT_OK);
1158
1159
1160 }
1161
1162
1163 /*
1164  * validate a user
1165  */
1166 void cmd_vali(char *v_args)
1167 {
1168         char user[SIZ];
1169         int newax;
1170         struct usersupp userbuf;
1171
1172         extract(user, v_args, 0);
1173         newax = extract_int(v_args, 1);
1174
1175         if (CtdlAccessCheck(ac_aide)) {
1176                 return;
1177         }
1178
1179         if (lgetuser(&userbuf, user) != 0) {
1180                 cprintf("%d '%s' not found.\n", ERROR + NO_SUCH_USER, user);
1181                 return;
1182         }
1183
1184         userbuf.axlevel = newax;
1185         userbuf.flags = (userbuf.flags & ~US_NEEDVALID);
1186
1187         lputuser(&userbuf);
1188
1189         /* If the access level was set to zero, delete the user */
1190         if (newax == 0) {
1191                 if (purge_user(user) == 0) {
1192                         cprintf("%d %s Deleted.\n", CIT_OK, userbuf.fullname);
1193                         return;
1194                 }
1195         }
1196         cprintf("%d User '%s' validated.\n", CIT_OK, userbuf.fullname);
1197 }
1198
1199
1200
1201 /* 
1202  *  Traverse the user file...
1203  */
1204 void ForEachUser(void (*CallBack) (struct usersupp * EachUser, void *out_data),
1205                  void *in_data)
1206 {
1207         struct usersupp usbuf;
1208         struct cdbdata *cdbus;
1209
1210         cdb_rewind(CDB_USERSUPP);
1211
1212         while (cdbus = cdb_next_item(CDB_USERSUPP), cdbus != NULL) {
1213                 memset(&usbuf, 0, sizeof(struct usersupp));
1214                 memcpy(&usbuf, cdbus->ptr,
1215                        ((cdbus->len > sizeof(struct usersupp)) ?
1216                         sizeof(struct usersupp) : cdbus->len));
1217                 cdb_free(cdbus);
1218                 (*CallBack) (&usbuf, in_data);
1219         }
1220 }
1221
1222
1223 /*
1224  * List one user (this works with cmd_list)
1225  */
1226 void ListThisUser(struct usersupp *usbuf, void *data)
1227 {
1228         if (usbuf->axlevel > 0) {
1229                 if ((CC->usersupp.axlevel >= 6)
1230                     || ((usbuf->flags & US_UNLISTED) == 0)
1231                     || ((CC->internal_pgm))) {
1232                         cprintf("%s|%d|%ld|%ld|%ld|%ld|",
1233                                 usbuf->fullname,
1234                                 usbuf->axlevel,
1235                                 usbuf->usernum,
1236                                 (long)usbuf->lastcall,
1237                                 usbuf->timescalled,
1238                                 usbuf->posted);
1239                         if (CC->usersupp.axlevel >= 6)
1240                                 cprintf("%s", usbuf->password);
1241                         cprintf("\n");
1242                 }
1243         }
1244 }
1245
1246 /* 
1247  *  List users
1248  */
1249 void cmd_list(void)
1250 {
1251         cprintf("%d \n", LISTING_FOLLOWS);
1252         ForEachUser(ListThisUser, NULL);
1253         cprintf("000\n");
1254 }
1255
1256
1257
1258
1259 /*
1260  * assorted info we need to check at login
1261  */
1262 void cmd_chek(void)
1263 {
1264         int mail = 0;
1265         int regis = 0;
1266         int vali = 0;
1267
1268         if (CtdlAccessCheck(ac_logged_in)) {
1269                 return;
1270         }
1271
1272         getuser(&CC->usersupp, CC->curr_user);  /* no lock is needed here */
1273         if ((REGISCALL != 0) && ((CC->usersupp.flags & US_REGIS) == 0))
1274                 regis = 1;
1275
1276         if (CC->usersupp.axlevel >= 6) {
1277                 get_control();
1278                 if (CitControl.MMflags & MM_VALID)
1279                         vali = 1;
1280         }
1281
1282         /* check for mail */
1283         mail = NewMailCount();
1284
1285         cprintf("%d %d|%d|%d\n", CIT_OK, mail, regis, vali);
1286 }
1287
1288
1289 /*
1290  * check to see if a user exists
1291  */
1292 void cmd_qusr(char *who)
1293 {
1294         struct usersupp usbuf;
1295
1296         if (getuser(&usbuf, who) == 0) {
1297                 cprintf("%d %s\n", CIT_OK, usbuf.fullname);
1298         } else {
1299                 cprintf("%d No such user.\n", ERROR + NO_SUCH_USER);
1300         }
1301 }
1302
1303
1304 /*
1305  * Administrative Get User Parameters
1306  */
1307 void cmd_agup(char *cmdbuf)
1308 {
1309         struct usersupp usbuf;
1310         char requested_user[SIZ];
1311
1312         if (CtdlAccessCheck(ac_aide)) {
1313                 return;
1314         }
1315
1316         extract(requested_user, cmdbuf, 0);
1317         if (getuser(&usbuf, requested_user) != 0) {
1318                 cprintf("%d No such user.\n", ERROR + NO_SUCH_USER);
1319                 return;
1320         }
1321         cprintf("%d %s|%s|%u|%ld|%ld|%d|%ld|%ld|%d\n",
1322                 CIT_OK,
1323                 usbuf.fullname,
1324                 usbuf.password,
1325                 usbuf.flags,
1326                 usbuf.timescalled,
1327                 usbuf.posted,
1328                 (int) usbuf.axlevel,
1329                 usbuf.usernum,
1330                 (long)usbuf.lastcall,
1331                 usbuf.USuserpurge);
1332 }
1333
1334
1335
1336 /*
1337  * Administrative Set User Parameters
1338  */
1339 void cmd_asup(char *cmdbuf)
1340 {
1341         struct usersupp usbuf;
1342         char requested_user[SIZ];
1343         int np;
1344         int newax;
1345         int deleted = 0;
1346
1347         if (CtdlAccessCheck(ac_aide))
1348                 return;
1349
1350         extract(requested_user, cmdbuf, 0);
1351         if (lgetuser(&usbuf, requested_user) != 0) {
1352                 cprintf("%d No such user.\n", ERROR + NO_SUCH_USER);
1353                 return;
1354         }
1355         np = num_parms(cmdbuf);
1356         if (np > 1)
1357                 extract(usbuf.password, cmdbuf, 1);
1358         if (np > 2)
1359                 usbuf.flags = extract_int(cmdbuf, 2);
1360         if (np > 3)
1361                 usbuf.timescalled = extract_int(cmdbuf, 3);
1362         if (np > 4)
1363                 usbuf.posted = extract_int(cmdbuf, 4);
1364         if (np > 5) {
1365                 newax = extract_int(cmdbuf, 5);
1366                 if ((newax >= 0) && (newax <= 6)) {
1367                         usbuf.axlevel = extract_int(cmdbuf, 5);
1368                 }
1369         }
1370         if (np > 7) {
1371                 usbuf.lastcall = extract_long(cmdbuf, 7);
1372         }
1373         if (np > 8) {
1374                 usbuf.USuserpurge = extract_int(cmdbuf, 8);
1375         }
1376         lputuser(&usbuf);
1377         if (usbuf.axlevel == 0) {
1378                 if (purge_user(requested_user) == 0) {
1379                         deleted = 1;
1380                 }
1381         }
1382         cprintf("%d Ok", CIT_OK);
1383         if (deleted)
1384                 cprintf(" (%s deleted)", requested_user);
1385         cprintf("\n");
1386 }
1387
1388
1389 /*
1390  * Count the number of new mail messages the user has
1391  */
1392 int NewMailCount()
1393 {
1394         int num_newmsgs = 0;
1395         int a;
1396         char mailboxname[ROOMNAMELEN];
1397         struct quickroom mailbox;
1398         struct visit vbuf;
1399         struct cdbdata *cdbfr;
1400         long *msglist = NULL;
1401         int num_msgs = 0;
1402
1403         MailboxName(mailboxname, sizeof mailboxname, &CC->usersupp, MAILROOM);
1404         if (getroom(&mailbox, mailboxname) != 0)
1405                 return (0);
1406         CtdlGetRelationship(&vbuf, &CC->usersupp, &mailbox);
1407
1408         cdbfr = cdb_fetch(CDB_MSGLISTS, &mailbox.QRnumber, sizeof(long));
1409
1410         if (cdbfr != NULL) {
1411                 msglist = mallok(cdbfr->len);
1412                 memcpy(msglist, cdbfr->ptr, cdbfr->len);
1413                 num_msgs = cdbfr->len / sizeof(long);
1414                 cdb_free(cdbfr);
1415         }
1416         if (num_msgs > 0)
1417                 for (a = 0; a < num_msgs; ++a) {
1418                         if (msglist[a] > 0L) {
1419                                 if (msglist[a] > vbuf.v_lastseen) {
1420                                         ++num_newmsgs;
1421                                 }
1422                         }
1423                 }
1424         if (msglist != NULL)
1425                 phree(msglist);
1426
1427         return (num_newmsgs);
1428 }
1429
1430
1431 /*
1432  * Set the preferred view for the current user/room combination
1433  */
1434 void cmd_view(char *cmdbuf) {
1435         int requested_view;
1436         struct visit vbuf;
1437
1438         if (CtdlAccessCheck(ac_logged_in)) {
1439                 return;
1440         }
1441
1442         requested_view = extract_int(cmdbuf, 0);
1443
1444         CtdlGetRelationship(&vbuf, &CC->usersupp, &CC->quickroom);
1445         vbuf.v_view = requested_view;
1446         CtdlSetRelationship(&vbuf, &CC->usersupp, &CC->quickroom);
1447         
1448         cprintf("%d ok\n", CIT_OK);
1449 }