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"
22 #include "makeuserkey.h"
23 #include "internet_addressing.h"
25 // These pipes are used to talk to the chkpwd daemon, which is forked during startup
26 int chkpwd_write_pipe[2];
27 int chkpwd_read_pipe[2];
30 // Compare two usernames to see if they are the same user after being keyed for the database
31 // Usage is identical to strcmp()
32 int CtdlUserCmp(char *s1, char *s2) {
33 char k1[USERNAME_SIZE];
34 char k2[USERNAME_SIZE];
38 return(strcmp(k1,k2));
42 // CtdlGetUser() retrieve named user into supplied buffer.
43 // returns 0 on success
44 int CtdlGetUser(struct ctdluser *usbuf, char *name) {
45 char usernamekey[USERNAME_SIZE];
49 memset(usbuf, 0, sizeof(struct ctdluser));
52 makeuserkey(usernamekey, name);
53 if (IsEmptyStr(usernamekey)) {
54 return(1); // empty user name
56 cdbus = cdb_fetch(CDB_USERS, usernamekey, strlen(usernamekey));
58 if (cdbus.ptr == NULL) { // user not found
62 memcpy(usbuf, cdbus.ptr, ((cdbus.len > sizeof(struct ctdluser)) ? sizeof(struct ctdluser) : cdbus.len));
68 int CtdlLockGetCurrentUser(void) {
69 return CtdlGetUser(&CC->user, CC->curr_user);
73 // CtdlGetUserLock() - same as getuser() but locks the record
74 int CtdlGetUserLock(struct ctdluser *usbuf, char *name) {
77 retcode = CtdlGetUser(usbuf, name);
79 begin_critical_section(S_USERS);
85 // CtdlPutUser() - write user buffer into the correct place on disk
86 void CtdlPutUser(struct ctdluser *usbuf) {
87 char usernamekey[USERNAME_SIZE];
88 makeuserkey(usernamekey, usbuf->fullname);
89 usbuf->version = REV_LEVEL;
90 cdb_store(CDB_USERS, usernamekey, strlen(usernamekey), usbuf, sizeof(struct ctdluser));
94 void CtdlPutCurrentUserLock() {
95 CtdlPutUser(&CC->user);
99 // CtdlPutUserLock() - same as putuser() but locks the record
100 void CtdlPutUserLock(struct ctdluser *usbuf) {
102 end_critical_section(S_USERS);
106 // rename_user() - this is tricky because the user's display name is the database key
107 // Returns 0 on success or nonzero if there was an error...
108 int rename_user(char *oldname, char *newname) {
109 int retcode = RENAMEUSER_OK;
110 struct ctdluser usbuf;
112 char oldnamekey[USERNAME_SIZE];
113 char newnamekey[USERNAME_SIZE];
115 // Create the database keys...
116 makeuserkey(oldnamekey, oldname);
117 makeuserkey(newnamekey, newname);
119 // Lock up and get going
120 begin_critical_section(S_USERS);
122 // We cannot rename a user who is currently logged in
123 if (CtdlIsUserLoggedIn(oldname)) {
124 end_critical_section(S_USERS);
125 return RENAMEUSER_LOGGED_IN;
128 if (CtdlGetUser(&usbuf, newname) == 0) {
129 retcode = RENAMEUSER_ALREADY_EXISTS;
133 if (CtdlGetUser(&usbuf, oldname) != 0) {
134 retcode = RENAMEUSER_NOT_FOUND;
136 else { // Sanity checks succeeded. Now rename the user.
137 if (usbuf.usernum == 0) {
138 syslog(LOG_DEBUG, "user_ops: can not rename user \"Citadel\".");
139 retcode = RENAMEUSER_NOT_FOUND;
142 syslog(LOG_DEBUG, "user_ops: renaming <%s> to <%s>", oldname, newname);
143 cdb_delete(CDB_USERS, oldnamekey, strlen(oldnamekey));
144 safestrncpy(usbuf.fullname, newname, sizeof usbuf.fullname);
146 cdb_store(CDB_USERSBYNUMBER, &usbuf.usernum, sizeof(long), usbuf.fullname, strlen(usbuf.fullname)+1 );
147 retcode = RENAMEUSER_OK;
153 end_critical_section(S_USERS);
158 // Convert a username into the format used as a database key prior to version 928
159 // This only gets called by reindex_user_928()
160 void makeuserkey_pre928(char *key, const char *username) {
163 int len = strlen(username);
165 if (len >= USERNAME_SIZE) {
166 syslog(LOG_INFO, "Username too long: %s", username);
167 len = USERNAME_SIZE - 1;
169 for (i=0; i<=len; ++i) {
170 key[i] = tolower(username[i]);
175 // Read a user record using the pre-v928 index format, and write it back using the v928-and-higher index format.
176 // This ONLY gets called during an upgrade from version <928 to version >=928.
177 void reindex_user_928(char *username, void *out_data) {
179 char oldkey[USERNAME_SIZE];
180 char newkey[USERNAME_SIZE];
181 struct cdbdata cdbus;
182 struct ctdluser usbuf;
184 makeuserkey_pre928(oldkey, username);
185 makeuserkey(newkey, username);
187 syslog(LOG_DEBUG, "user_ops: reindex_user_928: %s <%s> --> <%s>", username, oldkey, newkey);
189 // Fetch the user record using the old index format
190 cdbus = cdb_fetch(CDB_USERS, oldkey, strlen(oldkey));
191 if (cdbus.ptr == NULL) {
192 syslog(LOG_INFO, "user_ops: <%s> not found, were they already reindexed?", username);
195 memcpy(&usbuf, cdbus.ptr, ((cdbus.len > sizeof(struct ctdluser)) ? sizeof(struct ctdluser) : cdbus.len));
197 // delete the old record
198 cdb_delete(CDB_USERS, oldkey, strlen(oldkey));
200 // write the new record
201 cdb_store(CDB_USERS, newkey, strlen(newkey), &usbuf, sizeof(struct ctdluser));
205 // Index-generating function used by Ctdl[Get|Set]Relationship
206 int GenerateRelationshipIndex(char *IndexBuf, long RoomID, long RoomGen, long UserID) {
207 struct visit_index TheIndex;
208 TheIndex.iRoomID = RoomID;
209 TheIndex.iRoomGen = RoomGen;
210 TheIndex.iUserID = UserID;
212 memcpy(IndexBuf, &TheIndex, sizeof(TheIndex));
213 return(sizeof(TheIndex));
216 // Back end for CtdlSetRelationship()
217 void put_visit(struct visit *newvisit) {
218 cdb_store(CDB_VISIT, newvisit, (sizeof(long)*3), newvisit, sizeof(struct visit));
222 // Define a relationship between a user and a room
223 void CtdlSetRelationship(struct visit *newvisit, struct ctdluser *rel_user, struct ctdlroom *rel_room) {
224 // We don't use these in Citadel because they're implicit by the
225 // index, but they must be present if the database is exported.
226 newvisit->v_roomnum = rel_room->QRnumber;
227 newvisit->v_roomgen = rel_room->QRgen;
228 newvisit->v_usernum = rel_user->usernum;
235 // Locate a relationship between a user and a room
236 void CtdlGetRelationship(struct visit *vbuf, struct ctdluser *rel_user, struct ctdlroom *rel_room) {
237 struct cdbdata cdbvisit;
239 // Clear out the buffer
240 memset(vbuf, 0, sizeof(struct visit));
242 // Fill out the first three fields; they are also the index
243 vbuf->v_roomnum = rel_room->QRnumber;
244 vbuf->v_roomgen = rel_room->QRgen;
245 vbuf->v_usernum = rel_user->usernum;
247 cdbvisit = cdb_fetch(CDB_VISIT, vbuf, (sizeof(long)*3));
248 if (cdbvisit.ptr != NULL) {
249 memcpy(vbuf, cdbvisit.ptr, ((cdbvisit.len > sizeof(struct visit)) ? sizeof(struct visit) : cdbvisit.len));
252 // If this is the first time the user has seen this room, set the view to be the default for the room.
253 vbuf->v_view = rel_room->QRdefaultview;
256 // Set v_seen if necessary
257 if (vbuf->v_seen[0] == 0) {
258 snprintf(vbuf->v_seen, sizeof vbuf->v_seen, "*:%ld", vbuf->v_lastseen);
263 void CtdlMailboxName(char *buf, size_t n, const struct ctdluser *who, const char *prefix) {
264 snprintf(buf, n, "%010ld.%s", who->usernum, prefix);
268 // Check to see if the specified user has Internet mail permission
269 // (returns nonzero if permission is granted)
270 int CtdlCheckInternetMailPermission(struct ctdluser *who) {
272 // Do not allow twits to send Internet mail
273 if (who->axlevel <= AxProbU) return(0);
276 if (CtdlGetConfigInt("c_restrict") == 0) return(1);
279 if (who->flags & US_INTERNET) return(2);
281 // Admin level access?
282 if (who->axlevel >= AxAideU) return(3);
289 // This is a convenience function which follows the Citadel protocol semantics for most commands.
290 // If the current user does not have the requested access level, it outputs a protocol-friendly error message
291 // and then returns (-1). This allows calling functions to complete an access level check in one line of code.
292 int CtdlAccessCheck(int required_level) {
293 if (CC->internal_pgm) return(0);
294 if (required_level >= ac_internal) {
295 cprintf("%d This is not a user-level command.\n", ERROR + HIGHER_ACCESS_REQUIRED);
299 if ((required_level >= ac_logged_in_or_guest) && (CC->logged_in == 0) && (CtdlGetConfigInt("c_guest_logins") == 0)) {
300 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
304 if ((required_level >= ac_logged_in) && (CC->logged_in == 0)) {
305 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
309 if (CC->user.axlevel >= AxAideU) return(0);
310 if (required_level >= ac_aide) {
311 cprintf("%d This command requires Admin access.\n",
312 ERROR + HIGHER_ACCESS_REQUIRED);
316 if (is_room_aide()) return(0);
317 if (required_level >= ac_room_aide) {
318 cprintf("%d This command requires Admin or Room Admin access.\n",
319 ERROR + HIGHER_ACCESS_REQUIRED);
323 // Do not generate any output if we succeeded -- the calling function will handle that.
328 // Is the user currently logged in an Admin?
330 if (CC->user.axlevel >= AxAideU) {
339 // Is the user currently logged in an Admin *or* the room Admin for this room?
340 int is_room_aide(void) {
341 if (!CC->logged_in) {
345 if ((CC->user.axlevel >= AxAideU) || (CC->room.QRroomaide == CC->user.usernum)) {
354 // CtdlGetUserByNumber() - get user by number, returns 0 if user was found
355 // Note: fetching a user this way requires one additional database operation.
356 int CtdlGetUserByNumber(struct ctdluser *usbuf, long number) {
357 struct cdbdata cdbun;
360 cdbun = cdb_fetch(CDB_USERSBYNUMBER, &number, sizeof(long));
361 if (cdbun.ptr == NULL) {
362 syslog(LOG_INFO, "user_ops: %ld not found", number);
366 syslog(LOG_INFO, "user_ops: %ld maps to %s", number, cdbun.ptr);
367 r = CtdlGetUser(usbuf, cdbun.ptr);
372 // Helper function for rebuild_usersbynumber()
373 void rebuild_ubn_for_user(char *username, void *data) {
376 syslog(LOG_DEBUG, "user_ops: rebuilding usersbynumber index for %s", username);
377 if (CtdlGetUser(&u, username) == 0) {
378 cdb_store(CDB_USERSBYNUMBER, &(u.usernum), sizeof(long), u.fullname, strlen(u.fullname)+1);
383 // Rebuild the users-by-number index
384 void rebuild_usersbynumber(void) {
385 cdb_trunc(CDB_USERSBYNUMBER); // delete the old indices
386 ForEachUser(rebuild_ubn_for_user, NULL); // enumerate the users
390 // getuserbyuid() Get user by system uid (for PAM mode authentication)
391 // Returns 0 if user was found
392 int getuserbyuid(struct ctdluser *usbuf, uid_t number) {
394 struct cdbdata cdbus;
395 struct ctdluser *usptr;
396 int return_value = (-1);
398 // Yes, we do this the long way.
399 // No, we don't use CtdlForEachUser() because that requires multiple reads for each record
400 // TODO: make an index
401 cdb_rewind(CDB_USERS);
402 while (cdbus = cdb_next_item(CDB_USERS), cdbus.ptr!=NULL) {
403 usptr = (struct ctdluser *) cdbus.ptr;
405 if (usptr->uid == number) {
406 syslog(LOG_DEBUG, "user_ops: found uid=%d username=%s", usptr->uid, usptr->fullname);
407 memcpy(usbuf, usptr, sizeof(struct ctdluser));
408 return_value = 0; // success
412 if (return_value != 0) {
413 syslog(LOG_DEBUG, "user_ops: no user found with uid=%d", number);
415 return(return_value);
419 // Back end for cmd_user() and its ilk
420 int CtdlLoginExistingUser(const char *trythisname) {
424 syslog(LOG_DEBUG, "user_ops: CtdlLoginExistingUser(%s)", trythisname);
426 if ((CC->logged_in)) {
427 return login_already_logged_in;
430 if (trythisname == NULL) return login_not_found;
432 // We handle this a different way now (see below)
433 //if (!strncasecmp(trythisname, "SYS_", 4)) {
434 //syslog(LOG_DEBUG, "user_ops: system user \"%s\" is not allowed to log in.", trythisname);
435 //return login_not_found;
438 // Continue attempting user validation...
439 safestrncpy(username, trythisname, sizeof (username));
440 string_trim(username);
442 if (IsEmptyStr(username)) {
443 return login_not_found;
447 if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
449 struct passwd *tempPwdPtr;
452 syslog(LOG_DEBUG, "user_ops: asking host about <%s>", username);
453 #ifdef HAVE_GETPWNAM_R
454 syslog(LOG_DEBUG, "user_ops: calling getpwnam_r()");
455 getpwnam_r(username, &pd, pwdbuffer, sizeof pwdbuffer, &tempPwdPtr);
456 #else // HAVE_GETPWNAM_R
457 syslog(LOG_DEBUG, "user_ops: SHOULD NEVER GET HERE!!!");
459 #endif // HAVE_GETPWNAM_R
460 if (tempPwdPtr == NULL) {
461 syslog(LOG_DEBUG, "user_ops: no such user <%s>", username);
462 return login_not_found;
465 // Locate the associated Citadel account. If not found, make one attempt to create it.
466 found_user = getuserbyuid(&CC->user, pd.pw_uid);
467 if (found_user != 0) {
468 create_user(username, CREATE_USER_DO_NOT_BECOME_USER, pd.pw_uid);
469 found_user = getuserbyuid(&CC->user, pd.pw_uid);
471 syslog(LOG_DEBUG, "user_ops: found it: uid=%ld, gecos=%s here: %d", (long)pd.pw_uid, pd.pw_gecos, found_user);
476 else if ((CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP) || (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD)) {
482 found_user = CtdlTryUserLDAP(username, ldap_dn, sizeof ldap_dn, ldap_cn, sizeof ldap_cn, &ldap_uid);
483 if (found_user != 0) {
484 return login_not_found;
487 found_user = getuserbyuid(&CC->user, ldap_uid);
488 if (found_user != 0) {
489 create_user(ldap_cn, CREATE_USER_DO_NOT_BECOME_USER, ldap_uid);
490 found_user = getuserbyuid(&CC->user, ldap_uid);
493 if (found_user == 0) {
494 if (CC->ldap_dn != NULL) free(CC->ldap_dn);
495 CC->ldap_dn = strdup(ldap_dn);
500 // native auth mode...
502 struct recptypes *valid = NULL;
504 // First, try to log in as if the supplied name is a display name
505 found_user = CtdlGetUser(&CC->user, username);
507 // If that didn't work, try to log in as if the supplied name * is an e-mail address
508 if (found_user != 0) {
509 valid = validate_recipients(username, NULL, 0);
511 if (valid->num_local == 1) {
512 found_user = CtdlGetUser(&CC->user, valid->recp_local);
514 free_recipients(valid);
519 // User 0 is a system account and must not be used by a real user
520 if (CC->user.usernum <= 0) {
521 syslog(LOG_DEBUG, "user_ops: system account <%s> is not allowed to log in.", trythisname);
522 return login_not_found;
525 // Did we find something?
526 if (found_user == 0) {
527 if (((CC->nologin)) && (CC->user.axlevel < AxAideU)) {
528 return login_too_many_users;
531 safestrncpy(CC->curr_user, CC->user.fullname, sizeof CC->curr_user);
535 return login_not_found;
539 // session startup code which is common to both cmd_pass() and cmd_newu()
540 void do_login(void) {
542 syslog(LOG_NOTICE, "user_ops: <%s> logged in", CC->curr_user);
544 CtdlGetUserLock(&CC->user, CC->curr_user);
545 CC->previous_login = CC->user.lastcall;
546 time(&CC->user.lastcall);
548 // If this user's name is the name of the system administrator
549 // (as specified in setup), automatically assign access level 6.
550 if ( (!IsEmptyStr(CtdlGetConfigStr("c_sysadm"))) && (!strcasecmp(CC->user.fullname, CtdlGetConfigStr("c_sysadm"))) ) {
551 CC->user.axlevel = AxAideU;
554 // If we're authenticating off the host system, automatically give root the highest level of access.
555 if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
556 if (CC->user.uid == 0) {
557 CC->user.axlevel = AxAideU;
560 CtdlPutUserLock(&CC->user);
562 // If we are using LDAP authentication, extract the user's email addresses from the directory.
563 if ((CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP) || (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD)) {
564 char new_emailaddrs[512];
565 if (CtdlGetConfigInt("c_ldap_sync_email_addrs") > 0) {
566 if (extract_email_addresses_from_ldap(CC->ldap_dn, new_emailaddrs) == 0) {
567 CtdlSetEmailAddressesForUser(CC->user.fullname, new_emailaddrs);
572 // If the user does not have any email addresses assigned, generate one.
573 if (IsEmptyStr(CC->user.emailaddrs)) {
574 AutoGenerateEmailAddressForUser(&CC->user);
577 // Populate the user principal identity, which is consistent and never aliased
578 strcpy(CC->cs_principal_id, "");
579 makeuserkey(CC->cs_principal_id, CC->user.fullname);
580 strcat(CC->cs_principal_id, "@");
581 strcat(CC->cs_principal_id, CtdlGetConfigStr("c_fqdn"));
583 // Populate cs_inet_email and cs_inet_other_emails with valid email addresses from the user record
584 strcpy(CC->cs_inet_email, CC->user.emailaddrs);
585 char *firstsep = strstr(CC->cs_inet_email, "|");
587 strcpy(CC->cs_inet_other_emails, firstsep+1);
591 CC->cs_inet_other_emails[0] = 0;
594 // Create any personal rooms required by the system.
595 // (Technically, MAILROOM should be there already, but just in case...)
596 CtdlCreateRoom(MAILROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
597 CtdlCreateRoom(SENTITEMS, 4, "", 0, 1, 0, VIEW_MAILBOX);
598 CtdlCreateRoom(USERTRASHROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
599 CtdlCreateRoom(USERDRAFTROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
601 // Run any startup routines registered by loadable modules
602 PerformSessionHooks(EVT_LOGIN);
605 CtdlUserGoto(CtdlGetConfigStr("c_baseroom"), 0, 0, NULL, NULL, NULL, NULL);
609 void logged_in_response(void) {
610 cprintf("%d %s|%d|0|0|%u|%ld|%ld\n",
611 CIT_OK, CC->user.fullname, CC->user.axlevel,
612 CC->user.flags, CC->user.usernum,
618 void CtdlUserLogout(void) {
620 syslog(LOG_DEBUG, "user_ops: CtdlUserLogout() logging out <%s> from session %d", CC->curr_user, CC->cs_pid);
622 // Run any hooks registered by modules...
623 PerformSessionHooks(EVT_LOGOUT);
625 // Clear out some session data. Most likely, the CitContext for this
626 // session is about to get nuked when the session disconnects, but
627 // since it's possible to log in again without reconnecting, we cannot
628 // make that assumption.
631 // Check to see if the user was deleted while logged in and purge them if necessary
632 if ((CC->user.axlevel == AxDeleted) && (CC->user.usernum)) {
633 purge_user(CC->user.fullname);
636 // Clear out the user record in memory so we don't behave like a ghost
637 memset(&CC->user, 0, sizeof(struct ctdluser));
638 CC->curr_user[0] = 0;
639 CC->cs_inet_email[0] = 0;
640 CC->cs_inet_other_emails[0] = 0;
641 CC->cs_inet_fn[0] = 0;
643 // Free any output buffers
648 // Validate a password on the host unix system by talking to the chkpwd daemon
649 static int validpw(uid_t uid, const char *pass) {
653 if (IsEmptyStr(pass)) {
654 syslog(LOG_DEBUG, "user_ops: refusing to chkpwd for uid=%d with empty password", uid);
658 syslog(LOG_DEBUG, "user_ops: validating password for uid=%d using chkpwd...", uid);
660 begin_critical_section(S_CHKPWD);
661 rv = write(chkpwd_write_pipe[1], &uid, sizeof(uid_t));
663 syslog(LOG_ERR, "user_ops: communication with chkpwd broken: %m");
664 end_critical_section(S_CHKPWD);
667 rv = write(chkpwd_write_pipe[1], pass, 256);
669 syslog(LOG_ERR, "user_ops: communication with chkpwd broken: %m");
670 end_critical_section(S_CHKPWD);
673 rv = read(chkpwd_read_pipe[0], buf, 4);
675 syslog(LOG_ERR, "user_ops: ommunication with chkpwd broken: %m");
676 end_critical_section(S_CHKPWD);
679 end_critical_section(S_CHKPWD);
681 if (!strncmp(buf, "PASS", 4)) {
682 syslog(LOG_DEBUG, "user_ops: chkpwd pass");
686 syslog(LOG_DEBUG, "user_ops: chkpwd fail");
691 // Start up the chkpwd daemon so validpw() has something to talk to
692 void start_chkpwd_daemon(void) {
694 struct stat filestats;
697 syslog(LOG_DEBUG, "user_ops: starting chkpwd daemon for host authentication mode");
699 if ((stat(file_chkpwd, &filestats)==-1) || (filestats.st_size==0)) {
700 syslog(LOG_ERR, "user_ops: %s: %m", file_chkpwd);
701 exit(CTDLEXIT_CHKPWD);
703 if (pipe(chkpwd_write_pipe) != 0) {
704 syslog(LOG_ERR, "user_ops: unable to create pipe for chkpwd daemon: %m");
705 exit(CTDLEXIT_CHKPWD);
707 if (pipe(chkpwd_read_pipe) != 0) {
708 syslog(LOG_ERR, "user_ops: unable to create pipe for chkpwd daemon: %m");
709 exit(CTDLEXIT_CHKPWD);
713 if (chkpwd_pid < 0) {
714 syslog(LOG_ERR, "user_ops: unable to fork chkpwd daemon: %m");
715 exit(CTDLEXIT_CHKPWD);
717 if (chkpwd_pid == 0) {
718 dup2(chkpwd_write_pipe[0], 0);
719 dup2(chkpwd_read_pipe[1], 1);
720 for (i=2; i<256; ++i) close(i);
721 execl(file_chkpwd, file_chkpwd, NULL);
722 syslog(LOG_ERR, "user_ops: unable to exec chkpwd daemon: %m");
728 int CtdlTryPassword(const char *password, long len) {
731 if ((CC->logged_in)) {
732 syslog(LOG_WARNING, "user_ops: CtdlTryPassword: already logged in");
733 return pass_already_logged_in;
735 if (!strcmp(CC->curr_user, NLI)) {
736 syslog(LOG_WARNING, "user_ops: CtdlTryPassword: no user selected");
739 if (CtdlGetUser(&CC->user, CC->curr_user)) {
740 syslog(LOG_ERR, "user_ops: CtdlTryPassword: internal error");
741 return pass_internal_error;
743 if (password == NULL) {
744 syslog(LOG_INFO, "user_ops: CtdlTryPassword: NULL password string supplied");
745 return pass_wrong_password;
749 else if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
750 if (validpw(CC->user.uid, password)) {
753 // sooper-seekrit hack: populate the password field in the
754 // citadel database with the password that the user typed,
755 // if it's correct. This allows most sites to convert from
756 // host auth to native auth if they want to. If you think
757 // this is a security hazard, comment it out.
759 CtdlGetUserLock(&CC->user, CC->curr_user);
760 safestrncpy(CC->user.password, password, sizeof CC->user.password);
761 CtdlPutUserLock(&CC->user);
763 // (sooper-seekrit hack ends here)
771 else if ((CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP) || (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD)) {
773 if ((CC->ldap_dn) && (!CtdlTryPasswordLDAP(CC->ldap_dn, password))) {
781 // native auth mode...
785 pw = (char*) malloc(len + 1);
786 memcpy(pw, password, len + 1);
788 strproc(CC->user.password);
789 code = strcasecmp(CC->user.password, pw);
792 strproc(CC->user.password);
793 code = strcasecmp(CC->user.password, pw);
803 syslog(LOG_WARNING, "user_ops: bad password specified for <%s> Service <%s> Port <%ld> Remote <%s / %s>",
810 return pass_wrong_password;
815 // Delete a user record *and* all of its related resources.
816 int purge_user(char pname[]) {
817 struct ctdluser usbuf;
818 char usernamekey[USERNAME_SIZE];
820 makeuserkey(usernamekey, pname);
822 // If the name is empty we can't find them in the DB any way so just return
823 if (IsEmptyStr(pname)) {
824 return(ERROR + NO_SUCH_USER);
827 if (CtdlGetUser(&usbuf, pname) != 0) {
828 syslog(LOG_ERR, "user_ops: cannot purge user <%s> - not found", pname);
829 return(ERROR + NO_SUCH_USER);
832 // Don't delete a user who is currently logged in. Instead, just
833 // set the access level to 0, and let the account get swept up
834 // during the next purge.
835 if (CtdlIsUserLoggedInByNum(usbuf.usernum)) {
836 syslog(LOG_WARNING, "user_ops: <%s> is logged in; not deleting", pname);
837 usbuf.axlevel = AxDeleted;
842 syslog(LOG_NOTICE, "user_ops: deleting <%s>", pname);
844 // Perform any purge functions registered by server extensions
845 PerformUserHooks(&usbuf, EVT_PURGEUSER);
847 // delete any existing user/room relationships
848 // Commenting out since it was assuming the user number was
849 // at the top of the index. Room number is actually first.
850 // Auto-Purge will clean up the records later, so not worth
851 // scanning all the records here.
852 //cdb_delete(CDB_VISIT, &usbuf.usernum, sizeof(long));
854 // delete the users-by-number index record
855 cdb_delete(CDB_USERSBYNUMBER, &usbuf.usernum, sizeof(long));
857 // delete the user entry
858 cdb_delete(CDB_USERS, usernamekey, strlen(usernamekey));
864 // This is the back end processing that happens when we create a new user account.
865 int internal_create_user(char *username, struct ctdluser *usbuf, uid_t uid) {
866 if (!CtdlGetUser(usbuf, username)) {
867 return(ERROR + ALREADY_EXISTS);
870 // Go ahead and initialize a new user record
871 memset(usbuf, 0, sizeof(struct ctdluser));
872 safestrncpy(usbuf->fullname, username, sizeof usbuf->fullname);
873 strcpy(usbuf->password, "");
876 // These are the default flags on new accounts
877 usbuf->flags = US_LASTOLD | US_DISAPPEAR | US_PAGINATOR | US_FLOORS;
878 usbuf->axlevel = CtdlGetConfigInt("c_initax");
879 usbuf->lastcall = time(NULL);
881 // fetch a new user number
882 usbuf->usernum = get_new_user_number();
884 // add user to the database
886 cdb_store(CDB_USERSBYNUMBER, &usbuf->usernum, sizeof(long), usbuf->fullname, strlen(usbuf->fullname)+1);
888 // If non-native auth, index by uid
889 if ((usbuf->uid > 0) && (usbuf->uid != NATIVE_AUTH_UID)) {
890 StrBuf *claimed_id = NewStrBuf();
891 StrBufPrintf(claimed_id, "uid:%d", usbuf->uid);
892 FreeStrBuf(&claimed_id);
899 // create_user() - back end processing to create a new user
901 // Set 'newusername' to the desired account name.
902 // Set 'become_user' to CREATE_USER_BECOME_USER if this is self-service account creation and we want to
903 // actually log in as the user we just created, otherwise set it to CREATE_USER_DO_NOT_BECOME_USER
904 // Set 'uid' to some uid_t value to associate the account with an external auth user, or (-1) for native auth
905 int create_user(char *username, int become_user, uid_t uid) {
906 struct ctdluser usbuf;
907 struct ctdlroom qrbuf;
908 char mailboxname[ROOMNAMELEN];
913 if ((retval = internal_create_user(username, &usbuf, uid)) != 0) {
917 // Give the user a private mailbox and a configuration room.
918 // Make the latter an invisible system room.
919 CtdlMailboxName(mailboxname, sizeof mailboxname, &usbuf, MAILROOM);
920 CtdlCreateRoom(mailboxname, 5, "", 0, 1, 1, VIEW_MAILBOX);
922 CtdlMailboxName(mailboxname, sizeof mailboxname, &usbuf, USERCONFIGROOM);
923 CtdlCreateRoom(mailboxname, 5, "", 0, 1, 1, VIEW_BBS);
924 if (CtdlGetRoomLock(&qrbuf, mailboxname) == 0) {
925 qrbuf.QRflags2 |= QR2_SYSTEM;
926 CtdlPutRoomLock(&qrbuf);
929 // Perform any create functions registered by server extensions
930 PerformUserHooks(&usbuf, EVT_NEWUSER);
932 // Everything below this line can be bypassed if administratively
933 // creating a user, instead of doing self-service account creation
935 if (become_user == CREATE_USER_BECOME_USER) {
936 // Now become the user we just created
937 memcpy(&CC->user, &usbuf, sizeof(struct ctdluser));
938 safestrncpy(CC->curr_user, username, sizeof CC->curr_user);
941 // Check to make sure we're still who we think we are
942 if (CtdlGetUser(&CC->user, CC->curr_user)) {
943 return(ERROR + INTERNAL_ERROR);
948 "New user account <%s> has been created, from host %s [%s].\n",
953 CtdlAideMessage(buf, "User Creation Notice");
954 syslog(LOG_NOTICE, "user_ops: <%s> created", username);
959 // set password - back end api code
960 void CtdlSetPassword(char *new_pw) {
961 CtdlGetUserLock(&CC->user, CC->curr_user);
962 safestrncpy(CC->user.password, new_pw, sizeof(CC->user.password));
963 CtdlPutUserLock(&CC->user);
964 syslog(LOG_INFO, "user_ops: password changed for <%s>", CC->curr_user);
965 PerformSessionHooks(EVT_SETPASS);
969 // API function for cmd_invt_kick() and anything else that needs to
970 // invite or kick out a user to/from a room.
972 // Set iuser to the name of the user, and op to 1=invite or 0=kick
973 int CtdlInvtKick(char *iuser, int op) {
974 struct ctdluser USscratch;
978 if (CtdlGetUser(&USscratch, iuser) != 0) {
982 CtdlGetRelationship(&vbuf, &USscratch, &CC->room);
984 vbuf.v_flags = vbuf.v_flags & ~V_FORGET & ~V_LOCKOUT;
985 vbuf.v_flags = vbuf.v_flags | V_ACCESS;
988 vbuf.v_flags = vbuf.v_flags & ~V_ACCESS;
989 vbuf.v_flags = vbuf.v_flags | V_FORGET | V_LOCKOUT;
991 CtdlSetRelationship(&vbuf, &USscratch, &CC->room);
993 // post a message in Aide> saying what we just did
994 snprintf(bbb, sizeof bbb, "%s has been %s \"%s\" by %s.\n",
996 ((op == 1) ? "invited to" : "kicked out of"),
998 (CC->logged_in ? CC->user.fullname : "an administrator")
1000 CtdlAideMessage(bbb,"User Admin Message");
1005 // Forget (Zap) the current room (API call)
1006 // Returns 0 on success
1007 int CtdlForgetThisRoom(void) {
1010 // On some systems, Admins are not allowed to forget rooms
1011 if (is_aide() && (CtdlGetConfigInt("c_aide_zap") == 0)
1012 && ((CC->room.QRflags & QR_MAILBOX) == 0) ) {
1016 CtdlGetUserLock(&CC->user, CC->curr_user);
1017 CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
1019 vbuf.v_flags = vbuf.v_flags | V_FORGET;
1020 vbuf.v_flags = vbuf.v_flags & ~V_ACCESS;
1022 CtdlSetRelationship(&vbuf, &CC->user, &CC->room);
1023 CtdlPutUserLock(&CC->user);
1025 // Return to the Lobby, so we don't end up in an undefined room
1026 CtdlUserGoto(CtdlGetConfigStr("c_baseroom"), 0, 0, NULL, NULL, NULL, NULL);
1031 // Traverse the user file and perform a callback for each user record.
1032 // (New improved version that runs in two phases so that callbacks can perform writes without having a r/o cursor open)
1033 void ForEachUser(void (*CallBack) (char *, void *out_data), void *in_data) {
1034 struct cdbdata cdbus;
1035 struct ctdluser *usptr;
1037 Array *all_users = array_new(USERNAME_SIZE);
1038 if (all_users == NULL) {
1039 syslog(LOG_ERR, "user_ops: alloc failed, ForEachUser() exiting");
1044 cdb_rewind(CDB_USERS);
1046 // Phase 1 : build an array of all our user account names
1047 while (cdbus = cdb_next_item(CDB_USERS), cdbus.ptr!=NULL) {
1048 usptr = (struct ctdluser *) cdbus.ptr;
1049 if (strlen(usptr->fullname) > 0) {
1050 array_append(all_users, usptr->fullname);
1054 // Phase 2 : perform the callback for each user while de-allocating the list
1055 for (int i=0; i<array_len(all_users); ++i) {
1056 (*CallBack) (array_get_element_at(all_users, i), in_data);
1059 // Phase 3 : free the array
1060 array_free(all_users);
1064 // Return the number of new messages that have arrived in the user's inbox while they were logged in.
1065 // Resets to zero when called.
1066 int NewMailCount() {
1067 int num_newmsgs = 0;
1068 num_newmsgs = CC->newmail;
1070 return(num_newmsgs);
1074 // Count the number of new mail messages the user has
1075 int InitialMailCheck() {
1076 int num_newmsgs = 0;
1078 char mailboxname[ROOMNAMELEN];
1079 struct ctdlroom mailbox;
1081 long *msglist = NULL;
1084 CtdlMailboxName(mailboxname, sizeof mailboxname, &CC->user, MAILROOM);
1085 if (CtdlGetRoom(&mailbox, mailboxname) != 0) {
1088 CtdlGetRelationship(&vbuf, &CC->user, &mailbox);
1090 num_msgs = CtdlFetchMsgList(mailbox.QRnumber, &msglist);
1092 for (a = 0; a < num_msgs; ++a) {
1093 if (msglist[a] > 0L) {
1094 if (msglist[a] > vbuf.v_lastseen) {
1101 return(num_newmsgs);
1105 // This is an undocumented rescue mode that can be used to rewrite an admin user account that has been corrupted.
1106 // To prevent abuse, it can only run as a one-shot when the server is not otherwise operational.
1107 // Don't use this without asking about it.
1108 void undocumented_rescue_mode(char *rescue_string) {
1109 struct ctdluser usbuf;
1110 memset(&usbuf, 0, sizeof(struct ctdluser));
1111 extract_token(usbuf.fullname, rescue_string, 0, '|', sizeof usbuf.password);
1112 extract_token(usbuf.password, rescue_string, 1, '|', sizeof usbuf.password);
1113 usbuf.usernum = extract_long(rescue_string, 2);
1115 usbuf.lastcall = time(NULL);
1116 CtdlPutUser(&usbuf);