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