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