Temporary workaround to compile with old libical
[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         /* Free any output buffers */
611         if (who->output_buffer != NULL) {
612                 unbuffer_output();
613         }
614 }
615
616 /*
617  * Validate a password on the host unix system by talking to the chkpwd daemon
618  */
619 static int validpw(uid_t uid, const char *pass)
620 {
621         char buf[256];
622
623         lprintf(CTDL_DEBUG, "Validating password for uid=%d using chkpwd...\n", uid);
624
625         begin_critical_section(S_CHKPWD);
626         write(chkpwd_write_pipe[1], &uid, sizeof(uid_t));
627         write(chkpwd_write_pipe[1], pass, 256);
628         read(chkpwd_read_pipe[0], buf, 4);
629         end_critical_section(S_CHKPWD);
630
631         if (!strncmp(buf, "PASS", 4)) {
632                 lprintf(CTDL_DEBUG, "...pass\n");
633                 return(1);
634         }
635
636         lprintf(CTDL_DEBUG, "...fail\n");
637         return 0;
638 }
639
640 /* 
641  * Start up the chkpwd daemon so validpw() has something to talk to
642  */
643 void start_chkpwd_daemon(void) {
644         pid_t chkpwd_pid;
645         struct stat filestats;
646         int i;
647
648         lprintf(CTDL_DEBUG, "Starting chkpwd daemon for host authentication mode\n");
649
650         if ((stat(file_chkpwd, &filestats)==-1) ||
651             (filestats.st_size==0)){
652                 printf("didn't find chkpwd daemon in %s: %s\n", file_chkpwd, strerror(errno));
653                 abort();
654         }
655         if (pipe(chkpwd_write_pipe) != 0) {
656                 lprintf(CTDL_EMERG, "Unable to create pipe for chkpwd daemon: %s\n", strerror(errno));
657                 abort();
658         }
659         if (pipe(chkpwd_read_pipe) != 0) {
660                 lprintf(CTDL_EMERG, "Unable to create pipe for chkpwd daemon: %s\n", strerror(errno));
661                 abort();
662         }
663
664         chkpwd_pid = fork();
665         if (chkpwd_pid < 0) {
666                 lprintf(CTDL_EMERG, "Unable to fork chkpwd daemon: %s\n", strerror(errno));
667                 abort();
668         }
669         if (chkpwd_pid == 0) {
670                 lprintf(CTDL_DEBUG, "Now calling dup2() write\n");
671                 dup2(chkpwd_write_pipe[0], 0);
672                 lprintf(CTDL_DEBUG, "Now calling dup2() write\n");
673                 dup2(chkpwd_read_pipe[1], 1);
674                 lprintf(CTDL_DEBUG, "Now closing stuff\n");
675                 for (i=2; i<256; ++i) close(i);
676                 lprintf(CTDL_DEBUG, "Now calling execl(%s)\n", file_chkpwd);
677                 execl(file_chkpwd, file_chkpwd, NULL);
678                 lprintf(CTDL_EMERG, "Unable to exec chkpwd daemon: %s\n", strerror(errno));
679                 abort();
680                 exit(errno);
681         }
682 }
683
684
685 void do_login()
686 {
687         (CC->logged_in) = 1;
688         session_startup();
689 }
690
691
692 int CtdlTryPassword(char *password)
693 {
694         int code;
695
696         if ((CC->logged_in)) {
697                 lprintf(CTDL_WARNING, "CtdlTryPassword: already logged in\n");
698                 return pass_already_logged_in;
699         }
700         if (!strcmp(CC->curr_user, NLI)) {
701                 lprintf(CTDL_WARNING, "CtdlTryPassword: no user selected\n");
702                 return pass_no_user;
703         }
704         if (getuser(&CC->user, CC->curr_user)) {
705                 lprintf(CTDL_ERR, "CtdlTryPassword: internal error\n");
706                 return pass_internal_error;
707         }
708         if (password == NULL) {
709                 lprintf(CTDL_INFO, "CtdlTryPassword: NULL password string supplied\n");
710                 return pass_wrong_password;
711         }
712         code = (-1);
713
714         if (CC->is_master) {
715                 code = strcmp(password, config.c_master_pass);
716         }
717
718         else if (config.c_auth_mode == AUTHMODE_HOST) {
719
720                 /* host auth mode */
721
722                 if (validpw(CC->user.uid, password)) {
723                         code = 0;
724
725                         /*
726                          * sooper-seekrit hack: populate the password field in the
727                          * citadel database with the password that the user typed,
728                          * if it's correct.  This allows most sites to convert from
729                          * host auth to native auth if they want to.  If you think
730                          * this is a security hazard, comment it out.
731                          */
732
733                         lgetuser(&CC->user, CC->curr_user);
734                         safestrncpy(CC->user.password, password, sizeof CC->user.password);
735                         lputuser(&CC->user);
736
737                         /*
738                          * (sooper-seekrit hack ends here)
739                          */
740
741                 }
742                 else {
743                         code = (-1);
744                 }
745         }
746
747         else {
748
749                 /* native auth mode */
750
751                 strproc(password);
752                 strproc(CC->user.password);
753                 code = strcasecmp(CC->user.password, password);
754                 strproc(password);
755                 strproc(CC->user.password);
756                 code = strcasecmp(CC->user.password, password);
757         }
758
759         if (!code) {
760                 do_login();
761                 return pass_ok;
762         } else {
763                 lprintf(CTDL_WARNING, "Bad password specified for <%s>\n", CC->curr_user);
764                 return pass_wrong_password;
765         }
766 }
767
768
769 void cmd_pass(char *buf)
770 {
771         char password[256];
772         int a;
773
774         extract_token(password, buf, 0, '|', sizeof password);
775         a = CtdlTryPassword(password);
776
777         switch (a) {
778         case pass_already_logged_in:
779                 cprintf("%d Already logged in.\n", ERROR + ALREADY_LOGGED_IN);
780                 return;
781         case pass_no_user:
782                 cprintf("%d You must send a name with USER first.\n",
783                         ERROR + USERNAME_REQUIRED);
784                 return;
785         case pass_wrong_password:
786                 cprintf("%d Wrong password.\n", ERROR + PASSWORD_REQUIRED);
787                 return;
788         case pass_ok:
789                 logged_in_response();
790                 return;
791         }
792 }
793
794
795
796 /*
797  * Delete a user record *and* all of its related resources.
798  */
799 int purge_user(char pname[])
800 {
801         char filename[64];
802         struct ctdluser usbuf;
803         char usernamekey[USERNAME_SIZE];
804         struct CitContext *ccptr;
805         int user_is_logged_in = 0;
806
807         makeuserkey(usernamekey, pname);
808
809         if (getuser(&usbuf, pname) != 0) {
810                 lprintf(CTDL_ERR, "Cannot purge user <%s> - not found\n", pname);
811                 return (ERROR + NO_SUCH_USER);
812         }
813         /* Don't delete a user who is currently logged in.  Instead, just
814          * set the access level to 0, and let the account get swept up
815          * during the next purge.
816          */
817         user_is_logged_in = 0;
818         begin_critical_section(S_SESSION_TABLE);
819         for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
820                 if (ccptr->user.usernum == usbuf.usernum) {
821                         user_is_logged_in = 1;
822                 }
823         }
824         end_critical_section(S_SESSION_TABLE);
825         if (user_is_logged_in == 1) {
826                 lprintf(CTDL_WARNING, "User <%s> is logged in; not deleting.\n", pname);
827                 usbuf.axlevel = 0;
828                 putuser(&usbuf);
829                 return (1);
830         }
831         lprintf(CTDL_NOTICE, "Deleting user <%s>\n", pname);
832
833         /* Perform any purge functions registered by server extensions */
834         PerformUserHooks(&usbuf, EVT_PURGEUSER);
835
836         /* delete any existing user/room relationships */
837         cdb_delete(CDB_VISIT, &usbuf.usernum, sizeof(long));
838
839         /* delete the userlog entry */
840         cdb_delete(CDB_USERS, usernamekey, strlen(usernamekey));
841
842         /* remove the user's bio file */
843         snprintf(filename, 
844                          sizeof filename, 
845                          "%s/%ld",
846                          ctdl_bio_dir,
847                          usbuf.usernum);
848         unlink(filename);
849
850         /* remove the user's picture */
851         snprintf(filename, 
852                          sizeof filename, 
853                          "%s/%ld.gif",
854                          ctdl_image_dir,
855                          usbuf.usernum);
856         unlink(filename);
857
858         return (0);
859 }
860
861
862 /*
863  * create_user()  -  back end processing to create a new user
864  *
865  * Set 'newusername' to the desired account name.
866  * Set 'become_user' to nonzero if this is self-service account creation and we want
867  * to actually log in as the user we just created, otherwise set it to 0.
868  */
869 int create_user(char *newusername, int become_user)
870 {
871         struct ctdluser usbuf;
872         struct ctdlroom qrbuf;
873         char username[256];
874         char mailboxname[ROOMNAMELEN];
875         char buf[SIZ];
876         uid_t uid = (-1);
877
878         safestrncpy(username, newusername, sizeof username);
879         strproc(username);
880
881         if (config.c_auth_mode == AUTHMODE_HOST) {
882
883                 /* host auth mode */
884
885                 struct passwd pd;
886                 struct passwd *tempPwdPtr;
887                 char pwdbuffer[256];
888         
889 #ifdef HAVE_GETPWNAM_R
890 #ifdef SOLARIS_GETPWUID
891                 tempPwdPtr = getpwnam_r(username, &pd, pwdbuffer, sizeof(pwdbuffer));
892 #else // SOLARIS_GETPWUID
893                 getpwnam_r(username, &pd, pwdbuffer, sizeof pwdbuffer, &tempPwdPtr);
894 #endif // SOLARIS_GETPWUID
895 #else // HAVE_GETPWNAM_R
896                 tempPwdPtr = NULL;
897 #endif // HAVE_GETPWNAM_R
898                 if (tempPwdPtr != NULL) {
899                         extract_token(username, pd.pw_gecos, 0, ',', sizeof username);
900                         uid = pd.pw_uid;
901                         if (IsEmptyStr (username))
902                         {
903                                 lprintf (CTDL_EMERG, 
904                                          "Can't find Realname for user %s [%d] in the Host Auth Database; giving up.\n", 
905                                          newusername, pd.pw_uid);
906                                 snprintf(buf, SIZ, 
907                                          "Can't find Realname for user %s [%d] in the Host Auth Database; giving up.\n",
908                                          newusername, pd.pw_uid);
909                                 aide_message(buf, "User Creation Failure Notice");
910
911                         }
912                 }
913                 else {
914                         return (ERROR + NO_SUCH_USER);
915                 }
916         }
917
918         if (!getuser(&usbuf, username)) {
919                 return (ERROR + ALREADY_EXISTS);
920         }
921
922         /* Go ahead and initialize a new user record */
923         memset(&usbuf, 0, sizeof(struct ctdluser));
924         safestrncpy(usbuf.fullname, username, sizeof usbuf.fullname);
925         strcpy(usbuf.password, "");
926         usbuf.uid = uid;
927
928         /* These are the default flags on new accounts */
929         usbuf.flags = US_LASTOLD | US_DISAPPEAR | US_PAGINATOR | US_FLOORS;
930
931         usbuf.timescalled = 0;
932         usbuf.posted = 0;
933         usbuf.axlevel = config.c_initax;
934         usbuf.USscreenwidth = 80;
935         usbuf.USscreenheight = 24;
936         usbuf.lastcall = time(NULL);
937
938         /* fetch a new user number */
939         usbuf.usernum = get_new_user_number();
940
941         /* The very first user created on the system will always be an Aide */
942         if (usbuf.usernum == 1L) {
943                 usbuf.axlevel = 6;
944         }
945
946         /* add user to userlog */
947         putuser(&usbuf);
948
949         /*
950          * Give the user a private mailbox and a configuration room.
951          * Make the latter an invisible system room.
952          */
953         MailboxName(mailboxname, sizeof mailboxname, &usbuf, MAILROOM);
954         create_room(mailboxname, 5, "", 0, 1, 1, VIEW_MAILBOX);
955
956         MailboxName(mailboxname, sizeof mailboxname, &usbuf, USERCONFIGROOM);
957         create_room(mailboxname, 5, "", 0, 1, 1, VIEW_BBS);
958         if (lgetroom(&qrbuf, mailboxname) == 0) {
959                 qrbuf.QRflags2 |= QR2_SYSTEM;
960                 lputroom(&qrbuf);
961         }
962
963         /* Perform any create functions registered by server extensions */
964         PerformUserHooks(&usbuf, EVT_NEWUSER);
965
966         /* Everything below this line can be bypassed if administratively
967          * creating a user, instead of doing self-service account creation
968          */
969
970         if (become_user) {
971                 /* Now become the user we just created */
972                 memcpy(&CC->user, &usbuf, sizeof(struct ctdluser));
973                 safestrncpy(CC->curr_user, username, sizeof CC->curr_user);
974                 CC->logged_in = 1;
975         
976                 /* Check to make sure we're still who we think we are */
977                 if (getuser(&CC->user, CC->curr_user)) {
978                         return (ERROR + INTERNAL_ERROR);
979                 }
980         }
981         
982         snprintf(buf, SIZ, 
983                 "New user account <%s> has been created, from host %s [%s].\n",
984                 username,
985                 CC->cs_host,
986                 CC->cs_addr
987         );
988         aide_message(buf, "User Creation Notice");
989         lprintf(CTDL_NOTICE, "New user <%s> created\n", username);
990         return (0);
991 }
992
993
994
995
996 /*
997  * cmd_newu()  -  create a new user account and log in as that user
998  */
999 void cmd_newu(char *cmdbuf)
1000 {
1001         int a;
1002         char username[26];
1003
1004         if (config.c_auth_mode != AUTHMODE_NATIVE) {
1005                 cprintf("%d This system does not use native mode authentication.\n",
1006                         ERROR + NOT_HERE);
1007                 return;
1008         }
1009
1010         if (config.c_disable_newu) {
1011                 cprintf("%d Self-service user account creation "
1012                         "is disabled on this system.\n", ERROR + NOT_HERE);
1013                 return;
1014         }
1015
1016         if (CC->logged_in) {
1017                 cprintf("%d Already logged in.\n", ERROR + ALREADY_LOGGED_IN);
1018                 return;
1019         }
1020         if (CC->nologin) {
1021                 cprintf("%d %s: Too many users are already online (maximum is %d)\n",
1022                         ERROR + MAX_SESSIONS_EXCEEDED,
1023                         config.c_nodename, config.c_maxsessions);
1024         }
1025         extract_token(username, cmdbuf, 0, '|', sizeof username);
1026         username[25] = 0;
1027         strproc(username);
1028
1029         if (IsEmptyStr(username)) {
1030                 cprintf("%d You must supply a user name.\n", ERROR + USERNAME_REQUIRED);
1031                 return;
1032         }
1033
1034         if ((!strcasecmp(username, "bbs")) ||
1035             (!strcasecmp(username, "new")) ||
1036             (!strcasecmp(username, "."))) {
1037                 cprintf("%d '%s' is an invalid login name.\n", ERROR + ILLEGAL_VALUE, username);
1038                 return;
1039         }
1040
1041         a = create_user(username, 1);
1042
1043         if (a == 0) {
1044                 session_startup();
1045                 logged_in_response();
1046         } else if (a == ERROR + ALREADY_EXISTS) {
1047                 cprintf("%d '%s' already exists.\n",
1048                         ERROR + ALREADY_EXISTS, username);
1049                 return;
1050         } else if (a == ERROR + INTERNAL_ERROR) {
1051                 cprintf("%d Internal error - user record disappeared?\n",
1052                         ERROR + INTERNAL_ERROR);
1053                 return;
1054         } else {
1055                 cprintf("%d unknown error\n", ERROR + INTERNAL_ERROR);
1056         }
1057 }
1058
1059
1060
1061 /*
1062  * set password
1063  */
1064 void cmd_setp(char *new_pw)
1065 {
1066         if (CtdlAccessCheck(ac_logged_in)) {
1067                 return;
1068         }
1069         if ( (CC->user.uid != CTDLUID) && (CC->user.uid != (-1)) ) {
1070                 cprintf("%d Not allowed.  Use the 'passwd' command.\n", ERROR + NOT_HERE);
1071                 return;
1072         }
1073         if (CC->is_master) {
1074                 cprintf("%d The master prefix password cannot be changed with this command.\n",
1075                         ERROR + NOT_HERE);
1076                 return;
1077         }
1078         strproc(new_pw);
1079         if (IsEmptyStr(new_pw)) {
1080                 cprintf("%d Password unchanged.\n", CIT_OK);
1081                 return;
1082         }
1083         lgetuser(&CC->user, CC->curr_user);
1084         safestrncpy(CC->user.password, new_pw, sizeof(CC->user.password));
1085         lputuser(&CC->user);
1086         cprintf("%d Password changed.\n", CIT_OK);
1087         lprintf(CTDL_INFO, "Password changed for user <%s>\n", CC->curr_user);
1088         PerformSessionHooks(EVT_SETPASS);
1089 }
1090
1091
1092 /*
1093  * cmd_creu() - administratively create a new user account (do not log in to it)
1094  */
1095 void cmd_creu(char *cmdbuf)
1096 {
1097         int a;
1098         char username[26];
1099         char password[32];
1100         struct ctdluser tmp;
1101
1102         if (CtdlAccessCheck(ac_aide)) {
1103                 return;
1104         }
1105
1106         extract_token(username, cmdbuf, 0, '|', sizeof username);
1107         extract_token(password, cmdbuf, 1, '|', sizeof password);
1108         username[25] = 0;
1109         password[31] = 0;
1110         strproc(username);
1111         strproc(password);
1112
1113         if (IsEmptyStr(username)) {
1114                 cprintf("%d You must supply a user name.\n", ERROR + USERNAME_REQUIRED);
1115                 return;
1116         }
1117
1118         a = create_user(username, 0);
1119
1120         if (a == 0) {
1121                 if (!IsEmptyStr(password)) {
1122                         lgetuser(&tmp, username);
1123                         safestrncpy(tmp.password, password, sizeof(tmp.password));
1124                         lputuser(&tmp);
1125                 }
1126                 cprintf("%d User '%s' created %s.\n", CIT_OK, username,
1127                                 (!IsEmptyStr(password)) ? "and password set" :
1128                                 "with no password");
1129                 return;
1130         } else if (a == ERROR + ALREADY_EXISTS) {
1131                 cprintf("%d '%s' already exists.\n", ERROR + ALREADY_EXISTS, username);
1132                 return;
1133         } else if ( (config.c_auth_mode != AUTHMODE_NATIVE) && (a == ERROR + NO_SUCH_USER) ) {
1134                 cprintf("%d User accounts are not created within Citadel in host authentication mode.\n",
1135                         ERROR + NO_SUCH_USER);
1136                 return;
1137         } else {
1138                 cprintf("%d An error occurred creating the user account.\n", ERROR + INTERNAL_ERROR);
1139         }
1140 }
1141
1142
1143
1144 /*
1145  * get user parameters
1146  */
1147 void cmd_getu(void)
1148 {
1149
1150         if (CtdlAccessCheck(ac_logged_in))
1151                 return;
1152
1153         getuser(&CC->user, CC->curr_user);
1154         cprintf("%d %d|%d|%d|\n",
1155                 CIT_OK,
1156                 CC->user.USscreenwidth,
1157                 CC->user.USscreenheight,
1158                 (CC->user.flags & US_USER_SET)
1159             );
1160 }
1161
1162 /*
1163  * set user parameters
1164  */
1165 void cmd_setu(char *new_parms)
1166 {
1167         if (CtdlAccessCheck(ac_logged_in))
1168                 return;
1169
1170         if (num_parms(new_parms) < 3) {
1171                 cprintf("%d Usage error.\n", ERROR + ILLEGAL_VALUE);
1172                 return;
1173         }
1174         lgetuser(&CC->user, CC->curr_user);
1175         CC->user.USscreenwidth = extract_int(new_parms, 0);
1176         CC->user.USscreenheight = extract_int(new_parms, 1);
1177         CC->user.flags = CC->user.flags & (~US_USER_SET);
1178         CC->user.flags = CC->user.flags |
1179             (extract_int(new_parms, 2) & US_USER_SET);
1180
1181         lputuser(&CC->user);
1182         cprintf("%d Ok\n", CIT_OK);
1183 }
1184
1185 /*
1186  * set last read pointer
1187  */
1188 void cmd_slrp(char *new_ptr)
1189 {
1190         long newlr;
1191         struct visit vbuf;
1192         struct visit original_vbuf;
1193
1194         if (CtdlAccessCheck(ac_logged_in)) {
1195                 return;
1196         }
1197
1198         if (!strncasecmp(new_ptr, "highest", 7)) {
1199                 newlr = CC->room.QRhighest;
1200         } else {
1201                 newlr = atol(new_ptr);
1202         }
1203
1204         lgetuser(&CC->user, CC->curr_user);
1205
1206         CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
1207         memcpy(&original_vbuf, &vbuf, sizeof(struct visit));
1208         vbuf.v_lastseen = newlr;
1209         snprintf(vbuf.v_seen, sizeof vbuf.v_seen, "*:%ld", newlr);
1210
1211         /* Only rewrite the record if it changed */
1212         if ( (vbuf.v_lastseen != original_vbuf.v_lastseen)
1213            || (strcmp(vbuf.v_seen, original_vbuf.v_seen)) ) {
1214                 CtdlSetRelationship(&vbuf, &CC->user, &CC->room);
1215         }
1216
1217         lputuser(&CC->user);
1218         cprintf("%d %ld\n", CIT_OK, newlr);
1219 }
1220
1221
1222 void cmd_seen(char *argbuf) {
1223         long target_msgnum = 0L;
1224         int target_setting = 0;
1225
1226         if (CtdlAccessCheck(ac_logged_in)) {
1227                 return;
1228         }
1229
1230         if (num_parms(argbuf) != 2) {
1231                 cprintf("%d Invalid parameters\n", ERROR + ILLEGAL_VALUE);
1232                 return;
1233         }
1234
1235         target_msgnum = extract_long(argbuf, 0);
1236         target_setting = extract_int(argbuf, 1);
1237
1238         CtdlSetSeen(&target_msgnum, 1, target_setting,
1239                         ctdlsetseen_seen, NULL, NULL);
1240         cprintf("%d OK\n", CIT_OK);
1241 }
1242
1243
1244 void cmd_gtsn(char *argbuf) {
1245         char buf[SIZ];
1246
1247         if (CtdlAccessCheck(ac_logged_in)) {
1248                 return;
1249         }
1250
1251         CtdlGetSeen(buf, ctdlsetseen_seen);
1252         cprintf("%d %s\n", CIT_OK, buf);
1253 }
1254
1255
1256 /*
1257  * API function for cmd_invt_kick() and anything else that needs to
1258  * invite or kick out a user to/from a room.
1259  * 
1260  * Set iuser to the name of the user, and op to 1=invite or 0=kick
1261  */
1262 int CtdlInvtKick(char *iuser, int op) {
1263         struct ctdluser USscratch;
1264         struct visit vbuf;
1265         char bbb[SIZ];
1266
1267         if (getuser(&USscratch, iuser) != 0) {
1268                 return(1);
1269         }
1270
1271         CtdlGetRelationship(&vbuf, &USscratch, &CC->room);
1272         if (op == 1) {
1273                 vbuf.v_flags = vbuf.v_flags & ~V_FORGET & ~V_LOCKOUT;
1274                 vbuf.v_flags = vbuf.v_flags | V_ACCESS;
1275         }
1276         if (op == 0) {
1277                 vbuf.v_flags = vbuf.v_flags & ~V_ACCESS;
1278                 vbuf.v_flags = vbuf.v_flags | V_FORGET | V_LOCKOUT;
1279         }
1280         CtdlSetRelationship(&vbuf, &USscratch, &CC->room);
1281
1282         /* post a message in Aide> saying what we just did */
1283         snprintf(bbb, sizeof bbb, "%s has been %s \"%s\" by %s.\n",
1284                 iuser,
1285                 ((op == 1) ? "invited to" : "kicked out of"),
1286                 CC->room.QRname,
1287                 CC->user.fullname);
1288         aide_message(bbb,"User Admin Message");
1289
1290         return(0);
1291 }
1292
1293
1294 /*
1295  * INVT and KICK commands
1296  */
1297 void cmd_invt_kick(char *iuser, int op) {
1298
1299         /*
1300          * These commands are only allowed by aides, room aides,
1301          * and room namespace owners
1302          */
1303         if (is_room_aide()
1304            || (atol(CC->room.QRname) == CC->user.usernum) ) {
1305                 /* access granted */
1306         } else {
1307                 /* access denied */
1308                 cprintf("%d Higher access or room ownership required.\n",
1309                         ERROR + HIGHER_ACCESS_REQUIRED);
1310                 return;
1311         }
1312
1313         if (!strncasecmp(CC->room.QRname, config.c_baseroom,
1314                          ROOMNAMELEN)) {
1315                 cprintf("%d Can't add/remove users from this room.\n",
1316                         ERROR + NOT_HERE);
1317                 return;
1318         }
1319
1320         if (CtdlInvtKick(iuser, op) != 0) {
1321                 cprintf("%d No such user.\n", ERROR + NO_SUCH_USER);
1322                 return;
1323         }
1324
1325         cprintf("%d %s %s %s.\n",
1326                 CIT_OK, iuser,
1327                 ((op == 1) ? "invited to" : "kicked out of"),
1328                 CC->room.QRname);
1329         return;
1330 }
1331
1332
1333 /*
1334  * Forget (Zap) the current room (API call)
1335  * Returns 0 on success
1336  */
1337 int CtdlForgetThisRoom(void) {
1338         struct visit vbuf;
1339
1340         /* On some systems, Aides are not allowed to forget rooms */
1341         if (is_aide() && (config.c_aide_zap == 0)
1342            && ((CC->room.QRflags & QR_MAILBOX) == 0)  ) {
1343                 return(1);
1344         }
1345
1346         lgetuser(&CC->user, CC->curr_user);
1347         CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
1348
1349         vbuf.v_flags = vbuf.v_flags | V_FORGET;
1350         vbuf.v_flags = vbuf.v_flags & ~V_ACCESS;
1351
1352         CtdlSetRelationship(&vbuf, &CC->user, &CC->room);
1353         lputuser(&CC->user);
1354
1355         /* Return to the Lobby, so we don't end up in an undefined room */
1356         usergoto(config.c_baseroom, 0, 0, NULL, NULL);
1357         return(0);
1358
1359 }
1360
1361
1362 /*
1363  * forget (Zap) the current room
1364  */
1365 void cmd_forg(void)
1366 {
1367
1368         if (CtdlAccessCheck(ac_logged_in)) {
1369                 return;
1370         }
1371
1372         if (CtdlForgetThisRoom() == 0) {
1373                 cprintf("%d Ok\n", CIT_OK);
1374         }
1375         else {
1376                 cprintf("%d You may not forget this room.\n", ERROR + NOT_HERE);
1377         }
1378 }
1379
1380 /*
1381  * Get Next Unregistered User
1382  */
1383 void cmd_gnur(void)
1384 {
1385         struct cdbdata *cdbus;
1386         struct ctdluser usbuf;
1387
1388         if (CtdlAccessCheck(ac_aide)) {
1389                 return;
1390         }
1391
1392         if ((CitControl.MMflags & MM_VALID) == 0) {
1393                 cprintf("%d There are no unvalidated users.\n", CIT_OK);
1394                 return;
1395         }
1396
1397         /* There are unvalidated users.  Traverse the user database,
1398          * and return the first user we find that needs validation.
1399          */
1400         cdb_rewind(CDB_USERS);
1401         while (cdbus = cdb_next_item(CDB_USERS), cdbus != NULL) {
1402                 memset(&usbuf, 0, sizeof(struct ctdluser));
1403                 memcpy(&usbuf, cdbus->ptr,
1404                        ((cdbus->len > sizeof(struct ctdluser)) ?
1405                         sizeof(struct ctdluser) : cdbus->len));
1406                 cdb_free(cdbus);
1407                 if ((usbuf.flags & US_NEEDVALID)
1408                     && (usbuf.axlevel > 0)) {
1409                         cprintf("%d %s\n", MORE_DATA, usbuf.fullname);
1410                         cdb_close_cursor(CDB_USERS);
1411                         return;
1412                 }
1413         }
1414
1415         /* If we get to this point, there are no more unvalidated users.
1416          * Therefore we clear the "users need validation" flag.
1417          */
1418
1419         begin_critical_section(S_CONTROL);
1420         get_control();
1421         CitControl.MMflags = CitControl.MMflags & (~MM_VALID);
1422         put_control();
1423         end_critical_section(S_CONTROL);
1424         cprintf("%d *** End of registration.\n", CIT_OK);
1425
1426
1427 }
1428
1429
1430 /*
1431  * validate a user
1432  */
1433 void cmd_vali(char *v_args)
1434 {
1435         char user[128];
1436         int newax;
1437         struct ctdluser userbuf;
1438
1439         extract_token(user, v_args, 0, '|', sizeof user);
1440         newax = extract_int(v_args, 1);
1441
1442         if (CtdlAccessCheck(ac_aide)) {
1443                 return;
1444         }
1445
1446         if (lgetuser(&userbuf, user) != 0) {
1447                 cprintf("%d '%s' not found.\n", ERROR + NO_SUCH_USER, user);
1448                 return;
1449         }
1450
1451         userbuf.axlevel = newax;
1452         userbuf.flags = (userbuf.flags & ~US_NEEDVALID);
1453
1454         lputuser(&userbuf);
1455
1456         /* If the access level was set to zero, delete the user */
1457         if (newax == 0) {
1458                 if (purge_user(user) == 0) {
1459                         cprintf("%d %s Deleted.\n", CIT_OK, userbuf.fullname);
1460                         return;
1461                 }
1462         }
1463         cprintf("%d User '%s' validated.\n", CIT_OK, userbuf.fullname);
1464 }
1465
1466
1467
1468 /* 
1469  *  Traverse the user file...
1470  */
1471 void ForEachUser(void (*CallBack) (struct ctdluser * EachUser, void *out_data),
1472                  void *in_data)
1473 {
1474         struct ctdluser usbuf;
1475         struct cdbdata *cdbus;
1476
1477         cdb_rewind(CDB_USERS);
1478
1479         while (cdbus = cdb_next_item(CDB_USERS), cdbus != NULL) {
1480                 memset(&usbuf, 0, sizeof(struct ctdluser));
1481                 memcpy(&usbuf, cdbus->ptr,
1482                        ((cdbus->len > sizeof(struct ctdluser)) ?
1483                         sizeof(struct ctdluser) : cdbus->len));
1484                 cdb_free(cdbus);
1485                 (*CallBack) (&usbuf, in_data);
1486         }
1487 }
1488
1489
1490 /*
1491  * List one user (this works with cmd_list)
1492  */
1493 void ListThisUser(struct ctdluser *usbuf, void *data)
1494 {
1495         char *searchstring;
1496
1497         searchstring = (char *)data;
1498         if (bmstrcasestr(usbuf->fullname, searchstring) == NULL) {
1499                 return;
1500         }
1501
1502         if (usbuf->axlevel > 0) {
1503                 if ((CC->user.axlevel >= 6)
1504                     || ((usbuf->flags & US_UNLISTED) == 0)
1505                     || ((CC->internal_pgm))) {
1506                         cprintf("%s|%d|%ld|%ld|%ld|%ld|",
1507                                 usbuf->fullname,
1508                                 usbuf->axlevel,
1509                                 usbuf->usernum,
1510                                 (long)usbuf->lastcall,
1511                                 usbuf->timescalled,
1512                                 usbuf->posted);
1513                         if (CC->user.axlevel >= 6)
1514                                 cprintf("%s", usbuf->password);
1515                         cprintf("\n");
1516                 }
1517         }
1518 }
1519
1520 /* 
1521  *  List users (searchstring may be empty to list all users)
1522  */
1523 void cmd_list(char *cmdbuf)
1524 {
1525         char searchstring[256];
1526         extract_token(searchstring, cmdbuf, 0, '|', sizeof searchstring);
1527         striplt(searchstring);
1528         cprintf("%d \n", LISTING_FOLLOWS);
1529         ForEachUser(ListThisUser, (void *)searchstring );
1530         cprintf("000\n");
1531 }
1532
1533
1534
1535
1536 /*
1537  * assorted info we need to check at login
1538  */
1539 void cmd_chek(void)
1540 {
1541         int mail = 0;
1542         int regis = 0;
1543         int vali = 0;
1544
1545         if (CtdlAccessCheck(ac_logged_in)) {
1546                 return;
1547         }
1548
1549         getuser(&CC->user, CC->curr_user);      /* no lock is needed here */
1550         if ((REGISCALL != 0) && ((CC->user.flags & US_REGIS) == 0))
1551                 regis = 1;
1552
1553         if (CC->user.axlevel >= 6) {
1554                 get_control();
1555                 if (CitControl.MMflags & MM_VALID)
1556                         vali = 1;
1557         }
1558
1559         /* check for mail */
1560         mail = InitialMailCheck();
1561
1562         cprintf("%d %d|%d|%d|%s|\n", CIT_OK, mail, regis, vali, CC->cs_inet_email);
1563 }
1564
1565
1566 /*
1567  * check to see if a user exists
1568  */
1569 void cmd_qusr(char *who)
1570 {
1571         struct ctdluser usbuf;
1572
1573         if (getuser(&usbuf, who) == 0) {
1574                 cprintf("%d %s\n", CIT_OK, usbuf.fullname);
1575         } else {
1576                 cprintf("%d No such user.\n", ERROR + NO_SUCH_USER);
1577         }
1578 }
1579
1580
1581 /*
1582  * Administrative Get User Parameters
1583  */
1584 void cmd_agup(char *cmdbuf)
1585 {
1586         struct ctdluser usbuf;
1587         char requested_user[128];
1588
1589         if (CtdlAccessCheck(ac_aide)) {
1590                 return;
1591         }
1592
1593         extract_token(requested_user, cmdbuf, 0, '|', sizeof requested_user);
1594         if (getuser(&usbuf, requested_user) != 0) {
1595                 cprintf("%d No such user.\n", ERROR + NO_SUCH_USER);
1596                 return;
1597         }
1598         cprintf("%d %s|%s|%u|%ld|%ld|%d|%ld|%ld|%d\n",
1599                 CIT_OK,
1600                 usbuf.fullname,
1601                 usbuf.password,
1602                 usbuf.flags,
1603                 usbuf.timescalled,
1604                 usbuf.posted,
1605                 (int) usbuf.axlevel,
1606                 usbuf.usernum,
1607                 (long)usbuf.lastcall,
1608                 usbuf.USuserpurge);
1609 }
1610
1611
1612
1613 /*
1614  * Administrative Set User Parameters
1615  */
1616 void cmd_asup(char *cmdbuf)
1617 {
1618         struct ctdluser usbuf;
1619         char requested_user[128];
1620         char notify[SIZ];
1621         int np;
1622         int newax;
1623         int deleted = 0;
1624
1625         if (CtdlAccessCheck(ac_aide))
1626                 return;
1627
1628         extract_token(requested_user, cmdbuf, 0, '|', sizeof requested_user);
1629         if (lgetuser(&usbuf, requested_user) != 0) {
1630                 cprintf("%d No such user.\n", ERROR + NO_SUCH_USER);
1631                 return;
1632         }
1633         np = num_parms(cmdbuf);
1634         if (np > 1)
1635                 extract_token(usbuf.password, cmdbuf, 1, '|', sizeof usbuf.password);
1636         if (np > 2)
1637                 usbuf.flags = extract_int(cmdbuf, 2);
1638         if (np > 3)
1639                 usbuf.timescalled = extract_int(cmdbuf, 3);
1640         if (np > 4)
1641                 usbuf.posted = extract_int(cmdbuf, 4);
1642         if (np > 5) {
1643                 newax = extract_int(cmdbuf, 5);
1644                 if ((newax >= 0) && (newax <= 6)) {
1645                         usbuf.axlevel = extract_int(cmdbuf, 5);
1646                 }
1647         }
1648         if (np > 7) {
1649                 usbuf.lastcall = extract_long(cmdbuf, 7);
1650         }
1651         if (np > 8) {
1652                 usbuf.USuserpurge = extract_int(cmdbuf, 8);
1653         }
1654         lputuser(&usbuf);
1655         if (usbuf.axlevel == 0) {
1656                 if (purge_user(requested_user) == 0) {
1657                         deleted = 1;
1658                 }
1659         }
1660
1661         if (deleted) {
1662                 snprintf(notify, SIZ, 
1663                          "User \"%s\" has been deleted by %s.\n",
1664                          usbuf.fullname, CC->user.fullname);
1665                 aide_message(notify, "User Deletion Message");
1666         }
1667
1668         cprintf("%d Ok", CIT_OK);
1669         if (deleted)
1670                 cprintf(" (%s deleted)", requested_user);
1671         cprintf("\n");
1672 }
1673
1674
1675
1676 /*
1677  * Check to see if the user who we just sent mail to is logged in.  If yes,
1678  * bump the 'new mail' counter for their session.  That enables them to
1679  * receive a new mail notification without having to hit the database.
1680  */
1681 void BumpNewMailCounter(long which_user) {
1682         struct CitContext *ptr;
1683
1684         begin_critical_section(S_SESSION_TABLE);
1685
1686         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1687                 if (ptr->user.usernum == which_user) {
1688                         ptr->newmail += 1;
1689                 }
1690         }
1691
1692         end_critical_section(S_SESSION_TABLE);
1693 }
1694
1695
1696 /*
1697  * Count the number of new mail messages the user has
1698  */
1699 int NewMailCount()
1700 {
1701         int num_newmsgs = 0;
1702
1703         num_newmsgs = CC->newmail;
1704         CC->newmail = 0;
1705
1706         return (num_newmsgs);
1707 }
1708
1709
1710 /*
1711  * Count the number of new mail messages the user has
1712  */
1713 int InitialMailCheck()
1714 {
1715         int num_newmsgs = 0;
1716         int a;
1717         char mailboxname[ROOMNAMELEN];
1718         struct ctdlroom mailbox;
1719         struct visit vbuf;
1720         struct cdbdata *cdbfr;
1721         long *msglist = NULL;
1722         int num_msgs = 0;
1723
1724         MailboxName(mailboxname, sizeof mailboxname, &CC->user, MAILROOM);
1725         if (getroom(&mailbox, mailboxname) != 0)
1726                 return (0);
1727         CtdlGetRelationship(&vbuf, &CC->user, &mailbox);
1728
1729         cdbfr = cdb_fetch(CDB_MSGLISTS, &mailbox.QRnumber, sizeof(long));
1730
1731         if (cdbfr != NULL) {
1732                 msglist = malloc(cdbfr->len);
1733                 memcpy(msglist, cdbfr->ptr, cdbfr->len);
1734                 num_msgs = cdbfr->len / sizeof(long);
1735                 cdb_free(cdbfr);
1736         }
1737         if (num_msgs > 0)
1738                 for (a = 0; a < num_msgs; ++a) {
1739                         if (msglist[a] > 0L) {
1740                                 if (msglist[a] > vbuf.v_lastseen) {
1741                                         ++num_newmsgs;
1742                                 }
1743                         }
1744                 }
1745         if (msglist != NULL)
1746                 free(msglist);
1747
1748         return (num_newmsgs);
1749 }
1750
1751
1752
1753 /*
1754  * Set the preferred view for the current user/room combination
1755  */
1756 void cmd_view(char *cmdbuf) {
1757         int requested_view;
1758         struct visit vbuf;
1759
1760         if (CtdlAccessCheck(ac_logged_in)) {
1761                 return;
1762         }
1763
1764         requested_view = extract_int(cmdbuf, 0);
1765
1766         CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
1767         vbuf.v_view = requested_view;
1768         CtdlSetRelationship(&vbuf, &CC->user, &CC->room);
1769         
1770         cprintf("%d ok\n", CIT_OK);
1771 }