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