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