2240a55c2dc675d0ba5fc65afab349ab67ed8ab1
[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 usersupp *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 usersupp));
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_USERSUPP, 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 usersupp)) ?
97                 sizeof(struct usersupp) : 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 usersupp *usbuf, char *name)
108 {
109         int retcode;
110
111         retcode = getuser(usbuf, name);
112         if (retcode == 0) {
113                 begin_critical_section(S_USERSUPP);
114         }
115         return (retcode);
116 }
117
118
119 /*
120  * putuser()  -  write user buffer into the correct place on disk
121  */
122 void putuser(struct usersupp *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_USERSUPP,
135                   lowercase_name, strlen(lowercase_name),
136                   usbuf, sizeof(struct usersupp));
137
138 }
139
140
141 /*
142  * lputuser()  -  same as putuser() but locks the record
143  */
144 void lputuser(struct usersupp *usbuf)
145 {
146         putuser(usbuf);
147         end_critical_section(S_USERSUPP);
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 usersupp *rel_user,
203                          struct quickroom *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 usersupp *rel_user,
222                          struct quickroom *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 usersupp *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->usersupp.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->usersupp.axlevel >= 6)
288             || (CC->quickroom.QRroomaide == CC->usersupp.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 usersupp *usbuf, long int number)
303 {
304         struct cdbdata *cdbus;
305
306         cdb_rewind(CDB_USERSUPP);
307
308         while (cdbus = cdb_next_item(CDB_USERSUPP), cdbus != NULL) {
309                 memset(usbuf, 0, sizeof(struct usersupp));
310                 memcpy(usbuf, cdbus->ptr,
311                        ((cdbus->len > sizeof(struct usersupp)) ?
312                         sizeof(struct usersupp) : cdbus->len));
313                 cdb_free(cdbus);
314                 if (usbuf->usernum == number) {
315                         cdb_close_cursor(CDB_USERSUPP);
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->usersupp, username);
363
364         if (found_user == 0) {
365                 if (((CC->nologin)) && (CC->usersupp.axlevel < 6)) {
366                         return login_too_many_users;
367                 } else {
368                         strcpy(CC->curr_user, CC->usersupp.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->usersupp, CC->curr_user);
425         ++(CC->usersupp.timescalled);
426         CC->previous_login = CC->usersupp.lastcall;
427         time(&CC->usersupp.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->usersupp.fullname, config.c_sysadm)) {
433                 CC->usersupp.axlevel = 6;
434         }
435         lputuser(&CC->usersupp);
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->usersupp.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->usersupp.fullname, CC->usersupp.axlevel,
468                 CC->usersupp.timescalled, CC->usersupp.posted,
469                 CC->usersupp.flags, CC->usersupp.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->usersupp, 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         if (CC->usersupp.uid == BBSUID) {
598                 strproc(password);
599                 strproc(CC->usersupp.password);
600                 code = strcasecmp(CC->usersupp.password, password);
601         }
602         else {
603                 if (validpw(CC->usersupp.uid, password)) {
604                         code = 0;
605                         lgetuser(&CC->usersupp, CC->curr_user);
606                         safestrncpy(CC->usersupp.password, password,
607                                     sizeof CC->usersupp.password);
608                         lputuser(&CC->usersupp);
609                 }
610         }
611
612 #else /* ENABLE_AUTOLOGIN */
613         strproc(password);
614         strproc(CC->usersupp.password);
615         code = strcasecmp(CC->usersupp.password, password);
616
617 #endif /* ENABLE_AUTOLOGIN */
618
619         if (!code) {
620                 do_login();
621                 return pass_ok;
622         } else {
623                 lprintf(3, "Bad password specified for <%s>\n", CC->curr_user);
624                 return pass_wrong_password;
625         }
626 }
627
628
629 void cmd_pass(char *buf)
630 {
631         char password[SIZ];
632         int a;
633
634         extract(password, buf, 0);
635         a = CtdlTryPassword(password);
636
637         switch (a) {
638         case pass_already_logged_in:
639                 cprintf("%d Already logged in.\n", ERROR);
640                 return;
641         case pass_no_user:
642                 cprintf("%d You must send a name with USER first.\n",
643                         ERROR);
644                 return;
645         case pass_wrong_password:
646                 cprintf("%d Wrong password.\n", ERROR);
647                 return;
648         case pass_ok:
649                 logged_in_response();
650                 return;
651                 cprintf("%d Can't find user record!\n",
652                         ERROR + INTERNAL_ERROR);
653         }
654 }
655
656
657
658 /*
659  * Delete a user record *and* all of its related resources.
660  */
661 int purge_user(char pname[])
662 {
663         char filename[64];
664         struct usersupp usbuf;
665         char lowercase_name[USERNAME_SIZE];
666         int a;
667         struct CitContext *ccptr;
668         int user_is_logged_in = 0;
669
670         for (a = 0; a <= strlen(pname); ++a) {
671                 lowercase_name[a] = tolower(pname[a]);
672         }
673
674         if (getuser(&usbuf, pname) != 0) {
675                 lprintf(5, "Cannot purge user <%s> - not found\n", pname);
676                 return (ERROR + NO_SUCH_USER);
677         }
678         /* Don't delete a user who is currently logged in.  Instead, just
679          * set the access level to 0, and let the account get swept up
680          * during the next purge.
681          */
682         user_is_logged_in = 0;
683         begin_critical_section(S_SESSION_TABLE);
684         for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
685                 if (ccptr->usersupp.usernum == usbuf.usernum) {
686                         user_is_logged_in = 1;
687                 }
688         }
689         end_critical_section(S_SESSION_TABLE);
690         if (user_is_logged_in == 1) {
691                 lprintf(5, "User <%s> is logged in; not deleting.\n", pname);
692                 usbuf.axlevel = 0;
693                 putuser(&usbuf);
694                 return (1);
695         }
696         lprintf(5, "Deleting user <%s>\n", pname);
697
698         /* Perform any purge functions registered by server extensions */
699         PerformUserHooks(usbuf.fullname, usbuf.usernum, EVT_PURGEUSER);
700
701         /* delete any existing user/room relationships */
702         cdb_delete(CDB_VISIT, &usbuf.usernum, sizeof(long));
703
704         /* delete the userlog entry */
705         cdb_delete(CDB_USERSUPP, lowercase_name, strlen(lowercase_name));
706
707         /* remove the user's bio file */
708         snprintf(filename, sizeof filename, "./bio/%ld", usbuf.usernum);
709         unlink(filename);
710
711         /* remove the user's picture */
712         snprintf(filename, sizeof filename, "./userpics/%ld.gif", usbuf.usernum);
713         unlink(filename);
714
715         return (0);
716 }
717
718
719 /*
720  * create_user()  -  back end processing to create a new user
721  *
722  * Set 'newusername' to the desired account name.
723  * Set 'become_user' to nonzero if this is self-service account creation and we want
724  * to actually log in as the user we just created, otherwise set it to 0.
725  */
726 int create_user(char *newusername, int become_user)
727 {
728         struct usersupp usbuf;
729         struct quickroom qrbuf;
730         struct passwd *p = NULL;
731         char username[SIZ];
732         char mailboxname[ROOMNAMELEN];
733         uid_t uid;
734
735         strcpy(username, newusername);
736         strproc(username);
737
738 #ifdef ENABLE_AUTOLOGIN
739         p = (struct passwd *) getpwnam(username);
740         if (p != NULL) {
741                 extract_token(username, p->pw_gecos, 0, ',');
742                 uid = p->pw_uid;
743         } else {
744                 uid = BBSUID;
745         }
746 #else
747         uid = BBSUID;
748 #endif
749
750         if (!getuser(&usbuf, username)) {
751                 return (ERROR + ALREADY_EXISTS);
752         }
753
754         /* Go ahead and initialize a new user record */
755         memset(&usbuf, 0, sizeof(struct usersupp));
756         strcpy(usbuf.fullname, username);
757         strcpy(usbuf.password, "");
758         usbuf.uid = uid;
759
760         /* These are the default flags on new accounts */
761         usbuf.flags = US_LASTOLD | US_DISAPPEAR | US_PAGINATOR | US_FLOORS;
762
763         usbuf.timescalled = 0;
764         usbuf.posted = 0;
765         usbuf.axlevel = config.c_initax;
766         usbuf.USscreenwidth = 80;
767         usbuf.USscreenheight = 24;
768         usbuf.lastcall = time(NULL);
769
770         /* fetch a new user number */
771         usbuf.usernum = get_new_user_number();
772
773         /* The very first user created on the system will always be an Aide */
774         if (usbuf.usernum == 1L) {
775                 usbuf.axlevel = 6;
776         }
777
778         /* add user to userlog */
779         putuser(&usbuf);
780
781         /*
782          * Give the user a private mailbox and a configuration room.
783          * Make the latter an invisible system room.
784          */
785         MailboxName(mailboxname, sizeof mailboxname, &usbuf, MAILROOM);
786         create_room(mailboxname, 5, "", 0, 1, 1);
787
788         MailboxName(mailboxname, sizeof mailboxname, &usbuf, USERCONFIGROOM);
789         create_room(mailboxname, 5, "", 0, 1, 1);
790         if (lgetroom(&qrbuf, mailboxname) == 0) {
791                 qrbuf.QRflags2 |= QR2_SYSTEM;
792                 lputroom(&qrbuf);
793         }
794
795         /* Everything below this line can be bypassed if administratively
796            creating a user, instead of doing self-service account creation
797          */
798
799         if (become_user) {
800                 /* Now become the user we just created */
801                 memcpy(&CC->usersupp, &usbuf, sizeof(struct usersupp));
802                 strcpy(CC->curr_user, username);
803                 CC->logged_in = 1;
804         
805                 /* Check to make sure we're still who we think we are */
806                 if (getuser(&CC->usersupp, CC->curr_user)) {
807                         return (ERROR + INTERNAL_ERROR);
808                 }
809         }
810
811         lprintf(3, "New user <%s> created\n", username);
812         return (0);
813 }
814
815
816
817
818 /*
819  * cmd_newu()  -  create a new user account and log in as that user
820  */
821 void cmd_newu(char *cmdbuf)
822 {
823         int a;
824         char username[SIZ];
825
826         if (config.c_disable_newu) {
827                 cprintf("%d Self-service user account creation "
828                         "is disabled on this system.\n", ERROR);
829                 return;
830         }
831
832         if (CC->logged_in) {
833                 cprintf("%d Already logged in.\n", ERROR);
834                 return;
835         }
836         if (CC->nologin) {
837                 cprintf("%d %s: Too many users are already online (maximum is %d)\n",
838                         ERROR + MAX_SESSIONS_EXCEEDED,
839                         config.c_nodename, config.c_maxsessions);
840         }
841         extract(username, cmdbuf, 0);
842         username[25] = 0;
843         strproc(username);
844
845         if (strlen(username) == 0) {
846                 cprintf("%d You must supply a user name.\n", ERROR);
847                 return;
848         }
849
850         if ((!strcasecmp(username, "bbs")) ||
851             (!strcasecmp(username, "new")) ||
852             (!strcasecmp(username, "."))) {
853                 cprintf("%d '%s' is an invalid login name.\n", ERROR, username);
854                 return;
855         }
856
857         a = create_user(username, 1);
858
859         if (a == 0) {
860                 session_startup();
861                 logged_in_response();
862         } else if (a == ERROR + ALREADY_EXISTS) {
863                 cprintf("%d '%s' already exists.\n",
864                         ERROR + ALREADY_EXISTS, username);
865                 return;
866         } else if (a == ERROR + INTERNAL_ERROR) {
867                 cprintf("%d Internal error - user record disappeared?\n",
868                         ERROR + INTERNAL_ERROR);
869                 return;
870         } else {
871                 cprintf("%d unknown error\n", ERROR);
872         }
873 }
874
875
876
877 /*
878  * set password
879  */
880 void cmd_setp(char *new_pw)
881 {
882         if (CtdlAccessCheck(ac_logged_in)) {
883                 return;
884         }
885
886         if (CC->usersupp.uid != BBSUID) {
887                 cprintf("%d Not allowed.  Use the 'passwd' command.\n", ERROR);
888                 return;
889         }
890         strproc(new_pw);
891         if (strlen(new_pw) == 0) {
892                 cprintf("%d Password unchanged.\n", CIT_OK);
893                 return;
894         }
895         lgetuser(&CC->usersupp, CC->curr_user);
896         strcpy(CC->usersupp.password, new_pw);
897         lputuser(&CC->usersupp);
898         cprintf("%d Password changed.\n", CIT_OK);
899         lprintf(3, "Password changed for user <%s>\n", CC->curr_user);
900         PerformSessionHooks(EVT_SETPASS);
901 }
902
903
904 /*
905  * cmd_creu()  -  administratively create a new user account (do not log in to it)
906  */
907 void cmd_creu(char *cmdbuf)
908 {
909         int a;
910         char username[SIZ];
911
912         if (CtdlAccessCheck(ac_aide)) {
913                 return;
914         }
915
916         extract(username, cmdbuf, 0);
917         username[25] = 0;
918         strproc(username);
919
920         if (strlen(username) == 0) {
921                 cprintf("%d You must supply a user name.\n", ERROR);
922                 return;
923         }
924
925         a = create_user(username, 0);
926
927         if (a == 0) {
928                 cprintf("%d ok\n", CIT_OK);
929                 return;
930         } else if (a == ERROR + ALREADY_EXISTS) {
931                 cprintf("%d '%s' already exists.\n",
932                         ERROR + ALREADY_EXISTS, username);
933                 return;
934         } else {
935                 cprintf("%d An error occured creating the user account.\n", ERROR);
936         }
937 }
938
939
940
941 /*
942  * get user parameters
943  */
944 void cmd_getu(void)
945 {
946
947         if (CtdlAccessCheck(ac_logged_in))
948                 return;
949
950         getuser(&CC->usersupp, CC->curr_user);
951         cprintf("%d %d|%d|%d|\n",
952                 CIT_OK,
953                 CC->usersupp.USscreenwidth,
954                 CC->usersupp.USscreenheight,
955                 (CC->usersupp.flags & US_USER_SET)
956             );
957 }
958
959 /*
960  * set user parameters
961  */
962 void cmd_setu(char *new_parms)
963 {
964         if (CtdlAccessCheck(ac_logged_in))
965                 return;
966
967         if (num_parms(new_parms) < 3) {
968                 cprintf("%d Usage error.\n", ERROR);
969                 return;
970         }
971         lgetuser(&CC->usersupp, CC->curr_user);
972         CC->usersupp.USscreenwidth = extract_int(new_parms, 0);
973         CC->usersupp.USscreenheight = extract_int(new_parms, 1);
974         CC->usersupp.flags = CC->usersupp.flags & (~US_USER_SET);
975         CC->usersupp.flags = CC->usersupp.flags |
976             (extract_int(new_parms, 2) & US_USER_SET);
977
978         lputuser(&CC->usersupp);
979         cprintf("%d Ok\n", CIT_OK);
980 }
981
982 /*
983  * set last read pointer
984  */
985 void cmd_slrp(char *new_ptr)
986 {
987         long newlr;
988         struct visit vbuf;
989
990         if (CtdlAccessCheck(ac_logged_in)) {
991                 return;
992         }
993
994         if (!strncasecmp(new_ptr, "highest", 7)) {
995                 newlr = CC->quickroom.QRhighest;
996         } else {
997                 newlr = atol(new_ptr);
998         }
999
1000         lgetuser(&CC->usersupp, CC->curr_user);
1001
1002         CtdlGetRelationship(&vbuf, &CC->usersupp, &CC->quickroom);
1003         vbuf.v_lastseen = newlr;
1004         snprintf(vbuf.v_seen, sizeof vbuf.v_seen, "*:%ld", newlr);
1005         CtdlSetRelationship(&vbuf, &CC->usersupp, &CC->quickroom);
1006
1007         lputuser(&CC->usersupp);
1008         cprintf("%d %ld\n", CIT_OK, newlr);
1009 }
1010
1011
1012 void cmd_seen(char *argbuf) {
1013         long target_msgnum = 0L;
1014         int target_setting = 0;
1015
1016         if (CtdlAccessCheck(ac_logged_in)) {
1017                 return;
1018         }
1019
1020         if (num_parms(argbuf) != 2) {
1021                 cprintf("%d Invalid parameters\n", ERROR);
1022                 return;
1023         }
1024
1025         target_msgnum = extract_long(argbuf, 0);
1026         target_setting = extract_int(argbuf, 1);
1027
1028         CtdlSetSeen(target_msgnum, target_setting);
1029         cprintf("%d OK\n", CIT_OK);
1030 }
1031
1032
1033 void cmd_gtsn(char *argbuf) {
1034         char buf[SIZ];
1035
1036         if (CtdlAccessCheck(ac_logged_in)) {
1037                 return;
1038         }
1039
1040         CtdlGetSeen(buf);
1041         cprintf("%d %s\n", CIT_OK, buf);
1042 }
1043
1044
1045
1046 /*
1047  * INVT and KICK commands
1048  */
1049 void cmd_invt_kick(char *iuser, int op)
1050                         /* user name */
1051 {                               /* 1 = invite, 0 = kick out */
1052         struct usersupp USscratch;
1053         char bbb[SIZ];
1054         struct visit vbuf;
1055
1056         /*
1057          * These commands are only allowed by aides, room aides,
1058          * and room namespace owners
1059          */
1060         if (is_room_aide()
1061            || (atol(CC->quickroom.QRname) == CC->usersupp.usernum) ) {
1062                 /* access granted */
1063         } else {
1064                 /* access denied */
1065                 cprintf("%d Higher access or room ownership required.\n",
1066                         ERROR + HIGHER_ACCESS_REQUIRED);
1067                 return;
1068         }
1069
1070         if (!strncasecmp(CC->quickroom.QRname, config.c_baseroom,
1071                          ROOMNAMELEN)) {
1072                 cprintf("%d Can't add/remove users from this room.\n",
1073                         ERROR + NOT_HERE);
1074                 return;
1075         }
1076
1077         if (lgetuser(&USscratch, iuser) != 0) {
1078                 cprintf("%d No such user.\n", ERROR);
1079                 return;
1080         }
1081         CtdlGetRelationship(&vbuf, &USscratch, &CC->quickroom);
1082
1083         if (op == 1) {
1084                 vbuf.v_flags = vbuf.v_flags & ~V_FORGET & ~V_LOCKOUT;
1085                 vbuf.v_flags = vbuf.v_flags | V_ACCESS;
1086         }
1087         if (op == 0) {
1088                 vbuf.v_flags = vbuf.v_flags & ~V_ACCESS;
1089                 vbuf.v_flags = vbuf.v_flags | V_FORGET | V_LOCKOUT;
1090         }
1091         CtdlSetRelationship(&vbuf, &USscratch, &CC->quickroom);
1092
1093         lputuser(&USscratch);
1094
1095         /* post a message in Aide> saying what we just did */
1096         snprintf(bbb, sizeof bbb, "%s %s %s> by %s\n",
1097                 iuser,
1098                 ((op == 1) ? "invited to" : "kicked out of"),
1099                 CC->quickroom.QRname,
1100                 CC->usersupp.fullname);
1101         aide_message(bbb);
1102
1103         cprintf("%d %s %s %s.\n",
1104                 CIT_OK, iuser,
1105                 ((op == 1) ? "invited to" : "kicked out of"),
1106                 CC->quickroom.QRname);
1107         return;
1108 }
1109
1110
1111 /*
1112  * Forget (Zap) the current room (API call)
1113  * Returns 0 on success
1114  */
1115 int CtdlForgetThisRoom(void) {
1116         struct visit vbuf;
1117
1118         /* On some systems, Aides are not allowed to forget rooms */
1119         if (is_aide() && (config.c_aide_zap == 0)
1120            && ((CC->quickroom.QRflags & QR_MAILBOX) == 0)  ) {
1121                 return(1);
1122         }
1123
1124         lgetuser(&CC->usersupp, CC->curr_user);
1125         CtdlGetRelationship(&vbuf, &CC->usersupp, &CC->quickroom);
1126
1127         vbuf.v_flags = vbuf.v_flags | V_FORGET;
1128         vbuf.v_flags = vbuf.v_flags & ~V_ACCESS;
1129
1130         CtdlSetRelationship(&vbuf, &CC->usersupp, &CC->quickroom);
1131         lputuser(&CC->usersupp);
1132
1133         /* Return to the Lobby, so we don't end up in an undefined room */
1134         usergoto(config.c_baseroom, 0, 0, NULL, NULL);
1135         return(0);
1136
1137 }
1138
1139
1140 /*
1141  * forget (Zap) the current room
1142  */
1143 void cmd_forg(void)
1144 {
1145
1146         if (CtdlAccessCheck(ac_logged_in)) {
1147                 return;
1148         }
1149
1150         if (CtdlForgetThisRoom() == 0) {
1151                 cprintf("%d Ok\n", CIT_OK);
1152         }
1153         else {
1154                 cprintf("%d You may not forget this room.\n", ERROR);
1155         }
1156 }
1157
1158 /*
1159  * Get Next Unregistered User
1160  */
1161 void cmd_gnur(void)
1162 {
1163         struct cdbdata *cdbus;
1164         struct usersupp usbuf;
1165
1166         if (CtdlAccessCheck(ac_aide)) {
1167                 return;
1168         }
1169
1170         if ((CitControl.MMflags & MM_VALID) == 0) {
1171                 cprintf("%d There are no unvalidated users.\n", CIT_OK);
1172                 return;
1173         }
1174
1175         /* There are unvalidated users.  Traverse the usersupp database,
1176          * and return the first user we find that needs validation.
1177          */
1178         cdb_rewind(CDB_USERSUPP);
1179         while (cdbus = cdb_next_item(CDB_USERSUPP), cdbus != NULL) {
1180                 memset(&usbuf, 0, sizeof(struct usersupp));
1181                 memcpy(&usbuf, cdbus->ptr,
1182                        ((cdbus->len > sizeof(struct usersupp)) ?
1183                         sizeof(struct usersupp) : cdbus->len));
1184                 cdb_free(cdbus);
1185                 if ((usbuf.flags & US_NEEDVALID)
1186                     && (usbuf.axlevel > 0)) {
1187                         cprintf("%d %s\n", MORE_DATA, usbuf.fullname);
1188                         cdb_close_cursor(CDB_USERSUPP);
1189                         return;
1190                 }
1191         }
1192
1193         /* If we get to this point, there are no more unvalidated users.
1194          * Therefore we clear the "users need validation" flag.
1195          */
1196
1197         begin_critical_section(S_CONTROL);
1198         get_control();
1199         CitControl.MMflags = CitControl.MMflags & (~MM_VALID);
1200         put_control();
1201         end_critical_section(S_CONTROL);
1202         cprintf("%d *** End of registration.\n", CIT_OK);
1203
1204
1205 }
1206
1207
1208 /*
1209  * validate a user
1210  */
1211 void cmd_vali(char *v_args)
1212 {
1213         char user[SIZ];
1214         int newax;
1215         struct usersupp userbuf;
1216
1217         extract(user, v_args, 0);
1218         newax = extract_int(v_args, 1);
1219
1220         if (CtdlAccessCheck(ac_aide)) {
1221                 return;
1222         }
1223
1224         if (lgetuser(&userbuf, user) != 0) {
1225                 cprintf("%d '%s' not found.\n", ERROR + NO_SUCH_USER, user);
1226                 return;
1227         }
1228
1229         userbuf.axlevel = newax;
1230         userbuf.flags = (userbuf.flags & ~US_NEEDVALID);
1231
1232         lputuser(&userbuf);
1233
1234         /* If the access level was set to zero, delete the user */
1235         if (newax == 0) {
1236                 if (purge_user(user) == 0) {
1237                         cprintf("%d %s Deleted.\n", CIT_OK, userbuf.fullname);
1238                         return;
1239                 }
1240         }
1241         cprintf("%d User '%s' validated.\n", CIT_OK, userbuf.fullname);
1242 }
1243
1244
1245
1246 /* 
1247  *  Traverse the user file...
1248  */
1249 void ForEachUser(void (*CallBack) (struct usersupp * EachUser, void *out_data),
1250                  void *in_data)
1251 {
1252         struct usersupp usbuf;
1253         struct cdbdata *cdbus;
1254
1255         cdb_rewind(CDB_USERSUPP);
1256
1257         while (cdbus = cdb_next_item(CDB_USERSUPP), cdbus != NULL) {
1258                 memset(&usbuf, 0, sizeof(struct usersupp));
1259                 memcpy(&usbuf, cdbus->ptr,
1260                        ((cdbus->len > sizeof(struct usersupp)) ?
1261                         sizeof(struct usersupp) : cdbus->len));
1262                 cdb_free(cdbus);
1263                 (*CallBack) (&usbuf, in_data);
1264         }
1265 }
1266
1267
1268 /*
1269  * List one user (this works with cmd_list)
1270  */
1271 void ListThisUser(struct usersupp *usbuf, void *data)
1272 {
1273         if (usbuf->axlevel > 0) {
1274                 if ((CC->usersupp.axlevel >= 6)
1275                     || ((usbuf->flags & US_UNLISTED) == 0)
1276                     || ((CC->internal_pgm))) {
1277                         cprintf("%s|%d|%ld|%ld|%ld|%ld|",
1278                                 usbuf->fullname,
1279                                 usbuf->axlevel,
1280                                 usbuf->usernum,
1281                                 (long)usbuf->lastcall,
1282                                 usbuf->timescalled,
1283                                 usbuf->posted);
1284                         if (CC->usersupp.axlevel >= 6)
1285                                 cprintf("%s", usbuf->password);
1286                         cprintf("\n");
1287                 }
1288         }
1289 }
1290
1291 /* 
1292  *  List users
1293  */
1294 void cmd_list(void)
1295 {
1296         cprintf("%d \n", LISTING_FOLLOWS);
1297         ForEachUser(ListThisUser, NULL);
1298         cprintf("000\n");
1299 }
1300
1301
1302
1303
1304 /*
1305  * assorted info we need to check at login
1306  */
1307 void cmd_chek(void)
1308 {
1309         int mail = 0;
1310         int regis = 0;
1311         int vali = 0;
1312
1313         if (CtdlAccessCheck(ac_logged_in)) {
1314                 return;
1315         }
1316
1317         getuser(&CC->usersupp, CC->curr_user);  /* no lock is needed here */
1318         if ((REGISCALL != 0) && ((CC->usersupp.flags & US_REGIS) == 0))
1319                 regis = 1;
1320
1321         if (CC->usersupp.axlevel >= 6) {
1322                 get_control();
1323                 if (CitControl.MMflags & MM_VALID)
1324                         vali = 1;
1325         }
1326
1327         /* check for mail */
1328         mail = InitialMailCheck();
1329
1330         cprintf("%d %d|%d|%d|%s|\n", CIT_OK, mail, regis, vali, CC->cs_inet_email);
1331 }
1332
1333
1334 /*
1335  * check to see if a user exists
1336  */
1337 void cmd_qusr(char *who)
1338 {
1339         struct usersupp usbuf;
1340
1341         if (getuser(&usbuf, who) == 0) {
1342                 cprintf("%d %s\n", CIT_OK, usbuf.fullname);
1343         } else {
1344                 cprintf("%d No such user.\n", ERROR + NO_SUCH_USER);
1345         }
1346 }
1347
1348
1349 /*
1350  * Administrative Get User Parameters
1351  */
1352 void cmd_agup(char *cmdbuf)
1353 {
1354         struct usersupp usbuf;
1355         char requested_user[SIZ];
1356
1357         if (CtdlAccessCheck(ac_aide)) {
1358                 return;
1359         }
1360
1361         extract(requested_user, cmdbuf, 0);
1362         if (getuser(&usbuf, requested_user) != 0) {
1363                 cprintf("%d No such user.\n", ERROR + NO_SUCH_USER);
1364                 return;
1365         }
1366         cprintf("%d %s|%s|%u|%ld|%ld|%d|%ld|%ld|%d\n",
1367                 CIT_OK,
1368                 usbuf.fullname,
1369                 usbuf.password,
1370                 usbuf.flags,
1371                 usbuf.timescalled,
1372                 usbuf.posted,
1373                 (int) usbuf.axlevel,
1374                 usbuf.usernum,
1375                 (long)usbuf.lastcall,
1376                 usbuf.USuserpurge);
1377 }
1378
1379
1380
1381 /*
1382  * Administrative Set User Parameters
1383  */
1384 void cmd_asup(char *cmdbuf)
1385 {
1386         struct usersupp usbuf;
1387         char requested_user[SIZ];
1388         char notify[SIZ];
1389         int np;
1390         int newax;
1391         int deleted = 0;
1392
1393         if (CtdlAccessCheck(ac_aide))
1394                 return;
1395
1396         extract(requested_user, cmdbuf, 0);
1397         if (lgetuser(&usbuf, requested_user) != 0) {
1398                 cprintf("%d No such user.\n", ERROR + NO_SUCH_USER);
1399                 return;
1400         }
1401         np = num_parms(cmdbuf);
1402         if (np > 1)
1403                 extract(usbuf.password, cmdbuf, 1);
1404         if (np > 2)
1405                 usbuf.flags = extract_int(cmdbuf, 2);
1406         if (np > 3)
1407                 usbuf.timescalled = extract_int(cmdbuf, 3);
1408         if (np > 4)
1409                 usbuf.posted = extract_int(cmdbuf, 4);
1410         if (np > 5) {
1411                 newax = extract_int(cmdbuf, 5);
1412                 if ((newax >= 0) && (newax <= 6)) {
1413                         usbuf.axlevel = extract_int(cmdbuf, 5);
1414                 }
1415         }
1416         if (np > 7) {
1417                 usbuf.lastcall = extract_long(cmdbuf, 7);
1418         }
1419         if (np > 8) {
1420                 usbuf.USuserpurge = extract_int(cmdbuf, 8);
1421         }
1422         lputuser(&usbuf);
1423         if (usbuf.axlevel == 0) {
1424                 if (purge_user(requested_user) == 0) {
1425                         deleted = 1;
1426                 }
1427         }
1428
1429         if (deleted) {
1430                 sprintf(notify, "User <%s> deleted by %s\n",
1431                         usbuf.fullname, CC->usersupp.fullname);
1432                 aide_message(notify);
1433         }
1434
1435         cprintf("%d Ok", CIT_OK);
1436         if (deleted)
1437                 cprintf(" (%s deleted)", requested_user);
1438         cprintf("\n");
1439 }
1440
1441
1442
1443 /*
1444  * Check to see if the user who we just sent mail to is logged in.  If yes,
1445  * bump the 'new mail' counter for their session.  That enables them to
1446  * receive a new mail notification without having to hit the database.
1447  */
1448 void BumpNewMailCounter(long which_user) {
1449         struct CitContext *ptr;
1450
1451         begin_critical_section(S_SESSION_TABLE);
1452
1453         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1454                 if (ptr->usersupp.usernum == which_user) {
1455                         ptr->newmail += 1;
1456                 }
1457         }
1458
1459         end_critical_section(S_SESSION_TABLE);
1460 }
1461
1462
1463 /*
1464  * Count the number of new mail messages the user has
1465  */
1466 int NewMailCount()
1467 {
1468         int num_newmsgs = 0;
1469
1470         num_newmsgs = CC->newmail;
1471         CC->newmail = 0;
1472
1473         return (num_newmsgs);
1474 }
1475
1476
1477 /*
1478  * Count the number of new mail messages the user has
1479  */
1480 int InitialMailCheck()
1481 {
1482         int num_newmsgs = 0;
1483         int a;
1484         char mailboxname[ROOMNAMELEN];
1485         struct quickroom mailbox;
1486         struct visit vbuf;
1487         struct cdbdata *cdbfr;
1488         long *msglist = NULL;
1489         int num_msgs = 0;
1490
1491         MailboxName(mailboxname, sizeof mailboxname, &CC->usersupp, MAILROOM);
1492         if (getroom(&mailbox, mailboxname) != 0)
1493                 return (0);
1494         CtdlGetRelationship(&vbuf, &CC->usersupp, &mailbox);
1495
1496         cdbfr = cdb_fetch(CDB_MSGLISTS, &mailbox.QRnumber, sizeof(long));
1497
1498         if (cdbfr != NULL) {
1499                 msglist = mallok(cdbfr->len);
1500                 memcpy(msglist, cdbfr->ptr, cdbfr->len);
1501                 num_msgs = cdbfr->len / sizeof(long);
1502                 cdb_free(cdbfr);
1503         }
1504         if (num_msgs > 0)
1505                 for (a = 0; a < num_msgs; ++a) {
1506                         if (msglist[a] > 0L) {
1507                                 if (msglist[a] > vbuf.v_lastseen) {
1508                                         ++num_newmsgs;
1509                                 }
1510                         }
1511                 }
1512         if (msglist != NULL)
1513                 phree(msglist);
1514
1515         return (num_newmsgs);
1516 }
1517
1518
1519
1520 /*
1521  * Set the preferred view for the current user/room combination
1522  */
1523 void cmd_view(char *cmdbuf) {
1524         int requested_view;
1525         struct visit vbuf;
1526
1527         if (CtdlAccessCheck(ac_logged_in)) {
1528                 return;
1529         }
1530
1531         requested_view = extract_int(cmdbuf, 0);
1532
1533         CtdlGetRelationship(&vbuf, &CC->usersupp, &CC->quickroom);
1534         vbuf.v_view = requested_view;
1535         CtdlSetRelationship(&vbuf, &CC->usersupp, &CC->quickroom);
1536         
1537         cprintf("%d ok\n", CIT_OK);
1538 }