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