1 // Server functions which perform operations on user objects.
3 // Copyright (c) 1987-2021 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.
8 // This program is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 // GNU General Public License for more details.
18 #include <libcitadel.h>
21 #include "citserver.h"
23 #include "citadel_ldap.h"
24 #include "ctdl_module.h"
26 #include "internet_addressing.h"
28 /* These pipes are used to talk to the chkpwd daemon, which is forked during startup */
29 int chkpwd_write_pipe[2];
30 int chkpwd_read_pipe[2];
34 * makeuserkey() - convert a username into the format used as a database key
35 * "key" must be a buffer of at least USERNAME_SIZE
36 * (Key format is the username with all non-alphanumeric characters removed, and converted to lower case.)
38 void makeuserkey(char *key, const char *username) {
42 if (IsEmptyStr(username)) {
47 int len = strlen(username);
48 for (i=0; ((i<=len) && (i<USERNAME_SIZE-1)); ++i) {
49 if (isalnum((username[i]))) {
50 key[keylen++] = tolower(username[i]);
58 * Compare two usernames to see if they are the same user after being keyed for the database
59 * Usage is identical to strcmp()
61 int CtdlUserCmp(char *s1, char *s2) {
62 char k1[USERNAME_SIZE];
63 char k2[USERNAME_SIZE];
67 return(strcmp(k1,k2));
72 * CtdlGetUser() retrieve named user into supplied buffer.
73 * returns 0 on success
75 int CtdlGetUser(struct ctdluser *usbuf, char *name)
77 char usernamekey[USERNAME_SIZE];
78 struct cdbdata *cdbus;
81 memset(usbuf, 0, sizeof(struct ctdluser));
84 makeuserkey(usernamekey, name);
85 if (IsEmptyStr(usernamekey)) {
86 return(1); // empty user name
88 cdbus = cdb_fetch(CDB_USERS, usernamekey, strlen(usernamekey));
90 if (cdbus == NULL) { // user not found
94 memcpy(usbuf, cdbus->ptr, ((cdbus->len > sizeof(struct ctdluser)) ? sizeof(struct ctdluser) : cdbus->len));
101 int CtdlLockGetCurrentUser(void)
103 CitContext *CCC = CC;
104 return CtdlGetUser(&CCC->user, CCC->curr_user);
109 * CtdlGetUserLock() - same as getuser() but locks the record
111 int CtdlGetUserLock(struct ctdluser *usbuf, char *name)
115 retcode = CtdlGetUser(usbuf, name);
117 begin_critical_section(S_USERS);
124 * CtdlPutUser() - write user buffer into the correct place on disk
126 void CtdlPutUser(struct ctdluser *usbuf)
128 char usernamekey[USERNAME_SIZE];
130 makeuserkey(usernamekey, usbuf->fullname);
131 usbuf->version = REV_LEVEL;
132 cdb_store(CDB_USERS, usernamekey, strlen(usernamekey), usbuf, sizeof(struct ctdluser));
136 void CtdlPutCurrentUserLock()
138 CtdlPutUser(&CC->user);
143 * CtdlPutUserLock() - same as putuser() but locks the record
145 void CtdlPutUserLock(struct ctdluser *usbuf)
148 end_critical_section(S_USERS);
153 * rename_user() - this is tricky because the user's display name is the database key
155 * Returns 0 on success or nonzero if there was an error...
158 int rename_user(char *oldname, char *newname) {
159 int retcode = RENAMEUSER_OK;
160 struct ctdluser usbuf;
162 char oldnamekey[USERNAME_SIZE];
163 char newnamekey[USERNAME_SIZE];
165 /* Create the database keys... */
166 makeuserkey(oldnamekey, oldname);
167 makeuserkey(newnamekey, newname);
169 /* Lock up and get going */
170 begin_critical_section(S_USERS);
172 /* We cannot rename a user who is currently logged in */
173 if (CtdlIsUserLoggedIn(oldname)) {
174 end_critical_section(S_USERS);
175 return RENAMEUSER_LOGGED_IN;
178 if (CtdlGetUser(&usbuf, newname) == 0) {
179 retcode = RENAMEUSER_ALREADY_EXISTS;
183 if (CtdlGetUser(&usbuf, oldname) != 0) {
184 retcode = RENAMEUSER_NOT_FOUND;
186 else { /* Sanity checks succeeded. Now rename the user. */
187 if (usbuf.usernum == 0) {
188 syslog(LOG_DEBUG, "user_ops: can not rename user \"Citadel\".");
189 retcode = RENAMEUSER_NOT_FOUND;
191 syslog(LOG_DEBUG, "user_ops: renaming <%s> to <%s>", oldname, newname);
192 cdb_delete(CDB_USERS, oldnamekey, strlen(oldnamekey));
193 safestrncpy(usbuf.fullname, newname, sizeof usbuf.fullname);
195 cdb_store(CDB_USERSBYNUMBER, &usbuf.usernum, sizeof(long), usbuf.fullname, strlen(usbuf.fullname)+1 );
196 retcode = RENAMEUSER_OK;
202 end_critical_section(S_USERS);
208 * Convert a username into the format used as a database key prior to version 928
209 * This only gets called by reindex_user_928()
211 void makeuserkey_pre928(char *key, const char *username) {
214 int len = strlen(username);
216 if (len >= USERNAME_SIZE) {
217 syslog(LOG_INFO, "Username too long: %s", username);
218 len = USERNAME_SIZE - 1;
220 for (i=0; i<=len; ++i) {
221 key[i] = tolower(username[i]);
227 * Read a user record using the pre-v928 index format, and write it back using the v928-and-higher index format.
228 * This ONLY gets called during an upgrade from version <928 to version >=928.
230 void reindex_user_928(char *username, void *out_data) {
232 char oldkey[USERNAME_SIZE];
233 char newkey[USERNAME_SIZE];
234 struct cdbdata *cdbus;
235 struct ctdluser usbuf;
237 makeuserkey_pre928(oldkey, username);
238 makeuserkey(newkey, username);
240 syslog(LOG_DEBUG, "user_ops: reindex_user_928: %s <%s> --> <%s>", username, oldkey, newkey);
242 // Fetch the user record using the old index format
243 cdbus = cdb_fetch(CDB_USERS, oldkey, strlen(oldkey));
245 syslog(LOG_INFO, "user_ops: <%s> not found, were they already reindexed?", username);
248 memcpy(&usbuf, cdbus->ptr, ((cdbus->len > sizeof(struct ctdluser)) ? sizeof(struct ctdluser) : cdbus->len));
251 // delete the old record
252 cdb_delete(CDB_USERS, oldkey, strlen(oldkey));
254 // write the new record
255 cdb_store(CDB_USERS, newkey, strlen(newkey), &usbuf, sizeof(struct ctdluser));
260 * Index-generating function used by Ctdl[Get|Set]Relationship
262 int GenerateRelationshipIndex(char *IndexBuf,
273 TheIndex.iRoomID = RoomID;
274 TheIndex.iRoomGen = RoomGen;
275 TheIndex.iUserID = UserID;
277 memcpy(IndexBuf, &TheIndex, sizeof(TheIndex));
278 return(sizeof(TheIndex));
283 * Back end for CtdlSetRelationship()
285 void put_visit(visit *newvisit)
290 memset (IndexBuf, 0, sizeof (IndexBuf));
291 /* Generate an index */
292 IndexLen = GenerateRelationshipIndex(IndexBuf, newvisit->v_roomnum, newvisit->v_roomgen, newvisit->v_usernum);
294 /* Store the record */
295 cdb_store(CDB_VISIT, IndexBuf, IndexLen,
296 newvisit, sizeof(visit)
302 * Define a relationship between a user and a room
304 void CtdlSetRelationship(visit *newvisit, struct ctdluser *rel_user, struct ctdlroom *rel_room) {
305 /* We don't use these in Citadel because they're implicit by the
306 * index, but they must be present if the database is exported.
308 newvisit->v_roomnum = rel_room->QRnumber;
309 newvisit->v_roomgen = rel_room->QRgen;
310 newvisit->v_usernum = rel_user->usernum;
317 * Locate a relationship between a user and a room
319 void CtdlGetRelationship(visit *vbuf, struct ctdluser *rel_user, struct ctdlroom *rel_room) {
322 struct cdbdata *cdbvisit;
324 /* Generate an index */
325 IndexLen = GenerateRelationshipIndex(IndexBuf, rel_room->QRnumber, rel_room->QRgen, rel_user->usernum);
327 /* Clear out the buffer */
328 memset(vbuf, 0, sizeof(visit));
330 cdbvisit = cdb_fetch(CDB_VISIT, IndexBuf, IndexLen);
331 if (cdbvisit != NULL) {
332 memcpy(vbuf, cdbvisit->ptr, ((cdbvisit->len > sizeof(visit)) ? sizeof(visit) : cdbvisit->len));
336 /* If this is the first time the user has seen this room,
337 * set the view to be the default for the room.
339 vbuf->v_view = rel_room->QRdefaultview;
342 /* Set v_seen if necessary */
343 if (vbuf->v_seen[0] == 0) {
344 snprintf(vbuf->v_seen, sizeof vbuf->v_seen, "*:%ld", vbuf->v_lastseen);
349 void CtdlMailboxName(char *buf, size_t n, const struct ctdluser *who, const char *prefix)
351 snprintf(buf, n, "%010ld.%s", who->usernum, prefix);
355 void MailboxName(char *buf, size_t n, const struct ctdluser *who, const char *prefix)
357 snprintf(buf, n, "%010ld.%s", who->usernum, prefix);
362 * Check to see if the specified user has Internet mail permission
363 * (returns nonzero if permission is granted)
365 int CtdlCheckInternetMailPermission(struct ctdluser *who) {
367 /* Do not allow twits to send Internet mail */
368 if (who->axlevel <= AxProbU) return(0);
370 /* Globally enabled? */
371 if (CtdlGetConfigInt("c_restrict") == 0) return(1);
373 /* User flagged ok? */
374 if (who->flags & US_INTERNET) return(2);
376 /* Admin level access? */
377 if (who->axlevel >= AxAideU) return(3);
379 /* No mail for you! */
385 * Convenience function.
387 int CtdlAccessCheck(int required_level)
389 if (CC->internal_pgm) return(0);
390 if (required_level >= ac_internal) {
391 cprintf("%d This is not a user-level command.\n", ERROR + HIGHER_ACCESS_REQUIRED);
395 if ((required_level >= ac_logged_in_or_guest) && (CC->logged_in == 0) && (CtdlGetConfigInt("c_guest_logins") == 0)) {
396 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
400 if ((required_level >= ac_logged_in) && (CC->logged_in == 0)) {
401 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
405 if (CC->user.axlevel >= AxAideU) return(0);
406 if (required_level >= ac_aide) {
407 cprintf("%d This command requires Admin access.\n",
408 ERROR + HIGHER_ACCESS_REQUIRED);
412 if (is_room_aide()) return(0);
413 if (required_level >= ac_room_aide) {
414 cprintf("%d This command requires Admin or Room Admin access.\n",
415 ERROR + HIGHER_ACCESS_REQUIRED);
419 /* shhh ... succeed quietly */
425 * Is the user currently logged in an Admin?
429 if (CC->user.axlevel >= AxAideU)
437 * Is the user currently logged in an Admin *or* the room Admin for this room?
439 int is_room_aide(void)
442 if (!CC->logged_in) {
446 if ((CC->user.axlevel >= AxAideU) || (CC->room.QRroomaide == CC->user.usernum)) {
455 * CtdlGetUserByNumber() - get user by number
456 * returns 0 if user was found
458 * Note: fetching a user this way requires one additional database operation.
460 int CtdlGetUserByNumber(struct ctdluser *usbuf, long number)
462 struct cdbdata *cdbun;
465 cdbun = cdb_fetch(CDB_USERSBYNUMBER, &number, sizeof(long));
467 syslog(LOG_INFO, "user_ops: %ld not found", number);
471 syslog(LOG_INFO, "user_ops: %ld maps to %s", number, cdbun->ptr);
472 r = CtdlGetUser(usbuf, cdbun->ptr);
479 * Helper function for rebuild_usersbynumber()
481 void rebuild_ubn_for_user(char *username, void *data) {
484 syslog(LOG_DEBUG, "user_ops: rebuilding usersbynumber index for %s", username);
485 if (CtdlGetUser(&u, username) == 0) {
486 cdb_store(CDB_USERSBYNUMBER, &(u.usernum), sizeof(long), u.fullname, strlen(u.fullname)+1);
492 * Rebuild the users-by-number index
494 void rebuild_usersbynumber(void) {
495 cdb_trunc(CDB_USERSBYNUMBER); /* delete the old indices */
496 ForEachUser(rebuild_ubn_for_user, NULL); /* enumerate the users */
501 * getuserbyuid() Get user by system uid (for PAM mode authentication)
502 * Returns 0 if user was found
503 * This now uses an extauth index.
505 int getuserbyuid(struct ctdluser *usbuf, uid_t number)
507 struct cdbdata *cdbextauth;
511 claimed_id = NewStrBuf();
512 StrBufPrintf(claimed_id, "uid:%d", number);
513 cdbextauth = cdb_fetch(CDB_EXTAUTH, ChrPtr(claimed_id), StrLength(claimed_id));
514 FreeStrBuf(&claimed_id);
515 if (cdbextauth == NULL) {
519 memcpy(&usernum, cdbextauth->ptr, sizeof(long));
520 cdb_free(cdbextauth);
522 if (!CtdlGetUserByNumber(usbuf, usernum)) {
531 * Back end for cmd_user() and its ilk
533 int CtdlLoginExistingUser(const char *trythisname)
538 syslog(LOG_DEBUG, "user_ops: CtdlLoginExistingUser(%s)", trythisname);
540 if ((CC->logged_in)) {
541 return login_already_logged_in;
544 if (trythisname == NULL) return login_not_found;
546 if (!strncasecmp(trythisname, "SYS_", 4))
548 syslog(LOG_DEBUG, "user_ops: system user \"%s\" is not allowed to log in.", trythisname);
549 return login_not_found;
552 /* Continue attempting user validation... */
553 safestrncpy(username, trythisname, sizeof (username));
556 if (IsEmptyStr(username)) {
557 return login_not_found;
560 if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
565 struct passwd *tempPwdPtr;
568 syslog(LOG_DEBUG, "user_ops: asking host about <%s>", username);
569 #ifdef HAVE_GETPWNAM_R
570 #ifdef SOLARIS_GETPWUID
571 syslog(LOG_DEBUG, "user_ops: calling getpwnam_r()");
572 tempPwdPtr = getpwnam_r(username, &pd, pwdbuffer, sizeof pwdbuffer);
573 #else // SOLARIS_GETPWUID
574 syslog(LOG_DEBUG, "user_ops: calling getpwnam_r()");
575 getpwnam_r(username, &pd, pwdbuffer, sizeof pwdbuffer, &tempPwdPtr);
576 #endif // SOLARIS_GETPWUID
577 #else // HAVE_GETPWNAM_R
578 syslog(LOG_DEBUG, "user_ops: SHOULD NEVER GET HERE!!!");
580 #endif // HAVE_GETPWNAM_R
581 if (tempPwdPtr == NULL) {
582 syslog(LOG_DEBUG, "user_ops: no such user <%s>", username);
583 return login_not_found;
586 /* Locate the associated Citadel account. If not found, make one attempt to create it. */
587 found_user = getuserbyuid(&CC->user, pd.pw_uid);
588 if (found_user != 0) {
589 create_user(username, CREATE_USER_DO_NOT_BECOME_USER, pd.pw_uid);
590 found_user = getuserbyuid(&CC->user, pd.pw_uid);
592 syslog(LOG_DEBUG, "user_ops: found it: uid=%ld, gecos=%s here: %d", (long)pd.pw_uid, pd.pw_gecos, found_user);
596 else if ((CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP) || (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD)) {
604 found_user = CtdlTryUserLDAP(username, ldap_dn, sizeof ldap_dn, ldap_cn, sizeof ldap_cn, &ldap_uid);
605 if (found_user != 0) {
606 return login_not_found;
609 found_user = getuserbyuid(&CC->user, ldap_uid);
610 if (found_user != 0) {
611 create_user(ldap_cn, CREATE_USER_DO_NOT_BECOME_USER, ldap_uid);
612 found_user = getuserbyuid(&CC->user, ldap_uid);
615 if (found_user == 0) {
616 if (CC->ldap_dn != NULL) free(CC->ldap_dn);
617 CC->ldap_dn = strdup(ldap_dn);
623 /* native auth mode */
625 struct recptypes *valid = NULL;
627 /* First, try to log in as if the supplied name is a display name */
628 found_user = CtdlGetUser(&CC->user, username);
630 /* If that didn't work, try to log in as if the supplied name * is an e-mail address */
631 if (found_user != 0) {
632 valid = validate_recipients(username, NULL, 0);
634 if (valid->num_local == 1) {
635 found_user = CtdlGetUser(&CC->user, valid->recp_local);
637 free_recipients(valid);
642 /* Did we find something? */
643 if (found_user == 0) {
644 if (((CC->nologin)) && (CC->user.axlevel < AxAideU)) {
645 return login_too_many_users;
647 safestrncpy(CC->curr_user, CC->user.fullname, sizeof CC->curr_user);
651 return login_not_found;
656 * session startup code which is common to both cmd_pass() and cmd_newu()
661 syslog(LOG_NOTICE, "user_ops: <%s> logged in", CC->curr_user);
663 CtdlGetUserLock(&CC->user, CC->curr_user);
664 ++(CC->user.timescalled);
665 CC->previous_login = CC->user.lastcall;
666 time(&CC->user.lastcall);
668 /* If this user's name is the name of the system administrator
669 * (as specified in setup), automatically assign access level 6.
671 if ( (!IsEmptyStr(CtdlGetConfigStr("c_sysadm"))) && (!strcasecmp(CC->user.fullname, CtdlGetConfigStr("c_sysadm"))) ) {
672 CC->user.axlevel = AxAideU;
675 /* If we're authenticating off the host system, automatically give root the highest level of access. */
676 if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
677 if (CC->user.uid == 0) {
678 CC->user.axlevel = AxAideU;
681 CtdlPutUserLock(&CC->user);
683 /* If we are using LDAP authentication, extract the user's email addresses from the directory. */
684 if ((CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP) || (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD)) {
685 char new_emailaddrs[512];
686 if (CtdlGetConfigInt("c_ldap_sync_email_addrs") > 0) {
687 if (extract_email_addresses_from_ldap(CC->ldap_dn, new_emailaddrs) == 0) {
688 CtdlSetEmailAddressesForUser(CC->user.fullname, new_emailaddrs);
693 /* If the user does not have any email addresses assigned, generate one. */
694 if (IsEmptyStr(CC->user.emailaddrs)) {
695 AutoGenerateEmailAddressForUser(&CC->user);
698 /* Populate the user principal identity, which is consistent and never aliased */
699 strcpy(CC->cs_principal_id, "");
700 makeuserkey(CC->cs_principal_id, CC->user.fullname);
701 strcat(CC->cs_principal_id, "@");
702 strcat(CC->cs_principal_id, CtdlGetConfigStr("c_fqdn"));
705 * Populate cs_inet_email and cs_inet_other_emails with valid email addresses from the user record
707 strcpy(CC->cs_inet_email, CC->user.emailaddrs);
708 char *firstsep = strstr(CC->cs_inet_email, "|");
710 strcpy(CC->cs_inet_other_emails, firstsep+1);
714 CC->cs_inet_other_emails[0] = 0;
717 /* Create any personal rooms required by the system.
718 * (Technically, MAILROOM should be there already, but just in case...)
720 CtdlCreateRoom(MAILROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
721 CtdlCreateRoom(SENTITEMS, 4, "", 0, 1, 0, VIEW_MAILBOX);
722 CtdlCreateRoom(USERTRASHROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
723 CtdlCreateRoom(USERDRAFTROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
725 /* Run any startup routines registered by loadable modules */
726 PerformSessionHooks(EVT_LOGIN);
728 /* Enter the lobby */
729 CtdlUserGoto(CtdlGetConfigStr("c_baseroom"), 0, 0, NULL, NULL, NULL, NULL);
733 void logged_in_response(void)
735 cprintf("%d %s|%d|%ld|%ld|%u|%ld|%ld\n",
736 CIT_OK, CC->user.fullname, CC->user.axlevel,
737 CC->user.timescalled, CC->user.posted,
738 CC->user.flags, CC->user.usernum,
744 void CtdlUserLogout(void)
746 CitContext *CCC = MyContext();
748 syslog(LOG_DEBUG, "user_ops: CtdlUserLogout() logging out <%s> from session %d", CCC->curr_user, CCC->cs_pid);
750 /* Run any hooks registered by modules... */
751 PerformSessionHooks(EVT_LOGOUT);
754 * Clear out some session data. Most likely, the CitContext for this
755 * session is about to get nuked when the session disconnects, but
756 * since it's possible to log in again without reconnecting, we cannot
757 * make that assumption.
761 /* Check to see if the user was deleted while logged in and purge them if necessary */
762 if ((CCC->user.axlevel == AxDeleted) && (CCC->user.usernum)) {
763 purge_user(CCC->user.fullname);
766 /* Clear out the user record in memory so we don't behave like a ghost */
767 memset(&CCC->user, 0, sizeof(struct ctdluser));
768 CCC->curr_user[0] = 0;
769 CCC->cs_inet_email[0] = 0;
770 CCC->cs_inet_other_emails[0] = 0;
771 CCC->cs_inet_fn[0] = 0;
773 /* Free any output buffers */
779 * Validate a password on the host unix system by talking to the chkpwd daemon
781 static int validpw(uid_t uid, const char *pass)
786 if (IsEmptyStr(pass)) {
787 syslog(LOG_DEBUG, "user_ops: refusing to chkpwd for uid=%d with empty password", uid);
791 syslog(LOG_DEBUG, "user_ops: validating password for uid=%d using chkpwd...", uid);
793 begin_critical_section(S_CHKPWD);
794 rv = write(chkpwd_write_pipe[1], &uid, sizeof(uid_t));
796 syslog(LOG_ERR, "user_ops: communication with chkpwd broken: %m");
797 end_critical_section(S_CHKPWD);
800 rv = write(chkpwd_write_pipe[1], pass, 256);
802 syslog(LOG_ERR, "user_ops: communication with chkpwd broken: %m");
803 end_critical_section(S_CHKPWD);
806 rv = read(chkpwd_read_pipe[0], buf, 4);
808 syslog(LOG_ERR, "user_ops: ommunication with chkpwd broken: %m");
809 end_critical_section(S_CHKPWD);
812 end_critical_section(S_CHKPWD);
814 if (!strncmp(buf, "PASS", 4)) {
815 syslog(LOG_DEBUG, "user_ops: chkpwd pass");
819 syslog(LOG_DEBUG, "user_ops: chkpwd fail");
825 * Start up the chkpwd daemon so validpw() has something to talk to
827 void start_chkpwd_daemon(void) {
829 struct stat filestats;
832 syslog(LOG_DEBUG, "user_ops: starting chkpwd daemon for host authentication mode");
834 if ((stat(file_chkpwd, &filestats)==-1) || (filestats.st_size==0)) {
835 syslog(LOG_ERR, "user_ops: %s: %m", file_chkpwd);
838 if (pipe(chkpwd_write_pipe) != 0) {
839 syslog(LOG_ERR, "user_ops: unable to create pipe for chkpwd daemon: %m");
842 if (pipe(chkpwd_read_pipe) != 0) {
843 syslog(LOG_ERR, "user_ops: unable to create pipe for chkpwd daemon: %m");
848 if (chkpwd_pid < 0) {
849 syslog(LOG_ERR, "user_ops: unable to fork chkpwd daemon: %m");
852 if (chkpwd_pid == 0) {
853 dup2(chkpwd_write_pipe[0], 0);
854 dup2(chkpwd_read_pipe[1], 1);
855 for (i=2; i<256; ++i) close(i);
856 execl(file_chkpwd, file_chkpwd, NULL);
857 syslog(LOG_ERR, "user_ops: unable to exec chkpwd daemon: %m");
864 int CtdlTryPassword(const char *password, long len)
867 CitContext *CCC = CC;
869 if ((CCC->logged_in)) {
870 syslog(LOG_WARNING, "user_ops: CtdlTryPassword: already logged in");
871 return pass_already_logged_in;
873 if (!strcmp(CCC->curr_user, NLI)) {
874 syslog(LOG_WARNING, "user_ops: CtdlTryPassword: no user selected");
877 if (CtdlGetUser(&CCC->user, CCC->curr_user)) {
878 syslog(LOG_ERR, "user_ops: CtdlTryPassword: internal error");
879 return pass_internal_error;
881 if (password == NULL) {
882 syslog(LOG_INFO, "user_ops: CtdlTryPassword: NULL password string supplied");
883 return pass_wrong_password;
886 else if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
890 if (validpw(CCC->user.uid, password)) {
894 * sooper-seekrit hack: populate the password field in the
895 * citadel database with the password that the user typed,
896 * if it's correct. This allows most sites to convert from
897 * host auth to native auth if they want to. If you think
898 * this is a security hazard, comment it out.
901 CtdlGetUserLock(&CCC->user, CCC->curr_user);
902 safestrncpy(CCC->user.password, password, sizeof CCC->user.password);
903 CtdlPutUserLock(&CCC->user);
906 * (sooper-seekrit hack ends here)
914 else if ((CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP) || (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD)) {
918 if ((CCC->ldap_dn) && (!CtdlTryPasswordLDAP(CCC->ldap_dn, password))) {
928 /* native auth mode */
931 pw = (char*) malloc(len + 1);
932 memcpy(pw, password, len + 1);
934 strproc(CCC->user.password);
935 code = strcasecmp(CCC->user.password, pw);
938 strproc(CCC->user.password);
939 code = strcasecmp(CCC->user.password, pw);
949 syslog(LOG_WARNING, "user_ops: bad password specified for <%s> Service <%s> Port <%ld> Remote <%s / %s>",
956 return pass_wrong_password;
962 * Delete a user record *and* all of its related resources.
964 int purge_user(char pname[])
966 struct ctdluser usbuf;
967 char usernamekey[USERNAME_SIZE];
969 makeuserkey(usernamekey, pname);
971 /* If the name is empty we can't find them in the DB any way so just return */
972 if (IsEmptyStr(pname)) {
973 return(ERROR + NO_SUCH_USER);
976 if (CtdlGetUser(&usbuf, pname) != 0) {
977 syslog(LOG_ERR, "user_ops: cannot purge user <%s> - not found", pname);
978 return(ERROR + NO_SUCH_USER);
981 /* Don't delete a user who is currently logged in. Instead, just
982 * set the access level to 0, and let the account get swept up
983 * during the next purge.
985 if (CtdlIsUserLoggedInByNum(usbuf.usernum)) {
986 syslog(LOG_WARNING, "user_ops: <%s> is logged in; not deleting", pname);
987 usbuf.axlevel = AxDeleted;
992 syslog(LOG_NOTICE, "user_ops: deleting <%s>", pname);
994 /* Perform any purge functions registered by server extensions */
995 PerformUserHooks(&usbuf, EVT_PURGEUSER);
997 /* delete any existing user/room relationships */
998 cdb_delete(CDB_VISIT, &usbuf.usernum, sizeof(long));
1000 /* delete the users-by-number index record */
1001 cdb_delete(CDB_USERSBYNUMBER, &usbuf.usernum, sizeof(long));
1003 /* delete the userlog entry */
1004 cdb_delete(CDB_USERS, usernamekey, strlen(usernamekey));
1010 int internal_create_user(char *username, struct ctdluser *usbuf, uid_t uid)
1012 if (!CtdlGetUser(usbuf, username)) {
1013 return(ERROR + ALREADY_EXISTS);
1016 /* Go ahead and initialize a new user record */
1017 memset(usbuf, 0, sizeof(struct ctdluser));
1018 safestrncpy(usbuf->fullname, username, sizeof usbuf->fullname);
1019 strcpy(usbuf->password, "");
1022 /* These are the default flags on new accounts */
1023 usbuf->flags = US_LASTOLD | US_DISAPPEAR | US_PAGINATOR | US_FLOORS;
1025 usbuf->timescalled = 0;
1027 usbuf->axlevel = CtdlGetConfigInt("c_initax");
1028 usbuf->lastcall = time(NULL);
1030 /* fetch a new user number */
1031 usbuf->usernum = get_new_user_number();
1033 /* add user to the database */
1035 cdb_store(CDB_USERSBYNUMBER, &usbuf->usernum, sizeof(long), usbuf->fullname, strlen(usbuf->fullname)+1);
1037 /* If non-native auth, index by uid */
1038 if ((usbuf->uid > 0) && (usbuf->uid != NATIVE_AUTH_UID)) {
1039 StrBuf *claimed_id = NewStrBuf();
1040 StrBufPrintf(claimed_id, "uid:%d", usbuf->uid);
1041 attach_extauth(usbuf, claimed_id);
1042 FreeStrBuf(&claimed_id);
1050 * create_user() - back end processing to create a new user
1052 * Set 'newusername' to the desired account name.
1053 * Set 'become_user' to CREATE_USER_BECOME_USER if this is self-service account creation and we want to
1054 * actually log in as the user we just created, otherwise set it to CREATE_USER_DO_NOT_BECOME_USER
1055 * Set 'uid' to some uid_t value to associate the account with an external auth user, or (-1) for native auth
1057 int create_user(char *username, int become_user, uid_t uid)
1059 struct ctdluser usbuf;
1060 struct ctdlroom qrbuf;
1061 char mailboxname[ROOMNAMELEN];
1066 if ((retval = internal_create_user(username, &usbuf, uid)) != 0) {
1071 * Give the user a private mailbox and a configuration room.
1072 * Make the latter an invisible system room.
1074 CtdlMailboxName(mailboxname, sizeof mailboxname, &usbuf, MAILROOM);
1075 CtdlCreateRoom(mailboxname, 5, "", 0, 1, 1, VIEW_MAILBOX);
1077 CtdlMailboxName(mailboxname, sizeof mailboxname, &usbuf, USERCONFIGROOM);
1078 CtdlCreateRoom(mailboxname, 5, "", 0, 1, 1, VIEW_BBS);
1079 if (CtdlGetRoomLock(&qrbuf, mailboxname) == 0) {
1080 qrbuf.QRflags2 |= QR2_SYSTEM;
1081 CtdlPutRoomLock(&qrbuf);
1084 /* Perform any create functions registered by server extensions */
1085 PerformUserHooks(&usbuf, EVT_NEWUSER);
1087 /* Everything below this line can be bypassed if administratively
1088 * creating a user, instead of doing self-service account creation
1091 if (become_user == CREATE_USER_BECOME_USER) {
1092 /* Now become the user we just created */
1093 memcpy(&CC->user, &usbuf, sizeof(struct ctdluser));
1094 safestrncpy(CC->curr_user, username, sizeof CC->curr_user);
1097 /* Check to make sure we're still who we think we are */
1098 if (CtdlGetUser(&CC->user, CC->curr_user)) {
1099 return(ERROR + INTERNAL_ERROR);
1104 "New user account <%s> has been created, from host %s [%s].\n",
1109 CtdlAideMessage(buf, "User Creation Notice");
1110 syslog(LOG_NOTICE, "user_ops: <%s> created", username);
1116 * set password - back end api code
1118 void CtdlSetPassword(char *new_pw)
1120 CtdlGetUserLock(&CC->user, CC->curr_user);
1121 safestrncpy(CC->user.password, new_pw, sizeof(CC->user.password));
1122 CtdlPutUserLock(&CC->user);
1123 syslog(LOG_INFO, "user_ops: password changed for <%s>", CC->curr_user);
1124 PerformSessionHooks(EVT_SETPASS);
1129 * API function for cmd_invt_kick() and anything else that needs to
1130 * invite or kick out a user to/from a room.
1132 * Set iuser to the name of the user, and op to 1=invite or 0=kick
1134 int CtdlInvtKick(char *iuser, int op) {
1135 struct ctdluser USscratch;
1139 if (CtdlGetUser(&USscratch, iuser) != 0) {
1143 CtdlGetRelationship(&vbuf, &USscratch, &CC->room);
1145 vbuf.v_flags = vbuf.v_flags & ~V_FORGET & ~V_LOCKOUT;
1146 vbuf.v_flags = vbuf.v_flags | V_ACCESS;
1149 vbuf.v_flags = vbuf.v_flags & ~V_ACCESS;
1150 vbuf.v_flags = vbuf.v_flags | V_FORGET | V_LOCKOUT;
1152 CtdlSetRelationship(&vbuf, &USscratch, &CC->room);
1154 /* post a message in Aide> saying what we just did */
1155 snprintf(bbb, sizeof bbb, "%s has been %s \"%s\" by %s.\n",
1157 ((op == 1) ? "invited to" : "kicked out of"),
1159 (CC->logged_in ? CC->user.fullname : "an administrator")
1161 CtdlAideMessage(bbb,"User Admin Message");
1167 * Forget (Zap) the current room (API call)
1168 * Returns 0 on success
1170 int CtdlForgetThisRoom(void) {
1173 /* On some systems, Admins are not allowed to forget rooms */
1174 if (is_aide() && (CtdlGetConfigInt("c_aide_zap") == 0)
1175 && ((CC->room.QRflags & QR_MAILBOX) == 0) ) {
1179 CtdlGetUserLock(&CC->user, CC->curr_user);
1180 CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
1182 vbuf.v_flags = vbuf.v_flags | V_FORGET;
1183 vbuf.v_flags = vbuf.v_flags & ~V_ACCESS;
1185 CtdlSetRelationship(&vbuf, &CC->user, &CC->room);
1186 CtdlPutUserLock(&CC->user);
1188 /* Return to the Lobby, so we don't end up in an undefined room */
1189 CtdlUserGoto(CtdlGetConfigStr("c_baseroom"), 0, 0, NULL, NULL, NULL, NULL);
1195 * Traverse the user file and perform a callback for each user record.
1196 * (New improved version that runs in two phases so that callbacks can perform writes without having a r/o cursor open)
1198 void ForEachUser(void (*CallBack) (char *, void *out_data), void *in_data)
1200 struct cdbdata *cdbus;
1201 struct ctdluser *usptr;
1205 char username[USERNAME_SIZE];
1207 struct feu *ufirst = NULL;
1208 struct feu *ulast = NULL;
1209 struct feu *f = NULL;
1211 cdb_rewind(CDB_USERS);
1213 // Phase 1 : build a linked list of all our user account names
1214 while (cdbus = cdb_next_item(CDB_USERS), cdbus != NULL) {
1215 usptr = (struct ctdluser *) cdbus->ptr;
1217 if (strlen(usptr->fullname) > 0) {
1218 f = malloc(sizeof(struct feu));
1220 strncpy(f->username, usptr->fullname, USERNAME_SIZE);
1222 if (ufirst == NULL) {
1233 // Phase 2 : perform the callback for each user while de-allocating the list
1234 while (ufirst != NULL) {
1235 (*CallBack) (ufirst->username, in_data);
1237 ufirst = ufirst->next;
1244 * Count the number of new mail messages the user has
1248 int num_newmsgs = 0;
1249 num_newmsgs = CC->newmail;
1251 return(num_newmsgs);
1256 * Count the number of new mail messages the user has
1258 int InitialMailCheck()
1260 int num_newmsgs = 0;
1262 char mailboxname[ROOMNAMELEN];
1263 struct ctdlroom mailbox;
1265 struct cdbdata *cdbfr;
1266 long *msglist = NULL;
1269 CtdlMailboxName(mailboxname, sizeof mailboxname, &CC->user, MAILROOM);
1270 if (CtdlGetRoom(&mailbox, mailboxname) != 0)
1272 CtdlGetRelationship(&vbuf, &CC->user, &mailbox);
1274 cdbfr = cdb_fetch(CDB_MSGLISTS, &mailbox.QRnumber, sizeof(long));
1276 if (cdbfr != NULL) {
1277 msglist = malloc(cdbfr->len);
1278 memcpy(msglist, cdbfr->ptr, cdbfr->len);
1279 num_msgs = cdbfr->len / sizeof(long);
1283 for (a = 0; a < num_msgs; ++a) {
1284 if (msglist[a] > 0L) {
1285 if (msglist[a] > vbuf.v_lastseen) {
1290 if (msglist != NULL)
1293 return(num_newmsgs);