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