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