2 * Server functions which perform operations on user objects.
4 * Copyright (c) 1987-2020 by the citadel.org team
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.
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.
20 #include <libcitadel.h>
23 #include "citserver.h"
25 #include "citadel_ldap.h"
26 #include "ctdl_module.h"
28 #include "internet_addressing.h"
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];
36 * makeuserkey() - convert a username into the format used as a database key
37 * "key" must be a buffer of at least USERNAME_SIZE
38 * (Key format is the username with all non-alphanumeric characters removed, and converted to lower case.)
40 void makeuserkey(char *key, const char *username) {
44 if (IsEmptyStr(username)) {
49 int len = strlen(username);
50 for (i=0; ((i<=len) && (i<USERNAME_SIZE-1)); ++i) {
51 if (isalnum((username[i]))) {
52 key[keylen++] = tolower(username[i]);
60 * Compare two usernames to see if they are the same user after being keyed for the database
61 * Usage is identical to strcmp()
63 int CtdlUserCmp(char *s1, char *s2) {
64 char k1[USERNAME_SIZE];
65 char k2[USERNAME_SIZE];
69 return(strcmp(k1,k2));
74 * CtdlGetUser() retrieve named user into supplied buffer.
75 * returns 0 on success
77 int CtdlGetUser(struct ctdluser *usbuf, char *name)
79 char usernamekey[USERNAME_SIZE];
80 struct cdbdata *cdbus;
83 memset(usbuf, 0, sizeof(struct ctdluser));
86 makeuserkey(usernamekey, name);
87 if (IsEmptyStr(usernamekey)) {
88 return(1); // empty user name
90 cdbus = cdb_fetch(CDB_USERS, usernamekey, strlen(usernamekey));
92 if (cdbus == NULL) { // user not found
96 memcpy(usbuf, cdbus->ptr, ((cdbus->len > sizeof(struct ctdluser)) ? sizeof(struct ctdluser) : cdbus->len));
103 int CtdlLockGetCurrentUser(void)
105 CitContext *CCC = CC;
106 return CtdlGetUser(&CCC->user, CCC->curr_user);
111 * CtdlGetUserLock() - same as getuser() but locks the record
113 int CtdlGetUserLock(struct ctdluser *usbuf, char *name)
117 retcode = CtdlGetUser(usbuf, name);
119 begin_critical_section(S_USERS);
126 * CtdlPutUser() - write user buffer into the correct place on disk
128 void CtdlPutUser(struct ctdluser *usbuf)
130 char usernamekey[USERNAME_SIZE];
132 makeuserkey(usernamekey, usbuf->fullname);
133 usbuf->version = REV_LEVEL;
134 cdb_store(CDB_USERS, usernamekey, strlen(usernamekey), usbuf, sizeof(struct ctdluser));
138 void CtdlPutCurrentUserLock()
140 CtdlPutUser(&CC->user);
145 * CtdlPutUserLock() - same as putuser() but locks the record
147 void CtdlPutUserLock(struct ctdluser *usbuf)
150 end_critical_section(S_USERS);
155 * rename_user() - this is tricky because the user's display name is the database key
157 * Returns 0 on success or nonzero if there was an error...
160 int rename_user(char *oldname, char *newname) {
161 int retcode = RENAMEUSER_OK;
162 struct ctdluser usbuf;
164 char oldnamekey[USERNAME_SIZE];
165 char newnamekey[USERNAME_SIZE];
167 /* Create the database keys... */
168 makeuserkey(oldnamekey, oldname);
169 makeuserkey(newnamekey, newname);
171 /* Lock up and get going */
172 begin_critical_section(S_USERS);
174 /* We cannot rename a user who is currently logged in */
175 if (CtdlIsUserLoggedIn(oldname)) {
176 end_critical_section(S_USERS);
177 return RENAMEUSER_LOGGED_IN;
180 if (CtdlGetUser(&usbuf, newname) == 0) {
181 retcode = RENAMEUSER_ALREADY_EXISTS;
185 if (CtdlGetUser(&usbuf, oldname) != 0) {
186 retcode = RENAMEUSER_NOT_FOUND;
188 else { /* Sanity checks succeeded. Now rename the user. */
189 if (usbuf.usernum == 0) {
190 syslog(LOG_DEBUG, "user_ops: can not rename user \"Citadel\".");
191 retcode = RENAMEUSER_NOT_FOUND;
193 syslog(LOG_DEBUG, "user_ops: renaming <%s> to <%s>", oldname, newname);
194 cdb_delete(CDB_USERS, oldnamekey, strlen(oldnamekey));
195 safestrncpy(usbuf.fullname, newname, sizeof usbuf.fullname);
197 cdb_store(CDB_USERSBYNUMBER, &usbuf.usernum, sizeof(long), usbuf.fullname, strlen(usbuf.fullname)+1 );
198 retcode = RENAMEUSER_OK;
204 end_critical_section(S_USERS);
210 * Convert a username into the format used as a database key prior to version 928
211 * This only gets called by reindex_user_928()
213 void makeuserkey_pre928(char *key, const char *username) {
216 int len = strlen(username);
218 if (len >= USERNAME_SIZE) {
219 syslog(LOG_INFO, "Username too long: %s", username);
220 len = USERNAME_SIZE - 1;
222 for (i=0; i<=len; ++i) {
223 key[i] = tolower(username[i]);
229 * Read a user record using the pre-v928 index format, and write it back using the v928-and-higher index format.
230 * This ONLY gets called during an upgrade from version <928 to version >=928.
232 void reindex_user_928(char *username, void *out_data) {
234 char oldkey[USERNAME_SIZE];
235 char newkey[USERNAME_SIZE];
236 struct cdbdata *cdbus;
237 struct ctdluser usbuf;
239 makeuserkey_pre928(oldkey, username);
240 makeuserkey(newkey, username);
242 syslog(LOG_DEBUG, "user_ops: reindex_user_928: %s <%s> --> <%s>", username, oldkey, newkey);
244 // Fetch the user record using the old index format
245 cdbus = cdb_fetch(CDB_USERS, oldkey, strlen(oldkey));
247 syslog(LOG_INFO, "user_ops: <%s> not found, were they already reindexed?", username);
250 memcpy(&usbuf, cdbus->ptr, ((cdbus->len > sizeof(struct ctdluser)) ? sizeof(struct ctdluser) : cdbus->len));
253 // delete the old record
254 cdb_delete(CDB_USERS, oldkey, strlen(oldkey));
256 // write the new record
257 cdb_store(CDB_USERS, newkey, strlen(newkey), &usbuf, sizeof(struct ctdluser));
262 * Index-generating function used by Ctdl[Get|Set]Relationship
264 int GenerateRelationshipIndex(char *IndexBuf,
275 TheIndex.iRoomID = RoomID;
276 TheIndex.iRoomGen = RoomGen;
277 TheIndex.iUserID = UserID;
279 memcpy(IndexBuf, &TheIndex, sizeof(TheIndex));
280 return(sizeof(TheIndex));
285 * Back end for CtdlSetRelationship()
287 void put_visit(visit *newvisit)
292 memset (IndexBuf, 0, sizeof (IndexBuf));
293 /* Generate an index */
294 IndexLen = GenerateRelationshipIndex(IndexBuf, newvisit->v_roomnum, newvisit->v_roomgen, newvisit->v_usernum);
296 /* Store the record */
297 cdb_store(CDB_VISIT, IndexBuf, IndexLen,
298 newvisit, sizeof(visit)
304 * Define a relationship between a user and a room
306 void CtdlSetRelationship(visit *newvisit, struct ctdluser *rel_user, struct ctdlroom *rel_room) {
307 /* We don't use these in Citadel because they're implicit by the
308 * index, but they must be present if the database is exported.
310 newvisit->v_roomnum = rel_room->QRnumber;
311 newvisit->v_roomgen = rel_room->QRgen;
312 newvisit->v_usernum = rel_user->usernum;
319 * Locate a relationship between a user and a room
321 void CtdlGetRelationship(visit *vbuf, struct ctdluser *rel_user, struct ctdlroom *rel_room) {
324 struct cdbdata *cdbvisit;
326 /* Generate an index */
327 IndexLen = GenerateRelationshipIndex(IndexBuf, rel_room->QRnumber, rel_room->QRgen, rel_user->usernum);
329 /* Clear out the buffer */
330 memset(vbuf, 0, sizeof(visit));
332 cdbvisit = cdb_fetch(CDB_VISIT, IndexBuf, IndexLen);
333 if (cdbvisit != NULL) {
334 memcpy(vbuf, cdbvisit->ptr, ((cdbvisit->len > sizeof(visit)) ? sizeof(visit) : cdbvisit->len));
338 /* If this is the first time the user has seen this room,
339 * set the view to be the default for the room.
341 vbuf->v_view = rel_room->QRdefaultview;
344 /* Set v_seen if necessary */
345 if (vbuf->v_seen[0] == 0) {
346 snprintf(vbuf->v_seen, sizeof vbuf->v_seen, "*:%ld", vbuf->v_lastseen);
351 void CtdlMailboxName(char *buf, size_t n, const struct ctdluser *who, const char *prefix)
353 snprintf(buf, n, "%010ld.%s", who->usernum, prefix);
357 void MailboxName(char *buf, size_t n, const struct ctdluser *who, const char *prefix)
359 snprintf(buf, n, "%010ld.%s", who->usernum, prefix);
364 * Check to see if the specified user has Internet mail permission
365 * (returns nonzero if permission is granted)
367 int CtdlCheckInternetMailPermission(struct ctdluser *who) {
369 /* Do not allow twits to send Internet mail */
370 if (who->axlevel <= AxProbU) return(0);
372 /* Globally enabled? */
373 if (CtdlGetConfigInt("c_restrict") == 0) return(1);
375 /* User flagged ok? */
376 if (who->flags & US_INTERNET) return(2);
378 /* Admin level access? */
379 if (who->axlevel >= AxAideU) return(3);
381 /* No mail for you! */
387 * Convenience function.
389 int CtdlAccessCheck(int required_level)
391 if (CC->internal_pgm) return(0);
392 if (required_level >= ac_internal) {
393 cprintf("%d This is not a user-level command.\n", ERROR + HIGHER_ACCESS_REQUIRED);
397 if ((required_level >= ac_logged_in_or_guest) && (CC->logged_in == 0) && (CtdlGetConfigInt("c_guest_logins") == 0)) {
398 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
402 if ((required_level >= ac_logged_in) && (CC->logged_in == 0)) {
403 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
407 if (CC->user.axlevel >= AxAideU) return(0);
408 if (required_level >= ac_aide) {
409 cprintf("%d This command requires Admin access.\n",
410 ERROR + HIGHER_ACCESS_REQUIRED);
414 if (is_room_aide()) return(0);
415 if (required_level >= ac_room_aide) {
416 cprintf("%d This command requires Admin or Room Admin access.\n",
417 ERROR + HIGHER_ACCESS_REQUIRED);
421 /* shhh ... succeed quietly */
427 * Is the user currently logged in an Admin?
431 if (CC->user.axlevel >= AxAideU)
439 * Is the user currently logged in an Admin *or* the room Admin for this room?
441 int is_room_aide(void)
444 if (!CC->logged_in) {
448 if ((CC->user.axlevel >= AxAideU) || (CC->room.QRroomaide == CC->user.usernum)) {
457 * CtdlGetUserByNumber() - get user by number
458 * returns 0 if user was found
460 * Note: fetching a user this way requires one additional database operation.
462 int CtdlGetUserByNumber(struct ctdluser *usbuf, long number)
464 struct cdbdata *cdbun;
467 cdbun = cdb_fetch(CDB_USERSBYNUMBER, &number, sizeof(long));
469 syslog(LOG_INFO, "user_ops: %ld not found", number);
473 syslog(LOG_INFO, "user_ops: %ld maps to %s", number, cdbun->ptr);
474 r = CtdlGetUser(usbuf, cdbun->ptr);
481 * Helper function for rebuild_usersbynumber()
483 void rebuild_ubn_for_user(char *username, void *data) {
486 syslog(LOG_DEBUG, "user_ops: rebuilding usersbynumber index for %s", username);
487 if (CtdlGetUser(&u, username) == 0) {
488 cdb_store(CDB_USERSBYNUMBER, &(u.usernum), sizeof(long), u.fullname, strlen(u.fullname)+1);
494 * Rebuild the users-by-number index
496 void rebuild_usersbynumber(void) {
497 cdb_trunc(CDB_USERSBYNUMBER); /* delete the old indices */
498 ForEachUser(rebuild_ubn_for_user, NULL); /* enumerate the users */
503 * getuserbyuid() Get user by system uid (for PAM mode authentication)
504 * Returns 0 if user was found
505 * This now uses an extauth index.
507 int getuserbyuid(struct ctdluser *usbuf, uid_t number)
509 struct cdbdata *cdbextauth;
513 claimed_id = NewStrBuf();
514 StrBufPrintf(claimed_id, "uid:%d", number);
515 cdbextauth = cdb_fetch(CDB_EXTAUTH, ChrPtr(claimed_id), StrLength(claimed_id));
516 FreeStrBuf(&claimed_id);
517 if (cdbextauth == NULL) {
521 memcpy(&usernum, cdbextauth->ptr, sizeof(long));
522 cdb_free(cdbextauth);
524 if (!CtdlGetUserByNumber(usbuf, usernum)) {
533 * Back end for cmd_user() and its ilk
535 int CtdlLoginExistingUser(const char *trythisname)
540 syslog(LOG_DEBUG, "user_ops: CtdlLoginExistingUser(%s)", trythisname);
542 if ((CC->logged_in)) {
543 return login_already_logged_in;
546 if (trythisname == NULL) return login_not_found;
548 if (!strncasecmp(trythisname, "SYS_", 4))
550 syslog(LOG_DEBUG, "user_ops: system user \"%s\" is not allowed to log in.", trythisname);
551 return login_not_found;
554 /* Continue attempting user validation... */
555 safestrncpy(username, trythisname, sizeof (username));
558 if (IsEmptyStr(username)) {
559 return login_not_found;
562 if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
567 struct passwd *tempPwdPtr;
570 syslog(LOG_DEBUG, "user_ops: asking host about <%s>", username);
571 #ifdef HAVE_GETPWNAM_R
572 #ifdef SOLARIS_GETPWUID
573 syslog(LOG_DEBUG, "user_ops: calling getpwnam_r()");
574 tempPwdPtr = getpwnam_r(username, &pd, pwdbuffer, sizeof pwdbuffer);
575 #else // SOLARIS_GETPWUID
576 syslog(LOG_DEBUG, "user_ops: calling getpwnam_r()");
577 getpwnam_r(username, &pd, pwdbuffer, sizeof pwdbuffer, &tempPwdPtr);
578 #endif // SOLARIS_GETPWUID
579 #else // HAVE_GETPWNAM_R
580 syslog(LOG_DEBUG, "user_ops: SHOULD NEVER GET HERE!!!");
582 #endif // HAVE_GETPWNAM_R
583 if (tempPwdPtr == NULL) {
584 syslog(LOG_DEBUG, "user_ops: no such user <%s>", username);
585 return login_not_found;
588 /* Locate the associated Citadel account. If not found, make one attempt to create it. */
589 found_user = getuserbyuid(&CC->user, pd.pw_uid);
590 if (found_user != 0) {
591 create_user(username, CREATE_USER_DO_NOT_BECOME_USER, pd.pw_uid);
592 found_user = getuserbyuid(&CC->user, pd.pw_uid);
594 syslog(LOG_DEBUG, "user_ops: found it: uid=%ld, gecos=%s here: %d", (long)pd.pw_uid, pd.pw_gecos, found_user);
599 else if ((CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP) || (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD)) {
607 found_user = CtdlTryUserLDAP(username, ldap_dn, sizeof ldap_dn, ldap_cn, sizeof ldap_cn, &ldap_uid);
608 if (found_user != 0) {
609 return login_not_found;
612 found_user = getuserbyuid(&CC->user, ldap_uid);
613 if (found_user != 0) {
614 create_user(ldap_cn, CREATE_USER_DO_NOT_BECOME_USER, ldap_uid);
615 found_user = getuserbyuid(&CC->user, ldap_uid);
618 if (found_user == 0) {
619 if (CC->ldap_dn != NULL) free(CC->ldap_dn);
620 CC->ldap_dn = strdup(ldap_dn);
627 /* native auth mode */
629 struct recptypes *valid = NULL;
631 /* First, try to log in as if the supplied name is a display name */
632 found_user = CtdlGetUser(&CC->user, username);
634 /* If that didn't work, try to log in as if the supplied name * is an e-mail address */
635 if (found_user != 0) {
636 valid = validate_recipients(username, NULL, 0);
638 if (valid->num_local == 1) {
639 found_user = CtdlGetUser(&CC->user, valid->recp_local);
641 free_recipients(valid);
646 /* Did we find something? */
647 if (found_user == 0) {
648 if (((CC->nologin)) && (CC->user.axlevel < AxAideU)) {
649 return login_too_many_users;
651 safestrncpy(CC->curr_user, CC->user.fullname, sizeof CC->curr_user);
655 return login_not_found;
660 * session startup code which is common to both cmd_pass() and cmd_newu()
665 syslog(LOG_NOTICE, "user_ops: <%s> logged in", CC->curr_user);
667 CtdlGetUserLock(&CC->user, CC->curr_user);
668 ++(CC->user.timescalled);
669 CC->previous_login = CC->user.lastcall;
670 time(&CC->user.lastcall);
672 /* If this user's name is the name of the system administrator
673 * (as specified in setup), automatically assign access level 6.
675 if ( (!IsEmptyStr(CtdlGetConfigStr("c_sysadm"))) && (!strcasecmp(CC->user.fullname, CtdlGetConfigStr("c_sysadm"))) ) {
676 CC->user.axlevel = AxAideU;
679 /* If we're authenticating off the host system, automatically give root the highest level of access. */
680 if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
681 if (CC->user.uid == 0) {
682 CC->user.axlevel = AxAideU;
685 CtdlPutUserLock(&CC->user);
687 /* If we are using LDAP authentication, extract the user's email addresses from the directory. */
689 if ((CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP) || (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD)) {
690 char new_emailaddrs[512];
691 if (CtdlGetConfigInt("c_ldap_sync_email_addrs") > 0) {
692 if (extract_email_addresses_from_ldap(CC->ldap_dn, new_emailaddrs) == 0) {
693 CtdlSetEmailAddressesForUser(CC->user.fullname, new_emailaddrs);
699 /* If the user does not have any email addresses assigned, generate one. */
700 if (IsEmptyStr(CC->user.emailaddrs)) {
701 AutoGenerateEmailAddressForUser(&CC->user);
704 /* Populate the user principal identity, which is consistent and never aliased */
705 strcpy(CC->cs_principal_id, "");
706 makeuserkey(CC->cs_principal_id, CC->user.fullname);
707 strcat(CC->cs_principal_id, "@");
708 strcat(CC->cs_principal_id, CtdlGetConfigStr("c_fqdn"));
711 * Populate cs_inet_email and cs_inet_other_emails with valid email addresses from the user record
713 strcpy(CC->cs_inet_email, CC->user.emailaddrs);
714 char *firstsep = strstr(CC->cs_inet_email, "|");
716 strcpy(CC->cs_inet_other_emails, firstsep+1);
720 CC->cs_inet_other_emails[0] = 0;
723 /* Create any personal rooms required by the system.
724 * (Technically, MAILROOM should be there already, but just in case...)
726 CtdlCreateRoom(MAILROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
727 CtdlCreateRoom(SENTITEMS, 4, "", 0, 1, 0, VIEW_MAILBOX);
728 CtdlCreateRoom(USERTRASHROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
729 CtdlCreateRoom(USERDRAFTROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
731 /* Run any startup routines registered by loadable modules */
732 PerformSessionHooks(EVT_LOGIN);
734 /* Enter the lobby */
735 CtdlUserGoto(CtdlGetConfigStr("c_baseroom"), 0, 0, NULL, NULL, NULL, NULL);
739 void logged_in_response(void)
741 cprintf("%d %s|%d|%ld|%ld|%u|%ld|%ld\n",
742 CIT_OK, CC->user.fullname, CC->user.axlevel,
743 CC->user.timescalled, CC->user.posted,
744 CC->user.flags, CC->user.usernum,
750 void CtdlUserLogout(void)
752 CitContext *CCC = MyContext();
754 syslog(LOG_DEBUG, "user_ops: CtdlUserLogout() logging out <%s> from session %d", CCC->curr_user, CCC->cs_pid);
756 /* Run any hooks registered by modules... */
757 PerformSessionHooks(EVT_LOGOUT);
760 * Clear out some session data. Most likely, the CitContext for this
761 * session is about to get nuked when the session disconnects, but
762 * since it's possible to log in again without reconnecting, we cannot
763 * make that assumption.
767 /* Check to see if the user was deleted while logged in and purge them if necessary */
768 if ((CCC->user.axlevel == AxDeleted) && (CCC->user.usernum)) {
769 purge_user(CCC->user.fullname);
772 /* Clear out the user record in memory so we don't behave like a ghost */
773 memset(&CCC->user, 0, sizeof(struct ctdluser));
774 CCC->curr_user[0] = 0;
775 CCC->cs_inet_email[0] = 0;
776 CCC->cs_inet_other_emails[0] = 0;
777 CCC->cs_inet_fn[0] = 0;
779 /* Free any output buffers */
785 * Validate a password on the host unix system by talking to the chkpwd daemon
787 static int validpw(uid_t uid, const char *pass)
792 if (IsEmptyStr(pass)) {
793 syslog(LOG_DEBUG, "user_ops: refusing to chkpwd for uid=%d with empty password", uid);
797 syslog(LOG_DEBUG, "user_ops: validating password for uid=%d using chkpwd...", uid);
799 begin_critical_section(S_CHKPWD);
800 rv = write(chkpwd_write_pipe[1], &uid, sizeof(uid_t));
802 syslog(LOG_ERR, "user_ops: communication with chkpwd broken: %m");
803 end_critical_section(S_CHKPWD);
806 rv = write(chkpwd_write_pipe[1], pass, 256);
808 syslog(LOG_ERR, "user_ops: communication with chkpwd broken: %m");
809 end_critical_section(S_CHKPWD);
812 rv = read(chkpwd_read_pipe[0], buf, 4);
814 syslog(LOG_ERR, "user_ops: ommunication with chkpwd broken: %m");
815 end_critical_section(S_CHKPWD);
818 end_critical_section(S_CHKPWD);
820 if (!strncmp(buf, "PASS", 4)) {
821 syslog(LOG_DEBUG, "user_ops: chkpwd pass");
825 syslog(LOG_DEBUG, "user_ops: chkpwd fail");
831 * Start up the chkpwd daemon so validpw() has something to talk to
833 void start_chkpwd_daemon(void) {
835 struct stat filestats;
838 syslog(LOG_DEBUG, "user_ops: starting chkpwd daemon for host authentication mode");
840 if ((stat(file_chkpwd, &filestats)==-1) || (filestats.st_size==0)) {
841 syslog(LOG_ERR, "user_ops: %s: %m", file_chkpwd);
844 if (pipe(chkpwd_write_pipe) != 0) {
845 syslog(LOG_ERR, "user_ops: unable to create pipe for chkpwd daemon: %m");
848 if (pipe(chkpwd_read_pipe) != 0) {
849 syslog(LOG_ERR, "user_ops: unable to create pipe for chkpwd daemon: %m");
854 if (chkpwd_pid < 0) {
855 syslog(LOG_ERR, "user_ops: unable to fork chkpwd daemon: %m");
858 if (chkpwd_pid == 0) {
859 dup2(chkpwd_write_pipe[0], 0);
860 dup2(chkpwd_read_pipe[1], 1);
861 for (i=2; i<256; ++i) close(i);
862 execl(file_chkpwd, file_chkpwd, NULL);
863 syslog(LOG_ERR, "user_ops: unable to exec chkpwd daemon: %m");
870 int CtdlTryPassword(const char *password, long len)
873 CitContext *CCC = CC;
875 if ((CCC->logged_in)) {
876 syslog(LOG_WARNING, "user_ops: CtdlTryPassword: already logged in");
877 return pass_already_logged_in;
879 if (!strcmp(CCC->curr_user, NLI)) {
880 syslog(LOG_WARNING, "user_ops: CtdlTryPassword: no user selected");
883 if (CtdlGetUser(&CCC->user, CCC->curr_user)) {
884 syslog(LOG_ERR, "user_ops: CtdlTryPassword: internal error");
885 return pass_internal_error;
887 if (password == NULL) {
888 syslog(LOG_INFO, "user_ops: CtdlTryPassword: NULL password string supplied");
889 return pass_wrong_password;
892 else if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
896 if (validpw(CCC->user.uid, password)) {
900 * sooper-seekrit hack: populate the password field in the
901 * citadel database with the password that the user typed,
902 * if it's correct. This allows most sites to convert from
903 * host auth to native auth if they want to. If you think
904 * this is a security hazard, comment it out.
907 CtdlGetUserLock(&CCC->user, CCC->curr_user);
908 safestrncpy(CCC->user.password, password, sizeof CCC->user.password);
909 CtdlPutUserLock(&CCC->user);
912 * (sooper-seekrit hack ends here)
921 else if ((CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP) || (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD)) {
925 if ((CCC->ldap_dn) && (!CtdlTryPasswordLDAP(CCC->ldap_dn, password))) {
936 /* native auth mode */
939 pw = (char*) malloc(len + 1);
940 memcpy(pw, password, len + 1);
942 strproc(CCC->user.password);
943 code = strcasecmp(CCC->user.password, pw);
946 strproc(CCC->user.password);
947 code = strcasecmp(CCC->user.password, pw);
957 syslog(LOG_WARNING, "user_ops: bad password specified for <%s> Service <%s> Port <%ld> Remote <%s / %s>",
964 return pass_wrong_password;
970 * Delete a user record *and* all of its related resources.
972 int purge_user(char pname[])
974 struct ctdluser usbuf;
975 char usernamekey[USERNAME_SIZE];
977 makeuserkey(usernamekey, pname);
979 /* If the name is empty we can't find them in the DB any way so just return */
980 if (IsEmptyStr(pname)) {
981 return(ERROR + NO_SUCH_USER);
984 if (CtdlGetUser(&usbuf, pname) != 0) {
985 syslog(LOG_ERR, "user_ops: cannot purge user <%s> - not found", pname);
986 return(ERROR + NO_SUCH_USER);
989 /* Don't delete a user who is currently logged in. Instead, just
990 * set the access level to 0, and let the account get swept up
991 * during the next purge.
993 if (CtdlIsUserLoggedInByNum(usbuf.usernum)) {
994 syslog(LOG_WARNING, "user_ops: <%s> is logged in; not deleting", pname);
995 usbuf.axlevel = AxDeleted;
1000 syslog(LOG_NOTICE, "user_ops: deleting <%s>", pname);
1002 /* Perform any purge functions registered by server extensions */
1003 PerformUserHooks(&usbuf, EVT_PURGEUSER);
1005 /* delete any existing user/room relationships */
1006 cdb_delete(CDB_VISIT, &usbuf.usernum, sizeof(long));
1008 /* delete the users-by-number index record */
1009 cdb_delete(CDB_USERSBYNUMBER, &usbuf.usernum, sizeof(long));
1011 /* delete the userlog entry */
1012 cdb_delete(CDB_USERS, usernamekey, strlen(usernamekey));
1018 int internal_create_user(char *username, struct ctdluser *usbuf, uid_t uid)
1020 if (!CtdlGetUser(usbuf, username)) {
1021 return(ERROR + ALREADY_EXISTS);
1024 /* Go ahead and initialize a new user record */
1025 memset(usbuf, 0, sizeof(struct ctdluser));
1026 safestrncpy(usbuf->fullname, username, sizeof usbuf->fullname);
1027 strcpy(usbuf->password, "");
1030 /* These are the default flags on new accounts */
1031 usbuf->flags = US_LASTOLD | US_DISAPPEAR | US_PAGINATOR | US_FLOORS;
1033 usbuf->timescalled = 0;
1035 usbuf->axlevel = CtdlGetConfigInt("c_initax");
1036 usbuf->lastcall = time(NULL);
1038 /* fetch a new user number */
1039 usbuf->usernum = get_new_user_number();
1041 /* add user to the database */
1043 cdb_store(CDB_USERSBYNUMBER, &usbuf->usernum, sizeof(long), usbuf->fullname, strlen(usbuf->fullname)+1);
1045 /* If non-native auth, index by uid */
1046 if ((usbuf->uid > 0) && (usbuf->uid != NATIVE_AUTH_UID)) {
1047 StrBuf *claimed_id = NewStrBuf();
1048 StrBufPrintf(claimed_id, "uid:%d", usbuf->uid);
1049 attach_extauth(usbuf, claimed_id);
1050 FreeStrBuf(&claimed_id);
1058 * create_user() - back end processing to create a new user
1060 * Set 'newusername' to the desired account name.
1061 * Set 'become_user' to CREATE_USER_BECOME_USER if this is self-service account creation and we want to
1062 * actually log in as the user we just created, otherwise set it to CREATE_USER_DO_NOT_BECOME_USER
1063 * Set 'uid' to some uid_t value to associate the account with an external auth user, or (-1) for native auth
1065 int create_user(char *username, int become_user, uid_t uid)
1067 struct ctdluser usbuf;
1068 struct ctdlroom qrbuf;
1069 char mailboxname[ROOMNAMELEN];
1074 if ((retval = internal_create_user(username, &usbuf, uid)) != 0) {
1079 * Give the user a private mailbox and a configuration room.
1080 * Make the latter an invisible system room.
1082 CtdlMailboxName(mailboxname, sizeof mailboxname, &usbuf, MAILROOM);
1083 CtdlCreateRoom(mailboxname, 5, "", 0, 1, 1, VIEW_MAILBOX);
1085 CtdlMailboxName(mailboxname, sizeof mailboxname, &usbuf, USERCONFIGROOM);
1086 CtdlCreateRoom(mailboxname, 5, "", 0, 1, 1, VIEW_BBS);
1087 if (CtdlGetRoomLock(&qrbuf, mailboxname) == 0) {
1088 qrbuf.QRflags2 |= QR2_SYSTEM;
1089 CtdlPutRoomLock(&qrbuf);
1092 /* Perform any create functions registered by server extensions */
1093 PerformUserHooks(&usbuf, EVT_NEWUSER);
1095 /* Everything below this line can be bypassed if administratively
1096 * creating a user, instead of doing self-service account creation
1099 if (become_user == CREATE_USER_BECOME_USER) {
1100 /* Now become the user we just created */
1101 memcpy(&CC->user, &usbuf, sizeof(struct ctdluser));
1102 safestrncpy(CC->curr_user, username, sizeof CC->curr_user);
1105 /* Check to make sure we're still who we think we are */
1106 if (CtdlGetUser(&CC->user, CC->curr_user)) {
1107 return(ERROR + INTERNAL_ERROR);
1112 "New user account <%s> has been created, from host %s [%s].\n",
1117 CtdlAideMessage(buf, "User Creation Notice");
1118 syslog(LOG_NOTICE, "user_ops: <%s> created", username);
1124 * set password - back end api code
1126 void CtdlSetPassword(char *new_pw)
1128 CtdlGetUserLock(&CC->user, CC->curr_user);
1129 safestrncpy(CC->user.password, new_pw, sizeof(CC->user.password));
1130 CtdlPutUserLock(&CC->user);
1131 syslog(LOG_INFO, "user_ops: password changed for <%s>", CC->curr_user);
1132 PerformSessionHooks(EVT_SETPASS);
1137 * API function for cmd_invt_kick() and anything else that needs to
1138 * invite or kick out a user to/from a room.
1140 * Set iuser to the name of the user, and op to 1=invite or 0=kick
1142 int CtdlInvtKick(char *iuser, int op) {
1143 struct ctdluser USscratch;
1147 if (CtdlGetUser(&USscratch, iuser) != 0) {
1151 CtdlGetRelationship(&vbuf, &USscratch, &CC->room);
1153 vbuf.v_flags = vbuf.v_flags & ~V_FORGET & ~V_LOCKOUT;
1154 vbuf.v_flags = vbuf.v_flags | V_ACCESS;
1157 vbuf.v_flags = vbuf.v_flags & ~V_ACCESS;
1158 vbuf.v_flags = vbuf.v_flags | V_FORGET | V_LOCKOUT;
1160 CtdlSetRelationship(&vbuf, &USscratch, &CC->room);
1162 /* post a message in Aide> saying what we just did */
1163 snprintf(bbb, sizeof bbb, "%s has been %s \"%s\" by %s.\n",
1165 ((op == 1) ? "invited to" : "kicked out of"),
1167 (CC->logged_in ? CC->user.fullname : "an administrator")
1169 CtdlAideMessage(bbb,"User Admin Message");
1175 * Forget (Zap) the current room (API call)
1176 * Returns 0 on success
1178 int CtdlForgetThisRoom(void) {
1181 /* On some systems, Admins are not allowed to forget rooms */
1182 if (is_aide() && (CtdlGetConfigInt("c_aide_zap") == 0)
1183 && ((CC->room.QRflags & QR_MAILBOX) == 0) ) {
1187 CtdlGetUserLock(&CC->user, CC->curr_user);
1188 CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
1190 vbuf.v_flags = vbuf.v_flags | V_FORGET;
1191 vbuf.v_flags = vbuf.v_flags & ~V_ACCESS;
1193 CtdlSetRelationship(&vbuf, &CC->user, &CC->room);
1194 CtdlPutUserLock(&CC->user);
1196 /* Return to the Lobby, so we don't end up in an undefined room */
1197 CtdlUserGoto(CtdlGetConfigStr("c_baseroom"), 0, 0, NULL, NULL, NULL, NULL);
1203 * Traverse the user file and perform a callback for each user record.
1204 * (New improved version that runs in two phases so that callbacks can perform writes without having a r/o cursor open)
1206 void ForEachUser(void (*CallBack) (char *, void *out_data), void *in_data)
1208 struct cdbdata *cdbus;
1209 struct ctdluser *usptr;
1213 char username[USERNAME_SIZE];
1215 struct feu *ufirst = NULL;
1216 struct feu *ulast = NULL;
1217 struct feu *f = NULL;
1219 cdb_rewind(CDB_USERS);
1221 // Phase 1 : build a linked list of all our user account names
1222 while (cdbus = cdb_next_item(CDB_USERS), cdbus != NULL) {
1223 usptr = (struct ctdluser *) cdbus->ptr;
1225 if (strlen(usptr->fullname) > 0) {
1226 f = malloc(sizeof(struct feu));
1228 strncpy(f->username, usptr->fullname, USERNAME_SIZE);
1230 if (ufirst == NULL) {
1241 // Phase 2 : perform the callback for each user while de-allocating the list
1242 while (ufirst != NULL) {
1243 (*CallBack) (ufirst->username, in_data);
1245 ufirst = ufirst->next;
1252 * Count the number of new mail messages the user has
1256 int num_newmsgs = 0;
1257 num_newmsgs = CC->newmail;
1259 return(num_newmsgs);
1264 * Count the number of new mail messages the user has
1266 int InitialMailCheck()
1268 int num_newmsgs = 0;
1270 char mailboxname[ROOMNAMELEN];
1271 struct ctdlroom mailbox;
1273 struct cdbdata *cdbfr;
1274 long *msglist = NULL;
1277 CtdlMailboxName(mailboxname, sizeof mailboxname, &CC->user, MAILROOM);
1278 if (CtdlGetRoom(&mailbox, mailboxname) != 0)
1280 CtdlGetRelationship(&vbuf, &CC->user, &mailbox);
1282 cdbfr = cdb_fetch(CDB_MSGLISTS, &mailbox.QRnumber, sizeof(long));
1284 if (cdbfr != NULL) {
1285 msglist = malloc(cdbfr->len);
1286 memcpy(msglist, cdbfr->ptr, cdbfr->len);
1287 num_msgs = cdbfr->len / sizeof(long);
1291 for (a = 0; a < num_msgs; ++a) {
1292 if (msglist[a] > 0L) {
1293 if (msglist[a] > vbuf.v_lastseen) {
1298 if (msglist != NULL)
1301 return(num_newmsgs);