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 cdbus = cdb_fetch(CDB_USERS, usernamekey, strlen(usernamekey));
89 if (cdbus == NULL) { /* user not found */
93 memcpy(usbuf, cdbus->ptr, ((cdbus->len > sizeof(struct ctdluser)) ? sizeof(struct ctdluser) : cdbus->len));
100 int CtdlLockGetCurrentUser(void)
102 CitContext *CCC = CC;
103 return CtdlGetUser(&CCC->user, CCC->curr_user);
108 * CtdlGetUserLock() - same as getuser() but locks the record
110 int CtdlGetUserLock(struct ctdluser *usbuf, char *name)
114 retcode = CtdlGetUser(usbuf, name);
116 begin_critical_section(S_USERS);
123 * CtdlPutUser() - write user buffer into the correct place on disk
125 void CtdlPutUser(struct ctdluser *usbuf)
127 char usernamekey[USERNAME_SIZE];
129 makeuserkey(usernamekey, usbuf->fullname);
130 usbuf->version = REV_LEVEL;
131 cdb_store(CDB_USERS, usernamekey, strlen(usernamekey), usbuf, sizeof(struct ctdluser));
135 void CtdlPutCurrentUserLock()
137 CtdlPutUser(&CC->user);
142 * CtdlPutUserLock() - same as putuser() but locks the record
144 void CtdlPutUserLock(struct ctdluser *usbuf)
147 end_critical_section(S_USERS);
152 * rename_user() - this is tricky because the user's display name is the database key
154 * Returns 0 on success or nonzero if there was an error...
157 int rename_user(char *oldname, char *newname) {
158 int retcode = RENAMEUSER_OK;
159 struct ctdluser usbuf;
161 char oldnamekey[USERNAME_SIZE];
162 char newnamekey[USERNAME_SIZE];
164 /* Create the database keys... */
165 makeuserkey(oldnamekey, oldname);
166 makeuserkey(newnamekey, newname);
168 /* Lock up and get going */
169 begin_critical_section(S_USERS);
171 /* We cannot rename a user who is currently logged in */
172 if (CtdlIsUserLoggedIn(oldname)) {
173 end_critical_section(S_USERS);
174 return RENAMEUSER_LOGGED_IN;
177 if (CtdlGetUser(&usbuf, newname) == 0) {
178 retcode = RENAMEUSER_ALREADY_EXISTS;
182 if (CtdlGetUser(&usbuf, oldname) != 0) {
183 retcode = RENAMEUSER_NOT_FOUND;
185 else { /* Sanity checks succeeded. Now rename the user. */
186 if (usbuf.usernum == 0) {
187 syslog(LOG_DEBUG, "user_ops: can not rename user \"Citadel\".");
188 retcode = RENAMEUSER_NOT_FOUND;
190 syslog(LOG_DEBUG, "user_ops: renaming <%s> to <%s>", oldname, newname);
191 cdb_delete(CDB_USERS, oldnamekey, strlen(oldnamekey));
192 safestrncpy(usbuf.fullname, newname, sizeof usbuf.fullname);
194 cdb_store(CDB_USERSBYNUMBER, &usbuf.usernum, sizeof(long), usbuf.fullname, strlen(usbuf.fullname)+1 );
195 retcode = RENAMEUSER_OK;
201 end_critical_section(S_USERS);
207 * Convert a username into the format used as a database key prior to version 928
208 * This only gets called by reindex_user_928()
210 void makeuserkey_pre928(char *key, const char *username) {
213 int len = strlen(username);
215 if (len >= USERNAME_SIZE) {
216 syslog(LOG_INFO, "Username too long: %s", username);
217 len = USERNAME_SIZE - 1;
219 for (i=0; i<=len; ++i) {
220 key[i] = tolower(username[i]);
226 * Read a user record using the pre-v928 index format, and write it back using the v928-and-higher index format.
227 * This ONLY gets called during an upgrade from version <928 to version >=928.
229 void reindex_user_928(char *username, void *out_data) {
231 char oldkey[USERNAME_SIZE];
232 char newkey[USERNAME_SIZE];
233 struct cdbdata *cdbus;
234 struct ctdluser usbuf;
236 makeuserkey_pre928(oldkey, username);
237 makeuserkey(newkey, username);
239 syslog(LOG_DEBUG, "user_ops: reindex_user_928: %s <%s> --> <%s>", username, oldkey, newkey);
241 // Fetch the user record using the old index format
242 cdbus = cdb_fetch(CDB_USERS, oldkey, strlen(oldkey));
244 syslog(LOG_INFO, "user_ops: <%s> not found, were they already reindexed?", username);
247 memcpy(&usbuf, cdbus->ptr, ((cdbus->len > sizeof(struct ctdluser)) ? sizeof(struct ctdluser) : cdbus->len));
250 // delete the old record
251 cdb_delete(CDB_USERS, oldkey, strlen(oldkey));
253 // write the new record
254 cdb_store(CDB_USERS, newkey, strlen(newkey), &usbuf, sizeof(struct ctdluser));
259 * Index-generating function used by Ctdl[Get|Set]Relationship
261 int GenerateRelationshipIndex(char *IndexBuf,
272 TheIndex.iRoomID = RoomID;
273 TheIndex.iRoomGen = RoomGen;
274 TheIndex.iUserID = UserID;
276 memcpy(IndexBuf, &TheIndex, sizeof(TheIndex));
277 return(sizeof(TheIndex));
282 * Back end for CtdlSetRelationship()
284 void put_visit(visit *newvisit)
289 memset (IndexBuf, 0, sizeof (IndexBuf));
290 /* Generate an index */
291 IndexLen = GenerateRelationshipIndex(IndexBuf, newvisit->v_roomnum, newvisit->v_roomgen, newvisit->v_usernum);
293 /* Store the record */
294 cdb_store(CDB_VISIT, IndexBuf, IndexLen,
295 newvisit, sizeof(visit)
301 * Define a relationship between a user and a room
303 void CtdlSetRelationship(visit *newvisit, struct ctdluser *rel_user, struct ctdlroom *rel_room) {
304 /* We don't use these in Citadel because they're implicit by the
305 * index, but they must be present if the database is exported.
307 newvisit->v_roomnum = rel_room->QRnumber;
308 newvisit->v_roomgen = rel_room->QRgen;
309 newvisit->v_usernum = rel_user->usernum;
316 * Locate a relationship between a user and a room
318 void CtdlGetRelationship(visit *vbuf, struct ctdluser *rel_user, struct ctdlroom *rel_room) {
321 struct cdbdata *cdbvisit;
323 /* Generate an index */
324 IndexLen = GenerateRelationshipIndex(IndexBuf, rel_room->QRnumber, rel_room->QRgen, rel_user->usernum);
326 /* Clear out the buffer */
327 memset(vbuf, 0, sizeof(visit));
329 cdbvisit = cdb_fetch(CDB_VISIT, IndexBuf, IndexLen);
330 if (cdbvisit != NULL) {
331 memcpy(vbuf, cdbvisit->ptr, ((cdbvisit->len > sizeof(visit)) ? sizeof(visit) : cdbvisit->len));
335 /* If this is the first time the user has seen this room,
336 * set the view to be the default for the room.
338 vbuf->v_view = rel_room->QRdefaultview;
341 /* Set v_seen if necessary */
342 if (vbuf->v_seen[0] == 0) {
343 snprintf(vbuf->v_seen, sizeof vbuf->v_seen, "*:%ld", vbuf->v_lastseen);
348 void CtdlMailboxName(char *buf, size_t n, const struct ctdluser *who, const char *prefix)
350 snprintf(buf, n, "%010ld.%s", who->usernum, prefix);
354 void MailboxName(char *buf, size_t n, const struct ctdluser *who, const char *prefix)
356 snprintf(buf, n, "%010ld.%s", who->usernum, prefix);
361 * Check to see if the specified user has Internet mail permission
362 * (returns nonzero if permission is granted)
364 int CtdlCheckInternetMailPermission(struct ctdluser *who) {
366 /* Do not allow twits to send Internet mail */
367 if (who->axlevel <= AxProbU) return(0);
369 /* Globally enabled? */
370 if (CtdlGetConfigInt("c_restrict") == 0) return(1);
372 /* User flagged ok? */
373 if (who->flags & US_INTERNET) return(2);
375 /* Admin level access? */
376 if (who->axlevel >= AxAideU) return(3);
378 /* No mail for you! */
384 * Convenience function.
386 int CtdlAccessCheck(int required_level)
388 if (CC->internal_pgm) return(0);
389 if (required_level >= ac_internal) {
390 cprintf("%d This is not a user-level command.\n", ERROR + HIGHER_ACCESS_REQUIRED);
394 if ((required_level >= ac_logged_in_or_guest) && (CC->logged_in == 0) && (CtdlGetConfigInt("c_guest_logins") == 0)) {
395 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
399 if ((required_level >= ac_logged_in) && (CC->logged_in == 0)) {
400 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
404 if (CC->user.axlevel >= AxAideU) return(0);
405 if (required_level >= ac_aide) {
406 cprintf("%d This command requires Admin access.\n",
407 ERROR + HIGHER_ACCESS_REQUIRED);
411 if (is_room_aide()) return(0);
412 if (required_level >= ac_room_aide) {
413 cprintf("%d This command requires Admin or Room Admin access.\n",
414 ERROR + HIGHER_ACCESS_REQUIRED);
418 /* shhh ... succeed quietly */
424 * Is the user currently logged in an Admin?
428 if (CC->user.axlevel >= AxAideU)
436 * Is the user currently logged in an Admin *or* the room Admin for this room?
438 int is_room_aide(void)
441 if (!CC->logged_in) {
445 if ((CC->user.axlevel >= AxAideU) || (CC->room.QRroomaide == CC->user.usernum)) {
454 * CtdlGetUserByNumber() - get user by number
455 * returns 0 if user was found
457 * Note: fetching a user this way requires one additional database operation.
459 int CtdlGetUserByNumber(struct ctdluser *usbuf, long number)
461 struct cdbdata *cdbun;
464 cdbun = cdb_fetch(CDB_USERSBYNUMBER, &number, sizeof(long));
466 syslog(LOG_INFO, "user_ops: %ld not found", number);
470 syslog(LOG_INFO, "user_ops: %ld maps to %s", number, cdbun->ptr);
471 r = CtdlGetUser(usbuf, cdbun->ptr);
478 * Helper function for rebuild_usersbynumber()
480 void rebuild_ubn_for_user(char *username, void *data) {
483 syslog(LOG_DEBUG, "user_ops: rebuilding usersbynumber index for %s", username);
484 if (CtdlGetUser(&u, username) == 0) {
485 cdb_store(CDB_USERSBYNUMBER, &(u.usernum), sizeof(long), u.fullname, strlen(u.fullname)+1);
491 * Rebuild the users-by-number index
493 void rebuild_usersbynumber(void) {
494 cdb_trunc(CDB_USERSBYNUMBER); /* delete the old indices */
495 ForEachUser(rebuild_ubn_for_user, NULL); /* enumerate the users */
500 * getuserbyuid() Get user by system uid (for PAM mode authentication)
501 * Returns 0 if user was found
502 * This now uses an extauth index.
504 int getuserbyuid(struct ctdluser *usbuf, uid_t number)
506 struct cdbdata *cdbextauth;
510 claimed_id = NewStrBuf();
511 StrBufPrintf(claimed_id, "uid:%d", number);
512 cdbextauth = cdb_fetch(CDB_EXTAUTH, ChrPtr(claimed_id), StrLength(claimed_id));
513 FreeStrBuf(&claimed_id);
514 if (cdbextauth == NULL) {
518 memcpy(&usernum, cdbextauth->ptr, sizeof(long));
519 cdb_free(cdbextauth);
521 if (!CtdlGetUserByNumber(usbuf, usernum)) {
530 * Back end for cmd_user() and its ilk
532 int CtdlLoginExistingUser(const char *trythisname)
537 syslog(LOG_DEBUG, "user_ops: CtdlLoginExistingUser(%s)", trythisname);
539 if ((CC->logged_in)) {
540 return login_already_logged_in;
543 if (trythisname == NULL) return login_not_found;
545 if (!strncasecmp(trythisname, "SYS_", 4))
547 syslog(LOG_DEBUG, "user_ops: system user \"%s\" is not allowed to log in.", trythisname);
548 return login_not_found;
551 /* Continue attempting user validation... */
552 safestrncpy(username, trythisname, sizeof (username));
555 if (IsEmptyStr(username)) {
556 return login_not_found;
559 if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
564 struct passwd *tempPwdPtr;
567 syslog(LOG_DEBUG, "user_ops: asking host about <%s>", username);
568 #ifdef HAVE_GETPWNAM_R
569 #ifdef SOLARIS_GETPWUID
570 syslog(LOG_DEBUG, "user_ops: calling getpwnam_r()");
571 tempPwdPtr = getpwnam_r(username, &pd, pwdbuffer, sizeof pwdbuffer);
572 #else // SOLARIS_GETPWUID
573 syslog(LOG_DEBUG, "user_ops: calling getpwnam_r()");
574 getpwnam_r(username, &pd, pwdbuffer, sizeof pwdbuffer, &tempPwdPtr);
575 #endif // SOLARIS_GETPWUID
576 #else // HAVE_GETPWNAM_R
577 syslog(LOG_DEBUG, "user_ops: SHOULD NEVER GET HERE!!!");
579 #endif // HAVE_GETPWNAM_R
580 if (tempPwdPtr == NULL) {
581 syslog(LOG_DEBUG, "user_ops: no such user <%s>", username);
582 return login_not_found;
585 /* Locate the associated Citadel account. If not found, make one attempt to create it. */
586 found_user = getuserbyuid(&CC->user, pd.pw_uid);
587 if (found_user != 0) {
588 create_user(username, CREATE_USER_DO_NOT_BECOME_USER, pd.pw_uid);
589 found_user = getuserbyuid(&CC->user, pd.pw_uid);
591 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);
624 /* native auth mode */
626 struct recptypes *valid = NULL;
628 /* First, try to log in as if the supplied name is a display name */
629 found_user = CtdlGetUser(&CC->user, username);
631 /* If that didn't work, try to log in as if the supplied name * is an e-mail address */
632 if (found_user != 0) {
633 valid = validate_recipients(username, NULL, 0);
635 if (valid->num_local == 1) {
636 found_user = CtdlGetUser(&CC->user, valid->recp_local);
638 free_recipients(valid);
643 /* Did we find something? */
644 if (found_user == 0) {
645 if (((CC->nologin)) && (CC->user.axlevel < AxAideU)) {
646 return login_too_many_users;
648 safestrncpy(CC->curr_user, CC->user.fullname, sizeof CC->curr_user);
652 return login_not_found;
657 * session startup code which is common to both cmd_pass() and cmd_newu()
662 syslog(LOG_NOTICE, "user_ops: <%s> logged in", CC->curr_user);
664 CtdlGetUserLock(&CC->user, CC->curr_user);
665 ++(CC->user.timescalled);
666 CC->previous_login = CC->user.lastcall;
667 time(&CC->user.lastcall);
669 /* If this user's name is the name of the system administrator
670 * (as specified in setup), automatically assign access level 6.
672 if ( (!IsEmptyStr(CtdlGetConfigStr("c_sysadm"))) && (!strcasecmp(CC->user.fullname, CtdlGetConfigStr("c_sysadm"))) ) {
673 CC->user.axlevel = AxAideU;
676 /* If we're authenticating off the host system, automatically give root the highest level of access. */
677 if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
678 if (CC->user.uid == 0) {
679 CC->user.axlevel = AxAideU;
682 CtdlPutUserLock(&CC->user);
684 /* If we are using LDAP authentication, extract the user's email addresses from the directory. */
686 if ((CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP) || (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD)) {
687 char new_emailaddrs[512];
688 if (CtdlGetConfigInt("c_ldap_sync_email_addrs") > 0) {
689 if (extract_email_addresses_from_ldap(CC->ldap_dn, new_emailaddrs) == 0) {
690 CtdlSetEmailAddressesForUser(CC->user.fullname, new_emailaddrs);
696 /* If the user does not have any email addresses assigned, generate one. */
697 if (IsEmptyStr(CC->user.emailaddrs)) {
698 AutoGenerateEmailAddressForUser(&CC->user);
701 /* Populate the user principal identity, which is consistent and never aliased */
702 strcpy(CC->cs_principal_id, "");
703 makeuserkey(CC->cs_principal_id, CC->user.fullname);
704 strcat(CC->cs_principal_id, "@");
705 strcat(CC->cs_principal_id, CtdlGetConfigStr("c_fqdn"));
708 * Populate cs_inet_email and cs_inet_other_emails with valid email addresses from the user record
710 strcpy(CC->cs_inet_email, CC->user.emailaddrs);
711 char *firstsep = strstr(CC->cs_inet_email, "|");
713 strcpy(CC->cs_inet_other_emails, firstsep+1);
717 CC->cs_inet_other_emails[0] = 0;
720 /* Create any personal rooms required by the system.
721 * (Technically, MAILROOM should be there already, but just in case...)
723 CtdlCreateRoom(MAILROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
724 CtdlCreateRoom(SENTITEMS, 4, "", 0, 1, 0, VIEW_MAILBOX);
725 CtdlCreateRoom(USERTRASHROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
726 CtdlCreateRoom(USERDRAFTROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
728 /* Run any startup routines registered by loadable modules */
729 PerformSessionHooks(EVT_LOGIN);
731 /* Enter the lobby */
732 CtdlUserGoto(CtdlGetConfigStr("c_baseroom"), 0, 0, NULL, NULL, NULL, NULL);
736 void logged_in_response(void)
738 cprintf("%d %s|%d|%ld|%ld|%u|%ld|%ld\n",
739 CIT_OK, CC->user.fullname, CC->user.axlevel,
740 CC->user.timescalled, CC->user.posted,
741 CC->user.flags, CC->user.usernum,
747 void CtdlUserLogout(void)
749 CitContext *CCC = MyContext();
751 syslog(LOG_DEBUG, "user_ops: CtdlUserLogout() logging out <%s> from session %d", CCC->curr_user, CCC->cs_pid);
753 /* Run any hooks registered by modules... */
754 PerformSessionHooks(EVT_LOGOUT);
757 * Clear out some session data. Most likely, the CitContext for this
758 * session is about to get nuked when the session disconnects, but
759 * since it's possible to log in again without reconnecting, we cannot
760 * make that assumption.
764 /* Check to see if the user was deleted while logged in and purge them if necessary */
765 if ((CCC->user.axlevel == AxDeleted) && (CCC->user.usernum)) {
766 purge_user(CCC->user.fullname);
769 /* Clear out the user record in memory so we don't behave like a ghost */
770 memset(&CCC->user, 0, sizeof(struct ctdluser));
771 CCC->curr_user[0] = 0;
772 CCC->cs_inet_email[0] = 0;
773 CCC->cs_inet_other_emails[0] = 0;
774 CCC->cs_inet_fn[0] = 0;
776 /* Free any output buffers */
782 * Validate a password on the host unix system by talking to the chkpwd daemon
784 static int validpw(uid_t uid, const char *pass)
789 if (IsEmptyStr(pass)) {
790 syslog(LOG_DEBUG, "user_ops: refusing to chkpwd for uid=%d with empty password", uid);
794 syslog(LOG_DEBUG, "user_ops: validating password for uid=%d using chkpwd...", uid);
796 begin_critical_section(S_CHKPWD);
797 rv = write(chkpwd_write_pipe[1], &uid, sizeof(uid_t));
799 syslog(LOG_ERR, "user_ops: communication with chkpwd broken: %m");
800 end_critical_section(S_CHKPWD);
803 rv = write(chkpwd_write_pipe[1], pass, 256);
805 syslog(LOG_ERR, "user_ops: communication with chkpwd broken: %m");
806 end_critical_section(S_CHKPWD);
809 rv = read(chkpwd_read_pipe[0], buf, 4);
811 syslog(LOG_ERR, "user_ops: ommunication with chkpwd broken: %m");
812 end_critical_section(S_CHKPWD);
815 end_critical_section(S_CHKPWD);
817 if (!strncmp(buf, "PASS", 4)) {
818 syslog(LOG_DEBUG, "user_ops: chkpwd pass");
822 syslog(LOG_DEBUG, "user_ops: chkpwd fail");
828 * Start up the chkpwd daemon so validpw() has something to talk to
830 void start_chkpwd_daemon(void) {
832 struct stat filestats;
835 syslog(LOG_DEBUG, "user_ops: starting chkpwd daemon for host authentication mode");
837 if ((stat(file_chkpwd, &filestats)==-1) || (filestats.st_size==0)) {
838 syslog(LOG_ERR, "user_ops: %s: %m", file_chkpwd);
841 if (pipe(chkpwd_write_pipe) != 0) {
842 syslog(LOG_ERR, "user_ops: unable to create pipe for chkpwd daemon: %m");
845 if (pipe(chkpwd_read_pipe) != 0) {
846 syslog(LOG_ERR, "user_ops: unable to create pipe for chkpwd daemon: %m");
851 if (chkpwd_pid < 0) {
852 syslog(LOG_ERR, "user_ops: unable to fork chkpwd daemon: %m");
855 if (chkpwd_pid == 0) {
856 dup2(chkpwd_write_pipe[0], 0);
857 dup2(chkpwd_read_pipe[1], 1);
858 for (i=2; i<256; ++i) close(i);
859 execl(file_chkpwd, file_chkpwd, NULL);
860 syslog(LOG_ERR, "user_ops: unable to exec chkpwd daemon: %m");
867 int CtdlTryPassword(const char *password, long len)
870 CitContext *CCC = CC;
872 if ((CCC->logged_in)) {
873 syslog(LOG_WARNING, "user_ops: CtdlTryPassword: already logged in");
874 return pass_already_logged_in;
876 if (!strcmp(CCC->curr_user, NLI)) {
877 syslog(LOG_WARNING, "user_ops: CtdlTryPassword: no user selected");
880 if (CtdlGetUser(&CCC->user, CCC->curr_user)) {
881 syslog(LOG_ERR, "user_ops: CtdlTryPassword: internal error");
882 return pass_internal_error;
884 if (password == NULL) {
885 syslog(LOG_INFO, "user_ops: CtdlTryPassword: NULL password string supplied");
886 return pass_wrong_password;
889 else if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
893 if (validpw(CCC->user.uid, password)) {
897 * sooper-seekrit hack: populate the password field in the
898 * citadel database with the password that the user typed,
899 * if it's correct. This allows most sites to convert from
900 * host auth to native auth if they want to. If you think
901 * this is a security hazard, comment it out.
904 CtdlGetUserLock(&CCC->user, CCC->curr_user);
905 safestrncpy(CCC->user.password, password, sizeof CCC->user.password);
906 CtdlPutUserLock(&CCC->user);
909 * (sooper-seekrit hack ends here)
918 else if ((CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP) || (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD)) {
922 if ((CCC->ldap_dn) && (!CtdlTryPasswordLDAP(CCC->ldap_dn, password))) {
933 /* native auth mode */
936 pw = (char*) malloc(len + 1);
937 memcpy(pw, password, len + 1);
939 strproc(CCC->user.password);
940 code = strcasecmp(CCC->user.password, pw);
943 strproc(CCC->user.password);
944 code = strcasecmp(CCC->user.password, pw);
954 syslog(LOG_WARNING, "user_ops: bad password specified for <%s> Service <%s> Port <%ld> Remote <%s / %s>",
961 return pass_wrong_password;
967 * Delete a user record *and* all of its related resources.
969 int purge_user(char pname[])
971 struct ctdluser usbuf;
972 char usernamekey[USERNAME_SIZE];
974 makeuserkey(usernamekey, pname);
976 /* If the name is empty we can't find them in the DB any way so just return */
977 if (IsEmptyStr(pname)) {
978 return(ERROR + NO_SUCH_USER);
981 if (CtdlGetUser(&usbuf, pname) != 0) {
982 syslog(LOG_ERR, "user_ops: cannot purge user <%s> - not found", pname);
983 return(ERROR + NO_SUCH_USER);
986 /* Don't delete a user who is currently logged in. Instead, just
987 * set the access level to 0, and let the account get swept up
988 * during the next purge.
990 if (CtdlIsUserLoggedInByNum(usbuf.usernum)) {
991 syslog(LOG_WARNING, "user_ops: <%s> is logged in; not deleting", pname);
992 usbuf.axlevel = AxDeleted;
997 syslog(LOG_NOTICE, "user_ops: deleting <%s>", pname);
999 /* Perform any purge functions registered by server extensions */
1000 PerformUserHooks(&usbuf, EVT_PURGEUSER);
1002 /* delete any existing user/room relationships */
1003 cdb_delete(CDB_VISIT, &usbuf.usernum, sizeof(long));
1005 /* delete the users-by-number index record */
1006 cdb_delete(CDB_USERSBYNUMBER, &usbuf.usernum, sizeof(long));
1008 /* delete the userlog entry */
1009 cdb_delete(CDB_USERS, usernamekey, strlen(usernamekey));
1015 int internal_create_user(char *username, struct ctdluser *usbuf, uid_t uid)
1017 if (!CtdlGetUser(usbuf, username)) {
1018 return(ERROR + ALREADY_EXISTS);
1021 /* Go ahead and initialize a new user record */
1022 memset(usbuf, 0, sizeof(struct ctdluser));
1023 safestrncpy(usbuf->fullname, username, sizeof usbuf->fullname);
1024 strcpy(usbuf->password, "");
1027 /* These are the default flags on new accounts */
1028 usbuf->flags = US_LASTOLD | US_DISAPPEAR | US_PAGINATOR | US_FLOORS;
1030 usbuf->timescalled = 0;
1032 usbuf->axlevel = CtdlGetConfigInt("c_initax");
1033 usbuf->lastcall = time(NULL);
1035 /* fetch a new user number */
1036 usbuf->usernum = get_new_user_number();
1038 /* add user to the database */
1040 cdb_store(CDB_USERSBYNUMBER, &usbuf->usernum, sizeof(long), usbuf->fullname, strlen(usbuf->fullname)+1);
1042 /* If non-native auth, index by uid */
1043 if ((usbuf->uid > 0) && (usbuf->uid != NATIVE_AUTH_UID)) {
1044 StrBuf *claimed_id = NewStrBuf();
1045 StrBufPrintf(claimed_id, "uid:%d", usbuf->uid);
1046 attach_extauth(usbuf, claimed_id);
1047 FreeStrBuf(&claimed_id);
1055 * create_user() - back end processing to create a new user
1057 * Set 'newusername' to the desired account name.
1058 * Set 'become_user' to CREATE_USER_BECOME_USER if this is self-service account creation and we want to
1059 * actually log in as the user we just created, otherwise set it to CREATE_USER_DO_NOT_BECOME_USER
1060 * Set 'uid' to some uid_t value to associate the account with an external auth user, or (-1) for native auth
1062 int create_user(char *username, int become_user, uid_t uid)
1064 struct ctdluser usbuf;
1065 struct ctdlroom qrbuf;
1066 char mailboxname[ROOMNAMELEN];
1071 if ((retval = internal_create_user(username, &usbuf, uid)) != 0) {
1076 * Give the user a private mailbox and a configuration room.
1077 * Make the latter an invisible system room.
1079 CtdlMailboxName(mailboxname, sizeof mailboxname, &usbuf, MAILROOM);
1080 CtdlCreateRoom(mailboxname, 5, "", 0, 1, 1, VIEW_MAILBOX);
1082 CtdlMailboxName(mailboxname, sizeof mailboxname, &usbuf, USERCONFIGROOM);
1083 CtdlCreateRoom(mailboxname, 5, "", 0, 1, 1, VIEW_BBS);
1084 if (CtdlGetRoomLock(&qrbuf, mailboxname) == 0) {
1085 qrbuf.QRflags2 |= QR2_SYSTEM;
1086 CtdlPutRoomLock(&qrbuf);
1089 /* Perform any create functions registered by server extensions */
1090 PerformUserHooks(&usbuf, EVT_NEWUSER);
1092 /* Everything below this line can be bypassed if administratively
1093 * creating a user, instead of doing self-service account creation
1096 if (become_user == CREATE_USER_BECOME_USER) {
1097 /* Now become the user we just created */
1098 memcpy(&CC->user, &usbuf, sizeof(struct ctdluser));
1099 safestrncpy(CC->curr_user, username, sizeof CC->curr_user);
1102 /* Check to make sure we're still who we think we are */
1103 if (CtdlGetUser(&CC->user, CC->curr_user)) {
1104 return(ERROR + INTERNAL_ERROR);
1109 "New user account <%s> has been created, from host %s [%s].\n",
1114 CtdlAideMessage(buf, "User Creation Notice");
1115 syslog(LOG_NOTICE, "user_ops: <%s> created", username);
1121 * set password - back end api code
1123 void CtdlSetPassword(char *new_pw)
1125 CtdlGetUserLock(&CC->user, CC->curr_user);
1126 safestrncpy(CC->user.password, new_pw, sizeof(CC->user.password));
1127 CtdlPutUserLock(&CC->user);
1128 syslog(LOG_INFO, "user_ops: password changed for <%s>", CC->curr_user);
1129 PerformSessionHooks(EVT_SETPASS);
1134 * API function for cmd_invt_kick() and anything else that needs to
1135 * invite or kick out a user to/from a room.
1137 * Set iuser to the name of the user, and op to 1=invite or 0=kick
1139 int CtdlInvtKick(char *iuser, int op) {
1140 struct ctdluser USscratch;
1144 if (CtdlGetUser(&USscratch, iuser) != 0) {
1148 CtdlGetRelationship(&vbuf, &USscratch, &CC->room);
1150 vbuf.v_flags = vbuf.v_flags & ~V_FORGET & ~V_LOCKOUT;
1151 vbuf.v_flags = vbuf.v_flags | V_ACCESS;
1154 vbuf.v_flags = vbuf.v_flags & ~V_ACCESS;
1155 vbuf.v_flags = vbuf.v_flags | V_FORGET | V_LOCKOUT;
1157 CtdlSetRelationship(&vbuf, &USscratch, &CC->room);
1159 /* post a message in Aide> saying what we just did */
1160 snprintf(bbb, sizeof bbb, "%s has been %s \"%s\" by %s.\n",
1162 ((op == 1) ? "invited to" : "kicked out of"),
1164 (CC->logged_in ? CC->user.fullname : "an administrator")
1166 CtdlAideMessage(bbb,"User Admin Message");
1172 * Forget (Zap) the current room (API call)
1173 * Returns 0 on success
1175 int CtdlForgetThisRoom(void) {
1178 /* On some systems, Admins are not allowed to forget rooms */
1179 if (is_aide() && (CtdlGetConfigInt("c_aide_zap") == 0)
1180 && ((CC->room.QRflags & QR_MAILBOX) == 0) ) {
1184 CtdlGetUserLock(&CC->user, CC->curr_user);
1185 CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
1187 vbuf.v_flags = vbuf.v_flags | V_FORGET;
1188 vbuf.v_flags = vbuf.v_flags & ~V_ACCESS;
1190 CtdlSetRelationship(&vbuf, &CC->user, &CC->room);
1191 CtdlPutUserLock(&CC->user);
1193 /* Return to the Lobby, so we don't end up in an undefined room */
1194 CtdlUserGoto(CtdlGetConfigStr("c_baseroom"), 0, 0, NULL, NULL, NULL, NULL);
1200 * Traverse the user file and perform a callback for each user record.
1201 * (New improved version that runs in two phases so that callbacks can perform writes without having a r/o cursor open)
1203 void ForEachUser(void (*CallBack) (char *, void *out_data), void *in_data)
1205 struct cdbdata *cdbus;
1206 struct ctdluser *usptr;
1210 char username[USERNAME_SIZE];
1212 struct feu *ufirst = NULL;
1213 struct feu *ulast = NULL;
1214 struct feu *f = NULL;
1216 cdb_rewind(CDB_USERS);
1218 // Phase 1 : build a linked list of all our user account names
1219 while (cdbus = cdb_next_item(CDB_USERS), cdbus != NULL) {
1220 usptr = (struct ctdluser *) cdbus->ptr;
1222 if (strlen(usptr->fullname) > 0) {
1223 f = malloc(sizeof(struct feu));
1225 strncpy(f->username, usptr->fullname, USERNAME_SIZE);
1227 if (ufirst == NULL) {
1238 // Phase 2 : perform the callback for each user while de-allocating the list
1239 while (ufirst != NULL) {
1240 (*CallBack) (ufirst->username, in_data);
1242 ufirst = ufirst->next;
1249 * Count the number of new mail messages the user has
1253 int num_newmsgs = 0;
1254 num_newmsgs = CC->newmail;
1256 return(num_newmsgs);
1261 * Count the number of new mail messages the user has
1263 int InitialMailCheck()
1265 int num_newmsgs = 0;
1267 char mailboxname[ROOMNAMELEN];
1268 struct ctdlroom mailbox;
1270 struct cdbdata *cdbfr;
1271 long *msglist = NULL;
1274 CtdlMailboxName(mailboxname, sizeof mailboxname, &CC->user, MAILROOM);
1275 if (CtdlGetRoom(&mailbox, mailboxname) != 0)
1277 CtdlGetRelationship(&vbuf, &CC->user, &mailbox);
1279 cdbfr = cdb_fetch(CDB_MSGLISTS, &mailbox.QRnumber, sizeof(long));
1281 if (cdbfr != NULL) {
1282 msglist = malloc(cdbfr->len);
1283 memcpy(msglist, cdbfr->ptr, cdbfr->len);
1284 num_msgs = cdbfr->len / sizeof(long);
1288 for (a = 0; a < num_msgs; ++a) {
1289 if (msglist[a] > 0L) {
1290 if (msglist[a] > vbuf.v_lastseen) {
1295 if (msglist != NULL)
1298 return(num_newmsgs);