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