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