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 // Compare two usernames to see if they are the same user after being keyed for the database
29 // Usage is identical to strcmp()
30 int CtdlUserCmp(char *s1, char *s2) {
31 char k1[USERNAME_SIZE];
32 char k2[USERNAME_SIZE];
36 return(strcmp(k1,k2));
40 // CtdlGetUser() retrieve named user into supplied buffer.
41 // returns 0 on success
42 int CtdlGetUser(struct ctdluser *usbuf, char *name) {
43 char usernamekey[USERNAME_SIZE];
44 struct cdbdata *cdbus;
47 memset(usbuf, 0, sizeof(struct ctdluser));
50 makeuserkey(usernamekey, name);
51 if (IsEmptyStr(usernamekey)) {
52 return(1); // empty user name
54 cdbus = cdb_fetch(CDB_USERS, usernamekey, strlen(usernamekey));
56 if (cdbus == NULL) { // user not found
60 memcpy(usbuf, cdbus->ptr, ((cdbus->len > sizeof(struct ctdluser)) ? sizeof(struct ctdluser) : cdbus->len));
67 int CtdlLockGetCurrentUser(void) {
68 return CtdlGetUser(&CC->user, CC->curr_user);
72 // CtdlGetUserLock() - same as getuser() but locks the record
73 int CtdlGetUserLock(struct ctdluser *usbuf, char *name) {
76 retcode = CtdlGetUser(usbuf, name);
78 begin_critical_section(S_USERS);
84 // CtdlPutUser() - write user buffer into the correct place on disk
85 void CtdlPutUser(struct ctdluser *usbuf) {
86 char usernamekey[USERNAME_SIZE];
87 makeuserkey(usernamekey, usbuf->fullname);
88 usbuf->version = REV_LEVEL;
89 cdb_store(CDB_USERS, usernamekey, strlen(usernamekey), usbuf, sizeof(struct ctdluser));
93 void CtdlPutCurrentUserLock() {
94 CtdlPutUser(&CC->user);
98 // CtdlPutUserLock() - same as putuser() but locks the record
99 void CtdlPutUserLock(struct ctdluser *usbuf) {
101 end_critical_section(S_USERS);
105 // rename_user() - this is tricky because the user's display name is the database key
106 // Returns 0 on success or nonzero if there was an error...
107 int rename_user(char *oldname, char *newname) {
108 int retcode = RENAMEUSER_OK;
109 struct ctdluser usbuf;
111 char oldnamekey[USERNAME_SIZE];
112 char newnamekey[USERNAME_SIZE];
114 // Create the database keys...
115 makeuserkey(oldnamekey, oldname);
116 makeuserkey(newnamekey, newname);
118 // Lock up and get going
119 begin_critical_section(S_USERS);
121 // We cannot rename a user who is currently logged in
122 if (CtdlIsUserLoggedIn(oldname)) {
123 end_critical_section(S_USERS);
124 return RENAMEUSER_LOGGED_IN;
127 if (CtdlGetUser(&usbuf, newname) == 0) {
128 retcode = RENAMEUSER_ALREADY_EXISTS;
132 if (CtdlGetUser(&usbuf, oldname) != 0) {
133 retcode = RENAMEUSER_NOT_FOUND;
135 else { // Sanity checks succeeded. Now rename the user.
136 if (usbuf.usernum == 0) {
137 syslog(LOG_DEBUG, "user_ops: can not rename user \"Citadel\".");
138 retcode = RENAMEUSER_NOT_FOUND;
141 syslog(LOG_DEBUG, "user_ops: renaming <%s> to <%s>", oldname, newname);
142 cdb_delete(CDB_USERS, oldnamekey, strlen(oldnamekey));
143 safestrncpy(usbuf.fullname, newname, sizeof usbuf.fullname);
145 cdb_store(CDB_USERSBYNUMBER, &usbuf.usernum, sizeof(long), usbuf.fullname, strlen(usbuf.fullname)+1 );
146 retcode = RENAMEUSER_OK;
152 end_critical_section(S_USERS);
157 // Convert a username into the format used as a database key prior to version 928
158 // This only gets called by reindex_user_928()
159 void makeuserkey_pre928(char *key, const char *username) {
162 int len = strlen(username);
164 if (len >= USERNAME_SIZE) {
165 syslog(LOG_INFO, "Username too long: %s", username);
166 len = USERNAME_SIZE - 1;
168 for (i=0; i<=len; ++i) {
169 key[i] = tolower(username[i]);
174 // Read a user record using the pre-v928 index format, and write it back using the v928-and-higher index format.
175 // This ONLY gets called during an upgrade from version <928 to version >=928.
176 void reindex_user_928(char *username, void *out_data) {
178 char oldkey[USERNAME_SIZE];
179 char newkey[USERNAME_SIZE];
180 struct cdbdata *cdbus;
181 struct ctdluser usbuf;
183 makeuserkey_pre928(oldkey, username);
184 makeuserkey(newkey, username);
186 syslog(LOG_DEBUG, "user_ops: reindex_user_928: %s <%s> --> <%s>", username, oldkey, newkey);
188 // Fetch the user record using the old index format
189 cdbus = cdb_fetch(CDB_USERS, oldkey, strlen(oldkey));
191 syslog(LOG_INFO, "user_ops: <%s> not found, were they already reindexed?", username);
194 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 != NULL) {
249 memcpy(vbuf, cdbvisit->ptr, ((cdbvisit->len > sizeof(struct visit)) ? sizeof(struct visit) : cdbvisit->len));
253 // If this is the first time the user has seen this room, set the view to be the default for the room.
254 vbuf->v_view = rel_room->QRdefaultview;
257 // Set v_seen if necessary
258 if (vbuf->v_seen[0] == 0) {
259 snprintf(vbuf->v_seen, sizeof vbuf->v_seen, "*:%ld", vbuf->v_lastseen);
264 void CtdlMailboxName(char *buf, size_t n, const struct ctdluser *who, const char *prefix) {
265 snprintf(buf, n, "%010ld.%s", who->usernum, prefix);
269 // Check to see if the specified user has Internet mail permission
270 // (returns nonzero if permission is granted)
271 int CtdlCheckInternetMailPermission(struct ctdluser *who) {
273 // Do not allow twits to send Internet mail
274 if (who->axlevel <= AxProbU) return(0);
277 if (CtdlGetConfigInt("c_restrict") == 0) return(1);
280 if (who->flags & US_INTERNET) return(2);
282 // Admin level access?
283 if (who->axlevel >= AxAideU) return(3);
290 // This is a convenience function which follows the Citadel protocol semantics for most commands.
291 // If the current user does not have the requested access level, it outputs a protocol-friendly error message
292 // and then returns (-1). This allows calling functions to complete an access level check in one line of code.
293 int CtdlAccessCheck(int required_level) {
294 if (CC->internal_pgm) return(0);
295 if (required_level >= ac_internal) {
296 cprintf("%d This is not a user-level command.\n", ERROR + HIGHER_ACCESS_REQUIRED);
300 if ((required_level >= ac_logged_in_or_guest) && (CC->logged_in == 0) && (CtdlGetConfigInt("c_guest_logins") == 0)) {
301 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
305 if ((required_level >= ac_logged_in) && (CC->logged_in == 0)) {
306 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
310 if (CC->user.axlevel >= AxAideU) return(0);
311 if (required_level >= ac_aide) {
312 cprintf("%d This command requires Admin access.\n",
313 ERROR + HIGHER_ACCESS_REQUIRED);
317 if (is_room_aide()) return(0);
318 if (required_level >= ac_room_aide) {
319 cprintf("%d This command requires Admin or Room Admin access.\n",
320 ERROR + HIGHER_ACCESS_REQUIRED);
324 // Do not generate any output if we succeeded -- the calling function will handle that.
329 // Is the user currently logged in an Admin?
331 if (CC->user.axlevel >= AxAideU) {
340 // Is the user currently logged in an Admin *or* the room Admin for this room?
341 int is_room_aide(void) {
342 if (!CC->logged_in) {
346 if ((CC->user.axlevel >= AxAideU) || (CC->room.QRroomaide == CC->user.usernum)) {
355 // CtdlGetUserByNumber() - get user by number, returns 0 if user was found
356 // Note: fetching a user this way requires one additional database operation.
357 int CtdlGetUserByNumber(struct ctdluser *usbuf, long number) {
358 struct cdbdata *cdbun;
361 cdbun = cdb_fetch(CDB_USERSBYNUMBER, &number, sizeof(long));
363 syslog(LOG_INFO, "user_ops: %ld not found", number);
367 syslog(LOG_INFO, "user_ops: %ld maps to %s", number, cdbun->ptr);
368 r = CtdlGetUser(usbuf, cdbun->ptr);
374 // Helper function for rebuild_usersbynumber()
375 void rebuild_ubn_for_user(char *username, void *data) {
378 syslog(LOG_DEBUG, "user_ops: rebuilding usersbynumber index for %s", username);
379 if (CtdlGetUser(&u, username) == 0) {
380 cdb_store(CDB_USERSBYNUMBER, &(u.usernum), sizeof(long), u.fullname, strlen(u.fullname)+1);
385 // Rebuild the users-by-number index
386 void rebuild_usersbynumber(void) {
387 cdb_trunc(CDB_USERSBYNUMBER); // delete the old indices
388 ForEachUser(rebuild_ubn_for_user, NULL); // enumerate the users
392 // getuserbyuid() Get user by system uid (for PAM mode authentication)
393 // Returns 0 if user was found
394 int getuserbyuid(struct ctdluser *usbuf, uid_t number) {
396 struct cdbdata *cdbus;
397 struct ctdluser *usptr;
398 int return_value = (-1);
400 // Yes, we do this the long way.
401 // No, we don't use CtdlForEachUser() because that requires multiple reads for each record
402 // TODO: make an index
403 cdb_rewind(CDB_USERS);
404 while (cdbus = cdb_next_item(CDB_USERS), cdbus != NULL) {
405 usptr = (struct ctdluser *) cdbus->ptr;
407 if (usptr->uid == number) {
408 syslog(LOG_DEBUG, "user_ops: found uid=%d username=%s", usptr->uid, usptr->fullname);
409 memcpy(usbuf, usptr, sizeof(struct ctdluser));
410 return_value = 0; // success
414 if (return_value != 0) {
415 syslog(LOG_DEBUG, "user_ops: no user found with uid=%d", number);
417 return(return_value);
421 // Back end for cmd_user() and its ilk
422 int CtdlLoginExistingUser(const char *trythisname) {
426 syslog(LOG_DEBUG, "user_ops: CtdlLoginExistingUser(%s)", trythisname);
428 if ((CC->logged_in)) {
429 return login_already_logged_in;
432 if (trythisname == NULL) return login_not_found;
434 // We handle this a different way now (see below)
435 //if (!strncasecmp(trythisname, "SYS_", 4)) {
436 //syslog(LOG_DEBUG, "user_ops: system user \"%s\" is not allowed to log in.", trythisname);
437 //return login_not_found;
440 // Continue attempting user validation...
441 safestrncpy(username, trythisname, sizeof (username));
442 string_trim(username);
444 if (IsEmptyStr(username)) {
445 return login_not_found;
449 if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
451 struct passwd *tempPwdPtr;
454 syslog(LOG_DEBUG, "user_ops: asking host about <%s>", username);
455 #ifdef HAVE_GETPWNAM_R
456 syslog(LOG_DEBUG, "user_ops: calling getpwnam_r()");
457 getpwnam_r(username, &pd, pwdbuffer, sizeof pwdbuffer, &tempPwdPtr);
458 #else // HAVE_GETPWNAM_R
459 syslog(LOG_DEBUG, "user_ops: SHOULD NEVER GET HERE!!!");
461 #endif // HAVE_GETPWNAM_R
462 if (tempPwdPtr == NULL) {
463 syslog(LOG_DEBUG, "user_ops: no such user <%s>", username);
464 return login_not_found;
467 // Locate the associated Citadel account. If not found, make one attempt to create it.
468 found_user = getuserbyuid(&CC->user, pd.pw_uid);
469 if (found_user != 0) {
470 create_user(username, CREATE_USER_DO_NOT_BECOME_USER, pd.pw_uid);
471 found_user = getuserbyuid(&CC->user, pd.pw_uid);
473 syslog(LOG_DEBUG, "user_ops: found it: uid=%ld, gecos=%s here: %d", (long)pd.pw_uid, pd.pw_gecos, found_user);
478 else if ((CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP) || (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD)) {
484 found_user = CtdlTryUserLDAP(username, ldap_dn, sizeof ldap_dn, ldap_cn, sizeof ldap_cn, &ldap_uid);
485 if (found_user != 0) {
486 return login_not_found;
489 found_user = getuserbyuid(&CC->user, ldap_uid);
490 if (found_user != 0) {
491 create_user(ldap_cn, CREATE_USER_DO_NOT_BECOME_USER, ldap_uid);
492 found_user = getuserbyuid(&CC->user, ldap_uid);
495 if (found_user == 0) {
496 if (CC->ldap_dn != NULL) free(CC->ldap_dn);
497 CC->ldap_dn = strdup(ldap_dn);
502 // native auth mode...
504 struct recptypes *valid = NULL;
506 // First, try to log in as if the supplied name is a display name
507 found_user = CtdlGetUser(&CC->user, username);
509 // If that didn't work, try to log in as if the supplied name * is an e-mail address
510 if (found_user != 0) {
511 valid = validate_recipients(username, NULL, 0);
513 if (valid->num_local == 1) {
514 found_user = CtdlGetUser(&CC->user, valid->recp_local);
516 free_recipients(valid);
521 // User 0 is a system account and must not be used by a real user
522 if (CC->user.usernum <= 0) {
523 syslog(LOG_DEBUG, "user_ops: system account <%s> is not allowed to log in.", trythisname);
524 return login_not_found;
527 // Did we find something?
528 if (found_user == 0) {
529 if (((CC->nologin)) && (CC->user.axlevel < AxAideU)) {
530 return login_too_many_users;
533 safestrncpy(CC->curr_user, CC->user.fullname, sizeof CC->curr_user);
537 return login_not_found;
541 // session startup code which is common to both cmd_pass() and cmd_newu()
542 void do_login(void) {
544 syslog(LOG_NOTICE, "user_ops: <%s> logged in", CC->curr_user);
546 CtdlGetUserLock(&CC->user, CC->curr_user);
547 CC->previous_login = CC->user.lastcall;
548 time(&CC->user.lastcall);
550 // If this user's name is the name of the system administrator
551 // (as specified in setup), automatically assign access level 6.
552 if ( (!IsEmptyStr(CtdlGetConfigStr("c_sysadm"))) && (!strcasecmp(CC->user.fullname, CtdlGetConfigStr("c_sysadm"))) ) {
553 CC->user.axlevel = AxAideU;
556 // If we're authenticating off the host system, automatically give root the highest level of access.
557 if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
558 if (CC->user.uid == 0) {
559 CC->user.axlevel = AxAideU;
562 CtdlPutUserLock(&CC->user);
564 // If we are using LDAP authentication, extract the user's email addresses from the directory.
565 if ((CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP) || (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD)) {
566 char new_emailaddrs[512];
567 if (CtdlGetConfigInt("c_ldap_sync_email_addrs") > 0) {
568 if (extract_email_addresses_from_ldap(CC->ldap_dn, new_emailaddrs) == 0) {
569 CtdlSetEmailAddressesForUser(CC->user.fullname, new_emailaddrs);
574 // If the user does not have any email addresses assigned, generate one.
575 if (IsEmptyStr(CC->user.emailaddrs)) {
576 AutoGenerateEmailAddressForUser(&CC->user);
579 // Populate the user principal identity, which is consistent and never aliased
580 strcpy(CC->cs_principal_id, "");
581 makeuserkey(CC->cs_principal_id, CC->user.fullname);
582 strcat(CC->cs_principal_id, "@");
583 strcat(CC->cs_principal_id, CtdlGetConfigStr("c_fqdn"));
585 // Populate cs_inet_email and cs_inet_other_emails with valid email addresses from the user record
586 strcpy(CC->cs_inet_email, CC->user.emailaddrs);
587 char *firstsep = strstr(CC->cs_inet_email, "|");
589 strcpy(CC->cs_inet_other_emails, firstsep+1);
593 CC->cs_inet_other_emails[0] = 0;
596 // Create any personal rooms required by the system.
597 // (Technically, MAILROOM should be there already, but just in case...)
598 CtdlCreateRoom(MAILROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
599 CtdlCreateRoom(SENTITEMS, 4, "", 0, 1, 0, VIEW_MAILBOX);
600 CtdlCreateRoom(USERTRASHROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
601 CtdlCreateRoom(USERDRAFTROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
603 // Run any startup routines registered by loadable modules
604 PerformSessionHooks(EVT_LOGIN);
607 CtdlUserGoto(CtdlGetConfigStr("c_baseroom"), 0, 0, NULL, NULL, NULL, NULL);
611 void logged_in_response(void) {
612 cprintf("%d %s|%d|0|0|%u|%ld|%ld\n",
613 CIT_OK, CC->user.fullname, CC->user.axlevel,
614 CC->user.flags, CC->user.usernum,
620 void CtdlUserLogout(void) {
622 syslog(LOG_DEBUG, "user_ops: CtdlUserLogout() logging out <%s> from session %d", CC->curr_user, CC->cs_pid);
624 // Run any hooks registered by modules...
625 PerformSessionHooks(EVT_LOGOUT);
627 // Clear out some session data. Most likely, the CitContext for this
628 // session is about to get nuked when the session disconnects, but
629 // since it's possible to log in again without reconnecting, we cannot
630 // make that assumption.
633 // Check to see if the user was deleted while logged in and purge them if necessary
634 if ((CC->user.axlevel == AxDeleted) && (CC->user.usernum)) {
635 purge_user(CC->user.fullname);
638 // Clear out the user record in memory so we don't behave like a ghost
639 memset(&CC->user, 0, sizeof(struct ctdluser));
640 CC->curr_user[0] = 0;
641 CC->cs_inet_email[0] = 0;
642 CC->cs_inet_other_emails[0] = 0;
643 CC->cs_inet_fn[0] = 0;
645 // Free any output buffers
650 // Validate a password on the host unix system by talking to the chkpwd daemon
651 static int validpw(uid_t uid, const char *pass) {
655 if (IsEmptyStr(pass)) {
656 syslog(LOG_DEBUG, "user_ops: refusing to chkpwd for uid=%d with empty password", uid);
660 syslog(LOG_DEBUG, "user_ops: validating password for uid=%d using chkpwd...", uid);
662 begin_critical_section(S_CHKPWD);
663 rv = write(chkpwd_write_pipe[1], &uid, sizeof(uid_t));
665 syslog(LOG_ERR, "user_ops: communication with chkpwd broken: %m");
666 end_critical_section(S_CHKPWD);
669 rv = write(chkpwd_write_pipe[1], pass, 256);
671 syslog(LOG_ERR, "user_ops: communication with chkpwd broken: %m");
672 end_critical_section(S_CHKPWD);
675 rv = read(chkpwd_read_pipe[0], buf, 4);
677 syslog(LOG_ERR, "user_ops: ommunication with chkpwd broken: %m");
678 end_critical_section(S_CHKPWD);
681 end_critical_section(S_CHKPWD);
683 if (!strncmp(buf, "PASS", 4)) {
684 syslog(LOG_DEBUG, "user_ops: chkpwd pass");
688 syslog(LOG_DEBUG, "user_ops: chkpwd fail");
693 // Start up the chkpwd daemon so validpw() has something to talk to
694 void start_chkpwd_daemon(void) {
696 struct stat filestats;
699 syslog(LOG_DEBUG, "user_ops: starting chkpwd daemon for host authentication mode");
701 if ((stat(file_chkpwd, &filestats)==-1) || (filestats.st_size==0)) {
702 syslog(LOG_ERR, "user_ops: %s: %m", file_chkpwd);
703 exit(CTDLEXIT_CHKPWD);
705 if (pipe(chkpwd_write_pipe) != 0) {
706 syslog(LOG_ERR, "user_ops: unable to create pipe for chkpwd daemon: %m");
707 exit(CTDLEXIT_CHKPWD);
709 if (pipe(chkpwd_read_pipe) != 0) {
710 syslog(LOG_ERR, "user_ops: unable to create pipe for chkpwd daemon: %m");
711 exit(CTDLEXIT_CHKPWD);
715 if (chkpwd_pid < 0) {
716 syslog(LOG_ERR, "user_ops: unable to fork chkpwd daemon: %m");
717 exit(CTDLEXIT_CHKPWD);
719 if (chkpwd_pid == 0) {
720 dup2(chkpwd_write_pipe[0], 0);
721 dup2(chkpwd_read_pipe[1], 1);
722 for (i=2; i<256; ++i) close(i);
723 execl(file_chkpwd, file_chkpwd, NULL);
724 syslog(LOG_ERR, "user_ops: unable to exec chkpwd daemon: %m");
730 int CtdlTryPassword(const char *password, long len) {
733 if ((CC->logged_in)) {
734 syslog(LOG_WARNING, "user_ops: CtdlTryPassword: already logged in");
735 return pass_already_logged_in;
737 if (!strcmp(CC->curr_user, NLI)) {
738 syslog(LOG_WARNING, "user_ops: CtdlTryPassword: no user selected");
741 if (CtdlGetUser(&CC->user, CC->curr_user)) {
742 syslog(LOG_ERR, "user_ops: CtdlTryPassword: internal error");
743 return pass_internal_error;
745 if (password == NULL) {
746 syslog(LOG_INFO, "user_ops: CtdlTryPassword: NULL password string supplied");
747 return pass_wrong_password;
751 else if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
752 if (validpw(CC->user.uid, password)) {
755 // sooper-seekrit hack: populate the password field in the
756 // citadel database with the password that the user typed,
757 // if it's correct. This allows most sites to convert from
758 // host auth to native auth if they want to. If you think
759 // this is a security hazard, comment it out.
761 CtdlGetUserLock(&CC->user, CC->curr_user);
762 safestrncpy(CC->user.password, password, sizeof CC->user.password);
763 CtdlPutUserLock(&CC->user);
765 // (sooper-seekrit hack ends here)
773 else if ((CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP) || (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD)) {
775 if ((CC->ldap_dn) && (!CtdlTryPasswordLDAP(CC->ldap_dn, password))) {
783 // native auth mode...
787 pw = (char*) malloc(len + 1);
788 memcpy(pw, password, len + 1);
790 strproc(CC->user.password);
791 code = strcasecmp(CC->user.password, pw);
794 strproc(CC->user.password);
795 code = strcasecmp(CC->user.password, pw);
805 syslog(LOG_WARNING, "user_ops: bad password specified for <%s> Service <%s> Port <%ld> Remote <%s / %s>",
812 return pass_wrong_password;
817 // Delete a user record *and* all of its related resources.
818 int purge_user(char pname[]) {
819 struct ctdluser usbuf;
820 char usernamekey[USERNAME_SIZE];
822 makeuserkey(usernamekey, pname);
824 // If the name is empty we can't find them in the DB any way so just return
825 if (IsEmptyStr(pname)) {
826 return(ERROR + NO_SUCH_USER);
829 if (CtdlGetUser(&usbuf, pname) != 0) {
830 syslog(LOG_ERR, "user_ops: cannot purge user <%s> - not found", pname);
831 return(ERROR + NO_SUCH_USER);
834 // Don't delete a user who is currently logged in. Instead, just
835 // set the access level to 0, and let the account get swept up
836 // during the next purge.
837 if (CtdlIsUserLoggedInByNum(usbuf.usernum)) {
838 syslog(LOG_WARNING, "user_ops: <%s> is logged in; not deleting", pname);
839 usbuf.axlevel = AxDeleted;
844 syslog(LOG_NOTICE, "user_ops: deleting <%s>", pname);
846 // Perform any purge functions registered by server extensions
847 PerformUserHooks(&usbuf, EVT_PURGEUSER);
849 // delete any existing user/room relationships
850 // Commenting out since it was assuming the user number was
851 // at the top of the index. Room number is actually first.
852 // Auto-Purge will clean up the records later, so not worth
853 // scanning all the records here.
854 //cdb_delete(CDB_VISIT, &usbuf.usernum, sizeof(long));
856 // delete the users-by-number index record
857 cdb_delete(CDB_USERSBYNUMBER, &usbuf.usernum, sizeof(long));
859 // delete the user entry
860 cdb_delete(CDB_USERS, usernamekey, strlen(usernamekey));
866 // This is the back end processing that happens when we create a new user account.
867 int internal_create_user(char *username, struct ctdluser *usbuf, uid_t uid) {
868 if (!CtdlGetUser(usbuf, username)) {
869 return(ERROR + ALREADY_EXISTS);
872 // Go ahead and initialize a new user record
873 memset(usbuf, 0, sizeof(struct ctdluser));
874 safestrncpy(usbuf->fullname, username, sizeof usbuf->fullname);
875 strcpy(usbuf->password, "");
878 // These are the default flags on new accounts
879 usbuf->flags = US_LASTOLD | US_DISAPPEAR | US_PAGINATOR | US_FLOORS;
880 usbuf->axlevel = CtdlGetConfigInt("c_initax");
881 usbuf->lastcall = time(NULL);
883 // fetch a new user number
884 usbuf->usernum = get_new_user_number();
886 // add user to the database
888 cdb_store(CDB_USERSBYNUMBER, &usbuf->usernum, sizeof(long), usbuf->fullname, strlen(usbuf->fullname)+1);
890 // If non-native auth, index by uid
891 if ((usbuf->uid > 0) && (usbuf->uid != NATIVE_AUTH_UID)) {
892 StrBuf *claimed_id = NewStrBuf();
893 StrBufPrintf(claimed_id, "uid:%d", usbuf->uid);
894 FreeStrBuf(&claimed_id);
901 // create_user() - back end processing to create a new user
903 // Set 'newusername' to the desired account name.
904 // Set 'become_user' to CREATE_USER_BECOME_USER if this is self-service account creation and we want to
905 // actually log in as the user we just created, otherwise set it to CREATE_USER_DO_NOT_BECOME_USER
906 // Set 'uid' to some uid_t value to associate the account with an external auth user, or (-1) for native auth
907 int create_user(char *username, int become_user, uid_t uid) {
908 struct ctdluser usbuf;
909 struct ctdlroom qrbuf;
910 char mailboxname[ROOMNAMELEN];
915 if ((retval = internal_create_user(username, &usbuf, uid)) != 0) {
919 // Give the user a private mailbox and a configuration room.
920 // Make the latter an invisible system room.
921 CtdlMailboxName(mailboxname, sizeof mailboxname, &usbuf, MAILROOM);
922 CtdlCreateRoom(mailboxname, 5, "", 0, 1, 1, VIEW_MAILBOX);
924 CtdlMailboxName(mailboxname, sizeof mailboxname, &usbuf, USERCONFIGROOM);
925 CtdlCreateRoom(mailboxname, 5, "", 0, 1, 1, VIEW_BBS);
926 if (CtdlGetRoomLock(&qrbuf, mailboxname) == 0) {
927 qrbuf.QRflags2 |= QR2_SYSTEM;
928 CtdlPutRoomLock(&qrbuf);
931 // Perform any create functions registered by server extensions
932 PerformUserHooks(&usbuf, EVT_NEWUSER);
934 // Everything below this line can be bypassed if administratively
935 // creating a user, instead of doing self-service account creation
937 if (become_user == CREATE_USER_BECOME_USER) {
938 // Now become the user we just created
939 memcpy(&CC->user, &usbuf, sizeof(struct ctdluser));
940 safestrncpy(CC->curr_user, username, sizeof CC->curr_user);
943 // Check to make sure we're still who we think we are
944 if (CtdlGetUser(&CC->user, CC->curr_user)) {
945 return(ERROR + INTERNAL_ERROR);
950 "New user account <%s> has been created, from host %s [%s].\n",
955 CtdlAideMessage(buf, "User Creation Notice");
956 syslog(LOG_NOTICE, "user_ops: <%s> created", username);
961 // set password - back end api code
962 void CtdlSetPassword(char *new_pw) {
963 CtdlGetUserLock(&CC->user, CC->curr_user);
964 safestrncpy(CC->user.password, new_pw, sizeof(CC->user.password));
965 CtdlPutUserLock(&CC->user);
966 syslog(LOG_INFO, "user_ops: password changed for <%s>", CC->curr_user);
967 PerformSessionHooks(EVT_SETPASS);
971 // API function for cmd_invt_kick() and anything else that needs to
972 // invite or kick out a user to/from a room.
974 // Set iuser to the name of the user, and op to 1=invite or 0=kick
975 int CtdlInvtKick(char *iuser, int op) {
976 struct ctdluser USscratch;
980 if (CtdlGetUser(&USscratch, iuser) != 0) {
984 CtdlGetRelationship(&vbuf, &USscratch, &CC->room);
986 vbuf.v_flags = vbuf.v_flags & ~V_FORGET & ~V_LOCKOUT;
987 vbuf.v_flags = vbuf.v_flags | V_ACCESS;
990 vbuf.v_flags = vbuf.v_flags & ~V_ACCESS;
991 vbuf.v_flags = vbuf.v_flags | V_FORGET | V_LOCKOUT;
993 CtdlSetRelationship(&vbuf, &USscratch, &CC->room);
995 // post a message in Aide> saying what we just did
996 snprintf(bbb, sizeof bbb, "%s has been %s \"%s\" by %s.\n",
998 ((op == 1) ? "invited to" : "kicked out of"),
1000 (CC->logged_in ? CC->user.fullname : "an administrator")
1002 CtdlAideMessage(bbb,"User Admin Message");
1007 // Forget (Zap) the current room (API call)
1008 // Returns 0 on success
1009 int CtdlForgetThisRoom(void) {
1012 // On some systems, Admins are not allowed to forget rooms
1013 if (is_aide() && (CtdlGetConfigInt("c_aide_zap") == 0)
1014 && ((CC->room.QRflags & QR_MAILBOX) == 0) ) {
1018 CtdlGetUserLock(&CC->user, CC->curr_user);
1019 CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
1021 vbuf.v_flags = vbuf.v_flags | V_FORGET;
1022 vbuf.v_flags = vbuf.v_flags & ~V_ACCESS;
1024 CtdlSetRelationship(&vbuf, &CC->user, &CC->room);
1025 CtdlPutUserLock(&CC->user);
1027 // Return to the Lobby, so we don't end up in an undefined room
1028 CtdlUserGoto(CtdlGetConfigStr("c_baseroom"), 0, 0, NULL, NULL, NULL, NULL);
1033 // Traverse the user file and perform a callback for each user record.
1034 // (New improved version that runs in two phases so that callbacks can perform writes without having a r/o cursor open)
1035 void ForEachUser(void (*CallBack) (char *, void *out_data), void *in_data) {
1036 struct cdbdata *cdbus;
1037 struct ctdluser *usptr;
1039 Array *all_users = array_new(USERNAME_SIZE);
1040 if (all_users == NULL) {
1041 syslog(LOG_ERR, "user_ops: alloc failed, ForEachUser() exiting");
1046 cdb_rewind(CDB_USERS);
1048 // Phase 1 : build an array of all our user account names
1049 while (cdbus = cdb_next_item(CDB_USERS), cdbus != NULL) {
1050 usptr = (struct ctdluser *) cdbus->ptr;
1051 if (strlen(usptr->fullname) > 0) {
1052 array_append(all_users, usptr->fullname);
1056 // Phase 2 : perform the callback for each user while de-allocating the list
1057 for (int i=0; i<array_len(all_users); ++i) {
1058 (*CallBack) (array_get_element_at(all_users, i), in_data);
1061 // Phase 3 : free the array
1062 array_free(all_users);
1066 // Return the number of new messages that have arrived in the user's inbox while they were logged in.
1067 // Resets to zero when called.
1068 int NewMailCount() {
1069 int num_newmsgs = 0;
1070 num_newmsgs = CC->newmail;
1072 return(num_newmsgs);
1076 // Count the number of new mail messages the user has
1077 int InitialMailCheck() {
1078 int num_newmsgs = 0;
1080 char mailboxname[ROOMNAMELEN];
1081 struct ctdlroom mailbox;
1083 struct cdbdata *cdbfr;
1084 long *msglist = NULL;
1087 CtdlMailboxName(mailboxname, sizeof mailboxname, &CC->user, MAILROOM);
1088 if (CtdlGetRoom(&mailbox, mailboxname) != 0)
1090 CtdlGetRelationship(&vbuf, &CC->user, &mailbox);
1092 cdbfr = cdb_fetch(CDB_MSGLISTS, &mailbox.QRnumber, sizeof(long));
1094 if (cdbfr != NULL) {
1095 msglist = malloc(cdbfr->len);
1096 memcpy(msglist, cdbfr->ptr, cdbfr->len);
1097 num_msgs = cdbfr->len / sizeof(long);
1101 for (a = 0; a < num_msgs; ++a) {
1102 if (msglist[a] > 0L) {
1103 if (msglist[a] > vbuf.v_lastseen) {
1108 if (msglist != NULL)
1111 return(num_newmsgs);
1115 // This is an undocumented rescue mode that can be used to rewrite an admin user account that has been corrupted.
1116 // To prevent abuse, it can only run as a one-shot when the server is not otherwise operational.
1117 // Don't use this without asking about it.
1118 void undocumented_rescue_mode(char *rescue_string) {
1119 struct ctdluser usbuf;
1120 memset(&usbuf, 0, sizeof(struct ctdluser));
1121 extract_token(usbuf.fullname, rescue_string, 0, '|', sizeof usbuf.password);
1122 extract_token(usbuf.password, rescue_string, 1, '|', sizeof usbuf.password);
1123 usbuf.usernum = extract_long(rescue_string, 2);
1125 usbuf.lastcall = time(NULL);
1126 CtdlPutUser(&usbuf);