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