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