Added a RENU command (REName a User)
[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         for (i=0; !IsEmptyStr(&CC->cs_inet_email[i]); ++i) {
594                 if (isspace(CC->cs_inet_email[i])) {
595                         CC->cs_inet_email[i] = '_';
596                 }
597         }
598
599         /* Create any personal rooms required by the system.
600          * (Technically, MAILROOM should be there already, but just in case...)
601          */
602         create_room(MAILROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
603         create_room(SENTITEMS, 4, "", 0, 1, 0, VIEW_MAILBOX);
604         create_room(USERTRASHROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
605
606         /* Run any startup routines registered by loadable modules */
607         PerformSessionHooks(EVT_LOGIN);
608
609         /* Enter the lobby */
610         usergoto(config.c_baseroom, 0, 0, NULL, NULL);
611 }
612
613
614 void logged_in_response(void)
615 {
616         cprintf("%d %s|%d|%ld|%ld|%u|%ld|%ld\n",
617                 CIT_OK, CC->user.fullname, CC->user.axlevel,
618                 CC->user.timescalled, CC->user.posted,
619                 CC->user.flags, CC->user.usernum,
620                 CC->previous_login);
621 }
622
623
624
625 /* 
626  * misc things to be taken care of when a user is logged out
627  */
628 void logout(struct CitContext *who)
629 {
630         /*
631          * Clear out some session data.  Most likely, the CitContext for this
632          * session is about to get nuked when the session disconnects, but
633          * since it's possible to log in again without reconnecting, we cannot
634          * make that assumption.
635          */
636         strcpy(who->fake_username, "");
637         strcpy(who->fake_hostname, "");
638         strcpy(who->fake_roomname, "");
639         who->logged_in = 0;
640
641         /*
642          * If there is a download in progress, abort it.
643          */
644         if (who->download_fp != NULL) {
645                 fclose(who->download_fp);
646                 who->download_fp = NULL;
647         }
648
649         /*
650          * If there is an upload in progress, abort it.
651          */
652         if (who->upload_fp != NULL) {
653                 abort_upl(who);
654         }
655
656         /*
657          * If we were talking to a network node, we're not anymore...
658          */
659         if (!IsEmptyStr(who->net_node)) {
660                 network_talking_to(who->net_node, NTT_REMOVE);
661         }
662
663         /* Do modular stuff... */
664         PerformSessionHooks(EVT_LOGOUT);
665         
666         /* Check to see if the user was deleted whilst logged in and purge them if necessary */
667         if (who->user.axlevel == 0)
668                 purge_user(who->user.fullname);
669
670         /* Free any output buffers */
671         if (who->output_buffer != NULL) {
672                 unbuffer_output();
673         }
674 }
675
676 /*
677  * Validate a password on the host unix system by talking to the chkpwd daemon
678  */
679 static int validpw(uid_t uid, const char *pass)
680 {
681         char buf[256];
682
683         if (IsEmptyStr(pass)) {
684                 lprintf(CTDL_DEBUG, "refusing to check empty password for uid=%d using chkpwd...\n", uid);
685                 return 0;
686         }
687
688         lprintf(CTDL_DEBUG, "Validating password for uid=%d using chkpwd...\n", uid);
689
690         begin_critical_section(S_CHKPWD);
691         write(chkpwd_write_pipe[1], &uid, sizeof(uid_t));
692         write(chkpwd_write_pipe[1], pass, 256);
693         read(chkpwd_read_pipe[0], buf, 4);
694         end_critical_section(S_CHKPWD);
695
696         if (!strncmp(buf, "PASS", 4)) {
697                 lprintf(CTDL_DEBUG, "...pass\n");
698                 return(1);
699         }
700
701         lprintf(CTDL_DEBUG, "...fail\n");
702         return 0;
703 }
704
705 /* 
706  * Start up the chkpwd daemon so validpw() has something to talk to
707  */
708 void start_chkpwd_daemon(void) {
709         pid_t chkpwd_pid;
710         struct stat filestats;
711         int i;
712
713         lprintf(CTDL_DEBUG, "Starting chkpwd daemon for host authentication mode\n");
714
715         if ((stat(file_chkpwd, &filestats)==-1) ||
716             (filestats.st_size==0)){
717                 printf("didn't find chkpwd daemon in %s: %s\n", file_chkpwd, strerror(errno));
718                 abort();
719         }
720         if (pipe(chkpwd_write_pipe) != 0) {
721                 lprintf(CTDL_EMERG, "Unable to create pipe for chkpwd daemon: %s\n", strerror(errno));
722                 abort();
723         }
724         if (pipe(chkpwd_read_pipe) != 0) {
725                 lprintf(CTDL_EMERG, "Unable to create pipe for chkpwd daemon: %s\n", strerror(errno));
726                 abort();
727         }
728
729         chkpwd_pid = fork();
730         if (chkpwd_pid < 0) {
731                 lprintf(CTDL_EMERG, "Unable to fork chkpwd daemon: %s\n", strerror(errno));
732                 abort();
733         }
734         if (chkpwd_pid == 0) {
735                 lprintf(CTDL_DEBUG, "Now calling dup2() write\n");
736                 dup2(chkpwd_write_pipe[0], 0);
737                 lprintf(CTDL_DEBUG, "Now calling dup2() write\n");
738                 dup2(chkpwd_read_pipe[1], 1);
739                 lprintf(CTDL_DEBUG, "Now closing stuff\n");
740                 for (i=2; i<256; ++i) close(i);
741                 lprintf(CTDL_DEBUG, "Now calling execl(%s)\n", file_chkpwd);
742                 execl(file_chkpwd, file_chkpwd, NULL);
743                 lprintf(CTDL_EMERG, "Unable to exec chkpwd daemon: %s\n", strerror(errno));
744                 abort();
745                 exit(errno);
746         }
747 }
748
749
750 void do_login()
751 {
752         (CC->logged_in) = 1;
753         session_startup();
754 }
755
756
757 int CtdlTryPassword(char *password)
758 {
759         int code;
760
761         if ((CC->logged_in)) {
762                 lprintf(CTDL_WARNING, "CtdlTryPassword: already logged in\n");
763                 return pass_already_logged_in;
764         }
765         if (!strcmp(CC->curr_user, NLI)) {
766                 lprintf(CTDL_WARNING, "CtdlTryPassword: no user selected\n");
767                 return pass_no_user;
768         }
769         if (getuser(&CC->user, CC->curr_user)) {
770                 lprintf(CTDL_ERR, "CtdlTryPassword: internal error\n");
771                 return pass_internal_error;
772         }
773         if (password == NULL) {
774                 lprintf(CTDL_INFO, "CtdlTryPassword: NULL password string supplied\n");
775                 return pass_wrong_password;
776         }
777         code = (-1);
778
779         if (CC->is_master) {
780                 code = strcmp(password, config.c_master_pass);
781         }
782
783         else if (config.c_auth_mode == AUTHMODE_HOST) {
784
785                 /* host auth mode */
786
787                 if (validpw(CC->user.uid, password)) {
788                         code = 0;
789
790                         /*
791                          * sooper-seekrit hack: populate the password field in the
792                          * citadel database with the password that the user typed,
793                          * if it's correct.  This allows most sites to convert from
794                          * host auth to native auth if they want to.  If you think
795                          * this is a security hazard, comment it out.
796                          */
797
798                         lgetuser(&CC->user, CC->curr_user);
799                         safestrncpy(CC->user.password, password, sizeof CC->user.password);
800                         lputuser(&CC->user);
801
802                         /*
803                          * (sooper-seekrit hack ends here)
804                          */
805
806                 }
807                 else {
808                         code = (-1);
809                 }
810         }
811
812         else {
813
814                 /* native auth mode */
815
816                 strproc(password);
817                 strproc(CC->user.password);
818                 code = strcasecmp(CC->user.password, password);
819                 strproc(password);
820                 strproc(CC->user.password);
821                 code = strcasecmp(CC->user.password, password);
822         }
823
824         if (!code) {
825                 do_login();
826                 return pass_ok;
827         } else {
828                 lprintf(CTDL_WARNING, "Bad password specified for <%s>\n", CC->curr_user);
829                 return pass_wrong_password;
830         }
831 }
832
833
834 void cmd_pass(char *buf)
835 {
836         char password[256];
837         int a;
838
839         extract_token(password, buf, 0, '|', sizeof password);
840         a = CtdlTryPassword(password);
841
842         switch (a) {
843         case pass_already_logged_in:
844                 cprintf("%d Already logged in.\n", ERROR + ALREADY_LOGGED_IN);
845                 return;
846         case pass_no_user:
847                 cprintf("%d You must send a name with USER first.\n",
848                         ERROR + USERNAME_REQUIRED);
849                 return;
850         case pass_wrong_password:
851                 cprintf("%d Wrong password.\n", ERROR + PASSWORD_REQUIRED);
852                 return;
853         case pass_ok:
854                 logged_in_response();
855                 return;
856         }
857 }
858
859
860
861 /*
862  * Delete a user record *and* all of its related resources.
863  */
864 int purge_user(char pname[])
865 {
866         char filename[64];
867         struct ctdluser usbuf;
868         char usernamekey[USERNAME_SIZE];
869         struct CitContext *ccptr;
870         int user_is_logged_in = 0;
871
872         makeuserkey(usernamekey, pname);
873
874         /* If the name is empty we can't find them in the DB any way so just return */
875         if (IsEmptyStr(pname))
876                 return (ERROR + NO_SUCH_USER);
877
878         if (getuser(&usbuf, pname) != 0) {
879                 lprintf(CTDL_ERR, "Cannot purge user <%s> - not found\n", pname);
880                 return (ERROR + NO_SUCH_USER);
881         }
882         /* Don't delete a user who is currently logged in.  Instead, just
883          * set the access level to 0, and let the account get swept up
884          * during the next purge.
885          */
886         user_is_logged_in = 0;
887         begin_critical_section(S_SESSION_TABLE);
888         for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
889                 if (ccptr->user.usernum == usbuf.usernum) {
890                         user_is_logged_in = 1;
891                 }
892         }
893         end_critical_section(S_SESSION_TABLE);
894         if (user_is_logged_in == 1) {
895                 lprintf(CTDL_WARNING, "User <%s> is logged in; not deleting.\n", pname);
896                 usbuf.axlevel = 0;
897                 putuser(&usbuf);
898                 return (1);
899         }
900         lprintf(CTDL_NOTICE, "Deleting user <%s>\n", pname);
901
902         /* Perform any purge functions registered by server extensions */
903         PerformUserHooks(&usbuf, EVT_PURGEUSER);
904
905         /* delete any existing user/room relationships */
906         cdb_delete(CDB_VISIT, &usbuf.usernum, sizeof(long));
907
908         /* delete the userlog entry */
909         cdb_delete(CDB_USERS, usernamekey, strlen(usernamekey));
910
911         /* remove the user's bio file */
912         snprintf(filename, 
913                          sizeof filename, 
914                          "%s/%ld",
915                          ctdl_bio_dir,
916                          usbuf.usernum);
917         unlink(filename);
918
919         /* remove the user's picture */
920         snprintf(filename, 
921                          sizeof filename, 
922                          "%s/%ld.gif",
923                          ctdl_image_dir,
924                          usbuf.usernum);
925         unlink(filename);
926
927         return (0);
928 }
929
930
931 /*
932  * create_user()  -  back end processing to create a new user
933  *
934  * Set 'newusername' to the desired account name.
935  * Set 'become_user' to nonzero if this is self-service account creation and we want
936  * to actually log in as the user we just created, otherwise set it to 0.
937  */
938 int create_user(char *newusername, int become_user)
939 {
940         struct ctdluser usbuf;
941         struct ctdlroom qrbuf;
942         char username[256];
943         char mailboxname[ROOMNAMELEN];
944         char buf[SIZ];
945         uid_t uid = (-1);
946
947         safestrncpy(username, newusername, sizeof username);
948         strproc(username);
949
950         if (config.c_auth_mode == AUTHMODE_HOST) {
951
952                 /* host auth mode */
953
954                 struct passwd pd;
955                 struct passwd *tempPwdPtr;
956                 char pwdbuffer[256];
957         
958 #ifdef HAVE_GETPWNAM_R
959 #ifdef SOLARIS_GETPWUID
960                 tempPwdPtr = getpwnam_r(username, &pd, pwdbuffer, sizeof(pwdbuffer));
961 #else // SOLARIS_GETPWUID
962                 getpwnam_r(username, &pd, pwdbuffer, sizeof pwdbuffer, &tempPwdPtr);
963 #endif // SOLARIS_GETPWUID
964 #else // HAVE_GETPWNAM_R
965                 tempPwdPtr = NULL;
966 #endif // HAVE_GETPWNAM_R
967                 if (tempPwdPtr != NULL) {
968                         extract_token(username, pd.pw_gecos, 0, ',', sizeof username);
969                         uid = pd.pw_uid;
970                         if (IsEmptyStr (username))
971                         {
972                                 lprintf (CTDL_EMERG, 
973                                          "Can't find Realname for user %s [%d] in the Host Auth Database; giving up.\n", 
974                                          newusername, pd.pw_uid);
975                                 snprintf(buf, SIZ, 
976                                          "Can't find Realname for user %s [%d] in the Host Auth Database; giving up.\n",
977                                          newusername, pd.pw_uid);
978                                 aide_message(buf, "User Creation Failure Notice");
979
980                         }
981                 }
982                 else {
983                         return (ERROR + NO_SUCH_USER);
984                 }
985         }
986
987         if (!getuser(&usbuf, username)) {
988                 return (ERROR + ALREADY_EXISTS);
989         }
990
991         /* Go ahead and initialize a new user record */
992         memset(&usbuf, 0, sizeof(struct ctdluser));
993         safestrncpy(usbuf.fullname, username, sizeof usbuf.fullname);
994         strcpy(usbuf.password, "");
995         usbuf.uid = uid;
996
997         /* These are the default flags on new accounts */
998         usbuf.flags = US_LASTOLD | US_DISAPPEAR | US_PAGINATOR | US_FLOORS;
999
1000         usbuf.timescalled = 0;
1001         usbuf.posted = 0;
1002         usbuf.axlevel = config.c_initax;
1003         usbuf.USscreenwidth = 80;
1004         usbuf.USscreenheight = 24;
1005         usbuf.lastcall = time(NULL);
1006
1007         /* fetch a new user number */
1008         usbuf.usernum = get_new_user_number();
1009
1010         /* The very first user created on the system will always be an Aide */
1011         if (usbuf.usernum == 1L) {
1012                 usbuf.axlevel = 6;
1013         }
1014
1015         /* add user to userlog */
1016         putuser(&usbuf);
1017
1018         /*
1019          * Give the user a private mailbox and a configuration room.
1020          * Make the latter an invisible system room.
1021          */
1022         MailboxName(mailboxname, sizeof mailboxname, &usbuf, MAILROOM);
1023         create_room(mailboxname, 5, "", 0, 1, 1, VIEW_MAILBOX);
1024
1025         MailboxName(mailboxname, sizeof mailboxname, &usbuf, USERCONFIGROOM);
1026         create_room(mailboxname, 5, "", 0, 1, 1, VIEW_BBS);
1027         if (lgetroom(&qrbuf, mailboxname) == 0) {
1028                 qrbuf.QRflags2 |= QR2_SYSTEM;
1029                 lputroom(&qrbuf);
1030         }
1031
1032         /* Perform any create functions registered by server extensions */
1033         PerformUserHooks(&usbuf, EVT_NEWUSER);
1034
1035         /* Everything below this line can be bypassed if administratively
1036          * creating a user, instead of doing self-service account creation
1037          */
1038
1039         if (become_user) {
1040                 /* Now become the user we just created */
1041                 memcpy(&CC->user, &usbuf, sizeof(struct ctdluser));
1042                 safestrncpy(CC->curr_user, username, sizeof CC->curr_user);
1043                 CC->logged_in = 1;
1044         
1045                 /* Check to make sure we're still who we think we are */
1046                 if (getuser(&CC->user, CC->curr_user)) {
1047                         return (ERROR + INTERNAL_ERROR);
1048                 }
1049         }
1050         
1051         snprintf(buf, SIZ, 
1052                 "New user account <%s> has been created, from host %s [%s].\n",
1053                 username,
1054                 CC->cs_host,
1055                 CC->cs_addr
1056         );
1057         aide_message(buf, "User Creation Notice");
1058         lprintf(CTDL_NOTICE, "New user <%s> created\n", username);
1059         return (0);
1060 }
1061
1062
1063
1064
1065 /*
1066  * cmd_newu()  -  create a new user account and log in as that user
1067  */
1068 void cmd_newu(char *cmdbuf)
1069 {
1070         int a;
1071         char username[26];
1072
1073         if (config.c_auth_mode != AUTHMODE_NATIVE) {
1074                 cprintf("%d This system does not use native mode authentication.\n",
1075                         ERROR + NOT_HERE);
1076                 return;
1077         }
1078
1079         if (config.c_disable_newu) {
1080                 cprintf("%d Self-service user account creation "
1081                         "is disabled on this system.\n", ERROR + NOT_HERE);
1082                 return;
1083         }
1084
1085         if (CC->logged_in) {
1086                 cprintf("%d Already logged in.\n", ERROR + ALREADY_LOGGED_IN);
1087                 return;
1088         }
1089         if (CC->nologin) {
1090                 cprintf("%d %s: Too many users are already online (maximum is %d)\n",
1091                         ERROR + MAX_SESSIONS_EXCEEDED,
1092                         config.c_nodename, config.c_maxsessions);
1093         }
1094         extract_token(username, cmdbuf, 0, '|', sizeof username);
1095         username[25] = 0;
1096         strproc(username);
1097
1098         if (IsEmptyStr(username)) {
1099                 cprintf("%d You must supply a user name.\n", ERROR + USERNAME_REQUIRED);
1100                 return;
1101         }
1102
1103         if ((!strcasecmp(username, "bbs")) ||
1104             (!strcasecmp(username, "new")) ||
1105             (!strcasecmp(username, "."))) {
1106                 cprintf("%d '%s' is an invalid login name.\n", ERROR + ILLEGAL_VALUE, username);
1107                 return;
1108         }
1109
1110         a = create_user(username, 1);
1111
1112         if (a == 0) {
1113                 session_startup();
1114                 logged_in_response();
1115         } else if (a == ERROR + ALREADY_EXISTS) {
1116                 cprintf("%d '%s' already exists.\n",
1117                         ERROR + ALREADY_EXISTS, username);
1118                 return;
1119         } else if (a == ERROR + INTERNAL_ERROR) {
1120                 cprintf("%d Internal error - user record disappeared?\n",
1121                         ERROR + INTERNAL_ERROR);
1122                 return;
1123         } else {
1124                 cprintf("%d unknown error\n", ERROR + INTERNAL_ERROR);
1125         }
1126 }
1127
1128
1129
1130 /*
1131  * set password
1132  */
1133 void cmd_setp(char *new_pw)
1134 {
1135         if (CtdlAccessCheck(ac_logged_in)) {
1136                 return;
1137         }
1138         if ( (CC->user.uid != CTDLUID) && (CC->user.uid != (-1)) ) {
1139                 cprintf("%d Not allowed.  Use the 'passwd' command.\n", ERROR + NOT_HERE);
1140                 return;
1141         }
1142         if (CC->is_master) {
1143                 cprintf("%d The master prefix password cannot be changed with this command.\n",
1144                         ERROR + NOT_HERE);
1145                 return;
1146         }
1147         strproc(new_pw);
1148         if (IsEmptyStr(new_pw)) {
1149                 cprintf("%d Password unchanged.\n", CIT_OK);
1150                 return;
1151         }
1152         lgetuser(&CC->user, CC->curr_user);
1153         safestrncpy(CC->user.password, new_pw, sizeof(CC->user.password));
1154         lputuser(&CC->user);
1155         cprintf("%d Password changed.\n", CIT_OK);
1156         lprintf(CTDL_INFO, "Password changed for user <%s>\n", CC->curr_user);
1157         PerformSessionHooks(EVT_SETPASS);
1158 }
1159
1160
1161 /*
1162  * cmd_creu() - administratively create a new user account (do not log in to it)
1163  */
1164 void cmd_creu(char *cmdbuf)
1165 {
1166         int a;
1167         char username[26];
1168         char password[32];
1169         struct ctdluser tmp;
1170
1171         if (CtdlAccessCheck(ac_aide)) {
1172                 return;
1173         }
1174
1175         extract_token(username, cmdbuf, 0, '|', sizeof username);
1176         extract_token(password, cmdbuf, 1, '|', sizeof password);
1177         username[25] = 0;
1178         password[31] = 0;
1179         strproc(username);
1180         strproc(password);
1181
1182         if (IsEmptyStr(username)) {
1183                 cprintf("%d You must supply a user name.\n", ERROR + USERNAME_REQUIRED);
1184                 return;
1185         }
1186
1187         a = create_user(username, 0);
1188
1189         if (a == 0) {
1190                 if (!IsEmptyStr(password)) {
1191                         lgetuser(&tmp, username);
1192                         safestrncpy(tmp.password, password, sizeof(tmp.password));
1193                         lputuser(&tmp);
1194                 }
1195                 cprintf("%d User '%s' created %s.\n", CIT_OK, username,
1196                                 (!IsEmptyStr(password)) ? "and password set" :
1197                                 "with no password");
1198                 return;
1199         } else if (a == ERROR + ALREADY_EXISTS) {
1200                 cprintf("%d '%s' already exists.\n", ERROR + ALREADY_EXISTS, username);
1201                 return;
1202         } else if ( (config.c_auth_mode != AUTHMODE_NATIVE) && (a == ERROR + NO_SUCH_USER) ) {
1203                 cprintf("%d User accounts are not created within Citadel in host authentication mode.\n",
1204                         ERROR + NO_SUCH_USER);
1205                 return;
1206         } else {
1207                 cprintf("%d An error occurred creating the user account.\n", ERROR + INTERNAL_ERROR);
1208         }
1209 }
1210
1211
1212
1213 /*
1214  * get user parameters
1215  */
1216 void cmd_getu(void)
1217 {
1218
1219         if (CtdlAccessCheck(ac_logged_in))
1220                 return;
1221
1222         getuser(&CC->user, CC->curr_user);
1223         cprintf("%d %d|%d|%d|\n",
1224                 CIT_OK,
1225                 CC->user.USscreenwidth,
1226                 CC->user.USscreenheight,
1227                 (CC->user.flags & US_USER_SET)
1228             );
1229 }
1230
1231 /*
1232  * set user parameters
1233  */
1234 void cmd_setu(char *new_parms)
1235 {
1236         if (CtdlAccessCheck(ac_logged_in))
1237                 return;
1238
1239         if (num_parms(new_parms) < 3) {
1240                 cprintf("%d Usage error.\n", ERROR + ILLEGAL_VALUE);
1241                 return;
1242         }
1243         lgetuser(&CC->user, CC->curr_user);
1244         CC->user.USscreenwidth = extract_int(new_parms, 0);
1245         CC->user.USscreenheight = extract_int(new_parms, 1);
1246         CC->user.flags = CC->user.flags & (~US_USER_SET);
1247         CC->user.flags = CC->user.flags |
1248             (extract_int(new_parms, 2) & US_USER_SET);
1249
1250         lputuser(&CC->user);
1251         cprintf("%d Ok\n", CIT_OK);
1252 }
1253
1254 /*
1255  * set last read pointer
1256  */
1257 void cmd_slrp(char *new_ptr)
1258 {
1259         long newlr;
1260         struct visit vbuf;
1261         struct visit original_vbuf;
1262
1263         if (CtdlAccessCheck(ac_logged_in)) {
1264                 return;
1265         }
1266
1267         if (!strncasecmp(new_ptr, "highest", 7)) {
1268                 newlr = CC->room.QRhighest;
1269         } else {
1270                 newlr = atol(new_ptr);
1271         }
1272
1273         lgetuser(&CC->user, CC->curr_user);
1274
1275         CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
1276         memcpy(&original_vbuf, &vbuf, sizeof(struct visit));
1277         vbuf.v_lastseen = newlr;
1278         snprintf(vbuf.v_seen, sizeof vbuf.v_seen, "*:%ld", newlr);
1279
1280         /* Only rewrite the record if it changed */
1281         if ( (vbuf.v_lastseen != original_vbuf.v_lastseen)
1282            || (strcmp(vbuf.v_seen, original_vbuf.v_seen)) ) {
1283                 CtdlSetRelationship(&vbuf, &CC->user, &CC->room);
1284         }
1285
1286         lputuser(&CC->user);
1287         cprintf("%d %ld\n", CIT_OK, newlr);
1288 }
1289
1290
1291 void cmd_seen(char *argbuf) {
1292         long target_msgnum = 0L;
1293         int target_setting = 0;
1294
1295         if (CtdlAccessCheck(ac_logged_in)) {
1296                 return;
1297         }
1298
1299         if (num_parms(argbuf) != 2) {
1300                 cprintf("%d Invalid parameters\n", ERROR + ILLEGAL_VALUE);
1301                 return;
1302         }
1303
1304         target_msgnum = extract_long(argbuf, 0);
1305         target_setting = extract_int(argbuf, 1);
1306
1307         CtdlSetSeen(&target_msgnum, 1, target_setting,
1308                         ctdlsetseen_seen, NULL, NULL);
1309         cprintf("%d OK\n", CIT_OK);
1310 }
1311
1312
1313 void cmd_gtsn(char *argbuf) {
1314         char buf[SIZ];
1315
1316         if (CtdlAccessCheck(ac_logged_in)) {
1317                 return;
1318         }
1319
1320         CtdlGetSeen(buf, ctdlsetseen_seen);
1321         cprintf("%d %s\n", CIT_OK, buf);
1322 }
1323
1324
1325 /*
1326  * API function for cmd_invt_kick() and anything else that needs to
1327  * invite or kick out a user to/from a room.
1328  * 
1329  * Set iuser to the name of the user, and op to 1=invite or 0=kick
1330  */
1331 int CtdlInvtKick(char *iuser, int op) {
1332         struct ctdluser USscratch;
1333         struct visit vbuf;
1334         char bbb[SIZ];
1335
1336         if (getuser(&USscratch, iuser) != 0) {
1337                 return(1);
1338         }
1339
1340         CtdlGetRelationship(&vbuf, &USscratch, &CC->room);
1341         if (op == 1) {
1342                 vbuf.v_flags = vbuf.v_flags & ~V_FORGET & ~V_LOCKOUT;
1343                 vbuf.v_flags = vbuf.v_flags | V_ACCESS;
1344         }
1345         if (op == 0) {
1346                 vbuf.v_flags = vbuf.v_flags & ~V_ACCESS;
1347                 vbuf.v_flags = vbuf.v_flags | V_FORGET | V_LOCKOUT;
1348         }
1349         CtdlSetRelationship(&vbuf, &USscratch, &CC->room);
1350
1351         /* post a message in Aide> saying what we just did */
1352         snprintf(bbb, sizeof bbb, "%s has been %s \"%s\" by %s.\n",
1353                 iuser,
1354                 ((op == 1) ? "invited to" : "kicked out of"),
1355                 CC->room.QRname,
1356                 CC->user.fullname);
1357         aide_message(bbb,"User Admin Message");
1358
1359         return(0);
1360 }
1361
1362
1363 /*
1364  * INVT and KICK commands
1365  */
1366 void cmd_invt_kick(char *iuser, int op) {
1367
1368         /*
1369          * These commands are only allowed by aides, room aides,
1370          * and room namespace owners
1371          */
1372         if (is_room_aide()
1373            || (atol(CC->room.QRname) == CC->user.usernum) ) {
1374                 /* access granted */
1375         } else {
1376                 /* access denied */
1377                 cprintf("%d Higher access or room ownership required.\n",
1378                         ERROR + HIGHER_ACCESS_REQUIRED);
1379                 return;
1380         }
1381
1382         if (!strncasecmp(CC->room.QRname, config.c_baseroom,
1383                          ROOMNAMELEN)) {
1384                 cprintf("%d Can't add/remove users from this room.\n",
1385                         ERROR + NOT_HERE);
1386                 return;
1387         }
1388
1389         if (CtdlInvtKick(iuser, op) != 0) {
1390                 cprintf("%d No such user.\n", ERROR + NO_SUCH_USER);
1391                 return;
1392         }
1393
1394         cprintf("%d %s %s %s.\n",
1395                 CIT_OK, iuser,
1396                 ((op == 1) ? "invited to" : "kicked out of"),
1397                 CC->room.QRname);
1398         return;
1399 }
1400
1401
1402 /*
1403  * Forget (Zap) the current room (API call)
1404  * Returns 0 on success
1405  */
1406 int CtdlForgetThisRoom(void) {
1407         struct visit vbuf;
1408
1409         /* On some systems, Aides are not allowed to forget rooms */
1410         if (is_aide() && (config.c_aide_zap == 0)
1411            && ((CC->room.QRflags & QR_MAILBOX) == 0)  ) {
1412                 return(1);
1413         }
1414
1415         lgetuser(&CC->user, CC->curr_user);
1416         CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
1417
1418         vbuf.v_flags = vbuf.v_flags | V_FORGET;
1419         vbuf.v_flags = vbuf.v_flags & ~V_ACCESS;
1420
1421         CtdlSetRelationship(&vbuf, &CC->user, &CC->room);
1422         lputuser(&CC->user);
1423
1424         /* Return to the Lobby, so we don't end up in an undefined room */
1425         usergoto(config.c_baseroom, 0, 0, NULL, NULL);
1426         return(0);
1427
1428 }
1429
1430
1431 /*
1432  * forget (Zap) the current room
1433  */
1434 void cmd_forg(void)
1435 {
1436
1437         if (CtdlAccessCheck(ac_logged_in)) {
1438                 return;
1439         }
1440
1441         if (CtdlForgetThisRoom() == 0) {
1442                 cprintf("%d Ok\n", CIT_OK);
1443         }
1444         else {
1445                 cprintf("%d You may not forget this room.\n", ERROR + NOT_HERE);
1446         }
1447 }
1448
1449 /*
1450  * Get Next Unregistered User
1451  */
1452 void cmd_gnur(void)
1453 {
1454         struct cdbdata *cdbus;
1455         struct ctdluser usbuf;
1456
1457         if (CtdlAccessCheck(ac_aide)) {
1458                 return;
1459         }
1460
1461         if ((CitControl.MMflags & MM_VALID) == 0) {
1462                 cprintf("%d There are no unvalidated users.\n", CIT_OK);
1463                 return;
1464         }
1465
1466         /* There are unvalidated users.  Traverse the user database,
1467          * and return the first user we find that needs validation.
1468          */
1469         cdb_rewind(CDB_USERS);
1470         while (cdbus = cdb_next_item(CDB_USERS), cdbus != NULL) {
1471                 memset(&usbuf, 0, sizeof(struct ctdluser));
1472                 memcpy(&usbuf, cdbus->ptr,
1473                        ((cdbus->len > sizeof(struct ctdluser)) ?
1474                         sizeof(struct ctdluser) : cdbus->len));
1475                 cdb_free(cdbus);
1476                 if ((usbuf.flags & US_NEEDVALID)
1477                     && (usbuf.axlevel > 0)) {
1478                         cprintf("%d %s\n", MORE_DATA, usbuf.fullname);
1479                         cdb_close_cursor(CDB_USERS);
1480                         return;
1481                 }
1482         }
1483
1484         /* If we get to this point, there are no more unvalidated users.
1485          * Therefore we clear the "users need validation" flag.
1486          */
1487
1488         begin_critical_section(S_CONTROL);
1489         get_control();
1490         CitControl.MMflags = CitControl.MMflags & (~MM_VALID);
1491         put_control();
1492         end_critical_section(S_CONTROL);
1493         cprintf("%d *** End of registration.\n", CIT_OK);
1494
1495
1496 }
1497
1498
1499 /*
1500  * validate a user
1501  */
1502 void cmd_vali(char *v_args)
1503 {
1504         char user[128];
1505         int newax;
1506         struct ctdluser userbuf;
1507
1508         extract_token(user, v_args, 0, '|', sizeof user);
1509         newax = extract_int(v_args, 1);
1510
1511         if (CtdlAccessCheck(ac_aide)) {
1512                 return;
1513         }
1514
1515         if (lgetuser(&userbuf, user) != 0) {
1516                 cprintf("%d '%s' not found.\n", ERROR + NO_SUCH_USER, user);
1517                 return;
1518         }
1519
1520         userbuf.axlevel = newax;
1521         userbuf.flags = (userbuf.flags & ~US_NEEDVALID);
1522
1523         lputuser(&userbuf);
1524
1525         /* If the access level was set to zero, delete the user */
1526         if (newax == 0) {
1527                 if (purge_user(user) == 0) {
1528                         cprintf("%d %s Deleted.\n", CIT_OK, userbuf.fullname);
1529                         return;
1530                 }
1531         }
1532         cprintf("%d User '%s' validated.\n", CIT_OK, userbuf.fullname);
1533 }
1534
1535
1536
1537 /* 
1538  *  Traverse the user file...
1539  */
1540 void ForEachUser(void (*CallBack) (struct ctdluser * EachUser, void *out_data),
1541                  void *in_data)
1542 {
1543         struct ctdluser usbuf;
1544         struct cdbdata *cdbus;
1545
1546         cdb_rewind(CDB_USERS);
1547
1548         while (cdbus = cdb_next_item(CDB_USERS), cdbus != NULL) {
1549                 memset(&usbuf, 0, sizeof(struct ctdluser));
1550                 memcpy(&usbuf, cdbus->ptr,
1551                        ((cdbus->len > sizeof(struct ctdluser)) ?
1552                         sizeof(struct ctdluser) : cdbus->len));
1553                 cdb_free(cdbus);
1554                 (*CallBack) (&usbuf, in_data);
1555         }
1556 }
1557
1558
1559 /*
1560  * List one user (this works with cmd_list)
1561  */
1562 void ListThisUser(struct ctdluser *usbuf, void *data)
1563 {
1564         char *searchstring;
1565
1566         searchstring = (char *)data;
1567         if (bmstrcasestr(usbuf->fullname, searchstring) == NULL) {
1568                 return;
1569         }
1570
1571         if (usbuf->axlevel > 0) {
1572                 if ((CC->user.axlevel >= 6)
1573                     || ((usbuf->flags & US_UNLISTED) == 0)
1574                     || ((CC->internal_pgm))) {
1575                         cprintf("%s|%d|%ld|%ld|%ld|%ld|",
1576                                 usbuf->fullname,
1577                                 usbuf->axlevel,
1578                                 usbuf->usernum,
1579                                 (long)usbuf->lastcall,
1580                                 usbuf->timescalled,
1581                                 usbuf->posted);
1582                         if (CC->user.axlevel >= 6)
1583                                 cprintf("%s", usbuf->password);
1584                         cprintf("\n");
1585                 }
1586         }
1587 }
1588
1589 /* 
1590  *  List users (searchstring may be empty to list all users)
1591  */
1592 void cmd_list(char *cmdbuf)
1593 {
1594         char searchstring[256];
1595         extract_token(searchstring, cmdbuf, 0, '|', sizeof searchstring);
1596         striplt(searchstring);
1597         cprintf("%d \n", LISTING_FOLLOWS);
1598         ForEachUser(ListThisUser, (void *)searchstring );
1599         cprintf("000\n");
1600 }
1601
1602
1603
1604
1605 /*
1606  * assorted info we need to check at login
1607  */
1608 void cmd_chek(void)
1609 {
1610         int mail = 0;
1611         int regis = 0;
1612         int vali = 0;
1613
1614         if (CtdlAccessCheck(ac_logged_in)) {
1615                 return;
1616         }
1617
1618         getuser(&CC->user, CC->curr_user);      /* no lock is needed here */
1619         if ((REGISCALL != 0) && ((CC->user.flags & US_REGIS) == 0))
1620                 regis = 1;
1621
1622         if (CC->user.axlevel >= 6) {
1623                 get_control();
1624                 if (CitControl.MMflags & MM_VALID)
1625                         vali = 1;
1626         }
1627
1628         /* check for mail */
1629         mail = InitialMailCheck();
1630
1631         cprintf("%d %d|%d|%d|%s|\n", CIT_OK, mail, regis, vali, CC->cs_inet_email);
1632 }
1633
1634
1635 /*
1636  * check to see if a user exists
1637  */
1638 void cmd_qusr(char *who)
1639 {
1640         struct ctdluser usbuf;
1641
1642         if (getuser(&usbuf, who) == 0) {
1643                 cprintf("%d %s\n", CIT_OK, usbuf.fullname);
1644         } else {
1645                 cprintf("%d No such user.\n", ERROR + NO_SUCH_USER);
1646         }
1647 }
1648
1649
1650 /*
1651  * Administrative Get User Parameters
1652  */
1653 void cmd_agup(char *cmdbuf)
1654 {
1655         struct ctdluser usbuf;
1656         char requested_user[128];
1657
1658         if (CtdlAccessCheck(ac_aide)) {
1659                 return;
1660         }
1661
1662         extract_token(requested_user, cmdbuf, 0, '|', sizeof requested_user);
1663         if (getuser(&usbuf, requested_user) != 0) {
1664                 cprintf("%d No such user.\n", ERROR + NO_SUCH_USER);
1665                 return;
1666         }
1667         cprintf("%d %s|%s|%u|%ld|%ld|%d|%ld|%ld|%d\n",
1668                 CIT_OK,
1669                 usbuf.fullname,
1670                 usbuf.password,
1671                 usbuf.flags,
1672                 usbuf.timescalled,
1673                 usbuf.posted,
1674                 (int) usbuf.axlevel,
1675                 usbuf.usernum,
1676                 (long)usbuf.lastcall,
1677                 usbuf.USuserpurge);
1678 }
1679
1680
1681
1682 /*
1683  * Administrative Set User Parameters
1684  */
1685 void cmd_asup(char *cmdbuf)
1686 {
1687         struct ctdluser usbuf;
1688         char requested_user[128];
1689         char notify[SIZ];
1690         int np;
1691         int newax;
1692         int deleted = 0;
1693
1694         if (CtdlAccessCheck(ac_aide))
1695                 return;
1696
1697         extract_token(requested_user, cmdbuf, 0, '|', sizeof requested_user);
1698         if (lgetuser(&usbuf, requested_user) != 0) {
1699                 cprintf("%d No such user.\n", ERROR + NO_SUCH_USER);
1700                 return;
1701         }
1702         np = num_parms(cmdbuf);
1703         if (np > 1)
1704                 extract_token(usbuf.password, cmdbuf, 1, '|', sizeof usbuf.password);
1705         if (np > 2)
1706                 usbuf.flags = extract_int(cmdbuf, 2);
1707         if (np > 3)
1708                 usbuf.timescalled = extract_int(cmdbuf, 3);
1709         if (np > 4)
1710                 usbuf.posted = extract_int(cmdbuf, 4);
1711         if (np > 5) {
1712                 newax = extract_int(cmdbuf, 5);
1713                 if ((newax >= 0) && (newax <= 6)) {
1714                         usbuf.axlevel = extract_int(cmdbuf, 5);
1715                 }
1716         }
1717         if (np > 7) {
1718                 usbuf.lastcall = extract_long(cmdbuf, 7);
1719         }
1720         if (np > 8) {
1721                 usbuf.USuserpurge = extract_int(cmdbuf, 8);
1722         }
1723         lputuser(&usbuf);
1724         if (usbuf.axlevel == 0) {
1725                 if (purge_user(requested_user) == 0) {
1726                         deleted = 1;
1727                 }
1728         }
1729
1730         if (deleted) {
1731                 snprintf(notify, SIZ, 
1732                          "User \"%s\" has been deleted by %s.\n",
1733                          usbuf.fullname, CC->user.fullname);
1734                 aide_message(notify, "User Deletion Message");
1735         }
1736
1737         cprintf("%d Ok", CIT_OK);
1738         if (deleted)
1739                 cprintf(" (%s deleted)", requested_user);
1740         cprintf("\n");
1741 }
1742
1743
1744
1745 /*
1746  * Check to see if the user who we just sent mail to is logged in.  If yes,
1747  * bump the 'new mail' counter for their session.  That enables them to
1748  * receive a new mail notification without having to hit the database.
1749  */
1750 void BumpNewMailCounter(long which_user) {
1751         struct CitContext *ptr;
1752
1753         begin_critical_section(S_SESSION_TABLE);
1754
1755         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1756                 if (ptr->user.usernum == which_user) {
1757                         ptr->newmail += 1;
1758                 }
1759         }
1760
1761         end_critical_section(S_SESSION_TABLE);
1762 }
1763
1764
1765 /*
1766  * Count the number of new mail messages the user has
1767  */
1768 int NewMailCount()
1769 {
1770         int num_newmsgs = 0;
1771
1772         num_newmsgs = CC->newmail;
1773         CC->newmail = 0;
1774
1775         return (num_newmsgs);
1776 }
1777
1778
1779 /*
1780  * Count the number of new mail messages the user has
1781  */
1782 int InitialMailCheck()
1783 {
1784         int num_newmsgs = 0;
1785         int a;
1786         char mailboxname[ROOMNAMELEN];
1787         struct ctdlroom mailbox;
1788         struct visit vbuf;
1789         struct cdbdata *cdbfr;
1790         long *msglist = NULL;
1791         int num_msgs = 0;
1792
1793         MailboxName(mailboxname, sizeof mailboxname, &CC->user, MAILROOM);
1794         if (getroom(&mailbox, mailboxname) != 0)
1795                 return (0);
1796         CtdlGetRelationship(&vbuf, &CC->user, &mailbox);
1797
1798         cdbfr = cdb_fetch(CDB_MSGLISTS, &mailbox.QRnumber, sizeof(long));
1799
1800         if (cdbfr != NULL) {
1801                 msglist = malloc(cdbfr->len);
1802                 memcpy(msglist, cdbfr->ptr, cdbfr->len);
1803                 num_msgs = cdbfr->len / sizeof(long);
1804                 cdb_free(cdbfr);
1805         }
1806         if (num_msgs > 0)
1807                 for (a = 0; a < num_msgs; ++a) {
1808                         if (msglist[a] > 0L) {
1809                                 if (msglist[a] > vbuf.v_lastseen) {
1810                                         ++num_newmsgs;
1811                                 }
1812                         }
1813                 }
1814         if (msglist != NULL)
1815                 free(msglist);
1816
1817         return (num_newmsgs);
1818 }
1819
1820
1821
1822 /*
1823  * Set the preferred view for the current user/room combination
1824  */
1825 void cmd_view(char *cmdbuf) {
1826         int requested_view;
1827         struct visit vbuf;
1828
1829         if (CtdlAccessCheck(ac_logged_in)) {
1830                 return;
1831         }
1832
1833         requested_view = extract_int(cmdbuf, 0);
1834
1835         CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
1836         vbuf.v_view = requested_view;
1837         CtdlSetRelationship(&vbuf, &CC->user, &CC->room);
1838         
1839         cprintf("%d ok\n", CIT_OK);
1840 }
1841
1842
1843 /*
1844  * Rename a user
1845  */
1846 void cmd_renu(char *cmdbuf)
1847 {
1848         int retcode;
1849         char oldname[USERNAME_SIZE];
1850         char newname[USERNAME_SIZE];
1851
1852         if (CtdlAccessCheck(ac_aide)) {
1853                 return;
1854         }
1855
1856         extract_token(oldname, cmdbuf, 0, '|', sizeof oldname);
1857         extract_token(newname, cmdbuf, 1, '|', sizeof newname);
1858
1859         retcode = rename_user(oldname, newname);
1860         switch(retcode) {
1861                 case RENAMEUSER_OK:
1862                         cprintf("%d '%s' has been renamed to '%s'.\n", CIT_OK, oldname, newname);
1863                         return;
1864                 case RENAMEUSER_LOGGED_IN:
1865                         cprintf("%d '%s' is currently logged in and cannot be renamed.\n",
1866                                 ERROR + ALREADY_LOGGED_IN , oldname);
1867                         return;
1868                 case RENAMEUSER_NOT_FOUND:
1869                         cprintf("%d '%s' does not exist.\n", ERROR + NO_SUCH_USER, oldname);
1870                         return;
1871                 case RENAMEUSER_ALREADY_EXISTS:
1872                         cprintf("%d A user named '%s' already exists.\n", ERROR + ALREADY_EXISTS, newname);
1873                         return;
1874         }
1875
1876         cprintf("%d An unknown error occurred.\n", ERROR);
1877 }