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