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