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