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