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