rescue mode
[citadel.git] / citadel / server / user_ops.c
1 // Server functions which perform operations on user objects.
2 //
3 // Copyright (c) 1987-2023 by the citadel.org team
4 //
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.
7
8 #include <stdlib.h>
9 #include <unistd.h>
10 #include "sysdep.h"
11 #include <stdio.h>
12 #include <sys/stat.h>
13 #include <libcitadel.h>
14 #include "control.h"
15 #include "support.h"
16 #include "citserver.h"
17 #include "config.h"
18 #include "citadel_ldap.h"
19 #include "ctdl_module.h"
20 #include "user_ops.h"
21 #include "internet_addressing.h"
22
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];
26
27
28 // makeuserkey() - convert a username into the format used as a database key
29 //              "key" must be a buffer of at least USERNAME_SIZE
30 //              (Key format is the username with all non-alphanumeric characters removed, and converted to lower case.)
31 void makeuserkey(char *key, const char *username) {
32         int i;
33         int keylen = 0;
34
35         if (IsEmptyStr(username)) {
36                 key[0] = 0;
37                 return;
38         }
39
40         int len = strlen(username);
41         for (i=0; ((i<=len) && (i<USERNAME_SIZE-1)); ++i) {
42                 if (isalnum((username[i]))) {
43                         key[keylen++] = tolower(username[i]);
44                 }
45         }
46         key[keylen++] = 0;
47 }
48
49
50 // Compare two usernames to see if they are the same user after being keyed for the database
51 // Usage is identical to strcmp()
52 int CtdlUserCmp(char *s1, char *s2) {
53         char k1[USERNAME_SIZE];
54         char k2[USERNAME_SIZE];
55
56         makeuserkey(k1, s1);
57         makeuserkey(k2, s2);
58         return(strcmp(k1,k2));
59 }
60
61
62 // CtdlGetUser()        retrieve named user into supplied buffer.
63 //                      returns 0 on success
64 int CtdlGetUser(struct ctdluser *usbuf, char *name) {
65         char usernamekey[USERNAME_SIZE];
66         struct cdbdata *cdbus;
67
68         if (usbuf != NULL) {
69                 memset(usbuf, 0, sizeof(struct ctdluser));
70         }
71
72         makeuserkey(usernamekey, name);
73         if (IsEmptyStr(usernamekey)) {
74                 return(1);      // empty user name
75         }
76         cdbus = cdb_fetch(CDB_USERS, usernamekey, strlen(usernamekey));
77
78         if (cdbus == NULL) {    // user not found
79                 return(1);
80         }
81         if (usbuf != NULL) {
82                 memcpy(usbuf, cdbus->ptr, ((cdbus->len > sizeof(struct ctdluser)) ?  sizeof(struct ctdluser) : cdbus->len));
83         }
84         cdb_free(cdbus);
85         return(0);
86 }
87
88
89 int CtdlLockGetCurrentUser(void) {
90         return CtdlGetUser(&CC->user, CC->curr_user);
91 }
92
93
94 // CtdlGetUserLock()  -  same as getuser() but locks the record
95 int CtdlGetUserLock(struct ctdluser *usbuf, char *name) {
96         int retcode;
97
98         retcode = CtdlGetUser(usbuf, name);
99         if (retcode == 0) {
100                 begin_critical_section(S_USERS);
101         }
102         return(retcode);
103 }
104
105
106 // CtdlPutUser()  -  write user buffer into the correct place on disk
107 void CtdlPutUser(struct ctdluser *usbuf) {
108         char usernamekey[USERNAME_SIZE];
109         makeuserkey(usernamekey, usbuf->fullname);
110         usbuf->version = REV_LEVEL;
111         cdb_store(CDB_USERS, usernamekey, strlen(usernamekey), usbuf, sizeof(struct ctdluser));
112 }
113
114
115 void CtdlPutCurrentUserLock() {
116         CtdlPutUser(&CC->user);
117 }
118
119
120 // CtdlPutUserLock()  -  same as putuser() but locks the record
121 void CtdlPutUserLock(struct ctdluser *usbuf) {
122         CtdlPutUser(usbuf);
123         end_critical_section(S_USERS);
124 }
125
126
127 // rename_user()  -  this is tricky because the user's display name is the database key
128 // Returns 0 on success or nonzero if there was an error...
129 int rename_user(char *oldname, char *newname) {
130         int retcode = RENAMEUSER_OK;
131         struct ctdluser usbuf;
132
133         char oldnamekey[USERNAME_SIZE];
134         char newnamekey[USERNAME_SIZE];
135
136         // Create the database keys...
137         makeuserkey(oldnamekey, oldname);
138         makeuserkey(newnamekey, newname);
139
140         // Lock up and get going
141         begin_critical_section(S_USERS);
142
143         // We cannot rename a user who is currently logged in
144         if (CtdlIsUserLoggedIn(oldname)) {
145                 end_critical_section(S_USERS);
146                 return RENAMEUSER_LOGGED_IN;
147         }
148
149         if (CtdlGetUser(&usbuf, newname) == 0) {
150                 retcode = RENAMEUSER_ALREADY_EXISTS;
151         }
152         else {
153
154                 if (CtdlGetUser(&usbuf, oldname) != 0) {
155                         retcode = RENAMEUSER_NOT_FOUND;
156                 }
157                 else {          // Sanity checks succeeded.  Now rename the user.
158                         if (usbuf.usernum == 0) {
159                                 syslog(LOG_DEBUG, "user_ops: can not rename user \"Citadel\".");
160                                 retcode = RENAMEUSER_NOT_FOUND;
161                         }
162                         else {
163                                 syslog(LOG_DEBUG, "user_ops: renaming <%s> to <%s>", oldname, newname);
164                                 cdb_delete(CDB_USERS, oldnamekey, strlen(oldnamekey));
165                                 safestrncpy(usbuf.fullname, newname, sizeof usbuf.fullname);
166                                 CtdlPutUser(&usbuf);
167                                 cdb_store(CDB_USERSBYNUMBER, &usbuf.usernum, sizeof(long), usbuf.fullname, strlen(usbuf.fullname)+1 );
168                                 retcode = RENAMEUSER_OK;
169                         }
170                 }
171         
172         }
173
174         end_critical_section(S_USERS);
175         return(retcode);
176 }
177
178
179 // Convert a username into the format used as a database key prior to version 928
180 // This only gets called by reindex_user_928()
181 void makeuserkey_pre928(char *key, const char *username) {
182         int i;
183
184         int len = strlen(username);
185
186         if (len >= USERNAME_SIZE) {
187                 syslog(LOG_INFO, "Username too long: %s", username);
188                 len = USERNAME_SIZE - 1; 
189         }
190         for (i=0; i<=len; ++i) {
191                 key[i] = tolower(username[i]);
192         }
193 }
194
195
196 // Read a user record using the pre-v928 index format, and write it back using the v928-and-higher index format.
197 // This ONLY gets called during an upgrade from version <928 to version >=928.
198 void reindex_user_928(char *username, void *out_data) {
199
200         char oldkey[USERNAME_SIZE];
201         char newkey[USERNAME_SIZE];
202         struct cdbdata *cdbus;
203         struct ctdluser usbuf;
204
205         makeuserkey_pre928(oldkey, username);
206         makeuserkey(newkey, username);
207
208         syslog(LOG_DEBUG, "user_ops: reindex_user_928: %s <%s> --> <%s>", username, oldkey, newkey);
209
210         // Fetch the user record using the old index format
211         cdbus = cdb_fetch(CDB_USERS, oldkey, strlen(oldkey));
212         if (cdbus == NULL) {
213                 syslog(LOG_INFO, "user_ops: <%s> not found, were they already reindexed?", username);
214                 return;
215         }
216         memcpy(&usbuf, cdbus->ptr, ((cdbus->len > sizeof(struct ctdluser)) ? sizeof(struct ctdluser) : cdbus->len));
217         cdb_free(cdbus);
218
219         // delete the old record
220         cdb_delete(CDB_USERS, oldkey, strlen(oldkey));
221
222         // write the new record
223         cdb_store(CDB_USERS, newkey, strlen(newkey), &usbuf, sizeof(struct ctdluser));
224 }
225
226
227 // Index-generating function used by Ctdl[Get|Set]Relationship
228 int GenerateRelationshipIndex(char *IndexBuf, long RoomID, long RoomGen, long UserID) {
229         struct visit_index TheIndex;
230         TheIndex.iRoomID = RoomID;
231         TheIndex.iRoomGen = RoomGen;
232         TheIndex.iUserID = UserID;
233
234         memcpy(IndexBuf, &TheIndex, sizeof(TheIndex));
235         return(sizeof(TheIndex));
236 }
237
238 // Back end for CtdlSetRelationship()
239 void put_visit(struct visit *newvisit) {
240         cdb_store(CDB_VISIT, newvisit, (sizeof(long)*3), newvisit, sizeof(struct visit));
241 }
242
243
244 // Define a relationship between a user and a room
245 void CtdlSetRelationship(struct visit *newvisit, struct ctdluser *rel_user, struct ctdlroom *rel_room) {
246         // We don't use these in Citadel because they're implicit by the
247         // index, but they must be present if the database is exported.
248         newvisit->v_roomnum = rel_room->QRnumber;
249         newvisit->v_roomgen = rel_room->QRgen;
250         newvisit->v_usernum = rel_user->usernum;
251
252         // Store the record
253         put_visit(newvisit);
254 }
255
256
257 // Locate a relationship between a user and a room
258 void CtdlGetRelationship(struct visit *vbuf, struct ctdluser *rel_user, struct ctdlroom *rel_room) {
259         struct cdbdata *cdbvisit;
260
261         // Clear out the buffer
262         memset(vbuf, 0, sizeof(struct visit));
263
264         // Fill out the first three fields; they are also the index
265         vbuf->v_roomnum = rel_room->QRnumber;
266         vbuf->v_roomgen = rel_room->QRgen;
267         vbuf->v_usernum = rel_user->usernum;
268
269         cdbvisit = cdb_fetch(CDB_VISIT, vbuf, (sizeof(long)*3));
270         if (cdbvisit != NULL) {
271                 memcpy(vbuf, cdbvisit->ptr, ((cdbvisit->len > sizeof(struct visit)) ?  sizeof(struct visit) : cdbvisit->len));
272                 cdb_free(cdbvisit);
273         }
274         else {
275                 // If this is the first time the user has seen this room, set the view to be the default for the room.
276                 vbuf->v_view = rel_room->QRdefaultview;
277         }
278
279         // Set v_seen if necessary
280         if (vbuf->v_seen[0] == 0) {
281                 snprintf(vbuf->v_seen, sizeof vbuf->v_seen, "*:%ld", vbuf->v_lastseen);
282         }
283 }
284
285
286 void CtdlMailboxName(char *buf, size_t n, const struct ctdluser *who, const char *prefix) {
287         snprintf(buf, n, "%010ld.%s", who->usernum, prefix);
288 }
289
290
291 // Check to see if the specified user has Internet mail permission
292 // (returns nonzero if permission is granted)
293 int CtdlCheckInternetMailPermission(struct ctdluser *who) {
294
295         // Do not allow twits to send Internet mail
296         if (who->axlevel <= AxProbU) return(0);
297
298         // Globally enabled?
299         if (CtdlGetConfigInt("c_restrict") == 0) return(1);
300
301         // User flagged ok?
302         if (who->flags & US_INTERNET) return(2);
303
304         // Admin level access?
305         if (who->axlevel >= AxAideU) return(3);
306
307         // No mail for you!
308         return(0);
309 }
310
311
312 // This is a convenience function which follows the Citadel protocol semantics for most commands.
313 // If the current user does not have the requested access level, it outputs a protocol-friendly error message
314 // and then returns (-1).  This allows calling functions to complete an access level check in one line of code.
315 int CtdlAccessCheck(int required_level) {
316         if (CC->internal_pgm) return(0);
317         if (required_level >= ac_internal) {
318                 cprintf("%d This is not a user-level command.\n", ERROR + HIGHER_ACCESS_REQUIRED);
319                 return(-1);
320         }
321
322         if ((required_level >= ac_logged_in_or_guest) && (CC->logged_in == 0) && (CtdlGetConfigInt("c_guest_logins") == 0)) {
323                 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
324                 return(-1);
325         }
326
327         if ((required_level >= ac_logged_in) && (CC->logged_in == 0)) {
328                 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
329                 return(-1);
330         }
331
332         if (CC->user.axlevel >= AxAideU) return(0);
333         if (required_level >= ac_aide) {
334                 cprintf("%d This command requires Admin access.\n",
335                         ERROR + HIGHER_ACCESS_REQUIRED);
336                 return(-1);
337         }
338
339         if (is_room_aide()) return(0);
340         if (required_level >= ac_room_aide) {
341                 cprintf("%d This command requires Admin or Room Admin access.\n",
342                         ERROR + HIGHER_ACCESS_REQUIRED);
343                 return(-1);
344         }
345
346         // Do not generate any output if we succeeded -- the calling function will handle that.
347         return(0);
348 }
349
350
351 // Is the user currently logged in an Admin?
352 int is_aide(void) {
353         if (CC->user.axlevel >= AxAideU) {
354                 return(1);
355         }
356         else {
357                 return(0);
358         }
359 }
360
361
362 // Is the user currently logged in an Admin *or* the room Admin for this room?
363 int is_room_aide(void) {
364         if (!CC->logged_in) {
365                 return(0);
366         }
367
368         if ((CC->user.axlevel >= AxAideU) || (CC->room.QRroomaide == CC->user.usernum)) {
369                 return(1);
370         }
371         else {
372                 return(0);
373         }
374 }
375
376
377 // CtdlGetUserByNumber() - get user by number, returns 0 if user was found
378 // Note: fetching a user this way requires one additional database operation.
379 int CtdlGetUserByNumber(struct ctdluser *usbuf, long number) {
380         struct cdbdata *cdbun;
381         int r;
382
383         cdbun = cdb_fetch(CDB_USERSBYNUMBER, &number, sizeof(long));
384         if (cdbun == NULL) {
385                 syslog(LOG_INFO, "user_ops: %ld not found", number);
386                 return(-1);
387         }
388
389         syslog(LOG_INFO, "user_ops: %ld maps to %s", number, cdbun->ptr);
390         r = CtdlGetUser(usbuf, cdbun->ptr);
391         cdb_free(cdbun);
392         return(r);
393 }
394
395
396 // Helper function for rebuild_usersbynumber()
397 void rebuild_ubn_for_user(char *username, void *data) {
398         struct ctdluser u;
399
400         syslog(LOG_DEBUG, "user_ops: rebuilding usersbynumber index for %s", username);
401         if (CtdlGetUser(&u, username) == 0) {
402                 cdb_store(CDB_USERSBYNUMBER, &(u.usernum), sizeof(long), u.fullname, strlen(u.fullname)+1);
403         }
404 }
405
406
407 // Rebuild the users-by-number index
408 void rebuild_usersbynumber(void) {
409         cdb_trunc(CDB_USERSBYNUMBER);                   // delete the old indices
410         ForEachUser(rebuild_ubn_for_user, NULL);        // enumerate the users
411 }
412
413
414 // getuserbyuid()       Get user by system uid (for PAM mode authentication)
415 //                      Returns 0 if user was found
416 int getuserbyuid(struct ctdluser *usbuf, uid_t number) {
417
418         struct cdbdata *cdbus;
419         struct ctdluser *usptr;
420         int return_value = (-1);
421
422         // Yes, we do this the long way.
423         // No, we don't use CtdlForEachUser() because that requires multiple reads for each record
424         // TODO: make an index
425         cdb_rewind(CDB_USERS);
426         while (cdbus = cdb_next_item(CDB_USERS), cdbus != NULL) {
427                 usptr = (struct ctdluser *) cdbus->ptr;
428
429                 if (usptr->uid == number) {
430                         syslog(LOG_DEBUG, "user_ops: found uid=%d username=%s", usptr->uid, usptr->fullname);
431                         memcpy(usbuf, usptr, sizeof(struct ctdluser));
432                         return_value = 0;       // success
433                 }
434         }
435
436         if (return_value != 0) {
437                 syslog(LOG_DEBUG, "user_ops: no user found with uid=%d", number);
438         }
439         return(return_value);
440 }
441
442
443 // Back end for cmd_user() and its ilk
444 int CtdlLoginExistingUser(const char *trythisname) {
445         char username[SIZ];
446         int found_user;
447
448         syslog(LOG_DEBUG, "user_ops: CtdlLoginExistingUser(%s)", trythisname);
449
450         if ((CC->logged_in)) {
451                 return login_already_logged_in;
452         }
453
454         if (trythisname == NULL) return login_not_found;
455         
456         // We handle this a different way now (see below)
457         //if (!strncasecmp(trythisname, "SYS_", 4)) {
458                 //syslog(LOG_DEBUG, "user_ops: system user \"%s\" is not allowed to log in.", trythisname);
459                 //return login_not_found;
460         //}
461
462         // Continue attempting user validation...
463         safestrncpy(username, trythisname, sizeof (username));
464         string_trim(username);
465
466         if (IsEmptyStr(username)) {
467                 return login_not_found;
468         }
469
470         // host auth mode...
471         if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
472                 struct passwd pd;
473                 struct passwd *tempPwdPtr;
474                 char pwdbuffer[256];
475         
476                 syslog(LOG_DEBUG, "user_ops: asking host about <%s>", username);
477 #ifdef HAVE_GETPWNAM_R
478                 syslog(LOG_DEBUG, "user_ops: calling getpwnam_r()");
479                 getpwnam_r(username, &pd, pwdbuffer, sizeof pwdbuffer, &tempPwdPtr);
480 #else // HAVE_GETPWNAM_R
481                 syslog(LOG_DEBUG, "user_ops: SHOULD NEVER GET HERE!!!");
482                 tempPwdPtr = NULL;
483 #endif // HAVE_GETPWNAM_R
484                 if (tempPwdPtr == NULL) {
485                         syslog(LOG_DEBUG, "user_ops: no such user <%s>", username);
486                         return login_not_found;
487                 }
488         
489                 // Locate the associated Citadel account.  If not found, make one attempt to create it.
490                 found_user = getuserbyuid(&CC->user, pd.pw_uid);
491                 if (found_user != 0) {
492                         create_user(username, CREATE_USER_DO_NOT_BECOME_USER, pd.pw_uid);
493                         found_user = getuserbyuid(&CC->user, pd.pw_uid);
494                 }
495                 syslog(LOG_DEBUG, "user_ops: found it: uid=%ld, gecos=%s here: %d", (long)pd.pw_uid, pd.pw_gecos, found_user);
496
497         }
498
499         // LDAP auth mode...
500         else if ((CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP) || (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD)) {
501
502                 uid_t ldap_uid;
503                 char ldap_cn[256];
504                 char ldap_dn[256];
505
506                 found_user = CtdlTryUserLDAP(username, ldap_dn, sizeof ldap_dn, ldap_cn, sizeof ldap_cn, &ldap_uid);
507                 if (found_user != 0) {
508                         return login_not_found;
509                 }
510
511                 found_user = getuserbyuid(&CC->user, ldap_uid);
512                 if (found_user != 0) {
513                         create_user(ldap_cn, CREATE_USER_DO_NOT_BECOME_USER, ldap_uid);
514                         found_user = getuserbyuid(&CC->user, ldap_uid);
515                 }
516
517                 if (found_user == 0) {
518                         if (CC->ldap_dn != NULL) free(CC->ldap_dn);
519                         CC->ldap_dn = strdup(ldap_dn);
520                 }
521
522         }
523
524         // native auth mode...
525         else {
526                 struct recptypes *valid = NULL;
527         
528                 // First, try to log in as if the supplied name is a display name
529                 found_user = CtdlGetUser(&CC->user, username);
530         
531                 // If that didn't work, try to log in as if the supplied name * is an e-mail address
532                 if (found_user != 0) {
533                         valid = validate_recipients(username, NULL, 0);
534                         if (valid != NULL) {
535                                 if (valid->num_local == 1) {
536                                         found_user = CtdlGetUser(&CC->user, valid->recp_local);
537                                 }
538                                 free_recipients(valid);
539                         }
540                 }
541         }
542
543         // User 0 is a system account and must not be used by a real user
544         if (CC->user.usernum <= 0) {
545                 syslog(LOG_DEBUG, "user_ops: system account <%s> is not allowed to log in.", trythisname);
546                 return login_not_found;
547         }
548
549         // Did we find something?
550         if (found_user == 0) {
551                 if (((CC->nologin)) && (CC->user.axlevel < AxAideU)) {
552                         return login_too_many_users;
553                 }
554                 else {
555                         safestrncpy(CC->curr_user, CC->user.fullname, sizeof CC->curr_user);
556                         return login_ok;
557                 }
558         }
559         return login_not_found;
560 }
561
562
563 // session startup code which is common to both cmd_pass() and cmd_newu()
564 void do_login(void) {
565         CC->logged_in = 1;
566         syslog(LOG_NOTICE, "user_ops: <%s> logged in", CC->curr_user);
567
568         CtdlGetUserLock(&CC->user, CC->curr_user);
569         ++(CC->user.timescalled);
570         CC->previous_login = CC->user.lastcall;
571         time(&CC->user.lastcall);
572
573         // If this user's name is the name of the system administrator
574         // (as specified in setup), automatically assign access level 6.
575         if ( (!IsEmptyStr(CtdlGetConfigStr("c_sysadm"))) && (!strcasecmp(CC->user.fullname, CtdlGetConfigStr("c_sysadm"))) ) {
576                 CC->user.axlevel = AxAideU;
577         }
578
579         // If we're authenticating off the host system, automatically give root the highest level of access.
580         if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
581                 if (CC->user.uid == 0) {
582                         CC->user.axlevel = AxAideU;
583                 }
584         }
585         CtdlPutUserLock(&CC->user);
586
587         // If we are using LDAP authentication, extract the user's email addresses from the directory.
588         if ((CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP) || (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD)) {
589                 char new_emailaddrs[512];
590                 if (CtdlGetConfigInt("c_ldap_sync_email_addrs") > 0) {
591                         if (extract_email_addresses_from_ldap(CC->ldap_dn, new_emailaddrs) == 0) {
592                                 CtdlSetEmailAddressesForUser(CC->user.fullname, new_emailaddrs);
593                         }
594                 }
595         }
596
597         // If the user does not have any email addresses assigned, generate one.
598         if (IsEmptyStr(CC->user.emailaddrs)) {
599                 AutoGenerateEmailAddressForUser(&CC->user);
600         }
601
602         // Populate the user principal identity, which is consistent and never aliased
603         strcpy(CC->cs_principal_id, "");
604         makeuserkey(CC->cs_principal_id, CC->user.fullname);
605         strcat(CC->cs_principal_id, "@");
606         strcat(CC->cs_principal_id, CtdlGetConfigStr("c_fqdn"));
607
608         // Populate cs_inet_email and cs_inet_other_emails with valid email addresses from the user record
609         strcpy(CC->cs_inet_email, CC->user.emailaddrs);
610         char *firstsep = strstr(CC->cs_inet_email, "|");
611         if (firstsep) {
612                 strcpy(CC->cs_inet_other_emails, firstsep+1);
613                 *firstsep = 0;
614         }
615         else {
616                 CC->cs_inet_other_emails[0] = 0;
617         }
618
619         // Create any personal rooms required by the system.
620         // (Technically, MAILROOM should be there already, but just in case...)
621         CtdlCreateRoom(MAILROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
622         CtdlCreateRoom(SENTITEMS, 4, "", 0, 1, 0, VIEW_MAILBOX);
623         CtdlCreateRoom(USERTRASHROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
624         CtdlCreateRoom(USERDRAFTROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
625
626         // Run any startup routines registered by loadable modules
627         PerformSessionHooks(EVT_LOGIN);
628
629         // Enter the lobby
630         CtdlUserGoto(CtdlGetConfigStr("c_baseroom"), 0, 0, NULL, NULL, NULL, NULL);
631 }
632
633
634 void logged_in_response(void) {
635         cprintf("%d %s|%d|%ld|%ld|%u|%ld|%ld\n",
636                 CIT_OK, CC->user.fullname, CC->user.axlevel,
637                 CC->user.timescalled, CC->user.posted,
638                 CC->user.flags, CC->user.usernum,
639                 CC->previous_login
640         );
641 }
642
643
644 void CtdlUserLogout(void) {
645
646         syslog(LOG_DEBUG, "user_ops: CtdlUserLogout() logging out <%s> from session %d", CC->curr_user, CC->cs_pid);
647
648         // Run any hooks registered by modules...
649         PerformSessionHooks(EVT_LOGOUT);
650         
651         // Clear out some session data.  Most likely, the CitContext for this
652         // session is about to get nuked when the session disconnects, but
653         // since it's possible to log in again without reconnecting, we cannot
654         // make that assumption.
655         CC->logged_in = 0;
656
657         // Check to see if the user was deleted while logged in and purge them if necessary
658         if ((CC->user.axlevel == AxDeleted) && (CC->user.usernum)) {
659                 purge_user(CC->user.fullname);
660         }
661
662         // Clear out the user record in memory so we don't behave like a ghost
663         memset(&CC->user, 0, sizeof(struct ctdluser));
664         CC->curr_user[0] = 0;
665         CC->cs_inet_email[0] = 0;
666         CC->cs_inet_other_emails[0] = 0;
667         CC->cs_inet_fn[0] = 0;
668
669         // Free any output buffers
670         unbuffer_output();
671 }
672
673
674 // Validate a password on the host unix system by talking to the chkpwd daemon
675 static int validpw(uid_t uid, const char *pass) {
676         char buf[256];
677         int rv = 0;
678
679         if (IsEmptyStr(pass)) {
680                 syslog(LOG_DEBUG, "user_ops: refusing to chkpwd for uid=%d with empty password", uid);
681                 return 0;
682         }
683
684         syslog(LOG_DEBUG, "user_ops: validating password for uid=%d using chkpwd...", uid);
685
686         begin_critical_section(S_CHKPWD);
687         rv = write(chkpwd_write_pipe[1], &uid, sizeof(uid_t));
688         if (rv == -1) {
689                 syslog(LOG_ERR, "user_ops: communication with chkpwd broken: %m");
690                 end_critical_section(S_CHKPWD);
691                 return 0;
692         }
693         rv = write(chkpwd_write_pipe[1], pass, 256);
694         if (rv == -1) {
695                 syslog(LOG_ERR, "user_ops: communication with chkpwd broken: %m");
696                 end_critical_section(S_CHKPWD);
697                 return 0;
698         }
699         rv = read(chkpwd_read_pipe[0], buf, 4);
700         if (rv == -1) {
701                 syslog(LOG_ERR, "user_ops: ommunication with chkpwd broken: %m");
702                 end_critical_section(S_CHKPWD);
703                 return 0;
704         }
705         end_critical_section(S_CHKPWD);
706
707         if (!strncmp(buf, "PASS", 4)) {
708                 syslog(LOG_DEBUG, "user_ops: chkpwd pass");
709                 return(1);
710         }
711
712         syslog(LOG_DEBUG, "user_ops: chkpwd fail");
713         return 0;
714 }
715
716
717 // Start up the chkpwd daemon so validpw() has something to talk to
718 void start_chkpwd_daemon(void) {
719         pid_t chkpwd_pid;
720         struct stat filestats;
721         int i;
722
723         syslog(LOG_DEBUG, "user_ops: starting chkpwd daemon for host authentication mode");
724
725         if ((stat(file_chkpwd, &filestats)==-1) || (filestats.st_size==0)) {
726                 syslog(LOG_ERR, "user_ops: %s: %m", file_chkpwd);
727                 exit(CTDLEXIT_CHKPWD);
728         }
729         if (pipe(chkpwd_write_pipe) != 0) {
730                 syslog(LOG_ERR, "user_ops: unable to create pipe for chkpwd daemon: %m");
731                 exit(CTDLEXIT_CHKPWD);
732         }
733         if (pipe(chkpwd_read_pipe) != 0) {
734                 syslog(LOG_ERR, "user_ops: unable to create pipe for chkpwd daemon: %m");
735                 exit(CTDLEXIT_CHKPWD);
736         }
737
738         chkpwd_pid = fork();
739         if (chkpwd_pid < 0) {
740                 syslog(LOG_ERR, "user_ops: unable to fork chkpwd daemon: %m");
741                 exit(CTDLEXIT_CHKPWD);
742         }
743         if (chkpwd_pid == 0) {
744                 dup2(chkpwd_write_pipe[0], 0);
745                 dup2(chkpwd_read_pipe[1], 1);
746                 for (i=2; i<256; ++i) close(i);
747                 execl(file_chkpwd, file_chkpwd, NULL);
748                 syslog(LOG_ERR, "user_ops: unable to exec chkpwd daemon: %m");
749                 exit(errno);
750         }
751 }
752
753
754 int CtdlTryPassword(const char *password, long len) {
755         int code;
756
757         if ((CC->logged_in)) {
758                 syslog(LOG_WARNING, "user_ops: CtdlTryPassword: already logged in");
759                 return pass_already_logged_in;
760         }
761         if (!strcmp(CC->curr_user, NLI)) {
762                 syslog(LOG_WARNING, "user_ops: CtdlTryPassword: no user selected");
763                 return pass_no_user;
764         }
765         if (CtdlGetUser(&CC->user, CC->curr_user)) {
766                 syslog(LOG_ERR, "user_ops: CtdlTryPassword: internal error");
767                 return pass_internal_error;
768         }
769         if (password == NULL) {
770                 syslog(LOG_INFO, "user_ops: CtdlTryPassword: NULL password string supplied");
771                 return pass_wrong_password;
772         }
773
774         // host auth mode...
775         else if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
776                 if (validpw(CC->user.uid, password)) {
777                         code = 0;
778
779                         // sooper-seekrit hack: populate the password field in the
780                         // citadel database with the password that the user typed,
781                         // if it's correct.  This allows most sites to convert from
782                         // host auth to native auth if they want to.  If you think
783                         // this is a security hazard, comment it out.
784
785                         CtdlGetUserLock(&CC->user, CC->curr_user);
786                         safestrncpy(CC->user.password, password, sizeof CC->user.password);
787                         CtdlPutUserLock(&CC->user);
788
789                         // (sooper-seekrit hack ends here)
790                 }
791                 else {
792                         code = (-1);
793                 }
794         }
795
796         // LDAP auth mode...
797         else if ((CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP) || (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD)) {
798
799                 if ((CC->ldap_dn) && (!CtdlTryPasswordLDAP(CC->ldap_dn, password))) {
800                         code = 0;
801                 }
802                 else {
803                         code = (-1);
804                 }
805         }
806
807         // native auth mode...
808         else {
809                 char *pw;
810
811                 pw = (char*) malloc(len + 1);
812                 memcpy(pw, password, len + 1);
813                 strproc(pw);
814                 strproc(CC->user.password);
815                 code = strcasecmp(CC->user.password, pw);
816                 if (code != 0) {
817                         strproc(pw);
818                         strproc(CC->user.password);
819                         code = strcasecmp(CC->user.password, pw);
820                 }
821                 free (pw);
822         }
823
824         if (!code) {
825                 do_login();
826                 return pass_ok;
827         }
828         else {
829                 syslog(LOG_WARNING, "user_ops: bad password specified for <%s> Service <%s> Port <%ld> Remote <%s / %s>",
830                         CC->curr_user,
831                         CC->ServiceName,
832                         CC->tcp_port,
833                         CC->cs_host,
834                         CC->cs_addr
835                 );
836                 return pass_wrong_password;
837         }
838 }
839
840
841 // Delete a user record *and* all of its related resources.
842 int purge_user(char pname[]) {
843         struct ctdluser usbuf;
844         char usernamekey[USERNAME_SIZE];
845
846         makeuserkey(usernamekey, pname);
847
848         // If the name is empty we can't find them in the DB any way so just return
849         if (IsEmptyStr(pname)) {
850                 return(ERROR + NO_SUCH_USER);
851         }
852
853         if (CtdlGetUser(&usbuf, pname) != 0) {
854                 syslog(LOG_ERR, "user_ops: cannot purge user <%s> - not found", pname);
855                 return(ERROR + NO_SUCH_USER);
856         }
857
858         // Don't delete a user who is currently logged in.  Instead, just
859         // set the access level to 0, and let the account get swept up
860         // during the next purge.
861         if (CtdlIsUserLoggedInByNum(usbuf.usernum)) {
862                 syslog(LOG_WARNING, "user_ops: <%s> is logged in; not deleting", pname);
863                 usbuf.axlevel = AxDeleted;
864                 CtdlPutUser(&usbuf);
865                 return(1);
866         }
867
868         syslog(LOG_NOTICE, "user_ops: deleting <%s>", pname);
869
870         // Perform any purge functions registered by server extensions
871         PerformUserHooks(&usbuf, EVT_PURGEUSER);
872
873         // delete any existing user/room relationships
874         // Commenting out since it was assuming the user number was
875         //   at the top of the index.  Room number is actually first.
876         //   Auto-Purge will clean up the records later, so not worth
877         //   scanning all the records here.
878         //cdb_delete(CDB_VISIT, &usbuf.usernum, sizeof(long));
879
880         // delete the users-by-number index record
881         cdb_delete(CDB_USERSBYNUMBER, &usbuf.usernum, sizeof(long));
882
883         // delete the user entry
884         cdb_delete(CDB_USERS, usernamekey, strlen(usernamekey));
885
886         return(0);
887 }
888
889
890 // This is the back end processing that happens when we create a new user account.
891 int internal_create_user(char *username, struct ctdluser *usbuf, uid_t uid) {
892         if (!CtdlGetUser(usbuf, username)) {
893                 return(ERROR + ALREADY_EXISTS);
894         }
895
896         // Go ahead and initialize a new user record
897         memset(usbuf, 0, sizeof(struct ctdluser));
898         safestrncpy(usbuf->fullname, username, sizeof usbuf->fullname);
899         strcpy(usbuf->password, "");
900         usbuf->uid = uid;
901
902         // These are the default flags on new accounts
903         usbuf->flags = US_LASTOLD | US_DISAPPEAR | US_PAGINATOR | US_FLOORS;
904
905         usbuf->timescalled = 0;
906         usbuf->posted = 0;
907         usbuf->axlevel = CtdlGetConfigInt("c_initax");
908         usbuf->lastcall = time(NULL);
909
910         // fetch a new user number
911         usbuf->usernum = get_new_user_number();
912
913         // add user to the database
914         CtdlPutUser(usbuf);
915         cdb_store(CDB_USERSBYNUMBER, &usbuf->usernum, sizeof(long), usbuf->fullname, strlen(usbuf->fullname)+1);
916
917         // If non-native auth, index by uid
918         if ((usbuf->uid > 0) && (usbuf->uid != NATIVE_AUTH_UID)) {
919                 StrBuf *claimed_id = NewStrBuf();
920                 StrBufPrintf(claimed_id, "uid:%d", usbuf->uid);
921                 FreeStrBuf(&claimed_id);
922         }
923
924         return(0);
925 }
926
927
928 // create_user()  -  back end processing to create a new user
929 //
930 // Set 'newusername' to the desired account name.
931 // Set 'become_user' to CREATE_USER_BECOME_USER if this is self-service account creation and we want to
932 //                   actually log in as the user we just created, otherwise set it to CREATE_USER_DO_NOT_BECOME_USER
933 // Set 'uid' to some uid_t value to associate the account with an external auth user, or (-1) for native auth
934 int create_user(char *username, int become_user, uid_t uid) {
935         struct ctdluser usbuf;
936         struct ctdlroom qrbuf;
937         char mailboxname[ROOMNAMELEN];
938         char buf[SIZ];
939         int retval;
940
941         strproc(username);
942         if ((retval = internal_create_user(username, &usbuf, uid)) != 0) {
943                 return retval;
944         }
945
946         // Give the user a private mailbox and a configuration room.
947         // Make the latter an invisible system room.
948         CtdlMailboxName(mailboxname, sizeof mailboxname, &usbuf, MAILROOM);
949         CtdlCreateRoom(mailboxname, 5, "", 0, 1, 1, VIEW_MAILBOX);
950
951         CtdlMailboxName(mailboxname, sizeof mailboxname, &usbuf, USERCONFIGROOM);
952         CtdlCreateRoom(mailboxname, 5, "", 0, 1, 1, VIEW_BBS);
953         if (CtdlGetRoomLock(&qrbuf, mailboxname) == 0) {
954                 qrbuf.QRflags2 |= QR2_SYSTEM;
955                 CtdlPutRoomLock(&qrbuf);
956         }
957
958         // Perform any create functions registered by server extensions
959         PerformUserHooks(&usbuf, EVT_NEWUSER);
960
961         // Everything below this line can be bypassed if administratively
962         // creating a user, instead of doing self-service account creation
963
964         if (become_user == CREATE_USER_BECOME_USER) {
965                 // Now become the user we just created
966                 memcpy(&CC->user, &usbuf, sizeof(struct ctdluser));
967                 safestrncpy(CC->curr_user, username, sizeof CC->curr_user);
968                 do_login();
969         
970                 // Check to make sure we're still who we think we are
971                 if (CtdlGetUser(&CC->user, CC->curr_user)) {
972                         return(ERROR + INTERNAL_ERROR);
973                 }
974         }
975         
976         snprintf(buf, SIZ, 
977                 "New user account <%s> has been created, from host %s [%s].\n",
978                 username,
979                 CC->cs_host,
980                 CC->cs_addr
981         );
982         CtdlAideMessage(buf, "User Creation Notice");
983         syslog(LOG_NOTICE, "user_ops: <%s> created", username);
984         return(0);
985 }
986
987
988 // set password - back end api code
989 void CtdlSetPassword(char *new_pw) {
990         CtdlGetUserLock(&CC->user, CC->curr_user);
991         safestrncpy(CC->user.password, new_pw, sizeof(CC->user.password));
992         CtdlPutUserLock(&CC->user);
993         syslog(LOG_INFO, "user_ops: password changed for <%s>", CC->curr_user);
994         PerformSessionHooks(EVT_SETPASS);
995 }
996
997
998 // API function for cmd_invt_kick() and anything else that needs to
999 // invite or kick out a user to/from a room.
1000 // 
1001 // Set iuser to the name of the user, and op to 1=invite or 0=kick
1002 int CtdlInvtKick(char *iuser, int op) {
1003         struct ctdluser USscratch;
1004         struct visit vbuf;
1005         char bbb[SIZ];
1006
1007         if (CtdlGetUser(&USscratch, iuser) != 0) {
1008                 return(1);
1009         }
1010
1011         CtdlGetRelationship(&vbuf, &USscratch, &CC->room);
1012         if (op == 1) {
1013                 vbuf.v_flags = vbuf.v_flags & ~V_FORGET & ~V_LOCKOUT;
1014                 vbuf.v_flags = vbuf.v_flags | V_ACCESS;
1015         }
1016         if (op == 0) {
1017                 vbuf.v_flags = vbuf.v_flags & ~V_ACCESS;
1018                 vbuf.v_flags = vbuf.v_flags | V_FORGET | V_LOCKOUT;
1019         }
1020         CtdlSetRelationship(&vbuf, &USscratch, &CC->room);
1021
1022         // post a message in Aide> saying what we just did
1023         snprintf(bbb, sizeof bbb, "%s has been %s \"%s\" by %s.\n",
1024                 iuser,
1025                 ((op == 1) ? "invited to" : "kicked out of"),
1026                 CC->room.QRname,
1027                 (CC->logged_in ? CC->user.fullname : "an administrator")
1028         );
1029         CtdlAideMessage(bbb,"User Admin Message");
1030         return(0);
1031 }
1032
1033
1034 // Forget (Zap) the current room (API call)
1035 // Returns 0 on success
1036 int CtdlForgetThisRoom(void) {
1037         struct visit vbuf;
1038
1039         // On some systems, Admins are not allowed to forget rooms
1040         if (is_aide() && (CtdlGetConfigInt("c_aide_zap") == 0)
1041            && ((CC->room.QRflags & QR_MAILBOX) == 0)  ) {
1042                 return(1);
1043         }
1044
1045         CtdlGetUserLock(&CC->user, CC->curr_user);
1046         CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
1047
1048         vbuf.v_flags = vbuf.v_flags | V_FORGET;
1049         vbuf.v_flags = vbuf.v_flags & ~V_ACCESS;
1050
1051         CtdlSetRelationship(&vbuf, &CC->user, &CC->room);
1052         CtdlPutUserLock(&CC->user);
1053
1054         // Return to the Lobby, so we don't end up in an undefined room
1055         CtdlUserGoto(CtdlGetConfigStr("c_baseroom"), 0, 0, NULL, NULL, NULL, NULL);
1056         return(0);
1057 }
1058
1059
1060 // Traverse the user file and perform a callback for each user record.
1061 // (New improved version that runs in two phases so that callbacks can perform writes without having a r/o cursor open)
1062 void ForEachUser(void (*CallBack) (char *, void *out_data), void *in_data) {
1063         struct cdbdata *cdbus;
1064         struct ctdluser *usptr;
1065
1066         Array *all_users = array_new(USERNAME_SIZE);
1067         if (all_users == NULL) {
1068                 syslog(LOG_ERR, "user_ops: alloc failed, ForEachUser() exiting");
1069                 return;
1070         }
1071
1072
1073         cdb_rewind(CDB_USERS);
1074
1075         // Phase 1 : build an array of all our user account names
1076         while (cdbus = cdb_next_item(CDB_USERS), cdbus != NULL) {
1077                 usptr = (struct ctdluser *) cdbus->ptr;
1078                 if (strlen(usptr->fullname) > 0) {
1079                         array_append(all_users, usptr->fullname);
1080                 }
1081         }
1082
1083         // Phase 2 : perform the callback for each user while de-allocating the list
1084         for (int i=0; i<array_len(all_users); ++i) {
1085                 (*CallBack) (array_get_element_at(all_users, i), in_data);
1086         }
1087
1088         // Phase 3 : free the array
1089         array_free(all_users);
1090 }
1091
1092
1093 // Return the number of new messages that have arrived in the user's inbox while they were logged in.
1094 // Resets to zero when called.
1095 int NewMailCount() {
1096         int num_newmsgs = 0;
1097         num_newmsgs = CC->newmail;
1098         CC->newmail = 0;
1099         return(num_newmsgs);
1100 }
1101
1102
1103 // Count the number of new mail messages the user has
1104 int InitialMailCheck() {
1105         int num_newmsgs = 0;
1106         int a;
1107         char mailboxname[ROOMNAMELEN];
1108         struct ctdlroom mailbox;
1109         struct visit vbuf;
1110         struct cdbdata *cdbfr;
1111         long *msglist = NULL;
1112         int num_msgs = 0;
1113
1114         CtdlMailboxName(mailboxname, sizeof mailboxname, &CC->user, MAILROOM);
1115         if (CtdlGetRoom(&mailbox, mailboxname) != 0)
1116                 return(0);
1117         CtdlGetRelationship(&vbuf, &CC->user, &mailbox);
1118
1119         cdbfr = cdb_fetch(CDB_MSGLISTS, &mailbox.QRnumber, sizeof(long));
1120
1121         if (cdbfr != NULL) {
1122                 msglist = malloc(cdbfr->len);
1123                 memcpy(msglist, cdbfr->ptr, cdbfr->len);
1124                 num_msgs = cdbfr->len / sizeof(long);
1125                 cdb_free(cdbfr);
1126         }
1127         if (num_msgs > 0)
1128                 for (a = 0; a < num_msgs; ++a) {
1129                         if (msglist[a] > 0L) {
1130                                 if (msglist[a] > vbuf.v_lastseen) {
1131                                         ++num_newmsgs;
1132                                 }
1133                         }
1134                 }
1135         if (msglist != NULL)
1136                 free(msglist);
1137
1138         return(num_newmsgs);
1139 }
1140
1141
1142 // Undocumented rescue mode
1143 void undocumented_rescue_mode(char *rescue_string) {
1144         struct ctdluser usbuf;
1145         memset(&usbuf, 0, sizeof(struct ctdluser));
1146         extract_token(usbuf.fullname, rescue_string, 0, '|', sizeof usbuf.password);
1147         extract_token(usbuf.password, rescue_string, 1, '|', sizeof usbuf.password);
1148         usbuf.usernum = extract_long(rescue_string, 2);
1149         usbuf.axlevel = 6;
1150         usbuf.lastcall = time(NULL);
1151         CtdlPutUser(&usbuf);
1152 }