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