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