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