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));
239 // Back end for CtdlSetRelationship()
240 void put_visit(struct visit *newvisit) {
244 memset(IndexBuf, 0, sizeof (IndexBuf));
246 IndexLen = GenerateRelationshipIndex(IndexBuf, newvisit->v_roomnum, newvisit->v_roomgen, newvisit->v_usernum);
249 cdb_store(CDB_VISIT, IndexBuf, IndexLen, newvisit, sizeof(struct visit));
253 // Define a relationship between a user and a room
254 void CtdlSetRelationship(struct visit *newvisit, struct ctdluser *rel_user, struct ctdlroom *rel_room) {
255 // We don't use these in Citadel because they're implicit by the
256 // index, but they must be present if the database is exported.
257 newvisit->v_roomnum = rel_room->QRnumber;
258 newvisit->v_roomgen = rel_room->QRgen;
259 newvisit->v_usernum = rel_user->usernum;
265 // Locate a relationship between a user and a room
266 void CtdlGetRelationship(struct visit *vbuf, struct ctdluser *rel_user, struct ctdlroom *rel_room) {
269 struct cdbdata *cdbvisit;
272 IndexLen = GenerateRelationshipIndex(IndexBuf, rel_room->QRnumber, rel_room->QRgen, rel_user->usernum);
274 // Clear out the buffer
275 memset(vbuf, 0, sizeof(struct visit));
277 cdbvisit = cdb_fetch(CDB_VISIT, IndexBuf, IndexLen);
278 if (cdbvisit != NULL) {
279 memcpy(vbuf, cdbvisit->ptr, ((cdbvisit->len > sizeof(struct visit)) ? sizeof(struct visit) : cdbvisit->len));
283 // If this is the first time the user has seen this room, set the view to be the default for the room.
284 vbuf->v_view = rel_room->QRdefaultview;
287 // Set v_seen if necessary
288 if (vbuf->v_seen[0] == 0) {
289 snprintf(vbuf->v_seen, sizeof vbuf->v_seen, "*:%ld", vbuf->v_lastseen);
294 void CtdlMailboxName(char *buf, size_t n, const struct ctdluser *who, const char *prefix) {
295 snprintf(buf, n, "%010ld.%s", who->usernum, prefix);
299 // Check to see if the specified user has Internet mail permission
300 // (returns nonzero if permission is granted)
301 int CtdlCheckInternetMailPermission(struct ctdluser *who) {
303 // Do not allow twits to send Internet mail
304 if (who->axlevel <= AxProbU) return(0);
307 if (CtdlGetConfigInt("c_restrict") == 0) return(1);
310 if (who->flags & US_INTERNET) return(2);
312 // Admin level access?
313 if (who->axlevel >= AxAideU) return(3);
320 // This is a convenience function which follows the Citadel protocol semantics for most commands.
321 // If the current user does not have the requested access level, it outputs a protocol-friendly error message
322 // and then returns (-1). This allows calling functions to complete an access level check in one line of code.
323 int CtdlAccessCheck(int required_level) {
324 if (CC->internal_pgm) return(0);
325 if (required_level >= ac_internal) {
326 cprintf("%d This is not a user-level command.\n", ERROR + HIGHER_ACCESS_REQUIRED);
330 if ((required_level >= ac_logged_in_or_guest) && (CC->logged_in == 0) && (CtdlGetConfigInt("c_guest_logins") == 0)) {
331 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
335 if ((required_level >= ac_logged_in) && (CC->logged_in == 0)) {
336 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
340 if (CC->user.axlevel >= AxAideU) return(0);
341 if (required_level >= ac_aide) {
342 cprintf("%d This command requires Admin access.\n",
343 ERROR + HIGHER_ACCESS_REQUIRED);
347 if (is_room_aide()) return(0);
348 if (required_level >= ac_room_aide) {
349 cprintf("%d This command requires Admin or Room Admin access.\n",
350 ERROR + HIGHER_ACCESS_REQUIRED);
354 // Do not generate any output if we succeeded -- the calling function will handle that.
359 // Is the user currently logged in an Admin?
361 if (CC->user.axlevel >= AxAideU) {
370 // Is the user currently logged in an Admin *or* the room Admin for this room?
371 int is_room_aide(void) {
372 if (!CC->logged_in) {
376 if ((CC->user.axlevel >= AxAideU) || (CC->room.QRroomaide == CC->user.usernum)) {
385 // CtdlGetUserByNumber() - get user by number, returns 0 if user was found
386 // Note: fetching a user this way requires one additional database operation.
387 int CtdlGetUserByNumber(struct ctdluser *usbuf, long number) {
388 struct cdbdata *cdbun;
391 cdbun = cdb_fetch(CDB_USERSBYNUMBER, &number, sizeof(long));
393 syslog(LOG_INFO, "user_ops: %ld not found", number);
397 syslog(LOG_INFO, "user_ops: %ld maps to %s", number, cdbun->ptr);
398 r = CtdlGetUser(usbuf, cdbun->ptr);
404 // Helper function for rebuild_usersbynumber()
405 void rebuild_ubn_for_user(char *username, void *data) {
408 syslog(LOG_DEBUG, "user_ops: rebuilding usersbynumber index for %s", username);
409 if (CtdlGetUser(&u, username) == 0) {
410 cdb_store(CDB_USERSBYNUMBER, &(u.usernum), sizeof(long), u.fullname, strlen(u.fullname)+1);
415 // Rebuild the users-by-number index
416 void rebuild_usersbynumber(void) {
417 cdb_trunc(CDB_USERSBYNUMBER); // delete the old indices
418 ForEachUser(rebuild_ubn_for_user, NULL); // enumerate the users
422 // getuserbyuid() Get user by system uid (for PAM mode authentication)
423 // Returns 0 if user was found
424 // This now uses an extauth index.
425 int getuserbyuid(struct ctdluser *usbuf, uid_t number) {
426 struct cdbdata *cdbextauth;
430 claimed_id = NewStrBuf();
431 StrBufPrintf(claimed_id, "uid:%d", number);
432 cdbextauth = cdb_fetch(CDB_EXTAUTH, ChrPtr(claimed_id), StrLength(claimed_id));
433 FreeStrBuf(&claimed_id);
434 if (cdbextauth == NULL) {
438 memcpy(&usernum, cdbextauth->ptr, sizeof(long));
439 cdb_free(cdbextauth);
441 if (!CtdlGetUserByNumber(usbuf, usernum)) {
449 // Back end for cmd_user() and its ilk
450 int CtdlLoginExistingUser(const char *trythisname) {
454 syslog(LOG_DEBUG, "user_ops: CtdlLoginExistingUser(%s)", trythisname);
456 if ((CC->logged_in)) {
457 return login_already_logged_in;
460 if (trythisname == NULL) return login_not_found;
462 // We handle this a different way now (see below)
463 //if (!strncasecmp(trythisname, "SYS_", 4)) {
464 //syslog(LOG_DEBUG, "user_ops: system user \"%s\" is not allowed to log in.", trythisname);
465 //return login_not_found;
468 // Continue attempting user validation...
469 safestrncpy(username, trythisname, sizeof (username));
470 string_trim(username);
472 if (IsEmptyStr(username)) {
473 return login_not_found;
477 if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
479 struct passwd *tempPwdPtr;
482 syslog(LOG_DEBUG, "user_ops: asking host about <%s>", username);
483 #ifdef HAVE_GETPWNAM_R
484 syslog(LOG_DEBUG, "user_ops: calling getpwnam_r()");
485 getpwnam_r(username, &pd, pwdbuffer, sizeof pwdbuffer, &tempPwdPtr);
486 #else // HAVE_GETPWNAM_R
487 syslog(LOG_DEBUG, "user_ops: SHOULD NEVER GET HERE!!!");
489 #endif // HAVE_GETPWNAM_R
490 if (tempPwdPtr == NULL) {
491 syslog(LOG_DEBUG, "user_ops: no such user <%s>", username);
492 return login_not_found;
495 // Locate the associated Citadel account. If not found, make one attempt to create it.
496 found_user = getuserbyuid(&CC->user, pd.pw_uid);
497 if (found_user != 0) {
498 create_user(username, CREATE_USER_DO_NOT_BECOME_USER, pd.pw_uid);
499 found_user = getuserbyuid(&CC->user, pd.pw_uid);
501 syslog(LOG_DEBUG, "user_ops: found it: uid=%ld, gecos=%s here: %d", (long)pd.pw_uid, pd.pw_gecos, found_user);
506 else if ((CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP) || (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD)) {
512 found_user = CtdlTryUserLDAP(username, ldap_dn, sizeof ldap_dn, ldap_cn, sizeof ldap_cn, &ldap_uid);
513 if (found_user != 0) {
514 return login_not_found;
517 found_user = getuserbyuid(&CC->user, ldap_uid);
518 if (found_user != 0) {
519 create_user(ldap_cn, CREATE_USER_DO_NOT_BECOME_USER, ldap_uid);
520 found_user = getuserbyuid(&CC->user, ldap_uid);
523 if (found_user == 0) {
524 if (CC->ldap_dn != NULL) free(CC->ldap_dn);
525 CC->ldap_dn = strdup(ldap_dn);
530 // native auth mode...
532 struct recptypes *valid = NULL;
534 // First, try to log in as if the supplied name is a display name
535 found_user = CtdlGetUser(&CC->user, username);
537 // If that didn't work, try to log in as if the supplied name * is an e-mail address
538 if (found_user != 0) {
539 valid = validate_recipients(username, NULL, 0);
541 if (valid->num_local == 1) {
542 found_user = CtdlGetUser(&CC->user, valid->recp_local);
544 free_recipients(valid);
549 // User 0 is a system account and must not be used by a real user
550 if (CC->user.usernum <= 0) {
551 syslog(LOG_DEBUG, "user_ops: system account <%s> is not allowed to log in.", trythisname);
552 return login_not_found;
555 // Did we find something?
556 if (found_user == 0) {
557 if (((CC->nologin)) && (CC->user.axlevel < AxAideU)) {
558 return login_too_many_users;
561 safestrncpy(CC->curr_user, CC->user.fullname, sizeof CC->curr_user);
565 return login_not_found;
569 // session startup code which is common to both cmd_pass() and cmd_newu()
570 void do_login(void) {
572 syslog(LOG_NOTICE, "user_ops: <%s> logged in", CC->curr_user);
574 CtdlGetUserLock(&CC->user, CC->curr_user);
575 ++(CC->user.timescalled);
576 CC->previous_login = CC->user.lastcall;
577 time(&CC->user.lastcall);
579 // If this user's name is the name of the system administrator
580 // (as specified in setup), automatically assign access level 6.
581 if ( (!IsEmptyStr(CtdlGetConfigStr("c_sysadm"))) && (!strcasecmp(CC->user.fullname, CtdlGetConfigStr("c_sysadm"))) ) {
582 CC->user.axlevel = AxAideU;
585 // If we're authenticating off the host system, automatically give root the highest level of access.
586 if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
587 if (CC->user.uid == 0) {
588 CC->user.axlevel = AxAideU;
591 CtdlPutUserLock(&CC->user);
593 // If we are using LDAP authentication, extract the user's email addresses from the directory.
594 if ((CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP) || (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD)) {
595 char new_emailaddrs[512];
596 if (CtdlGetConfigInt("c_ldap_sync_email_addrs") > 0) {
597 if (extract_email_addresses_from_ldap(CC->ldap_dn, new_emailaddrs) == 0) {
598 CtdlSetEmailAddressesForUser(CC->user.fullname, new_emailaddrs);
603 // If the user does not have any email addresses assigned, generate one.
604 if (IsEmptyStr(CC->user.emailaddrs)) {
605 AutoGenerateEmailAddressForUser(&CC->user);
608 // Populate the user principal identity, which is consistent and never aliased
609 strcpy(CC->cs_principal_id, "");
610 makeuserkey(CC->cs_principal_id, CC->user.fullname);
611 strcat(CC->cs_principal_id, "@");
612 strcat(CC->cs_principal_id, CtdlGetConfigStr("c_fqdn"));
614 // Populate cs_inet_email and cs_inet_other_emails with valid email addresses from the user record
615 strcpy(CC->cs_inet_email, CC->user.emailaddrs);
616 char *firstsep = strstr(CC->cs_inet_email, "|");
618 strcpy(CC->cs_inet_other_emails, firstsep+1);
622 CC->cs_inet_other_emails[0] = 0;
625 // Create any personal rooms required by the system.
626 // (Technically, MAILROOM should be there already, but just in case...)
627 CtdlCreateRoom(MAILROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
628 CtdlCreateRoom(SENTITEMS, 4, "", 0, 1, 0, VIEW_MAILBOX);
629 CtdlCreateRoom(USERTRASHROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
630 CtdlCreateRoom(USERDRAFTROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
632 // Run any startup routines registered by loadable modules
633 PerformSessionHooks(EVT_LOGIN);
636 CtdlUserGoto(CtdlGetConfigStr("c_baseroom"), 0, 0, NULL, NULL, NULL, NULL);
640 void logged_in_response(void) {
641 cprintf("%d %s|%d|%ld|%ld|%u|%ld|%ld\n",
642 CIT_OK, CC->user.fullname, CC->user.axlevel,
643 CC->user.timescalled, CC->user.posted,
644 CC->user.flags, CC->user.usernum,
650 void CtdlUserLogout(void) {
652 syslog(LOG_DEBUG, "user_ops: CtdlUserLogout() logging out <%s> from session %d", CC->curr_user, CC->cs_pid);
654 // Run any hooks registered by modules...
655 PerformSessionHooks(EVT_LOGOUT);
657 // Clear out some session data. Most likely, the CitContext for this
658 // session is about to get nuked when the session disconnects, but
659 // since it's possible to log in again without reconnecting, we cannot
660 // make that assumption.
663 // Check to see if the user was deleted while logged in and purge them if necessary
664 if ((CC->user.axlevel == AxDeleted) && (CC->user.usernum)) {
665 purge_user(CC->user.fullname);
668 // Clear out the user record in memory so we don't behave like a ghost
669 memset(&CC->user, 0, sizeof(struct ctdluser));
670 CC->curr_user[0] = 0;
671 CC->cs_inet_email[0] = 0;
672 CC->cs_inet_other_emails[0] = 0;
673 CC->cs_inet_fn[0] = 0;
675 // Free any output buffers
680 // Validate a password on the host unix system by talking to the chkpwd daemon
681 static int validpw(uid_t uid, const char *pass) {
685 if (IsEmptyStr(pass)) {
686 syslog(LOG_DEBUG, "user_ops: refusing to chkpwd for uid=%d with empty password", uid);
690 syslog(LOG_DEBUG, "user_ops: validating password for uid=%d using chkpwd...", uid);
692 begin_critical_section(S_CHKPWD);
693 rv = write(chkpwd_write_pipe[1], &uid, sizeof(uid_t));
695 syslog(LOG_ERR, "user_ops: communication with chkpwd broken: %m");
696 end_critical_section(S_CHKPWD);
699 rv = write(chkpwd_write_pipe[1], pass, 256);
701 syslog(LOG_ERR, "user_ops: communication with chkpwd broken: %m");
702 end_critical_section(S_CHKPWD);
705 rv = read(chkpwd_read_pipe[0], buf, 4);
707 syslog(LOG_ERR, "user_ops: ommunication with chkpwd broken: %m");
708 end_critical_section(S_CHKPWD);
711 end_critical_section(S_CHKPWD);
713 if (!strncmp(buf, "PASS", 4)) {
714 syslog(LOG_DEBUG, "user_ops: chkpwd pass");
718 syslog(LOG_DEBUG, "user_ops: chkpwd fail");
723 // Start up the chkpwd daemon so validpw() has something to talk to
724 void start_chkpwd_daemon(void) {
726 struct stat filestats;
729 syslog(LOG_DEBUG, "user_ops: starting chkpwd daemon for host authentication mode");
731 if ((stat(file_chkpwd, &filestats)==-1) || (filestats.st_size==0)) {
732 syslog(LOG_ERR, "user_ops: %s: %m", file_chkpwd);
733 exit(CTDLEXIT_CHKPWD);
735 if (pipe(chkpwd_write_pipe) != 0) {
736 syslog(LOG_ERR, "user_ops: unable to create pipe for chkpwd daemon: %m");
737 exit(CTDLEXIT_CHKPWD);
739 if (pipe(chkpwd_read_pipe) != 0) {
740 syslog(LOG_ERR, "user_ops: unable to create pipe for chkpwd daemon: %m");
741 exit(CTDLEXIT_CHKPWD);
745 if (chkpwd_pid < 0) {
746 syslog(LOG_ERR, "user_ops: unable to fork chkpwd daemon: %m");
747 exit(CTDLEXIT_CHKPWD);
749 if (chkpwd_pid == 0) {
750 dup2(chkpwd_write_pipe[0], 0);
751 dup2(chkpwd_read_pipe[1], 1);
752 for (i=2; i<256; ++i) close(i);
753 execl(file_chkpwd, file_chkpwd, NULL);
754 syslog(LOG_ERR, "user_ops: unable to exec chkpwd daemon: %m");
760 int CtdlTryPassword(const char *password, long len) {
763 if ((CC->logged_in)) {
764 syslog(LOG_WARNING, "user_ops: CtdlTryPassword: already logged in");
765 return pass_already_logged_in;
767 if (!strcmp(CC->curr_user, NLI)) {
768 syslog(LOG_WARNING, "user_ops: CtdlTryPassword: no user selected");
771 if (CtdlGetUser(&CC->user, CC->curr_user)) {
772 syslog(LOG_ERR, "user_ops: CtdlTryPassword: internal error");
773 return pass_internal_error;
775 if (password == NULL) {
776 syslog(LOG_INFO, "user_ops: CtdlTryPassword: NULL password string supplied");
777 return pass_wrong_password;
781 else if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
782 if (validpw(CC->user.uid, password)) {
785 // sooper-seekrit hack: populate the password field in the
786 // citadel database with the password that the user typed,
787 // if it's correct. This allows most sites to convert from
788 // host auth to native auth if they want to. If you think
789 // this is a security hazard, comment it out.
791 CtdlGetUserLock(&CC->user, CC->curr_user);
792 safestrncpy(CC->user.password, password, sizeof CC->user.password);
793 CtdlPutUserLock(&CC->user);
795 // (sooper-seekrit hack ends here)
803 else if ((CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP) || (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD)) {
805 if ((CC->ldap_dn) && (!CtdlTryPasswordLDAP(CC->ldap_dn, password))) {
813 // native auth mode...
817 pw = (char*) malloc(len + 1);
818 memcpy(pw, password, len + 1);
820 strproc(CC->user.password);
821 code = strcasecmp(CC->user.password, pw);
824 strproc(CC->user.password);
825 code = strcasecmp(CC->user.password, pw);
835 syslog(LOG_WARNING, "user_ops: bad password specified for <%s> Service <%s> Port <%ld> Remote <%s / %s>",
842 return pass_wrong_password;
847 // Delete a user record *and* all of its related resources.
848 int purge_user(char pname[]) {
849 struct ctdluser usbuf;
850 char usernamekey[USERNAME_SIZE];
852 makeuserkey(usernamekey, pname);
854 // If the name is empty we can't find them in the DB any way so just return
855 if (IsEmptyStr(pname)) {
856 return(ERROR + NO_SUCH_USER);
859 if (CtdlGetUser(&usbuf, pname) != 0) {
860 syslog(LOG_ERR, "user_ops: cannot purge user <%s> - not found", pname);
861 return(ERROR + NO_SUCH_USER);
864 // Don't delete a user who is currently logged in. Instead, just
865 // set the access level to 0, and let the account get swept up
866 // during the next purge.
867 if (CtdlIsUserLoggedInByNum(usbuf.usernum)) {
868 syslog(LOG_WARNING, "user_ops: <%s> is logged in; not deleting", pname);
869 usbuf.axlevel = AxDeleted;
874 syslog(LOG_NOTICE, "user_ops: deleting <%s>", pname);
876 // Perform any purge functions registered by server extensions
877 PerformUserHooks(&usbuf, EVT_PURGEUSER);
879 // delete any existing user/room relationships
880 cdb_delete(CDB_VISIT, &usbuf.usernum, sizeof(long));
882 // delete the users-by-number index record
883 cdb_delete(CDB_USERSBYNUMBER, &usbuf.usernum, sizeof(long));
885 // delete the user entry
886 cdb_delete(CDB_USERS, usernamekey, strlen(usernamekey));
892 // This is the back end processing that happens when we create a new user account.
893 int internal_create_user(char *username, struct ctdluser *usbuf, uid_t uid) {
894 if (!CtdlGetUser(usbuf, username)) {
895 return(ERROR + ALREADY_EXISTS);
898 // Go ahead and initialize a new user record
899 memset(usbuf, 0, sizeof(struct ctdluser));
900 safestrncpy(usbuf->fullname, username, sizeof usbuf->fullname);
901 strcpy(usbuf->password, "");
904 // These are the default flags on new accounts
905 usbuf->flags = US_LASTOLD | US_DISAPPEAR | US_PAGINATOR | US_FLOORS;
907 usbuf->timescalled = 0;
909 usbuf->axlevel = CtdlGetConfigInt("c_initax");
910 usbuf->lastcall = time(NULL);
912 // fetch a new user number
913 usbuf->usernum = get_new_user_number();
915 // add user to the database
917 cdb_store(CDB_USERSBYNUMBER, &usbuf->usernum, sizeof(long), usbuf->fullname, strlen(usbuf->fullname)+1);
919 // If non-native auth, index by uid
920 if ((usbuf->uid > 0) && (usbuf->uid != NATIVE_AUTH_UID)) {
921 StrBuf *claimed_id = NewStrBuf();
922 StrBufPrintf(claimed_id, "uid:%d", usbuf->uid);
923 attach_extauth(usbuf, claimed_id);
924 FreeStrBuf(&claimed_id);
931 // create_user() - back end processing to create a new user
933 // Set 'newusername' to the desired account name.
934 // Set 'become_user' to CREATE_USER_BECOME_USER if this is self-service account creation and we want to
935 // actually log in as the user we just created, otherwise set it to CREATE_USER_DO_NOT_BECOME_USER
936 // Set 'uid' to some uid_t value to associate the account with an external auth user, or (-1) for native auth
937 int create_user(char *username, int become_user, uid_t uid) {
938 struct ctdluser usbuf;
939 struct ctdlroom qrbuf;
940 char mailboxname[ROOMNAMELEN];
945 if ((retval = internal_create_user(username, &usbuf, uid)) != 0) {
949 // Give the user a private mailbox and a configuration room.
950 // Make the latter an invisible system room.
951 CtdlMailboxName(mailboxname, sizeof mailboxname, &usbuf, MAILROOM);
952 CtdlCreateRoom(mailboxname, 5, "", 0, 1, 1, VIEW_MAILBOX);
954 CtdlMailboxName(mailboxname, sizeof mailboxname, &usbuf, USERCONFIGROOM);
955 CtdlCreateRoom(mailboxname, 5, "", 0, 1, 1, VIEW_BBS);
956 if (CtdlGetRoomLock(&qrbuf, mailboxname) == 0) {
957 qrbuf.QRflags2 |= QR2_SYSTEM;
958 CtdlPutRoomLock(&qrbuf);
961 // Perform any create functions registered by server extensions
962 PerformUserHooks(&usbuf, EVT_NEWUSER);
964 // Everything below this line can be bypassed if administratively
965 // creating a user, instead of doing self-service account creation
967 if (become_user == CREATE_USER_BECOME_USER) {
968 // Now become the user we just created
969 memcpy(&CC->user, &usbuf, sizeof(struct ctdluser));
970 safestrncpy(CC->curr_user, username, sizeof CC->curr_user);
973 // Check to make sure we're still who we think we are
974 if (CtdlGetUser(&CC->user, CC->curr_user)) {
975 return(ERROR + INTERNAL_ERROR);
980 "New user account <%s> has been created, from host %s [%s].\n",
985 CtdlAideMessage(buf, "User Creation Notice");
986 syslog(LOG_NOTICE, "user_ops: <%s> created", username);
991 // set password - back end api code
992 void CtdlSetPassword(char *new_pw) {
993 CtdlGetUserLock(&CC->user, CC->curr_user);
994 safestrncpy(CC->user.password, new_pw, sizeof(CC->user.password));
995 CtdlPutUserLock(&CC->user);
996 syslog(LOG_INFO, "user_ops: password changed for <%s>", CC->curr_user);
997 PerformSessionHooks(EVT_SETPASS);
1001 // API function for cmd_invt_kick() and anything else that needs to
1002 // invite or kick out a user to/from a room.
1004 // Set iuser to the name of the user, and op to 1=invite or 0=kick
1005 int CtdlInvtKick(char *iuser, int op) {
1006 struct ctdluser USscratch;
1010 if (CtdlGetUser(&USscratch, iuser) != 0) {
1014 CtdlGetRelationship(&vbuf, &USscratch, &CC->room);
1016 vbuf.v_flags = vbuf.v_flags & ~V_FORGET & ~V_LOCKOUT;
1017 vbuf.v_flags = vbuf.v_flags | V_ACCESS;
1020 vbuf.v_flags = vbuf.v_flags & ~V_ACCESS;
1021 vbuf.v_flags = vbuf.v_flags | V_FORGET | V_LOCKOUT;
1023 CtdlSetRelationship(&vbuf, &USscratch, &CC->room);
1025 // post a message in Aide> saying what we just did
1026 snprintf(bbb, sizeof bbb, "%s has been %s \"%s\" by %s.\n",
1028 ((op == 1) ? "invited to" : "kicked out of"),
1030 (CC->logged_in ? CC->user.fullname : "an administrator")
1032 CtdlAideMessage(bbb,"User Admin Message");
1037 // Forget (Zap) the current room (API call)
1038 // Returns 0 on success
1039 int CtdlForgetThisRoom(void) {
1042 // On some systems, Admins are not allowed to forget rooms
1043 if (is_aide() && (CtdlGetConfigInt("c_aide_zap") == 0)
1044 && ((CC->room.QRflags & QR_MAILBOX) == 0) ) {
1048 CtdlGetUserLock(&CC->user, CC->curr_user);
1049 CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
1051 vbuf.v_flags = vbuf.v_flags | V_FORGET;
1052 vbuf.v_flags = vbuf.v_flags & ~V_ACCESS;
1054 CtdlSetRelationship(&vbuf, &CC->user, &CC->room);
1055 CtdlPutUserLock(&CC->user);
1057 // Return to the Lobby, so we don't end up in an undefined room
1058 CtdlUserGoto(CtdlGetConfigStr("c_baseroom"), 0, 0, NULL, NULL, NULL, NULL);
1063 // Traverse the user file and perform a callback for each user record.
1064 // (New improved version that runs in two phases so that callbacks can perform writes without having a r/o cursor open)
1065 void ForEachUser(void (*CallBack) (char *, void *out_data), void *in_data) {
1066 struct cdbdata *cdbus;
1067 struct ctdluser *usptr;
1071 char username[USERNAME_SIZE];
1073 struct feu *ufirst = NULL;
1074 struct feu *ulast = NULL;
1075 struct feu *f = NULL;
1077 cdb_rewind(CDB_USERS);
1079 // Phase 1 : build a linked list of all our user account names
1080 while (cdbus = cdb_next_item(CDB_USERS), cdbus != NULL) {
1081 usptr = (struct ctdluser *) cdbus->ptr;
1083 if (strlen(usptr->fullname) > 0) {
1084 f = malloc(sizeof(struct feu));
1086 strncpy(f->username, usptr->fullname, USERNAME_SIZE);
1088 if (ufirst == NULL) {
1099 // Phase 2 : perform the callback for each user while de-allocating the list
1100 while (ufirst != NULL) {
1101 (*CallBack) (ufirst->username, in_data);
1103 ufirst = ufirst->next;
1109 // Return the number of new messages that have arrived in the user's inbox while they were logged in.
1110 // Resets to zero when called.
1111 int NewMailCount() {
1112 int num_newmsgs = 0;
1113 num_newmsgs = CC->newmail;
1115 return(num_newmsgs);
1119 // Count the number of new mail messages the user has
1120 int InitialMailCheck() {
1121 int num_newmsgs = 0;
1123 char mailboxname[ROOMNAMELEN];
1124 struct ctdlroom mailbox;
1126 struct cdbdata *cdbfr;
1127 long *msglist = NULL;
1130 CtdlMailboxName(mailboxname, sizeof mailboxname, &CC->user, MAILROOM);
1131 if (CtdlGetRoom(&mailbox, mailboxname) != 0)
1133 CtdlGetRelationship(&vbuf, &CC->user, &mailbox);
1135 cdbfr = cdb_fetch(CDB_MSGLISTS, &mailbox.QRnumber, sizeof(long));
1137 if (cdbfr != NULL) {
1138 msglist = malloc(cdbfr->len);
1139 memcpy(msglist, cdbfr->ptr, cdbfr->len);
1140 num_msgs = cdbfr->len / sizeof(long);
1144 for (a = 0; a < num_msgs; ++a) {
1145 if (msglist[a] > 0L) {
1146 if (msglist[a] > vbuf.v_lastseen) {
1151 if (msglist != NULL)
1154 return(num_newmsgs);