1 // Server functions which perform operations on user objects.
3 // Copyright (c) 1987-2023 by the citadel.org team
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.
13 #include <libcitadel.h>
16 #include "citserver.h"
18 #include "citadel_ldap.h"
19 #include "ctdl_module.h"
21 #include "internet_addressing.h"
23 // These pipes are used to talk to the chkpwd daemon, which is forked during startup
24 int chkpwd_write_pipe[2];
25 int chkpwd_read_pipe[2];
28 // makeuserkey() - convert a username into the format used as a database key
29 // "key" must be a buffer of at least USERNAME_SIZE
30 // (Key format is the username with all non-alphanumeric characters removed, and converted to lower case.)
31 void makeuserkey(char *key, const char *username) {
35 if (IsEmptyStr(username)) {
40 int len = strlen(username);
41 for (i=0; ((i<=len) && (i<USERNAME_SIZE-1)); ++i) {
42 if (isalnum((username[i]))) {
43 key[keylen++] = tolower(username[i]);
50 // Compare two usernames to see if they are the same user after being keyed for the database
51 // Usage is identical to strcmp()
52 int CtdlUserCmp(char *s1, char *s2) {
53 char k1[USERNAME_SIZE];
54 char k2[USERNAME_SIZE];
58 return(strcmp(k1,k2));
62 // CtdlGetUser() retrieve named user into supplied buffer.
63 // returns 0 on success
64 int CtdlGetUser(struct ctdluser *usbuf, char *name) {
65 char usernamekey[USERNAME_SIZE];
66 struct cdbdata *cdbus;
69 memset(usbuf, 0, sizeof(struct ctdluser));
72 makeuserkey(usernamekey, name);
73 if (IsEmptyStr(usernamekey)) {
74 return(1); // empty user name
76 cdbus = cdb_fetch(CDB_USERS, usernamekey, strlen(usernamekey));
78 if (cdbus == NULL) { // user not found
82 memcpy(usbuf, cdbus->ptr, ((cdbus->len > sizeof(struct ctdluser)) ? sizeof(struct ctdluser) : cdbus->len));
89 int CtdlLockGetCurrentUser(void) {
90 return CtdlGetUser(&CC->user, CC->curr_user);
94 // CtdlGetUserLock() - same as getuser() but locks the record
95 int CtdlGetUserLock(struct ctdluser *usbuf, char *name) {
98 retcode = CtdlGetUser(usbuf, name);
100 begin_critical_section(S_USERS);
106 // CtdlPutUser() - write user buffer into the correct place on disk
107 void CtdlPutUser(struct ctdluser *usbuf) {
108 char usernamekey[USERNAME_SIZE];
109 makeuserkey(usernamekey, usbuf->fullname);
110 usbuf->version = REV_LEVEL;
111 cdb_store(CDB_USERS, usernamekey, strlen(usernamekey), usbuf, sizeof(struct ctdluser));
115 void CtdlPutCurrentUserLock() {
116 CtdlPutUser(&CC->user);
120 // CtdlPutUserLock() - same as putuser() but locks the record
121 void CtdlPutUserLock(struct ctdluser *usbuf) {
123 end_critical_section(S_USERS);
127 // rename_user() - this is tricky because the user's display name is the database key
128 // Returns 0 on success or nonzero if there was an error...
129 int rename_user(char *oldname, char *newname) {
130 int retcode = RENAMEUSER_OK;
131 struct ctdluser usbuf;
133 char oldnamekey[USERNAME_SIZE];
134 char newnamekey[USERNAME_SIZE];
136 // Create the database keys...
137 makeuserkey(oldnamekey, oldname);
138 makeuserkey(newnamekey, newname);
140 // Lock up and get going
141 begin_critical_section(S_USERS);
143 // We cannot rename a user who is currently logged in
144 if (CtdlIsUserLoggedIn(oldname)) {
145 end_critical_section(S_USERS);
146 return RENAMEUSER_LOGGED_IN;
149 if (CtdlGetUser(&usbuf, newname) == 0) {
150 retcode = RENAMEUSER_ALREADY_EXISTS;
154 if (CtdlGetUser(&usbuf, oldname) != 0) {
155 retcode = RENAMEUSER_NOT_FOUND;
157 else { // Sanity checks succeeded. Now rename the user.
158 if (usbuf.usernum == 0) {
159 syslog(LOG_DEBUG, "user_ops: can not rename user \"Citadel\".");
160 retcode = RENAMEUSER_NOT_FOUND;
163 syslog(LOG_DEBUG, "user_ops: renaming <%s> to <%s>", oldname, newname);
164 cdb_delete(CDB_USERS, oldnamekey, strlen(oldnamekey));
165 safestrncpy(usbuf.fullname, newname, sizeof usbuf.fullname);
167 cdb_store(CDB_USERSBYNUMBER, &usbuf.usernum, sizeof(long), usbuf.fullname, strlen(usbuf.fullname)+1 );
168 retcode = RENAMEUSER_OK;
174 end_critical_section(S_USERS);
179 // Convert a username into the format used as a database key prior to version 928
180 // This only gets called by reindex_user_928()
181 void makeuserkey_pre928(char *key, const char *username) {
184 int len = strlen(username);
186 if (len >= USERNAME_SIZE) {
187 syslog(LOG_INFO, "Username too long: %s", username);
188 len = USERNAME_SIZE - 1;
190 for (i=0; i<=len; ++i) {
191 key[i] = tolower(username[i]);
196 // Read a user record using the pre-v928 index format, and write it back using the v928-and-higher index format.
197 // This ONLY gets called during an upgrade from version <928 to version >=928.
198 void reindex_user_928(char *username, void *out_data) {
200 char oldkey[USERNAME_SIZE];
201 char newkey[USERNAME_SIZE];
202 struct cdbdata *cdbus;
203 struct ctdluser usbuf;
205 makeuserkey_pre928(oldkey, username);
206 makeuserkey(newkey, username);
208 syslog(LOG_DEBUG, "user_ops: reindex_user_928: %s <%s> --> <%s>", username, oldkey, newkey);
210 // Fetch the user record using the old index format
211 cdbus = cdb_fetch(CDB_USERS, oldkey, strlen(oldkey));
213 syslog(LOG_INFO, "user_ops: <%s> not found, were they already reindexed?", username);
216 memcpy(&usbuf, cdbus->ptr, ((cdbus->len > sizeof(struct ctdluser)) ? sizeof(struct ctdluser) : cdbus->len));
219 // delete the old record
220 cdb_delete(CDB_USERS, oldkey, strlen(oldkey));
222 // write the new record
223 cdb_store(CDB_USERS, newkey, strlen(newkey), &usbuf, sizeof(struct ctdluser));
227 // Index-generating function used by Ctdl[Get|Set]Relationship
228 int GenerateRelationshipIndex(char *IndexBuf, long RoomID, long RoomGen, long UserID) {
229 struct visit_index TheIndex;
230 TheIndex.iRoomID = RoomID;
231 TheIndex.iRoomGen = RoomGen;
232 TheIndex.iUserID = UserID;
234 memcpy(IndexBuf, &TheIndex, sizeof(TheIndex));
235 return(sizeof(TheIndex));
238 // Back end for CtdlSetRelationship()
239 void put_visit(struct visit *newvisit) {
240 cdb_store(CDB_VISIT, newvisit, (sizeof(long)*3), newvisit, sizeof(struct visit));
244 // Define a relationship between a user and a room
245 void CtdlSetRelationship(struct visit *newvisit, struct ctdluser *rel_user, struct ctdlroom *rel_room) {
246 // We don't use these in Citadel because they're implicit by the
247 // index, but they must be present if the database is exported.
248 newvisit->v_roomnum = rel_room->QRnumber;
249 newvisit->v_roomgen = rel_room->QRgen;
250 newvisit->v_usernum = rel_user->usernum;
257 // Locate a relationship between a user and a room
258 void CtdlGetRelationship(struct visit *vbuf, struct ctdluser *rel_user, struct ctdlroom *rel_room) {
259 struct cdbdata *cdbvisit;
261 // Clear out the buffer
262 memset(vbuf, 0, sizeof(struct visit));
264 // Fill out the first three fields; they are also the index
265 vbuf->v_roomnum = rel_room->QRnumber;
266 vbuf->v_roomgen = rel_room->QRgen;
267 vbuf->v_usernum = rel_user->usernum;
269 cdbvisit = cdb_fetch(CDB_VISIT, vbuf, (sizeof(long)*3));
270 if (cdbvisit != NULL) {
271 memcpy(vbuf, cdbvisit->ptr, ((cdbvisit->len > sizeof(struct visit)) ? sizeof(struct visit) : cdbvisit->len));
275 // If this is the first time the user has seen this room, set the view to be the default for the room.
276 vbuf->v_view = rel_room->QRdefaultview;
279 // Set v_seen if necessary
280 if (vbuf->v_seen[0] == 0) {
281 snprintf(vbuf->v_seen, sizeof vbuf->v_seen, "*:%ld", vbuf->v_lastseen);
286 void CtdlMailboxName(char *buf, size_t n, const struct ctdluser *who, const char *prefix) {
287 snprintf(buf, n, "%010ld.%s", who->usernum, prefix);
291 // Check to see if the specified user has Internet mail permission
292 // (returns nonzero if permission is granted)
293 int CtdlCheckInternetMailPermission(struct ctdluser *who) {
295 // Do not allow twits to send Internet mail
296 if (who->axlevel <= AxProbU) return(0);
299 if (CtdlGetConfigInt("c_restrict") == 0) return(1);
302 if (who->flags & US_INTERNET) return(2);
304 // Admin level access?
305 if (who->axlevel >= AxAideU) return(3);
312 // This is a convenience function which follows the Citadel protocol semantics for most commands.
313 // If the current user does not have the requested access level, it outputs a protocol-friendly error message
314 // and then returns (-1). This allows calling functions to complete an access level check in one line of code.
315 int CtdlAccessCheck(int required_level) {
316 if (CC->internal_pgm) return(0);
317 if (required_level >= ac_internal) {
318 cprintf("%d This is not a user-level command.\n", ERROR + HIGHER_ACCESS_REQUIRED);
322 if ((required_level >= ac_logged_in_or_guest) && (CC->logged_in == 0) && (CtdlGetConfigInt("c_guest_logins") == 0)) {
323 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
327 if ((required_level >= ac_logged_in) && (CC->logged_in == 0)) {
328 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
332 if (CC->user.axlevel >= AxAideU) return(0);
333 if (required_level >= ac_aide) {
334 cprintf("%d This command requires Admin access.\n",
335 ERROR + HIGHER_ACCESS_REQUIRED);
339 if (is_room_aide()) return(0);
340 if (required_level >= ac_room_aide) {
341 cprintf("%d This command requires Admin or Room Admin access.\n",
342 ERROR + HIGHER_ACCESS_REQUIRED);
346 // Do not generate any output if we succeeded -- the calling function will handle that.
351 // Is the user currently logged in an Admin?
353 if (CC->user.axlevel >= AxAideU) {
362 // Is the user currently logged in an Admin *or* the room Admin for this room?
363 int is_room_aide(void) {
364 if (!CC->logged_in) {
368 if ((CC->user.axlevel >= AxAideU) || (CC->room.QRroomaide == CC->user.usernum)) {
377 // CtdlGetUserByNumber() - get user by number, returns 0 if user was found
378 // Note: fetching a user this way requires one additional database operation.
379 int CtdlGetUserByNumber(struct ctdluser *usbuf, long number) {
380 struct cdbdata *cdbun;
383 cdbun = cdb_fetch(CDB_USERSBYNUMBER, &number, sizeof(long));
385 syslog(LOG_INFO, "user_ops: %ld not found", number);
389 syslog(LOG_INFO, "user_ops: %ld maps to %s", number, cdbun->ptr);
390 r = CtdlGetUser(usbuf, cdbun->ptr);
396 // Helper function for rebuild_usersbynumber()
397 void rebuild_ubn_for_user(char *username, void *data) {
400 syslog(LOG_DEBUG, "user_ops: rebuilding usersbynumber index for %s", username);
401 if (CtdlGetUser(&u, username) == 0) {
402 cdb_store(CDB_USERSBYNUMBER, &(u.usernum), sizeof(long), u.fullname, strlen(u.fullname)+1);
407 // Rebuild the users-by-number index
408 void rebuild_usersbynumber(void) {
409 cdb_trunc(CDB_USERSBYNUMBER); // delete the old indices
410 ForEachUser(rebuild_ubn_for_user, NULL); // enumerate the users
414 // getuserbyuid() Get user by system uid (for PAM mode authentication)
415 // Returns 0 if user was found
416 int getuserbyuid(struct ctdluser *usbuf, uid_t number) {
418 struct cdbdata *cdbus;
419 struct ctdluser *usptr;
420 int return_value = (-1);
422 // Yes, we do this the long way.
423 // No, we don't use CtdlForEachUser() because that requires multiple reads for each record
424 // TODO: make an index
425 cdb_rewind(CDB_USERS);
426 while (cdbus = cdb_next_item(CDB_USERS), cdbus != NULL) {
427 usptr = (struct ctdluser *) cdbus->ptr;
429 if (usptr->uid == number) {
430 syslog(LOG_DEBUG, "user_ops: found uid=%d username=%s", usptr->uid, usptr->fullname);
431 memcpy(usbuf, usptr, sizeof(struct ctdluser));
432 return_value = 0; // success
436 if (return_value != 0) {
437 syslog(LOG_DEBUG, "user_ops: no user found with uid=%d", number);
439 return(return_value);
443 // Back end for cmd_user() and its ilk
444 int CtdlLoginExistingUser(const char *trythisname) {
448 syslog(LOG_DEBUG, "user_ops: CtdlLoginExistingUser(%s)", trythisname);
450 if ((CC->logged_in)) {
451 return login_already_logged_in;
454 if (trythisname == NULL) return login_not_found;
456 // We handle this a different way now (see below)
457 //if (!strncasecmp(trythisname, "SYS_", 4)) {
458 //syslog(LOG_DEBUG, "user_ops: system user \"%s\" is not allowed to log in.", trythisname);
459 //return login_not_found;
462 // Continue attempting user validation...
463 safestrncpy(username, trythisname, sizeof (username));
464 string_trim(username);
466 if (IsEmptyStr(username)) {
467 return login_not_found;
471 if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
473 struct passwd *tempPwdPtr;
476 syslog(LOG_DEBUG, "user_ops: asking host about <%s>", username);
477 #ifdef HAVE_GETPWNAM_R
478 syslog(LOG_DEBUG, "user_ops: calling getpwnam_r()");
479 getpwnam_r(username, &pd, pwdbuffer, sizeof pwdbuffer, &tempPwdPtr);
480 #else // HAVE_GETPWNAM_R
481 syslog(LOG_DEBUG, "user_ops: SHOULD NEVER GET HERE!!!");
483 #endif // HAVE_GETPWNAM_R
484 if (tempPwdPtr == NULL) {
485 syslog(LOG_DEBUG, "user_ops: no such user <%s>", username);
486 return login_not_found;
489 // Locate the associated Citadel account. If not found, make one attempt to create it.
490 found_user = getuserbyuid(&CC->user, pd.pw_uid);
491 if (found_user != 0) {
492 create_user(username, CREATE_USER_DO_NOT_BECOME_USER, pd.pw_uid);
493 found_user = getuserbyuid(&CC->user, pd.pw_uid);
495 syslog(LOG_DEBUG, "user_ops: found it: uid=%ld, gecos=%s here: %d", (long)pd.pw_uid, pd.pw_gecos, found_user);
500 else if ((CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP) || (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD)) {
506 found_user = CtdlTryUserLDAP(username, ldap_dn, sizeof ldap_dn, ldap_cn, sizeof ldap_cn, &ldap_uid);
507 if (found_user != 0) {
508 return login_not_found;
511 found_user = getuserbyuid(&CC->user, ldap_uid);
512 if (found_user != 0) {
513 create_user(ldap_cn, CREATE_USER_DO_NOT_BECOME_USER, ldap_uid);
514 found_user = getuserbyuid(&CC->user, ldap_uid);
517 if (found_user == 0) {
518 if (CC->ldap_dn != NULL) free(CC->ldap_dn);
519 CC->ldap_dn = strdup(ldap_dn);
524 // native auth mode...
526 struct recptypes *valid = NULL;
528 // First, try to log in as if the supplied name is a display name
529 found_user = CtdlGetUser(&CC->user, username);
531 // If that didn't work, try to log in as if the supplied name * is an e-mail address
532 if (found_user != 0) {
533 valid = validate_recipients(username, NULL, 0);
535 if (valid->num_local == 1) {
536 found_user = CtdlGetUser(&CC->user, valid->recp_local);
538 free_recipients(valid);
543 // User 0 is a system account and must not be used by a real user
544 if (CC->user.usernum <= 0) {
545 syslog(LOG_DEBUG, "user_ops: system account <%s> is not allowed to log in.", trythisname);
546 return login_not_found;
549 // Did we find something?
550 if (found_user == 0) {
551 if (((CC->nologin)) && (CC->user.axlevel < AxAideU)) {
552 return login_too_many_users;
555 safestrncpy(CC->curr_user, CC->user.fullname, sizeof CC->curr_user);
559 return login_not_found;
563 // session startup code which is common to both cmd_pass() and cmd_newu()
564 void do_login(void) {
566 syslog(LOG_NOTICE, "user_ops: <%s> logged in", CC->curr_user);
568 CtdlGetUserLock(&CC->user, CC->curr_user);
569 CC->previous_login = CC->user.lastcall;
570 time(&CC->user.lastcall);
572 // If this user's name is the name of the system administrator
573 // (as specified in setup), automatically assign access level 6.
574 if ( (!IsEmptyStr(CtdlGetConfigStr("c_sysadm"))) && (!strcasecmp(CC->user.fullname, CtdlGetConfigStr("c_sysadm"))) ) {
575 CC->user.axlevel = AxAideU;
578 // If we're authenticating off the host system, automatically give root the highest level of access.
579 if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
580 if (CC->user.uid == 0) {
581 CC->user.axlevel = AxAideU;
584 CtdlPutUserLock(&CC->user);
586 // If we are using LDAP authentication, extract the user's email addresses from the directory.
587 if ((CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP) || (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD)) {
588 char new_emailaddrs[512];
589 if (CtdlGetConfigInt("c_ldap_sync_email_addrs") > 0) {
590 if (extract_email_addresses_from_ldap(CC->ldap_dn, new_emailaddrs) == 0) {
591 CtdlSetEmailAddressesForUser(CC->user.fullname, new_emailaddrs);
596 // If the user does not have any email addresses assigned, generate one.
597 if (IsEmptyStr(CC->user.emailaddrs)) {
598 AutoGenerateEmailAddressForUser(&CC->user);
601 // Populate the user principal identity, which is consistent and never aliased
602 strcpy(CC->cs_principal_id, "");
603 makeuserkey(CC->cs_principal_id, CC->user.fullname);
604 strcat(CC->cs_principal_id, "@");
605 strcat(CC->cs_principal_id, CtdlGetConfigStr("c_fqdn"));
607 // Populate cs_inet_email and cs_inet_other_emails with valid email addresses from the user record
608 strcpy(CC->cs_inet_email, CC->user.emailaddrs);
609 char *firstsep = strstr(CC->cs_inet_email, "|");
611 strcpy(CC->cs_inet_other_emails, firstsep+1);
615 CC->cs_inet_other_emails[0] = 0;
618 // Create any personal rooms required by the system.
619 // (Technically, MAILROOM should be there already, but just in case...)
620 CtdlCreateRoom(MAILROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
621 CtdlCreateRoom(SENTITEMS, 4, "", 0, 1, 0, VIEW_MAILBOX);
622 CtdlCreateRoom(USERTRASHROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
623 CtdlCreateRoom(USERDRAFTROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
625 // Run any startup routines registered by loadable modules
626 PerformSessionHooks(EVT_LOGIN);
629 CtdlUserGoto(CtdlGetConfigStr("c_baseroom"), 0, 0, NULL, NULL, NULL, NULL);
633 void logged_in_response(void) {
634 cprintf("%d %s|%d|0|0|%u|%ld|%ld\n",
635 CIT_OK, CC->user.fullname, CC->user.axlevel,
636 CC->user.flags, CC->user.usernum,
642 void CtdlUserLogout(void) {
644 syslog(LOG_DEBUG, "user_ops: CtdlUserLogout() logging out <%s> from session %d", CC->curr_user, CC->cs_pid);
646 // Run any hooks registered by modules...
647 PerformSessionHooks(EVT_LOGOUT);
649 // Clear out some session data. Most likely, the CitContext for this
650 // session is about to get nuked when the session disconnects, but
651 // since it's possible to log in again without reconnecting, we cannot
652 // make that assumption.
655 // Check to see if the user was deleted while logged in and purge them if necessary
656 if ((CC->user.axlevel == AxDeleted) && (CC->user.usernum)) {
657 purge_user(CC->user.fullname);
660 // Clear out the user record in memory so we don't behave like a ghost
661 memset(&CC->user, 0, sizeof(struct ctdluser));
662 CC->curr_user[0] = 0;
663 CC->cs_inet_email[0] = 0;
664 CC->cs_inet_other_emails[0] = 0;
665 CC->cs_inet_fn[0] = 0;
667 // Free any output buffers
672 // Validate a password on the host unix system by talking to the chkpwd daemon
673 static int validpw(uid_t uid, const char *pass) {
677 if (IsEmptyStr(pass)) {
678 syslog(LOG_DEBUG, "user_ops: refusing to chkpwd for uid=%d with empty password", uid);
682 syslog(LOG_DEBUG, "user_ops: validating password for uid=%d using chkpwd...", uid);
684 begin_critical_section(S_CHKPWD);
685 rv = write(chkpwd_write_pipe[1], &uid, sizeof(uid_t));
687 syslog(LOG_ERR, "user_ops: communication with chkpwd broken: %m");
688 end_critical_section(S_CHKPWD);
691 rv = write(chkpwd_write_pipe[1], pass, 256);
693 syslog(LOG_ERR, "user_ops: communication with chkpwd broken: %m");
694 end_critical_section(S_CHKPWD);
697 rv = read(chkpwd_read_pipe[0], buf, 4);
699 syslog(LOG_ERR, "user_ops: ommunication with chkpwd broken: %m");
700 end_critical_section(S_CHKPWD);
703 end_critical_section(S_CHKPWD);
705 if (!strncmp(buf, "PASS", 4)) {
706 syslog(LOG_DEBUG, "user_ops: chkpwd pass");
710 syslog(LOG_DEBUG, "user_ops: chkpwd fail");
715 // Start up the chkpwd daemon so validpw() has something to talk to
716 void start_chkpwd_daemon(void) {
718 struct stat filestats;
721 syslog(LOG_DEBUG, "user_ops: starting chkpwd daemon for host authentication mode");
723 if ((stat(file_chkpwd, &filestats)==-1) || (filestats.st_size==0)) {
724 syslog(LOG_ERR, "user_ops: %s: %m", file_chkpwd);
725 exit(CTDLEXIT_CHKPWD);
727 if (pipe(chkpwd_write_pipe) != 0) {
728 syslog(LOG_ERR, "user_ops: unable to create pipe for chkpwd daemon: %m");
729 exit(CTDLEXIT_CHKPWD);
731 if (pipe(chkpwd_read_pipe) != 0) {
732 syslog(LOG_ERR, "user_ops: unable to create pipe for chkpwd daemon: %m");
733 exit(CTDLEXIT_CHKPWD);
737 if (chkpwd_pid < 0) {
738 syslog(LOG_ERR, "user_ops: unable to fork chkpwd daemon: %m");
739 exit(CTDLEXIT_CHKPWD);
741 if (chkpwd_pid == 0) {
742 dup2(chkpwd_write_pipe[0], 0);
743 dup2(chkpwd_read_pipe[1], 1);
744 for (i=2; i<256; ++i) close(i);
745 execl(file_chkpwd, file_chkpwd, NULL);
746 syslog(LOG_ERR, "user_ops: unable to exec chkpwd daemon: %m");
752 int CtdlTryPassword(const char *password, long len) {
755 if ((CC->logged_in)) {
756 syslog(LOG_WARNING, "user_ops: CtdlTryPassword: already logged in");
757 return pass_already_logged_in;
759 if (!strcmp(CC->curr_user, NLI)) {
760 syslog(LOG_WARNING, "user_ops: CtdlTryPassword: no user selected");
763 if (CtdlGetUser(&CC->user, CC->curr_user)) {
764 syslog(LOG_ERR, "user_ops: CtdlTryPassword: internal error");
765 return pass_internal_error;
767 if (password == NULL) {
768 syslog(LOG_INFO, "user_ops: CtdlTryPassword: NULL password string supplied");
769 return pass_wrong_password;
773 else if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
774 if (validpw(CC->user.uid, password)) {
777 // sooper-seekrit hack: populate the password field in the
778 // citadel database with the password that the user typed,
779 // if it's correct. This allows most sites to convert from
780 // host auth to native auth if they want to. If you think
781 // this is a security hazard, comment it out.
783 CtdlGetUserLock(&CC->user, CC->curr_user);
784 safestrncpy(CC->user.password, password, sizeof CC->user.password);
785 CtdlPutUserLock(&CC->user);
787 // (sooper-seekrit hack ends here)
795 else if ((CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP) || (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD)) {
797 if ((CC->ldap_dn) && (!CtdlTryPasswordLDAP(CC->ldap_dn, password))) {
805 // native auth mode...
809 pw = (char*) malloc(len + 1);
810 memcpy(pw, password, len + 1);
812 strproc(CC->user.password);
813 code = strcasecmp(CC->user.password, pw);
816 strproc(CC->user.password);
817 code = strcasecmp(CC->user.password, pw);
827 syslog(LOG_WARNING, "user_ops: bad password specified for <%s> Service <%s> Port <%ld> Remote <%s / %s>",
834 return pass_wrong_password;
839 // Delete a user record *and* all of its related resources.
840 int purge_user(char pname[]) {
841 struct ctdluser usbuf;
842 char usernamekey[USERNAME_SIZE];
844 makeuserkey(usernamekey, pname);
846 // If the name is empty we can't find them in the DB any way so just return
847 if (IsEmptyStr(pname)) {
848 return(ERROR + NO_SUCH_USER);
851 if (CtdlGetUser(&usbuf, pname) != 0) {
852 syslog(LOG_ERR, "user_ops: cannot purge user <%s> - not found", pname);
853 return(ERROR + NO_SUCH_USER);
856 // Don't delete a user who is currently logged in. Instead, just
857 // set the access level to 0, and let the account get swept up
858 // during the next purge.
859 if (CtdlIsUserLoggedInByNum(usbuf.usernum)) {
860 syslog(LOG_WARNING, "user_ops: <%s> is logged in; not deleting", pname);
861 usbuf.axlevel = AxDeleted;
866 syslog(LOG_NOTICE, "user_ops: deleting <%s>", pname);
868 // Perform any purge functions registered by server extensions
869 PerformUserHooks(&usbuf, EVT_PURGEUSER);
871 // delete any existing user/room relationships
872 // Commenting out since it was assuming the user number was
873 // at the top of the index. Room number is actually first.
874 // Auto-Purge will clean up the records later, so not worth
875 // scanning all the records here.
876 //cdb_delete(CDB_VISIT, &usbuf.usernum, sizeof(long));
878 // delete the users-by-number index record
879 cdb_delete(CDB_USERSBYNUMBER, &usbuf.usernum, sizeof(long));
881 // delete the user entry
882 cdb_delete(CDB_USERS, usernamekey, strlen(usernamekey));
888 // This is the back end processing that happens when we create a new user account.
889 int internal_create_user(char *username, struct ctdluser *usbuf, uid_t uid) {
890 if (!CtdlGetUser(usbuf, username)) {
891 return(ERROR + ALREADY_EXISTS);
894 // Go ahead and initialize a new user record
895 memset(usbuf, 0, sizeof(struct ctdluser));
896 safestrncpy(usbuf->fullname, username, sizeof usbuf->fullname);
897 strcpy(usbuf->password, "");
900 // These are the default flags on new accounts
901 usbuf->flags = US_LASTOLD | US_DISAPPEAR | US_PAGINATOR | US_FLOORS;
902 usbuf->axlevel = CtdlGetConfigInt("c_initax");
903 usbuf->lastcall = time(NULL);
905 // fetch a new user number
906 usbuf->usernum = get_new_user_number();
908 // add user to the database
910 cdb_store(CDB_USERSBYNUMBER, &usbuf->usernum, sizeof(long), usbuf->fullname, strlen(usbuf->fullname)+1);
912 // If non-native auth, index by uid
913 if ((usbuf->uid > 0) && (usbuf->uid != NATIVE_AUTH_UID)) {
914 StrBuf *claimed_id = NewStrBuf();
915 StrBufPrintf(claimed_id, "uid:%d", usbuf->uid);
916 FreeStrBuf(&claimed_id);
923 // create_user() - back end processing to create a new user
925 // Set 'newusername' to the desired account name.
926 // Set 'become_user' to CREATE_USER_BECOME_USER if this is self-service account creation and we want to
927 // actually log in as the user we just created, otherwise set it to CREATE_USER_DO_NOT_BECOME_USER
928 // Set 'uid' to some uid_t value to associate the account with an external auth user, or (-1) for native auth
929 int create_user(char *username, int become_user, uid_t uid) {
930 struct ctdluser usbuf;
931 struct ctdlroom qrbuf;
932 char mailboxname[ROOMNAMELEN];
937 if ((retval = internal_create_user(username, &usbuf, uid)) != 0) {
941 // Give the user a private mailbox and a configuration room.
942 // Make the latter an invisible system room.
943 CtdlMailboxName(mailboxname, sizeof mailboxname, &usbuf, MAILROOM);
944 CtdlCreateRoom(mailboxname, 5, "", 0, 1, 1, VIEW_MAILBOX);
946 CtdlMailboxName(mailboxname, sizeof mailboxname, &usbuf, USERCONFIGROOM);
947 CtdlCreateRoom(mailboxname, 5, "", 0, 1, 1, VIEW_BBS);
948 if (CtdlGetRoomLock(&qrbuf, mailboxname) == 0) {
949 qrbuf.QRflags2 |= QR2_SYSTEM;
950 CtdlPutRoomLock(&qrbuf);
953 // Perform any create functions registered by server extensions
954 PerformUserHooks(&usbuf, EVT_NEWUSER);
956 // Everything below this line can be bypassed if administratively
957 // creating a user, instead of doing self-service account creation
959 if (become_user == CREATE_USER_BECOME_USER) {
960 // Now become the user we just created
961 memcpy(&CC->user, &usbuf, sizeof(struct ctdluser));
962 safestrncpy(CC->curr_user, username, sizeof CC->curr_user);
965 // Check to make sure we're still who we think we are
966 if (CtdlGetUser(&CC->user, CC->curr_user)) {
967 return(ERROR + INTERNAL_ERROR);
972 "New user account <%s> has been created, from host %s [%s].\n",
977 CtdlAideMessage(buf, "User Creation Notice");
978 syslog(LOG_NOTICE, "user_ops: <%s> created", username);
983 // set password - back end api code
984 void CtdlSetPassword(char *new_pw) {
985 CtdlGetUserLock(&CC->user, CC->curr_user);
986 safestrncpy(CC->user.password, new_pw, sizeof(CC->user.password));
987 CtdlPutUserLock(&CC->user);
988 syslog(LOG_INFO, "user_ops: password changed for <%s>", CC->curr_user);
989 PerformSessionHooks(EVT_SETPASS);
993 // API function for cmd_invt_kick() and anything else that needs to
994 // invite or kick out a user to/from a room.
996 // Set iuser to the name of the user, and op to 1=invite or 0=kick
997 int CtdlInvtKick(char *iuser, int op) {
998 struct ctdluser USscratch;
1002 if (CtdlGetUser(&USscratch, iuser) != 0) {
1006 CtdlGetRelationship(&vbuf, &USscratch, &CC->room);
1008 vbuf.v_flags = vbuf.v_flags & ~V_FORGET & ~V_LOCKOUT;
1009 vbuf.v_flags = vbuf.v_flags | V_ACCESS;
1012 vbuf.v_flags = vbuf.v_flags & ~V_ACCESS;
1013 vbuf.v_flags = vbuf.v_flags | V_FORGET | V_LOCKOUT;
1015 CtdlSetRelationship(&vbuf, &USscratch, &CC->room);
1017 // post a message in Aide> saying what we just did
1018 snprintf(bbb, sizeof bbb, "%s has been %s \"%s\" by %s.\n",
1020 ((op == 1) ? "invited to" : "kicked out of"),
1022 (CC->logged_in ? CC->user.fullname : "an administrator")
1024 CtdlAideMessage(bbb,"User Admin Message");
1029 // Forget (Zap) the current room (API call)
1030 // Returns 0 on success
1031 int CtdlForgetThisRoom(void) {
1034 // On some systems, Admins are not allowed to forget rooms
1035 if (is_aide() && (CtdlGetConfigInt("c_aide_zap") == 0)
1036 && ((CC->room.QRflags & QR_MAILBOX) == 0) ) {
1040 CtdlGetUserLock(&CC->user, CC->curr_user);
1041 CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
1043 vbuf.v_flags = vbuf.v_flags | V_FORGET;
1044 vbuf.v_flags = vbuf.v_flags & ~V_ACCESS;
1046 CtdlSetRelationship(&vbuf, &CC->user, &CC->room);
1047 CtdlPutUserLock(&CC->user);
1049 // Return to the Lobby, so we don't end up in an undefined room
1050 CtdlUserGoto(CtdlGetConfigStr("c_baseroom"), 0, 0, NULL, NULL, NULL, NULL);
1055 // Traverse the user file and perform a callback for each user record.
1056 // (New improved version that runs in two phases so that callbacks can perform writes without having a r/o cursor open)
1057 void ForEachUser(void (*CallBack) (char *, void *out_data), void *in_data) {
1058 struct cdbdata *cdbus;
1059 struct ctdluser *usptr;
1061 Array *all_users = array_new(USERNAME_SIZE);
1062 if (all_users == NULL) {
1063 syslog(LOG_ERR, "user_ops: alloc failed, ForEachUser() exiting");
1068 cdb_rewind(CDB_USERS);
1070 // Phase 1 : build an array of all our user account names
1071 while (cdbus = cdb_next_item(CDB_USERS), cdbus != NULL) {
1072 usptr = (struct ctdluser *) cdbus->ptr;
1073 if (strlen(usptr->fullname) > 0) {
1074 array_append(all_users, usptr->fullname);
1078 // Phase 2 : perform the callback for each user while de-allocating the list
1079 for (int i=0; i<array_len(all_users); ++i) {
1080 (*CallBack) (array_get_element_at(all_users, i), in_data);
1083 // Phase 3 : free the array
1084 array_free(all_users);
1088 // Return the number of new messages that have arrived in the user's inbox while they were logged in.
1089 // Resets to zero when called.
1090 int NewMailCount() {
1091 int num_newmsgs = 0;
1092 num_newmsgs = CC->newmail;
1094 return(num_newmsgs);
1098 // Count the number of new mail messages the user has
1099 int InitialMailCheck() {
1100 int num_newmsgs = 0;
1102 char mailboxname[ROOMNAMELEN];
1103 struct ctdlroom mailbox;
1105 struct cdbdata *cdbfr;
1106 long *msglist = NULL;
1109 CtdlMailboxName(mailboxname, sizeof mailboxname, &CC->user, MAILROOM);
1110 if (CtdlGetRoom(&mailbox, mailboxname) != 0)
1112 CtdlGetRelationship(&vbuf, &CC->user, &mailbox);
1114 cdbfr = cdb_fetch(CDB_MSGLISTS, &mailbox.QRnumber, sizeof(long));
1116 if (cdbfr != NULL) {
1117 msglist = malloc(cdbfr->len);
1118 memcpy(msglist, cdbfr->ptr, cdbfr->len);
1119 num_msgs = cdbfr->len / sizeof(long);
1123 for (a = 0; a < num_msgs; ++a) {
1124 if (msglist[a] > 0L) {
1125 if (msglist[a] > vbuf.v_lastseen) {
1130 if (msglist != NULL)
1133 return(num_newmsgs);
1137 // This is an undocumented rescue mode that can be used to rewrite an admin user account that has been corrupted.
1138 // To prevent abuse, it can only run as a one-shot when the server is not otherwise operational.
1139 // Don't use this without asking about it.
1140 void undocumented_rescue_mode(char *rescue_string) {
1141 struct ctdluser usbuf;
1142 memset(&usbuf, 0, sizeof(struct ctdluser));
1143 extract_token(usbuf.fullname, rescue_string, 0, '|', sizeof usbuf.password);
1144 extract_token(usbuf.password, rescue_string, 1, '|', sizeof usbuf.password);
1145 usbuf.usernum = extract_long(rescue_string, 2);
1147 usbuf.lastcall = time(NULL);
1148 CtdlPutUser(&usbuf);