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