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