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