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