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