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