Modified the behavior of ForEachUser() to do the two phase load/perform cycle
[citadel.git] / citadel / user_ops.c
1 /* 
2  * Server functions which perform operations on user objects.
3  *
4  * Copyright (c) 1987-2019 by the citadel.org team
5  *
6  * This program is open source software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License, version 3.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  */
14
15 #include <stdlib.h>
16 #include <unistd.h>
17 #include "sysdep.h"
18 #include <stdio.h>
19 #include <sys/stat.h>
20 #include <libcitadel.h>
21 #include "control.h"
22 #include "support.h"
23 #include "citserver.h"
24 #include "config.h"
25 #include "citadel_ldap.h"
26 #include "ctdl_module.h"
27 #include "user_ops.h"
28 #include "internet_addressing.h"
29
30 /* These pipes are used to talk to the chkpwd daemon, which is forked during startup */
31 int chkpwd_write_pipe[2];
32 int chkpwd_read_pipe[2];
33
34 /*
35  * Trim a string down to the maximum username size and return the new length
36  */
37 long cutusername(char *username) { 
38         long len;
39         len = strlen(username);
40         if (len >= USERNAME_SIZE)
41         {
42                 syslog(LOG_INFO, "Username too long: %s", username);
43                 len = USERNAME_SIZE - 1; 
44                 username[len]='\0';
45         }
46         return len;
47 }
48
49
50 /*
51  * makeuserkey() - convert a username into the format used as a database key
52  *               (it's just the username converted into lower case)
53  */
54 void makeuserkey(char *key, const char *username, long len) {
55         int i;
56
57         if (len >= USERNAME_SIZE)
58         {
59                 syslog(LOG_INFO, "Username too long: %s", username);
60                 len = USERNAME_SIZE - 1; 
61         }
62         for (i=0; i<=len; ++i) {
63                 key[i] = tolower(username[i]);
64         }
65 }
66
67
68 /*
69  * CtdlGetUser()        retrieve named user into supplied buffer.
70  *                      returns 0 on success
71  */
72 int CtdlGetUser(struct ctdluser *usbuf, char *name)
73 {
74         char usernamekey[USERNAME_SIZE];
75         struct cdbdata *cdbus;
76         long len = cutusername(name);
77
78         if (usbuf != NULL) {
79                 memset(usbuf, 0, sizeof(struct ctdluser));
80         }
81
82         makeuserkey(usernamekey, name, len);
83         cdbus = cdb_fetch(CDB_USERS, usernamekey, strlen(usernamekey));
84
85         if (cdbus == NULL) {    /* user not found */
86                 return(1);
87         }
88         if (usbuf != NULL) {
89                 memcpy(usbuf, cdbus->ptr, ((cdbus->len > sizeof(struct ctdluser)) ?  sizeof(struct ctdluser) : cdbus->len));
90         }
91         cdb_free(cdbus);
92         return(0);
93 }
94
95
96 int CtdlLockGetCurrentUser(void)
97 {
98         CitContext *CCC = CC;
99         return CtdlGetUser(&CCC->user, CCC->curr_user);
100 }
101
102
103 /*
104  * CtdlGetUserLock()  -  same as getuser() but locks the record
105  */
106 int CtdlGetUserLock(struct ctdluser *usbuf, char *name)
107 {
108         int retcode;
109
110         retcode = CtdlGetUser(usbuf, name);
111         if (retcode == 0) {
112                 begin_critical_section(S_USERS);
113         }
114         return(retcode);
115 }
116
117
118 /*
119  * CtdlPutUser()  -  write user buffer into the correct place on disk
120  */
121 void CtdlPutUser(struct ctdluser *usbuf)
122 {
123         char usernamekey[USERNAME_SIZE];
124
125         makeuserkey(usernamekey, usbuf->fullname, cutusername(usbuf->fullname));
126         usbuf->version = REV_LEVEL;
127         cdb_store(CDB_USERS, usernamekey, strlen(usernamekey), usbuf, sizeof(struct ctdluser));
128 }
129
130
131 void CtdlPutCurrentUserLock()
132 {
133         CtdlPutUser(&CC->user);
134 }
135
136
137 /*
138  * CtdlPutUserLock()  -  same as putuser() but locks the record
139  */
140 void CtdlPutUserLock(struct ctdluser *usbuf)
141 {
142         CtdlPutUser(usbuf);
143         end_critical_section(S_USERS);
144 }
145
146
147 /*
148  * rename_user()  -  this is tricky because the user's display name is the database key
149  *
150  * Returns 0 on success or nonzero if there was an error...
151  *
152  */
153 int rename_user(char *oldname, char *newname) {
154         int retcode = RENAMEUSER_OK;
155         struct ctdluser usbuf;
156
157         char oldnamekey[USERNAME_SIZE];
158         char newnamekey[USERNAME_SIZE];
159
160         /* Create the database keys... */
161         makeuserkey(oldnamekey, oldname, cutusername(oldname));
162         makeuserkey(newnamekey, newname, cutusername(newname));
163
164         /* Lock up and get going */
165         begin_critical_section(S_USERS);
166
167         /* We cannot rename a user who is currently logged in */
168         if (CtdlIsUserLoggedIn(oldname)) {
169                 end_critical_section(S_USERS);
170                 return RENAMEUSER_LOGGED_IN;
171         }
172
173         if (CtdlGetUser(&usbuf, newname) == 0) {
174                 retcode = RENAMEUSER_ALREADY_EXISTS;
175         }
176         else {
177
178                 if (CtdlGetUser(&usbuf, oldname) != 0) {
179                         retcode = RENAMEUSER_NOT_FOUND;
180                 }
181
182                 else {          /* Sanity checks succeeded.  Now rename the user. */
183                         if (usbuf.usernum == 0)
184                         {
185                                 syslog(LOG_DEBUG, "user_ops: can not rename user \"Citadel\".");
186                                 retcode = RENAMEUSER_NOT_FOUND;
187                         } else {
188                                 syslog(LOG_DEBUG, "user_ops: renaming <%s> to <%s>", oldname, newname);
189                                 cdb_delete(CDB_USERS, oldnamekey, strlen(oldnamekey));
190                                 safestrncpy(usbuf.fullname, newname, sizeof usbuf.fullname);
191                                 CtdlPutUser(&usbuf);
192                                 cdb_store(CDB_USERSBYNUMBER, &usbuf.usernum, sizeof(long), usbuf.fullname, strlen(usbuf.fullname)+1 );
193                                 retcode = RENAMEUSER_OK;
194                         }
195                 }
196         
197         }
198
199         end_critical_section(S_USERS);
200         return(retcode);
201 }
202
203
204 /*
205  * Index-generating function used by Ctdl[Get|Set]Relationship
206  */
207 int GenerateRelationshipIndex(char *IndexBuf,
208                               long RoomID,
209                               long RoomGen,
210                               long UserID)
211 {
212
213         struct {
214                 long iRoomID;
215                 long iRoomGen;
216                 long iUserID;
217         } TheIndex;
218
219         TheIndex.iRoomID = RoomID;
220         TheIndex.iRoomGen = RoomGen;
221         TheIndex.iUserID = UserID;
222
223         memcpy(IndexBuf, &TheIndex, sizeof(TheIndex));
224         return(sizeof(TheIndex));
225 }
226
227
228 /*
229  * Back end for CtdlSetRelationship()
230  */
231 void put_visit(visit *newvisit)
232 {
233         char IndexBuf[32];
234         int IndexLen = 0;
235
236         memset (IndexBuf, 0, sizeof (IndexBuf));
237         /* Generate an index */
238         IndexLen = GenerateRelationshipIndex(IndexBuf, newvisit->v_roomnum, newvisit->v_roomgen, newvisit->v_usernum);
239
240         /* Store the record */
241         cdb_store(CDB_VISIT, IndexBuf, IndexLen,
242                   newvisit, sizeof(visit)
243         );
244 }
245
246
247 /*
248  * Define a relationship between a user and a room
249  */
250 void CtdlSetRelationship(visit *newvisit,
251                          struct ctdluser *rel_user,
252                          struct ctdlroom *rel_room)
253 {
254         /* We don't use these in Citadel because they're implicit by the
255          * index, but they must be present if the database is exported.
256          */
257         newvisit->v_roomnum = rel_room->QRnumber;
258         newvisit->v_roomgen = rel_room->QRgen;
259         newvisit->v_usernum = rel_user->usernum;
260
261         put_visit(newvisit);
262 }
263
264
265 /*
266  * Locate a relationship between a user and a room
267  */
268 void CtdlGetRelationship(visit *vbuf,
269                          struct ctdluser *rel_user,
270                          struct ctdlroom *rel_room)
271 {
272         char IndexBuf[32];
273         int IndexLen;
274         struct cdbdata *cdbvisit;
275
276         /* Generate an index */
277         IndexLen = GenerateRelationshipIndex(IndexBuf, rel_room->QRnumber, rel_room->QRgen, rel_user->usernum);
278
279         /* Clear out the buffer */
280         memset(vbuf, 0, sizeof(visit));
281
282         cdbvisit = cdb_fetch(CDB_VISIT, IndexBuf, IndexLen);
283         if (cdbvisit != NULL) {
284                 memcpy(vbuf, cdbvisit->ptr, ((cdbvisit->len > sizeof(visit)) ?  sizeof(visit) : cdbvisit->len));
285                 cdb_free(cdbvisit);
286         }
287         else {
288                 /* If this is the first time the user has seen this room,
289                  * set the view to be the default for the room.
290                  */
291                 vbuf->v_view = rel_room->QRdefaultview;
292         }
293
294         /* Set v_seen if necessary */
295         if (vbuf->v_seen[0] == 0) {
296                 snprintf(vbuf->v_seen, sizeof vbuf->v_seen, "*:%ld", vbuf->v_lastseen);
297         }
298 }
299
300
301 void CtdlMailboxName(char *buf, size_t n, const struct ctdluser *who, const char *prefix)
302 {
303         snprintf(buf, n, "%010ld.%s", who->usernum, prefix);
304 }
305
306
307 void MailboxName(char *buf, size_t n, const struct ctdluser *who, const char *prefix)
308 {
309         snprintf(buf, n, "%010ld.%s", who->usernum, prefix);
310 }
311
312
313 /*
314  * Check to see if the specified user has Internet mail permission
315  * (returns nonzero if permission is granted)
316  */
317 int CtdlCheckInternetMailPermission(struct ctdluser *who) {
318
319         /* Do not allow twits to send Internet mail */
320         if (who->axlevel <= AxProbU) return(0);
321
322         /* Globally enabled? */
323         if (CtdlGetConfigInt("c_restrict") == 0) return(1);
324
325         /* User flagged ok? */
326         if (who->flags & US_INTERNET) return(2);
327
328         /* Admin level access? */
329         if (who->axlevel >= AxAideU) return(3);
330
331         /* No mail for you! */
332         return(0);
333 }
334
335
336 /*
337  * Convenience function.
338  */
339 int CtdlAccessCheck(int required_level)
340 {
341         if (CC->internal_pgm) return(0);
342         if (required_level >= ac_internal) {
343                 cprintf("%d This is not a user-level command.\n", ERROR + HIGHER_ACCESS_REQUIRED);
344                 return(-1);
345         }
346
347         if ((required_level >= ac_logged_in_or_guest) && (CC->logged_in == 0) && (CtdlGetConfigInt("c_guest_logins") == 0)) {
348                 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
349                 return(-1);
350         }
351
352         if ((required_level >= ac_logged_in) && (CC->logged_in == 0)) {
353                 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
354                 return(-1);
355         }
356
357         if (CC->user.axlevel >= AxAideU) return(0);
358         if (required_level >= ac_aide) {
359                 cprintf("%d This command requires Admin access.\n",
360                         ERROR + HIGHER_ACCESS_REQUIRED);
361                 return(-1);
362         }
363
364         if (is_room_aide()) return(0);
365         if (required_level >= ac_room_aide) {
366                 cprintf("%d This command requires Admin or Room Admin access.\n",
367                         ERROR + HIGHER_ACCESS_REQUIRED);
368                 return(-1);
369         }
370
371         /* shhh ... succeed quietly */
372         return(0);
373 }
374
375
376 /*
377  * Is the user currently logged in an Admin?
378  */
379 int is_aide(void)
380 {
381         if (CC->user.axlevel >= AxAideU)
382                 return(1);
383         else
384                 return(0);
385 }
386
387
388 /*
389  * Is the user currently logged in an Admin *or* the room Admin for this room?
390  */
391 int is_room_aide(void)
392 {
393
394         if (!CC->logged_in) {
395                 return(0);
396         }
397
398         if ((CC->user.axlevel >= AxAideU) || (CC->room.QRroomaide == CC->user.usernum)) {
399                 return(1);
400         } else {
401                 return(0);
402         }
403 }
404
405
406 /*
407  * CtdlGetUserByNumber() -      get user by number
408  *                      returns 0 if user was found
409  *
410  * Note: fetching a user this way requires one additional database operation.
411  */
412 int CtdlGetUserByNumber(struct ctdluser *usbuf, long number)
413 {
414         struct cdbdata *cdbun;
415         int r;
416
417         cdbun = cdb_fetch(CDB_USERSBYNUMBER, &number, sizeof(long));
418         if (cdbun == NULL) {
419                 syslog(LOG_INFO, "user_ops: %ld not found", number);
420                 return(-1);
421         }
422
423         syslog(LOG_INFO, "user_ops: %ld maps to %s", number, cdbun->ptr);
424         r = CtdlGetUser(usbuf, cdbun->ptr);
425         cdb_free(cdbun);
426         return(r);
427 }
428
429
430 /*
431  * Helper function for rebuild_usersbynumber()
432  */
433 void rebuild_ubn_for_user(char *username, void *data) {
434         struct ctdluser u;
435
436         syslog(LOG_DEBUG, "user_ops: rebuilding usersbynumber index for %s", username);
437         if (CtdlGetUser(&u, username) == 0) {
438                 cdb_store(CDB_USERSBYNUMBER, &(u.usernum), sizeof(long), u.fullname, strlen(u.fullname)+1);
439         }
440 }
441
442
443 /*
444  * Rebuild the users-by-number index
445  */
446 void rebuild_usersbynumber(void) {
447         cdb_trunc(CDB_USERSBYNUMBER);                   /* delete the old indices */
448         ForEachUser(rebuild_ubn_for_user, NULL);        /* enumerate the users */
449 }
450
451
452 /*
453  * getuserbyuid()       Get user by system uid (for PAM mode authentication)
454  *                      Returns 0 if user was found
455  *                      This now uses an extauth index.
456  */
457 int getuserbyuid(struct ctdluser *usbuf, uid_t number)
458 {
459         struct cdbdata *cdbextauth;
460         long usernum = 0;
461         StrBuf *claimed_id;
462
463         claimed_id = NewStrBuf();
464         StrBufPrintf(claimed_id, "uid:%d", number);
465         cdbextauth = cdb_fetch(CDB_EXTAUTH, ChrPtr(claimed_id), StrLength(claimed_id));
466         FreeStrBuf(&claimed_id);
467         if (cdbextauth == NULL) {
468                 return(-1);
469         }
470
471         memcpy(&usernum, cdbextauth->ptr, sizeof(long));
472         cdb_free(cdbextauth);
473
474         if (!CtdlGetUserByNumber(usbuf, usernum)) {
475                 return(0);
476         }
477
478         return(-1);
479 }
480
481
482 /*
483  * Back end for cmd_user() and its ilk
484  */
485 int CtdlLoginExistingUser(const char *trythisname)
486 {
487         char username[SIZ];
488         int found_user;
489
490         syslog(LOG_DEBUG, "user_ops: CtdlLoginExistingUser(%s)", trythisname);
491
492         if ((CC->logged_in)) {
493                 return login_already_logged_in;
494         }
495
496         if (trythisname == NULL) return login_not_found;
497         
498         if (!strncasecmp(trythisname, "SYS_", 4))
499         {
500                 syslog(LOG_DEBUG, "user_ops: system user \"%s\" is not allowed to log in.", trythisname);
501                 return login_not_found;
502         }
503
504         /* Continue attempting user validation... */
505         safestrncpy(username, trythisname, sizeof (username));
506         striplt(username);
507
508         if (IsEmptyStr(username)) {
509                 return login_not_found;
510         }
511
512         if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
513
514                 /* host auth mode */
515
516                 struct passwd pd;
517                 struct passwd *tempPwdPtr;
518                 char pwdbuffer[256];
519         
520                 syslog(LOG_DEBUG, "user_ops: asking host about <%s>", username);
521 #ifdef HAVE_GETPWNAM_R
522 #ifdef SOLARIS_GETPWUID
523                 syslog(LOG_DEBUG, "user_ops: calling getpwnam_r()");
524                 tempPwdPtr = getpwnam_r(username, &pd, pwdbuffer, sizeof pwdbuffer);
525 #else // SOLARIS_GETPWUID
526                 syslog(LOG_DEBUG, "user_ops: calling getpwnam_r()");
527                 getpwnam_r(username, &pd, pwdbuffer, sizeof pwdbuffer, &tempPwdPtr);
528 #endif // SOLARIS_GETPWUID
529 #else // HAVE_GETPWNAM_R
530                 syslog(LOG_DEBUG, "user_ops: SHOULD NEVER GET HERE!!!");
531                 tempPwdPtr = NULL;
532 #endif // HAVE_GETPWNAM_R
533                 if (tempPwdPtr == NULL) {
534                         syslog(LOG_DEBUG, "user_ops: no such user <%s>", username);
535                         return login_not_found;
536                 }
537         
538                 /* Locate the associated Citadel account.  If not found, make one attempt to create it. */
539                 found_user = getuserbyuid(&CC->user, pd.pw_uid);
540                 if (found_user != 0) {
541                         create_user(username, CREATE_USER_DO_NOT_BECOME_USER, pd.pw_uid);
542                         found_user = getuserbyuid(&CC->user, pd.pw_uid);
543                 }
544                 syslog(LOG_DEBUG, "user_ops: found it: uid=%ld, gecos=%s here: %d", (long)pd.pw_uid, pd.pw_gecos, found_user);
545
546         }
547
548 #ifdef HAVE_LDAP
549         else if ((CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP) || (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD)) {
550         
551                 /* LDAP auth mode */
552
553                 uid_t ldap_uid;
554                 char ldap_cn[256];
555                 char ldap_dn[256];
556
557                 found_user = CtdlTryUserLDAP(username, ldap_dn, sizeof ldap_dn, ldap_cn, sizeof ldap_cn, &ldap_uid);
558                 if (found_user != 0) {
559                         return login_not_found;
560                 }
561
562                 found_user = getuserbyuid(&CC->user, ldap_uid);
563                 if (found_user != 0) {
564                         create_user(ldap_cn, CREATE_USER_DO_NOT_BECOME_USER, ldap_uid);
565                         found_user = getuserbyuid(&CC->user, ldap_uid);
566                 }
567
568                 if (found_user == 0) {
569                         if (CC->ldap_dn != NULL) free(CC->ldap_dn);
570                         CC->ldap_dn = strdup(ldap_dn);
571                 }
572
573         }
574 #endif
575
576         else {
577                 /* native auth mode */
578
579                 recptypes *valid = NULL;
580         
581                 /* First, try to log in as if the supplied name is a display name */
582                 found_user = CtdlGetUser(&CC->user, username);
583         
584                 /* If that didn't work, try to log in as if the supplied name * is an e-mail address */
585                 if (found_user != 0) {
586                         valid = validate_recipients(username, NULL, 0);
587                         if (valid != NULL) {
588                                 if (valid->num_local == 1) {
589                                         found_user = CtdlGetUser(&CC->user, valid->recp_local);
590                                 }
591                                 free_recipients(valid);
592                         }
593                 }
594         }
595
596         /* Did we find something? */
597         if (found_user == 0) {
598                 if (((CC->nologin)) && (CC->user.axlevel < AxAideU)) {
599                         return login_too_many_users;
600                 } else {
601                         safestrncpy(CC->curr_user, CC->user.fullname, sizeof CC->curr_user);
602                         return login_ok;
603                 }
604         }
605         return login_not_found;
606 }
607
608
609 /*
610  * session startup code which is common to both cmd_pass() and cmd_newu()
611  */
612 void do_login(void)
613 {
614         CC->logged_in = 1;
615         syslog(LOG_NOTICE, "user_ops: <%s> logged in", CC->curr_user);
616
617         CtdlGetUserLock(&CC->user, CC->curr_user);
618         ++(CC->user.timescalled);
619         CC->previous_login = CC->user.lastcall;
620         time(&CC->user.lastcall);
621
622         /* If this user's name is the name of the system administrator
623          * (as specified in setup), automatically assign access level 6.
624          */
625         if ( (!IsEmptyStr(CtdlGetConfigStr("c_sysadm"))) && (!strcasecmp(CC->user.fullname, CtdlGetConfigStr("c_sysadm"))) ) {
626                 CC->user.axlevel = AxAideU;
627         }
628
629         /* If we're authenticating off the host system, automatically give root the highest level of access. */
630         if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
631                 if (CC->user.uid == 0) {
632                         CC->user.axlevel = AxAideU;
633                 }
634         }
635         CtdlPutUserLock(&CC->user);
636
637         /* If we are using LDAP authentication, extract the user's email addresses from the directory. */
638 #ifdef HAVE_LDAP
639         if ((CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP) || (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD)) {
640                 char new_emailaddrs[512];
641                 if (CtdlGetConfigInt("c_ldap_sync_email_addrs") > 0) {
642                         if (extract_email_addresses_from_ldap(CC->ldap_dn, new_emailaddrs) == 0) {
643                                 CtdlSetEmailAddressesForUser(CC->user.fullname, new_emailaddrs);
644                         }
645                 }
646         }
647 #endif
648
649         /* If the user does not have any email addresses assigned, generate one. */
650         if (IsEmptyStr(CC->user.emailaddrs)) {
651                 AutoGenerateEmailAddressForUser(&CC->user);
652         }
653
654         /*
655          * Populate cs_inet_email and cs_inet_other_emails with valid email addresses from the user record
656          */
657         strcpy(CC->cs_inet_email, CC->user.emailaddrs);
658         char *firstsep = strstr(CC->cs_inet_email, "|");
659         if (firstsep) {
660                 strcpy(CC->cs_inet_other_emails, firstsep+1);
661                 *firstsep = 0;
662         }
663         else {
664                 CC->cs_inet_other_emails[0] = 0;
665         }
666
667         /* Create any personal rooms required by the system.
668          * (Technically, MAILROOM should be there already, but just in case...)
669          */
670         CtdlCreateRoom(MAILROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
671         CtdlCreateRoom(SENTITEMS, 4, "", 0, 1, 0, VIEW_MAILBOX);
672         CtdlCreateRoom(USERTRASHROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
673         CtdlCreateRoom(USERDRAFTROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
674
675         /* Run any startup routines registered by loadable modules */
676         PerformSessionHooks(EVT_LOGIN);
677
678         /* Enter the lobby */
679         CtdlUserGoto(CtdlGetConfigStr("c_baseroom"), 0, 0, NULL, NULL, NULL, NULL);
680 }
681
682
683 void logged_in_response(void)
684 {
685         cprintf("%d %s|%d|%ld|%ld|%u|%ld|%ld\n",
686                 CIT_OK, CC->user.fullname, CC->user.axlevel,
687                 CC->user.timescalled, CC->user.posted,
688                 CC->user.flags, CC->user.usernum,
689                 CC->previous_login
690         );
691 }
692
693
694 void CtdlUserLogout(void)
695 {
696         CitContext *CCC = MyContext();
697
698         syslog(LOG_DEBUG, "user_ops: CtdlUserLogout() logging out <%s> from session %d", CCC->curr_user, CCC->cs_pid);
699
700         /* Run any hooks registered by modules... */
701         PerformSessionHooks(EVT_LOGOUT);
702         
703         /*
704          * Clear out some session data.  Most likely, the CitContext for this
705          * session is about to get nuked when the session disconnects, but
706          * since it's possible to log in again without reconnecting, we cannot
707          * make that assumption.
708          */
709         CCC->logged_in = 0;
710
711         /* Check to see if the user was deleted while logged in and purge them if necessary */
712         if ((CCC->user.axlevel == AxDeleted) && (CCC->user.usernum)) {
713                 purge_user(CCC->user.fullname);
714         }
715
716         /* Clear out the user record in memory so we don't behave like a ghost */
717         memset(&CCC->user, 0, sizeof(struct ctdluser));
718         CCC->curr_user[0] = 0;
719         CCC->cs_inet_email[0] = 0;
720         CCC->cs_inet_other_emails[0] = 0;
721         CCC->cs_inet_fn[0] = 0;
722
723         /* Free any output buffers */
724         unbuffer_output();
725 }
726
727
728 /*
729  * Validate a password on the host unix system by talking to the chkpwd daemon
730  */
731 static int validpw(uid_t uid, const char *pass)
732 {
733         char buf[256];
734         int rv = 0;
735
736         if (IsEmptyStr(pass)) {
737                 syslog(LOG_DEBUG, "user_ops: refusing to chkpwd for uid=%d with empty password", uid);
738                 return 0;
739         }
740
741         syslog(LOG_DEBUG, "user_ops: validating password for uid=%d using chkpwd...", uid);
742
743         begin_critical_section(S_CHKPWD);
744         rv = write(chkpwd_write_pipe[1], &uid, sizeof(uid_t));
745         if (rv == -1) {
746                 syslog(LOG_ERR, "user_ops: communication with chkpwd broken: %m");
747                 end_critical_section(S_CHKPWD);
748                 return 0;
749         }
750         rv = write(chkpwd_write_pipe[1], pass, 256);
751         if (rv == -1) {
752                 syslog(LOG_ERR, "user_ops: communication with chkpwd broken: %m");
753                 end_critical_section(S_CHKPWD);
754                 return 0;
755         }
756         rv = read(chkpwd_read_pipe[0], buf, 4);
757         if (rv == -1) {
758                 syslog(LOG_ERR, "user_ops: ommunication with chkpwd broken: %m");
759                 end_critical_section(S_CHKPWD);
760                 return 0;
761         }
762         end_critical_section(S_CHKPWD);
763
764         if (!strncmp(buf, "PASS", 4)) {
765                 syslog(LOG_DEBUG, "user_ops: chkpwd pass");
766                 return(1);
767         }
768
769         syslog(LOG_DEBUG, "user_ops: chkpwd fail");
770         return 0;
771 }
772
773
774 /* 
775  * Start up the chkpwd daemon so validpw() has something to talk to
776  */
777 void start_chkpwd_daemon(void) {
778         pid_t chkpwd_pid;
779         struct stat filestats;
780         int i;
781
782         syslog(LOG_DEBUG, "user_ops: starting chkpwd daemon for host authentication mode");
783
784         if ((stat(file_chkpwd, &filestats)==-1) || (filestats.st_size==0)) {
785                 syslog(LOG_ERR, "user_ops: %s: %m", file_chkpwd);
786                 abort();
787         }
788         if (pipe(chkpwd_write_pipe) != 0) {
789                 syslog(LOG_ERR, "user_ops: unable to create pipe for chkpwd daemon: %m");
790                 abort();
791         }
792         if (pipe(chkpwd_read_pipe) != 0) {
793                 syslog(LOG_ERR, "user_ops: unable to create pipe for chkpwd daemon: %m");
794                 abort();
795         }
796
797         chkpwd_pid = fork();
798         if (chkpwd_pid < 0) {
799                 syslog(LOG_ERR, "user_ops: unable to fork chkpwd daemon: %m");
800                 abort();
801         }
802         if (chkpwd_pid == 0) {
803                 dup2(chkpwd_write_pipe[0], 0);
804                 dup2(chkpwd_read_pipe[1], 1);
805                 for (i=2; i<256; ++i) close(i);
806                 execl(file_chkpwd, file_chkpwd, NULL);
807                 syslog(LOG_ERR, "user_ops: unable to exec chkpwd daemon: %m");
808                 abort();
809                 exit(errno);
810         }
811 }
812
813
814 int CtdlTryPassword(const char *password, long len)
815 {
816         int code;
817         CitContext *CCC = CC;
818
819         if ((CCC->logged_in)) {
820                 syslog(LOG_WARNING, "user_ops: CtdlTryPassword: already logged in");
821                 return pass_already_logged_in;
822         }
823         if (!strcmp(CCC->curr_user, NLI)) {
824                 syslog(LOG_WARNING, "user_ops: CtdlTryPassword: no user selected");
825                 return pass_no_user;
826         }
827         if (CtdlGetUser(&CCC->user, CCC->curr_user)) {
828                 syslog(LOG_ERR, "user_ops: CtdlTryPassword: internal error");
829                 return pass_internal_error;
830         }
831         if (password == NULL) {
832                 syslog(LOG_INFO, "user_ops: CtdlTryPassword: NULL password string supplied");
833                 return pass_wrong_password;
834         }
835
836         else if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
837
838                 /* host auth mode */
839
840                 if (validpw(CCC->user.uid, password)) {
841                         code = 0;
842
843                         /*
844                          * sooper-seekrit hack: populate the password field in the
845                          * citadel database with the password that the user typed,
846                          * if it's correct.  This allows most sites to convert from
847                          * host auth to native auth if they want to.  If you think
848                          * this is a security hazard, comment it out.
849                          */
850
851                         CtdlGetUserLock(&CCC->user, CCC->curr_user);
852                         safestrncpy(CCC->user.password, password, sizeof CCC->user.password);
853                         CtdlPutUserLock(&CCC->user);
854
855                         /*
856                          * (sooper-seekrit hack ends here)
857                          */
858                 }
859                 else {
860                         code = (-1);
861                 }
862         }
863
864 #ifdef HAVE_LDAP
865         else if ((CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP) || (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD)) {
866
867                 /* LDAP auth mode */
868
869                 if ((CCC->ldap_dn) && (!CtdlTryPasswordLDAP(CCC->ldap_dn, password))) {
870                         code = 0;
871                 }
872                 else {
873                         code = (-1);
874                 }
875         }
876 #endif
877
878         else {
879
880                 /* native auth mode */
881                 char *pw;
882
883                 pw = (char*) malloc(len + 1);
884                 memcpy(pw, password, len + 1);
885                 strproc(pw);
886                 strproc(CCC->user.password);
887                 code = strcasecmp(CCC->user.password, pw);
888                 if (code != 0) {
889                         strproc(pw);
890                         strproc(CCC->user.password);
891                         code = strcasecmp(CCC->user.password, pw);
892                 }
893                 free (pw);
894         }
895
896         if (!code) {
897                 do_login();
898                 return pass_ok;
899         }
900         else {
901                 syslog(LOG_WARNING, "user_ops: bad password specified for <%s> Service <%s> Port <%ld> Remote <%s / %s>",
902                         CCC->curr_user,
903                         CCC->ServiceName,
904                         CCC->tcp_port,
905                         CCC->cs_host,
906                         CCC->cs_addr
907                 );
908                 return pass_wrong_password;
909         }
910 }
911
912
913 /*
914  * Delete a user record *and* all of its related resources.
915  */
916 int purge_user(char pname[])
917 {
918         struct ctdluser usbuf;
919         char usernamekey[USERNAME_SIZE];
920
921         makeuserkey(usernamekey, pname, cutusername(pname));
922
923         /* If the name is empty we can't find them in the DB any way so just return */
924         if (IsEmptyStr(pname)) {
925                 return(ERROR + NO_SUCH_USER);
926         }
927
928         if (CtdlGetUser(&usbuf, pname) != 0) {
929                 syslog(LOG_ERR, "user_ops: cannot purge user <%s> - not found", pname);
930                 return(ERROR + NO_SUCH_USER);
931         }
932
933         /* Don't delete a user who is currently logged in.  Instead, just
934          * set the access level to 0, and let the account get swept up
935          * during the next purge.
936          */
937         if (CtdlIsUserLoggedInByNum(usbuf.usernum)) {
938                 syslog(LOG_WARNING, "user_ops: <%s> is logged in; not deleting", pname);
939                 usbuf.axlevel = AxDeleted;
940                 CtdlPutUser(&usbuf);
941                 return(1);
942         }
943
944         syslog(LOG_NOTICE, "user_ops: deleting <%s>", pname);
945
946         /* Perform any purge functions registered by server extensions */
947         PerformUserHooks(&usbuf, EVT_PURGEUSER);
948
949         /* delete any existing user/room relationships */
950         cdb_delete(CDB_VISIT, &usbuf.usernum, sizeof(long));
951
952         /* delete the users-by-number index record */
953         cdb_delete(CDB_USERSBYNUMBER, &usbuf.usernum, sizeof(long));
954
955         /* delete the userlog entry */
956         cdb_delete(CDB_USERS, usernamekey, strlen(usernamekey));
957
958         return(0);
959 }
960
961
962 int internal_create_user(char *username, struct ctdluser *usbuf, uid_t uid)
963 {
964         if (!CtdlGetUser(usbuf, username)) {
965                 return(ERROR + ALREADY_EXISTS);
966         }
967
968         /* Go ahead and initialize a new user record */
969         memset(usbuf, 0, sizeof(struct ctdluser));
970         safestrncpy(usbuf->fullname, username, sizeof usbuf->fullname);
971         strcpy(usbuf->password, "");
972         usbuf->uid = uid;
973
974         /* These are the default flags on new accounts */
975         usbuf->flags = US_LASTOLD | US_DISAPPEAR | US_PAGINATOR | US_FLOORS;
976
977         usbuf->timescalled = 0;
978         usbuf->posted = 0;
979         usbuf->axlevel = CtdlGetConfigInt("c_initax");
980         usbuf->lastcall = time(NULL);
981
982         /* fetch a new user number */
983         usbuf->usernum = get_new_user_number();
984
985         /* add user to the database */
986         CtdlPutUser(usbuf);
987         cdb_store(CDB_USERSBYNUMBER, &usbuf->usernum, sizeof(long), usbuf->fullname, strlen(usbuf->fullname)+1);
988
989         /* If non-native auth, index by uid */
990         if ((usbuf->uid > 0) && (usbuf->uid != NATIVE_AUTH_UID)) {
991                 StrBuf *claimed_id = NewStrBuf();
992                 StrBufPrintf(claimed_id, "uid:%d", usbuf->uid);
993                 attach_extauth(usbuf, claimed_id);
994                 FreeStrBuf(&claimed_id);
995         }
996
997         return(0);
998 }
999
1000
1001 /*
1002  * create_user()  -  back end processing to create a new user
1003  *
1004  * Set 'newusername' to the desired account name.
1005  * Set 'become_user' to CREATE_USER_BECOME_USER if this is self-service account creation and we want to
1006  *                   actually log in as the user we just created, otherwise set it to CREATE_USER_DO_NOT_BECOME_USER
1007  * Set 'uid' to some uid_t value to associate the account with an external auth user, or (-1) for native auth
1008  */
1009 int create_user(char *username, int become_user, uid_t uid)
1010 {
1011         struct ctdluser usbuf;
1012         struct ctdlroom qrbuf;
1013         char mailboxname[ROOMNAMELEN];
1014         char buf[SIZ];
1015         int retval;
1016
1017         strproc(username);
1018         if ((retval = internal_create_user(username, &usbuf, uid)) != 0) {
1019                 return retval;
1020         }
1021
1022         /*
1023          * Give the user a private mailbox and a configuration room.
1024          * Make the latter an invisible system room.
1025          */
1026         CtdlMailboxName(mailboxname, sizeof mailboxname, &usbuf, MAILROOM);
1027         CtdlCreateRoom(mailboxname, 5, "", 0, 1, 1, VIEW_MAILBOX);
1028
1029         CtdlMailboxName(mailboxname, sizeof mailboxname, &usbuf, USERCONFIGROOM);
1030         CtdlCreateRoom(mailboxname, 5, "", 0, 1, 1, VIEW_BBS);
1031         if (CtdlGetRoomLock(&qrbuf, mailboxname) == 0) {
1032                 qrbuf.QRflags2 |= QR2_SYSTEM;
1033                 CtdlPutRoomLock(&qrbuf);
1034         }
1035
1036         /* Perform any create functions registered by server extensions */
1037         PerformUserHooks(&usbuf, EVT_NEWUSER);
1038
1039         /* Everything below this line can be bypassed if administratively
1040          * creating a user, instead of doing self-service account creation
1041          */
1042
1043         if (become_user == CREATE_USER_BECOME_USER) {
1044                 /* Now become the user we just created */
1045                 memcpy(&CC->user, &usbuf, sizeof(struct ctdluser));
1046                 safestrncpy(CC->curr_user, username, sizeof CC->curr_user);
1047                 do_login();
1048         
1049                 /* Check to make sure we're still who we think we are */
1050                 if (CtdlGetUser(&CC->user, CC->curr_user)) {
1051                         return(ERROR + INTERNAL_ERROR);
1052                 }
1053         }
1054         
1055         snprintf(buf, SIZ, 
1056                 "New user account <%s> has been created, from host %s [%s].\n",
1057                 username,
1058                 CC->cs_host,
1059                 CC->cs_addr
1060         );
1061         CtdlAideMessage(buf, "User Creation Notice");
1062         syslog(LOG_NOTICE, "user_ops: <%s> created", username);
1063         return(0);
1064 }
1065
1066
1067 /*
1068  * set password - back end api code
1069  */
1070 void CtdlSetPassword(char *new_pw)
1071 {
1072         CtdlGetUserLock(&CC->user, CC->curr_user);
1073         safestrncpy(CC->user.password, new_pw, sizeof(CC->user.password));
1074         CtdlPutUserLock(&CC->user);
1075         syslog(LOG_INFO, "user_ops: password changed for <%s>", CC->curr_user);
1076         PerformSessionHooks(EVT_SETPASS);
1077 }
1078
1079
1080 /*
1081  * API function for cmd_invt_kick() and anything else that needs to
1082  * invite or kick out a user to/from a room.
1083  * 
1084  * Set iuser to the name of the user, and op to 1=invite or 0=kick
1085  */
1086 int CtdlInvtKick(char *iuser, int op) {
1087         struct ctdluser USscratch;
1088         visit vbuf;
1089         char bbb[SIZ];
1090
1091         if (CtdlGetUser(&USscratch, iuser) != 0) {
1092                 return(1);
1093         }
1094
1095         CtdlGetRelationship(&vbuf, &USscratch, &CC->room);
1096         if (op == 1) {
1097                 vbuf.v_flags = vbuf.v_flags & ~V_FORGET & ~V_LOCKOUT;
1098                 vbuf.v_flags = vbuf.v_flags | V_ACCESS;
1099         }
1100         if (op == 0) {
1101                 vbuf.v_flags = vbuf.v_flags & ~V_ACCESS;
1102                 vbuf.v_flags = vbuf.v_flags | V_FORGET | V_LOCKOUT;
1103         }
1104         CtdlSetRelationship(&vbuf, &USscratch, &CC->room);
1105
1106         /* post a message in Aide> saying what we just did */
1107         snprintf(bbb, sizeof bbb, "%s has been %s \"%s\" by %s.\n",
1108                 iuser,
1109                 ((op == 1) ? "invited to" : "kicked out of"),
1110                 CC->room.QRname,
1111                 (CC->logged_in ? CC->user.fullname : "an administrator")
1112         );
1113         CtdlAideMessage(bbb,"User Admin Message");
1114         return(0);
1115 }
1116
1117
1118 /*
1119  * Forget (Zap) the current room (API call)
1120  * Returns 0 on success
1121  */
1122 int CtdlForgetThisRoom(void) {
1123         visit vbuf;
1124
1125         /* On some systems, Admins are not allowed to forget rooms */
1126         if (is_aide() && (CtdlGetConfigInt("c_aide_zap") == 0)
1127            && ((CC->room.QRflags & QR_MAILBOX) == 0)  ) {
1128                 return(1);
1129         }
1130
1131         CtdlGetUserLock(&CC->user, CC->curr_user);
1132         CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
1133
1134         vbuf.v_flags = vbuf.v_flags | V_FORGET;
1135         vbuf.v_flags = vbuf.v_flags & ~V_ACCESS;
1136
1137         CtdlSetRelationship(&vbuf, &CC->user, &CC->room);
1138         CtdlPutUserLock(&CC->user);
1139
1140         /* Return to the Lobby, so we don't end up in an undefined room */
1141         CtdlUserGoto(CtdlGetConfigStr("c_baseroom"), 0, 0, NULL, NULL, NULL, NULL);
1142         return(0);
1143 }
1144
1145
1146 /* 
1147  * Traverse the user file and perform a callback for each user record.
1148  * (New improved version that runs in two phases so that callbacks can perform writes without having a r/o cursor open)
1149  */
1150 void ForEachUser(void (*CallBack) (char *, void *out_data), void *in_data)
1151 {
1152         struct feu {
1153                 char username[USERNAME_SIZE];
1154                 int version;
1155         };
1156
1157         struct cdbdata *cdbus;
1158         struct ctdluser *usptr;
1159         int i = 0;
1160         struct feu *usernames = NULL;
1161         int num_users = 0;
1162         int num_users_alloc = 0;
1163
1164         cdb_rewind(CDB_USERS);
1165
1166         // Phase 1 : load list of usernames
1167         while (cdbus = cdb_next_item(CDB_USERS), cdbus != NULL) {
1168                 usptr = (struct ctdluser *) cdbus->ptr;
1169
1170                 if (strlen(usptr->fullname) > 0) {
1171                         ++num_users;
1172                         if (num_users > num_users_alloc) {
1173                                 num_users_alloc = ((num_users_alloc == 0) ? 1 : (num_users_alloc * 2));
1174                                 usernames = realloc(usernames, num_users_alloc * sizeof(struct feu));
1175                         }
1176                         strcpy(usernames[num_users-1].username, usptr->fullname);
1177                         usernames[num_users-1].version = usptr->version;
1178                 }
1179         }
1180
1181         // Phase 2 : perform the callback for each username
1182         for (i=0; i<num_users; ++i) {
1183                 if (usernames[i].version < 927) {
1184                         // FIXME we have to reindex this record
1185                 }
1186                 (*CallBack) (usernames[i].username, in_data);
1187         }
1188
1189         free(usernames);
1190 }
1191
1192
1193 /*
1194  * Count the number of new mail messages the user has
1195  */
1196 int NewMailCount()
1197 {
1198         int num_newmsgs = 0;
1199         num_newmsgs = CC->newmail;
1200         CC->newmail = 0;
1201         return(num_newmsgs);
1202 }
1203
1204
1205 /*
1206  * Count the number of new mail messages the user has
1207  */
1208 int InitialMailCheck()
1209 {
1210         int num_newmsgs = 0;
1211         int a;
1212         char mailboxname[ROOMNAMELEN];
1213         struct ctdlroom mailbox;
1214         visit vbuf;
1215         struct cdbdata *cdbfr;
1216         long *msglist = NULL;
1217         int num_msgs = 0;
1218
1219         CtdlMailboxName(mailboxname, sizeof mailboxname, &CC->user, MAILROOM);
1220         if (CtdlGetRoom(&mailbox, mailboxname) != 0)
1221                 return(0);
1222         CtdlGetRelationship(&vbuf, &CC->user, &mailbox);
1223
1224         cdbfr = cdb_fetch(CDB_MSGLISTS, &mailbox.QRnumber, sizeof(long));
1225
1226         if (cdbfr != NULL) {
1227                 msglist = malloc(cdbfr->len);
1228                 memcpy(msglist, cdbfr->ptr, cdbfr->len);
1229                 num_msgs = cdbfr->len / sizeof(long);
1230                 cdb_free(cdbfr);
1231         }
1232         if (num_msgs > 0)
1233                 for (a = 0; a < num_msgs; ++a) {
1234                         if (msglist[a] > 0L) {
1235                                 if (msglist[a] > vbuf.v_lastseen) {
1236                                         ++num_newmsgs;
1237                                 }
1238                         }
1239                 }
1240         if (msglist != NULL)
1241                 free(msglist);
1242
1243         return(num_newmsgs);
1244 }