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