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];
46 struct cdbdata *cdbus;
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 == NULL) { // user not found
62 memcpy(usbuf, cdbus->ptr, ((cdbus->len > sizeof(struct ctdluser)) ? sizeof(struct ctdluser) : cdbus->len));
69 int CtdlLockGetCurrentUser(void) {
70 return CtdlGetUser(&CC->user, CC->curr_user);
74 // CtdlGetUserLock() - same as getuser() but locks the record
75 int CtdlGetUserLock(struct ctdluser *usbuf, char *name) {
78 retcode = CtdlGetUser(usbuf, name);
80 begin_critical_section(S_USERS);
86 // CtdlPutUser() - write user buffer into the correct place on disk
87 void CtdlPutUser(struct ctdluser *usbuf) {
88 char usernamekey[USERNAME_SIZE];
89 makeuserkey(usernamekey, usbuf->fullname);
90 usbuf->version = REV_LEVEL;
91 cdb_store(CDB_USERS, usernamekey, strlen(usernamekey), usbuf, sizeof(struct ctdluser));
95 void CtdlPutCurrentUserLock() {
96 CtdlPutUser(&CC->user);
100 // CtdlPutUserLock() - same as putuser() but locks the record
101 void CtdlPutUserLock(struct ctdluser *usbuf) {
103 end_critical_section(S_USERS);
107 // rename_user() - this is tricky because the user's display name is the database key
108 // Returns 0 on success or nonzero if there was an error...
109 int rename_user(char *oldname, char *newname) {
110 int retcode = RENAMEUSER_OK;
111 struct ctdluser usbuf;
113 char oldnamekey[USERNAME_SIZE];
114 char newnamekey[USERNAME_SIZE];
116 // Create the database keys...
117 makeuserkey(oldnamekey, oldname);
118 makeuserkey(newnamekey, newname);
120 // Lock up and get going
121 begin_critical_section(S_USERS);
123 // We cannot rename a user who is currently logged in
124 if (CtdlIsUserLoggedIn(oldname)) {
125 end_critical_section(S_USERS);
126 return RENAMEUSER_LOGGED_IN;
129 if (CtdlGetUser(&usbuf, newname) == 0) {
130 retcode = RENAMEUSER_ALREADY_EXISTS;
134 if (CtdlGetUser(&usbuf, oldname) != 0) {
135 retcode = RENAMEUSER_NOT_FOUND;
137 else { // Sanity checks succeeded. Now rename the user.
138 if (usbuf.usernum == 0) {
139 syslog(LOG_DEBUG, "user_ops: can not rename user \"Citadel\".");
140 retcode = RENAMEUSER_NOT_FOUND;
143 syslog(LOG_DEBUG, "user_ops: renaming <%s> to <%s>", oldname, newname);
144 cdb_delete(CDB_USERS, oldnamekey, strlen(oldnamekey));
145 safestrncpy(usbuf.fullname, newname, sizeof usbuf.fullname);
147 cdb_store(CDB_USERSBYNUMBER, &usbuf.usernum, sizeof(long), usbuf.fullname, strlen(usbuf.fullname)+1 );
148 retcode = RENAMEUSER_OK;
154 end_critical_section(S_USERS);
159 // Convert a username into the format used as a database key prior to version 928
160 // This only gets called by reindex_user_928()
161 void makeuserkey_pre928(char *key, const char *username) {
164 int len = strlen(username);
166 if (len >= USERNAME_SIZE) {
167 syslog(LOG_INFO, "Username too long: %s", username);
168 len = USERNAME_SIZE - 1;
170 for (i=0; i<=len; ++i) {
171 key[i] = tolower(username[i]);
176 // Read a user record using the pre-v928 index format, and write it back using the v928-and-higher index format.
177 // This ONLY gets called during an upgrade from version <928 to version >=928.
178 void reindex_user_928(char *username, void *out_data) {
180 char oldkey[USERNAME_SIZE];
181 char newkey[USERNAME_SIZE];
182 struct cdbdata *cdbus;
183 struct ctdluser usbuf;
185 makeuserkey_pre928(oldkey, username);
186 makeuserkey(newkey, username);
188 syslog(LOG_DEBUG, "user_ops: reindex_user_928: %s <%s> --> <%s>", username, oldkey, newkey);
190 // Fetch the user record using the old index format
191 cdbus = cdb_fetch(CDB_USERS, oldkey, strlen(oldkey));
193 syslog(LOG_INFO, "user_ops: <%s> not found, were they already reindexed?", username);
196 memcpy(&usbuf, cdbus->ptr, ((cdbus->len > sizeof(struct ctdluser)) ? sizeof(struct ctdluser) : cdbus->len));
199 // delete the old record
200 cdb_delete(CDB_USERS, oldkey, strlen(oldkey));
202 // write the new record
203 cdb_store(CDB_USERS, newkey, strlen(newkey), &usbuf, sizeof(struct ctdluser));
207 // Index-generating function used by Ctdl[Get|Set]Relationship
208 int GenerateRelationshipIndex(char *IndexBuf, long RoomID, long RoomGen, long UserID) {
209 struct visit_index TheIndex;
210 TheIndex.iRoomID = RoomID;
211 TheIndex.iRoomGen = RoomGen;
212 TheIndex.iUserID = UserID;
214 memcpy(IndexBuf, &TheIndex, sizeof(TheIndex));
215 return(sizeof(TheIndex));
218 // Back end for CtdlSetRelationship()
219 void put_visit(struct visit *newvisit) {
220 cdb_store(CDB_VISIT, newvisit, (sizeof(long)*3), newvisit, sizeof(struct visit));
224 // Define a relationship between a user and a room
225 void CtdlSetRelationship(struct visit *newvisit, struct ctdluser *rel_user, struct ctdlroom *rel_room) {
226 // We don't use these in Citadel because they're implicit by the
227 // index, but they must be present if the database is exported.
228 newvisit->v_roomnum = rel_room->QRnumber;
229 newvisit->v_roomgen = rel_room->QRgen;
230 newvisit->v_usernum = rel_user->usernum;
237 // Locate a relationship between a user and a room
238 void CtdlGetRelationship(struct visit *vbuf, struct ctdluser *rel_user, struct ctdlroom *rel_room) {
239 struct cdbdata *cdbvisit;
241 // Clear out the buffer
242 memset(vbuf, 0, sizeof(struct visit));
244 // Fill out the first three fields; they are also the index
245 vbuf->v_roomnum = rel_room->QRnumber;
246 vbuf->v_roomgen = rel_room->QRgen;
247 vbuf->v_usernum = rel_user->usernum;
249 cdbvisit = cdb_fetch(CDB_VISIT, vbuf, (sizeof(long)*3));
250 if (cdbvisit != NULL) {
251 memcpy(vbuf, cdbvisit->ptr, ((cdbvisit->len > sizeof(struct visit)) ? sizeof(struct visit) : cdbvisit->len));
255 // If this is the first time the user has seen this room, set the view to be the default for the room.
256 vbuf->v_view = rel_room->QRdefaultview;
259 // Set v_seen if necessary
260 if (vbuf->v_seen[0] == 0) {
261 snprintf(vbuf->v_seen, sizeof vbuf->v_seen, "*:%ld", vbuf->v_lastseen);
266 void CtdlMailboxName(char *buf, size_t n, const struct ctdluser *who, const char *prefix) {
267 snprintf(buf, n, "%010ld.%s", who->usernum, prefix);
271 // Check to see if the specified user has Internet mail permission
272 // (returns nonzero if permission is granted)
273 int CtdlCheckInternetMailPermission(struct ctdluser *who) {
275 // Do not allow twits to send Internet mail
276 if (who->axlevel <= AxProbU) return(0);
279 if (CtdlGetConfigInt("c_restrict") == 0) return(1);
282 if (who->flags & US_INTERNET) return(2);
284 // Admin level access?
285 if (who->axlevel >= AxAideU) return(3);
292 // This is a convenience function which follows the Citadel protocol semantics for most commands.
293 // If the current user does not have the requested access level, it outputs a protocol-friendly error message
294 // and then returns (-1). This allows calling functions to complete an access level check in one line of code.
295 int CtdlAccessCheck(int required_level) {
296 if (CC->internal_pgm) return(0);
297 if (required_level >= ac_internal) {
298 cprintf("%d This is not a user-level command.\n", ERROR + HIGHER_ACCESS_REQUIRED);
302 if ((required_level >= ac_logged_in_or_guest) && (CC->logged_in == 0) && (CtdlGetConfigInt("c_guest_logins") == 0)) {
303 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
307 if ((required_level >= ac_logged_in) && (CC->logged_in == 0)) {
308 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
312 if (CC->user.axlevel >= AxAideU) return(0);
313 if (required_level >= ac_aide) {
314 cprintf("%d This command requires Admin access.\n",
315 ERROR + HIGHER_ACCESS_REQUIRED);
319 if (is_room_aide()) return(0);
320 if (required_level >= ac_room_aide) {
321 cprintf("%d This command requires Admin or Room Admin access.\n",
322 ERROR + HIGHER_ACCESS_REQUIRED);
326 // Do not generate any output if we succeeded -- the calling function will handle that.
331 // Is the user currently logged in an Admin?
333 if (CC->user.axlevel >= AxAideU) {
342 // Is the user currently logged in an Admin *or* the room Admin for this room?
343 int is_room_aide(void) {
344 if (!CC->logged_in) {
348 if ((CC->user.axlevel >= AxAideU) || (CC->room.QRroomaide == CC->user.usernum)) {
357 // CtdlGetUserByNumber() - get user by number, returns 0 if user was found
358 // Note: fetching a user this way requires one additional database operation.
359 int CtdlGetUserByNumber(struct ctdluser *usbuf, long number) {
360 struct cdbdata *cdbun;
363 cdbun = cdb_fetch(CDB_USERSBYNUMBER, &number, sizeof(long));
365 syslog(LOG_INFO, "user_ops: %ld not found", number);
369 syslog(LOG_INFO, "user_ops: %ld maps to %s", number, cdbun->ptr);
370 r = CtdlGetUser(usbuf, cdbun->ptr);
376 // Helper function for rebuild_usersbynumber()
377 void rebuild_ubn_for_user(char *username, void *data) {
380 syslog(LOG_DEBUG, "user_ops: rebuilding usersbynumber index for %s", username);
381 if (CtdlGetUser(&u, username) == 0) {
382 cdb_store(CDB_USERSBYNUMBER, &(u.usernum), sizeof(long), u.fullname, strlen(u.fullname)+1);
387 // Rebuild the users-by-number index
388 void rebuild_usersbynumber(void) {
389 cdb_trunc(CDB_USERSBYNUMBER); // delete the old indices
390 ForEachUser(rebuild_ubn_for_user, NULL); // enumerate the users
394 // getuserbyuid() Get user by system uid (for PAM mode authentication)
395 // Returns 0 if user was found
396 int getuserbyuid(struct ctdluser *usbuf, uid_t number) {
398 struct cdbdata *cdbus;
399 struct ctdluser *usptr;
400 int return_value = (-1);
402 // Yes, we do this the long way.
403 // No, we don't use CtdlForEachUser() because that requires multiple reads for each record
404 // TODO: make an index
405 cdb_rewind(CDB_USERS);
406 while (cdbus = cdb_next_item(CDB_USERS), cdbus != NULL) {
407 usptr = (struct ctdluser *) cdbus->ptr;
409 if (usptr->uid == number) {
410 syslog(LOG_DEBUG, "user_ops: found uid=%d username=%s", usptr->uid, usptr->fullname);
411 memcpy(usbuf, usptr, sizeof(struct ctdluser));
412 return_value = 0; // success
416 if (return_value != 0) {
417 syslog(LOG_DEBUG, "user_ops: no user found with uid=%d", number);
419 return(return_value);
423 // Back end for cmd_user() and its ilk
424 int CtdlLoginExistingUser(const char *trythisname) {
428 syslog(LOG_DEBUG, "user_ops: CtdlLoginExistingUser(%s)", trythisname);
430 if ((CC->logged_in)) {
431 return login_already_logged_in;
434 if (trythisname == NULL) return login_not_found;
436 // We handle this a different way now (see below)
437 //if (!strncasecmp(trythisname, "SYS_", 4)) {
438 //syslog(LOG_DEBUG, "user_ops: system user \"%s\" is not allowed to log in.", trythisname);
439 //return login_not_found;
442 // Continue attempting user validation...
443 safestrncpy(username, trythisname, sizeof (username));
444 string_trim(username);
446 if (IsEmptyStr(username)) {
447 return login_not_found;
451 if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
453 struct passwd *tempPwdPtr;
456 syslog(LOG_DEBUG, "user_ops: asking host about <%s>", username);
457 #ifdef HAVE_GETPWNAM_R
458 syslog(LOG_DEBUG, "user_ops: calling getpwnam_r()");
459 getpwnam_r(username, &pd, pwdbuffer, sizeof pwdbuffer, &tempPwdPtr);
460 #else // HAVE_GETPWNAM_R
461 syslog(LOG_DEBUG, "user_ops: SHOULD NEVER GET HERE!!!");
463 #endif // HAVE_GETPWNAM_R
464 if (tempPwdPtr == NULL) {
465 syslog(LOG_DEBUG, "user_ops: no such user <%s>", username);
466 return login_not_found;
469 // Locate the associated Citadel account. If not found, make one attempt to create it.
470 found_user = getuserbyuid(&CC->user, pd.pw_uid);
471 if (found_user != 0) {
472 create_user(username, CREATE_USER_DO_NOT_BECOME_USER, pd.pw_uid);
473 found_user = getuserbyuid(&CC->user, pd.pw_uid);
475 syslog(LOG_DEBUG, "user_ops: found it: uid=%ld, gecos=%s here: %d", (long)pd.pw_uid, pd.pw_gecos, found_user);
480 else if ((CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP) || (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD)) {
486 found_user = CtdlTryUserLDAP(username, ldap_dn, sizeof ldap_dn, ldap_cn, sizeof ldap_cn, &ldap_uid);
487 if (found_user != 0) {
488 return login_not_found;
491 found_user = getuserbyuid(&CC->user, ldap_uid);
492 if (found_user != 0) {
493 create_user(ldap_cn, CREATE_USER_DO_NOT_BECOME_USER, ldap_uid);
494 found_user = getuserbyuid(&CC->user, ldap_uid);
497 if (found_user == 0) {
498 if (CC->ldap_dn != NULL) free(CC->ldap_dn);
499 CC->ldap_dn = strdup(ldap_dn);
504 // native auth mode...
506 struct recptypes *valid = NULL;
508 // First, try to log in as if the supplied name is a display name
509 found_user = CtdlGetUser(&CC->user, username);
511 // If that didn't work, try to log in as if the supplied name * is an e-mail address
512 if (found_user != 0) {
513 valid = validate_recipients(username, NULL, 0);
515 if (valid->num_local == 1) {
516 found_user = CtdlGetUser(&CC->user, valid->recp_local);
518 free_recipients(valid);
523 // User 0 is a system account and must not be used by a real user
524 if (CC->user.usernum <= 0) {
525 syslog(LOG_DEBUG, "user_ops: system account <%s> is not allowed to log in.", trythisname);
526 return login_not_found;
529 // Did we find something?
530 if (found_user == 0) {
531 if (((CC->nologin)) && (CC->user.axlevel < AxAideU)) {
532 return login_too_many_users;
535 safestrncpy(CC->curr_user, CC->user.fullname, sizeof CC->curr_user);
539 return login_not_found;
543 // session startup code which is common to both cmd_pass() and cmd_newu()
544 void do_login(void) {
546 syslog(LOG_NOTICE, "user_ops: <%s> logged in", CC->curr_user);
548 CtdlGetUserLock(&CC->user, CC->curr_user);
549 CC->previous_login = CC->user.lastcall;
550 time(&CC->user.lastcall);
552 // If this user's name is the name of the system administrator
553 // (as specified in setup), automatically assign access level 6.
554 if ( (!IsEmptyStr(CtdlGetConfigStr("c_sysadm"))) && (!strcasecmp(CC->user.fullname, CtdlGetConfigStr("c_sysadm"))) ) {
555 CC->user.axlevel = AxAideU;
558 // If we're authenticating off the host system, automatically give root the highest level of access.
559 if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
560 if (CC->user.uid == 0) {
561 CC->user.axlevel = AxAideU;
564 CtdlPutUserLock(&CC->user);
566 // If we are using LDAP authentication, extract the user's email addresses from the directory.
567 if ((CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP) || (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD)) {
568 char new_emailaddrs[512];
569 if (CtdlGetConfigInt("c_ldap_sync_email_addrs") > 0) {
570 if (extract_email_addresses_from_ldap(CC->ldap_dn, new_emailaddrs) == 0) {
571 CtdlSetEmailAddressesForUser(CC->user.fullname, new_emailaddrs);
576 // If the user does not have any email addresses assigned, generate one.
577 if (IsEmptyStr(CC->user.emailaddrs)) {
578 AutoGenerateEmailAddressForUser(&CC->user);
581 // Populate the user principal identity, which is consistent and never aliased
582 strcpy(CC->cs_principal_id, "");
583 makeuserkey(CC->cs_principal_id, CC->user.fullname);
584 strcat(CC->cs_principal_id, "@");
585 strcat(CC->cs_principal_id, CtdlGetConfigStr("c_fqdn"));
587 // Populate cs_inet_email and cs_inet_other_emails with valid email addresses from the user record
588 strcpy(CC->cs_inet_email, CC->user.emailaddrs);
589 char *firstsep = strstr(CC->cs_inet_email, "|");
591 strcpy(CC->cs_inet_other_emails, firstsep+1);
595 CC->cs_inet_other_emails[0] = 0;
598 // Create any personal rooms required by the system.
599 // (Technically, MAILROOM should be there already, but just in case...)
600 CtdlCreateRoom(MAILROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
601 CtdlCreateRoom(SENTITEMS, 4, "", 0, 1, 0, VIEW_MAILBOX);
602 CtdlCreateRoom(USERTRASHROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
603 CtdlCreateRoom(USERDRAFTROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
605 // Run any startup routines registered by loadable modules
606 PerformSessionHooks(EVT_LOGIN);
609 CtdlUserGoto(CtdlGetConfigStr("c_baseroom"), 0, 0, NULL, NULL, NULL, NULL);
613 void logged_in_response(void) {
614 cprintf("%d %s|%d|0|0|%u|%ld|%ld\n",
615 CIT_OK, CC->user.fullname, CC->user.axlevel,
616 CC->user.flags, CC->user.usernum,
622 void CtdlUserLogout(void) {
624 syslog(LOG_DEBUG, "user_ops: CtdlUserLogout() logging out <%s> from session %d", CC->curr_user, CC->cs_pid);
626 // Run any hooks registered by modules...
627 PerformSessionHooks(EVT_LOGOUT);
629 // Clear out some session data. Most likely, the CitContext for this
630 // session is about to get nuked when the session disconnects, but
631 // since it's possible to log in again without reconnecting, we cannot
632 // make that assumption.
635 // Check to see if the user was deleted while logged in and purge them if necessary
636 if ((CC->user.axlevel == AxDeleted) && (CC->user.usernum)) {
637 purge_user(CC->user.fullname);
640 // Clear out the user record in memory so we don't behave like a ghost
641 memset(&CC->user, 0, sizeof(struct ctdluser));
642 CC->curr_user[0] = 0;
643 CC->cs_inet_email[0] = 0;
644 CC->cs_inet_other_emails[0] = 0;
645 CC->cs_inet_fn[0] = 0;
647 // Free any output buffers
652 // Validate a password on the host unix system by talking to the chkpwd daemon
653 static int validpw(uid_t uid, const char *pass) {
657 if (IsEmptyStr(pass)) {
658 syslog(LOG_DEBUG, "user_ops: refusing to chkpwd for uid=%d with empty password", uid);
662 syslog(LOG_DEBUG, "user_ops: validating password for uid=%d using chkpwd...", uid);
664 begin_critical_section(S_CHKPWD);
665 rv = write(chkpwd_write_pipe[1], &uid, sizeof(uid_t));
667 syslog(LOG_ERR, "user_ops: communication with chkpwd broken: %m");
668 end_critical_section(S_CHKPWD);
671 rv = write(chkpwd_write_pipe[1], pass, 256);
673 syslog(LOG_ERR, "user_ops: communication with chkpwd broken: %m");
674 end_critical_section(S_CHKPWD);
677 rv = read(chkpwd_read_pipe[0], buf, 4);
679 syslog(LOG_ERR, "user_ops: ommunication with chkpwd broken: %m");
680 end_critical_section(S_CHKPWD);
683 end_critical_section(S_CHKPWD);
685 if (!strncmp(buf, "PASS", 4)) {
686 syslog(LOG_DEBUG, "user_ops: chkpwd pass");
690 syslog(LOG_DEBUG, "user_ops: chkpwd fail");
695 // Start up the chkpwd daemon so validpw() has something to talk to
696 void start_chkpwd_daemon(void) {
698 struct stat filestats;
701 syslog(LOG_DEBUG, "user_ops: starting chkpwd daemon for host authentication mode");
703 if ((stat(file_chkpwd, &filestats)==-1) || (filestats.st_size==0)) {
704 syslog(LOG_ERR, "user_ops: %s: %m", file_chkpwd);
705 exit(CTDLEXIT_CHKPWD);
707 if (pipe(chkpwd_write_pipe) != 0) {
708 syslog(LOG_ERR, "user_ops: unable to create pipe for chkpwd daemon: %m");
709 exit(CTDLEXIT_CHKPWD);
711 if (pipe(chkpwd_read_pipe) != 0) {
712 syslog(LOG_ERR, "user_ops: unable to create pipe for chkpwd daemon: %m");
713 exit(CTDLEXIT_CHKPWD);
717 if (chkpwd_pid < 0) {
718 syslog(LOG_ERR, "user_ops: unable to fork chkpwd daemon: %m");
719 exit(CTDLEXIT_CHKPWD);
721 if (chkpwd_pid == 0) {
722 dup2(chkpwd_write_pipe[0], 0);
723 dup2(chkpwd_read_pipe[1], 1);
724 for (i=2; i<256; ++i) close(i);
725 execl(file_chkpwd, file_chkpwd, NULL);
726 syslog(LOG_ERR, "user_ops: unable to exec chkpwd daemon: %m");
732 int CtdlTryPassword(const char *password, long len) {
735 if ((CC->logged_in)) {
736 syslog(LOG_WARNING, "user_ops: CtdlTryPassword: already logged in");
737 return pass_already_logged_in;
739 if (!strcmp(CC->curr_user, NLI)) {
740 syslog(LOG_WARNING, "user_ops: CtdlTryPassword: no user selected");
743 if (CtdlGetUser(&CC->user, CC->curr_user)) {
744 syslog(LOG_ERR, "user_ops: CtdlTryPassword: internal error");
745 return pass_internal_error;
747 if (password == NULL) {
748 syslog(LOG_INFO, "user_ops: CtdlTryPassword: NULL password string supplied");
749 return pass_wrong_password;
753 else if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
754 if (validpw(CC->user.uid, password)) {
757 // sooper-seekrit hack: populate the password field in the
758 // citadel database with the password that the user typed,
759 // if it's correct. This allows most sites to convert from
760 // host auth to native auth if they want to. If you think
761 // this is a security hazard, comment it out.
763 CtdlGetUserLock(&CC->user, CC->curr_user);
764 safestrncpy(CC->user.password, password, sizeof CC->user.password);
765 CtdlPutUserLock(&CC->user);
767 // (sooper-seekrit hack ends here)
775 else if ((CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP) || (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD)) {
777 if ((CC->ldap_dn) && (!CtdlTryPasswordLDAP(CC->ldap_dn, password))) {
785 // native auth mode...
789 pw = (char*) malloc(len + 1);
790 memcpy(pw, password, len + 1);
792 strproc(CC->user.password);
793 code = strcasecmp(CC->user.password, pw);
796 strproc(CC->user.password);
797 code = strcasecmp(CC->user.password, pw);
807 syslog(LOG_WARNING, "user_ops: bad password specified for <%s> Service <%s> Port <%ld> Remote <%s / %s>",
814 return pass_wrong_password;
819 // Delete a user record *and* all of its related resources.
820 int purge_user(char pname[]) {
821 struct ctdluser usbuf;
822 char usernamekey[USERNAME_SIZE];
824 makeuserkey(usernamekey, pname);
826 // If the name is empty we can't find them in the DB any way so just return
827 if (IsEmptyStr(pname)) {
828 return(ERROR + NO_SUCH_USER);
831 if (CtdlGetUser(&usbuf, pname) != 0) {
832 syslog(LOG_ERR, "user_ops: cannot purge user <%s> - not found", pname);
833 return(ERROR + NO_SUCH_USER);
836 // Don't delete a user who is currently logged in. Instead, just
837 // set the access level to 0, and let the account get swept up
838 // during the next purge.
839 if (CtdlIsUserLoggedInByNum(usbuf.usernum)) {
840 syslog(LOG_WARNING, "user_ops: <%s> is logged in; not deleting", pname);
841 usbuf.axlevel = AxDeleted;
846 syslog(LOG_NOTICE, "user_ops: deleting <%s>", pname);
848 // Perform any purge functions registered by server extensions
849 PerformUserHooks(&usbuf, EVT_PURGEUSER);
851 // delete any existing user/room relationships
852 // Commenting out since it was assuming the user number was
853 // at the top of the index. Room number is actually first.
854 // Auto-Purge will clean up the records later, so not worth
855 // scanning all the records here.
856 //cdb_delete(CDB_VISIT, &usbuf.usernum, sizeof(long));
858 // delete the users-by-number index record
859 cdb_delete(CDB_USERSBYNUMBER, &usbuf.usernum, sizeof(long));
861 // delete the user entry
862 cdb_delete(CDB_USERS, usernamekey, strlen(usernamekey));
868 // This is the back end processing that happens when we create a new user account.
869 int internal_create_user(char *username, struct ctdluser *usbuf, uid_t uid) {
870 if (!CtdlGetUser(usbuf, username)) {
871 return(ERROR + ALREADY_EXISTS);
874 // Go ahead and initialize a new user record
875 memset(usbuf, 0, sizeof(struct ctdluser));
876 safestrncpy(usbuf->fullname, username, sizeof usbuf->fullname);
877 strcpy(usbuf->password, "");
880 // These are the default flags on new accounts
881 usbuf->flags = US_LASTOLD | US_DISAPPEAR | US_PAGINATOR | US_FLOORS;
882 usbuf->axlevel = CtdlGetConfigInt("c_initax");
883 usbuf->lastcall = time(NULL);
885 // fetch a new user number
886 usbuf->usernum = get_new_user_number();
888 // add user to the database
890 cdb_store(CDB_USERSBYNUMBER, &usbuf->usernum, sizeof(long), usbuf->fullname, strlen(usbuf->fullname)+1);
892 // If non-native auth, index by uid
893 if ((usbuf->uid > 0) && (usbuf->uid != NATIVE_AUTH_UID)) {
894 StrBuf *claimed_id = NewStrBuf();
895 StrBufPrintf(claimed_id, "uid:%d", usbuf->uid);
896 FreeStrBuf(&claimed_id);
903 // create_user() - back end processing to create a new user
905 // Set 'newusername' to the desired account name.
906 // Set 'become_user' to CREATE_USER_BECOME_USER if this is self-service account creation and we want to
907 // actually log in as the user we just created, otherwise set it to CREATE_USER_DO_NOT_BECOME_USER
908 // Set 'uid' to some uid_t value to associate the account with an external auth user, or (-1) for native auth
909 int create_user(char *username, int become_user, uid_t uid) {
910 struct ctdluser usbuf;
911 struct ctdlroom qrbuf;
912 char mailboxname[ROOMNAMELEN];
917 if ((retval = internal_create_user(username, &usbuf, uid)) != 0) {
921 // Give the user a private mailbox and a configuration room.
922 // Make the latter an invisible system room.
923 CtdlMailboxName(mailboxname, sizeof mailboxname, &usbuf, MAILROOM);
924 CtdlCreateRoom(mailboxname, 5, "", 0, 1, 1, VIEW_MAILBOX);
926 CtdlMailboxName(mailboxname, sizeof mailboxname, &usbuf, USERCONFIGROOM);
927 CtdlCreateRoom(mailboxname, 5, "", 0, 1, 1, VIEW_BBS);
928 if (CtdlGetRoomLock(&qrbuf, mailboxname) == 0) {
929 qrbuf.QRflags2 |= QR2_SYSTEM;
930 CtdlPutRoomLock(&qrbuf);
933 // Perform any create functions registered by server extensions
934 PerformUserHooks(&usbuf, EVT_NEWUSER);
936 // Everything below this line can be bypassed if administratively
937 // creating a user, instead of doing self-service account creation
939 if (become_user == CREATE_USER_BECOME_USER) {
940 // Now become the user we just created
941 memcpy(&CC->user, &usbuf, sizeof(struct ctdluser));
942 safestrncpy(CC->curr_user, username, sizeof CC->curr_user);
945 // Check to make sure we're still who we think we are
946 if (CtdlGetUser(&CC->user, CC->curr_user)) {
947 return(ERROR + INTERNAL_ERROR);
952 "New user account <%s> has been created, from host %s [%s].\n",
957 CtdlAideMessage(buf, "User Creation Notice");
958 syslog(LOG_NOTICE, "user_ops: <%s> created", username);
963 // set password - back end api code
964 void CtdlSetPassword(char *new_pw) {
965 CtdlGetUserLock(&CC->user, CC->curr_user);
966 safestrncpy(CC->user.password, new_pw, sizeof(CC->user.password));
967 CtdlPutUserLock(&CC->user);
968 syslog(LOG_INFO, "user_ops: password changed for <%s>", CC->curr_user);
969 PerformSessionHooks(EVT_SETPASS);
973 // API function for cmd_invt_kick() and anything else that needs to
974 // invite or kick out a user to/from a room.
976 // Set iuser to the name of the user, and op to 1=invite or 0=kick
977 int CtdlInvtKick(char *iuser, int op) {
978 struct ctdluser USscratch;
982 if (CtdlGetUser(&USscratch, iuser) != 0) {
986 CtdlGetRelationship(&vbuf, &USscratch, &CC->room);
988 vbuf.v_flags = vbuf.v_flags & ~V_FORGET & ~V_LOCKOUT;
989 vbuf.v_flags = vbuf.v_flags | V_ACCESS;
992 vbuf.v_flags = vbuf.v_flags & ~V_ACCESS;
993 vbuf.v_flags = vbuf.v_flags | V_FORGET | V_LOCKOUT;
995 CtdlSetRelationship(&vbuf, &USscratch, &CC->room);
997 // post a message in Aide> saying what we just did
998 snprintf(bbb, sizeof bbb, "%s has been %s \"%s\" by %s.\n",
1000 ((op == 1) ? "invited to" : "kicked out of"),
1002 (CC->logged_in ? CC->user.fullname : "an administrator")
1004 CtdlAideMessage(bbb,"User Admin Message");
1009 // Forget (Zap) the current room (API call)
1010 // Returns 0 on success
1011 int CtdlForgetThisRoom(void) {
1014 // On some systems, Admins are not allowed to forget rooms
1015 if (is_aide() && (CtdlGetConfigInt("c_aide_zap") == 0)
1016 && ((CC->room.QRflags & QR_MAILBOX) == 0) ) {
1020 CtdlGetUserLock(&CC->user, CC->curr_user);
1021 CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
1023 vbuf.v_flags = vbuf.v_flags | V_FORGET;
1024 vbuf.v_flags = vbuf.v_flags & ~V_ACCESS;
1026 CtdlSetRelationship(&vbuf, &CC->user, &CC->room);
1027 CtdlPutUserLock(&CC->user);
1029 // Return to the Lobby, so we don't end up in an undefined room
1030 CtdlUserGoto(CtdlGetConfigStr("c_baseroom"), 0, 0, NULL, NULL, NULL, NULL);
1035 // Traverse the user file and perform a callback for each user record.
1036 // (New improved version that runs in two phases so that callbacks can perform writes without having a r/o cursor open)
1037 void ForEachUser(void (*CallBack) (char *, void *out_data), void *in_data) {
1038 struct cdbdata *cdbus;
1039 struct ctdluser *usptr;
1041 Array *all_users = array_new(USERNAME_SIZE);
1042 if (all_users == NULL) {
1043 syslog(LOG_ERR, "user_ops: alloc failed, ForEachUser() exiting");
1048 cdb_rewind(CDB_USERS);
1050 // Phase 1 : build an array of all our user account names
1051 while (cdbus = cdb_next_item(CDB_USERS), cdbus != NULL) {
1052 usptr = (struct ctdluser *) cdbus->ptr;
1053 if (strlen(usptr->fullname) > 0) {
1054 array_append(all_users, usptr->fullname);
1058 // Phase 2 : perform the callback for each user while de-allocating the list
1059 for (int i=0; i<array_len(all_users); ++i) {
1060 (*CallBack) (array_get_element_at(all_users, i), in_data);
1063 // Phase 3 : free the array
1064 array_free(all_users);
1068 // Return the number of new messages that have arrived in the user's inbox while they were logged in.
1069 // Resets to zero when called.
1070 int NewMailCount() {
1071 int num_newmsgs = 0;
1072 num_newmsgs = CC->newmail;
1074 return(num_newmsgs);
1078 // Count the number of new mail messages the user has
1079 int InitialMailCheck() {
1080 int num_newmsgs = 0;
1082 char mailboxname[ROOMNAMELEN];
1083 struct ctdlroom mailbox;
1085 long *msglist = NULL;
1088 CtdlMailboxName(mailboxname, sizeof mailboxname, &CC->user, MAILROOM);
1089 if (CtdlGetRoom(&mailbox, mailboxname) != 0) {
1092 CtdlGetRelationship(&vbuf, &CC->user, &mailbox);
1094 num_msgs = CtdlFetchMsgList(mailbox.QRnumber, &msglist);
1096 for (a = 0; a < num_msgs; ++a) {
1097 if (msglist[a] > 0L) {
1098 if (msglist[a] > vbuf.v_lastseen) {
1105 return(num_newmsgs);
1109 // This is an undocumented rescue mode that can be used to rewrite an admin user account that has been corrupted.
1110 // To prevent abuse, it can only run as a one-shot when the server is not otherwise operational.
1111 // Don't use this without asking about it.
1112 void undocumented_rescue_mode(char *rescue_string) {
1113 struct ctdluser usbuf;
1114 memset(&usbuf, 0, sizeof(struct ctdluser));
1115 extract_token(usbuf.fullname, rescue_string, 0, '|', sizeof usbuf.password);
1116 extract_token(usbuf.password, rescue_string, 1, '|', sizeof usbuf.password);
1117 usbuf.usernum = extract_long(rescue_string, 2);
1119 usbuf.lastcall = time(NULL);
1120 CtdlPutUser(&usbuf);