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