]> code.citadel.org Git - citadel.git/blob - citadel/server/user_ops.c
serv_imap.c: moved to new CtdlFetchMsgList() API.
[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 "room_ops.h"
22 #include "makeuserkey.h"
23 #include "internet_addressing.h"
24
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];
28
29
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];
35
36         makeuserkey(k1, s1);
37         makeuserkey(k2, s2);
38         return(strcmp(k1,k2));
39 }
40
41
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;
47
48         if (usbuf != NULL) {
49                 memset(usbuf, 0, sizeof(struct ctdluser));
50         }
51
52         makeuserkey(usernamekey, name);
53         if (IsEmptyStr(usernamekey)) {
54                 return(1);      // empty user name
55         }
56         cdbus = cdb_fetch(CDB_USERS, usernamekey, strlen(usernamekey));
57
58         if (cdbus == NULL) {    // user not found
59                 return(1);
60         }
61         if (usbuf != NULL) {
62                 memcpy(usbuf, cdbus->ptr, ((cdbus->len > sizeof(struct ctdluser)) ?  sizeof(struct ctdluser) : cdbus->len));
63         }
64         cdb_free(cdbus);
65         return(0);
66 }
67
68
69 int CtdlLockGetCurrentUser(void) {
70         return CtdlGetUser(&CC->user, CC->curr_user);
71 }
72
73
74 // CtdlGetUserLock()  -  same as getuser() but locks the record
75 int CtdlGetUserLock(struct ctdluser *usbuf, char *name) {
76         int retcode;
77
78         retcode = CtdlGetUser(usbuf, name);
79         if (retcode == 0) {
80                 begin_critical_section(S_USERS);
81         }
82         return(retcode);
83 }
84
85
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));
92 }
93
94
95 void CtdlPutCurrentUserLock() {
96         CtdlPutUser(&CC->user);
97 }
98
99
100 // CtdlPutUserLock()  -  same as putuser() but locks the record
101 void CtdlPutUserLock(struct ctdluser *usbuf) {
102         CtdlPutUser(usbuf);
103         end_critical_section(S_USERS);
104 }
105
106
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;
112
113         char oldnamekey[USERNAME_SIZE];
114         char newnamekey[USERNAME_SIZE];
115
116         // Create the database keys...
117         makeuserkey(oldnamekey, oldname);
118         makeuserkey(newnamekey, newname);
119
120         // Lock up and get going
121         begin_critical_section(S_USERS);
122
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;
127         }
128
129         if (CtdlGetUser(&usbuf, newname) == 0) {
130                 retcode = RENAMEUSER_ALREADY_EXISTS;
131         }
132         else {
133
134                 if (CtdlGetUser(&usbuf, oldname) != 0) {
135                         retcode = RENAMEUSER_NOT_FOUND;
136                 }
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;
141                         }
142                         else {
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);
146                                 CtdlPutUser(&usbuf);
147                                 cdb_store(CDB_USERSBYNUMBER, &usbuf.usernum, sizeof(long), usbuf.fullname, strlen(usbuf.fullname)+1 );
148                                 retcode = RENAMEUSER_OK;
149                         }
150                 }
151         
152         }
153
154         end_critical_section(S_USERS);
155         return(retcode);
156 }
157
158
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) {
162         int i;
163
164         int len = strlen(username);
165
166         if (len >= USERNAME_SIZE) {
167                 syslog(LOG_INFO, "Username too long: %s", username);
168                 len = USERNAME_SIZE - 1; 
169         }
170         for (i=0; i<=len; ++i) {
171                 key[i] = tolower(username[i]);
172         }
173 }
174
175
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) {
179
180         char oldkey[USERNAME_SIZE];
181         char newkey[USERNAME_SIZE];
182         struct cdbdata *cdbus;
183         struct ctdluser usbuf;
184
185         makeuserkey_pre928(oldkey, username);
186         makeuserkey(newkey, username);
187
188         syslog(LOG_DEBUG, "user_ops: reindex_user_928: %s <%s> --> <%s>", username, oldkey, newkey);
189
190         // Fetch the user record using the old index format
191         cdbus = cdb_fetch(CDB_USERS, oldkey, strlen(oldkey));
192         if (cdbus == NULL) {
193                 syslog(LOG_INFO, "user_ops: <%s> not found, were they already reindexed?", username);
194                 return;
195         }
196         memcpy(&usbuf, cdbus->ptr, ((cdbus->len > sizeof(struct ctdluser)) ? sizeof(struct ctdluser) : cdbus->len));
197         cdb_free(cdbus);
198
199         // delete the old record
200         cdb_delete(CDB_USERS, oldkey, strlen(oldkey));
201
202         // write the new record
203         cdb_store(CDB_USERS, newkey, strlen(newkey), &usbuf, sizeof(struct ctdluser));
204 }
205
206
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;
213
214         memcpy(IndexBuf, &TheIndex, sizeof(TheIndex));
215         return(sizeof(TheIndex));
216 }
217
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));
221 }
222
223
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;
231
232         // Store the record
233         put_visit(newvisit);
234 }
235
236
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;
240
241         // Clear out the buffer
242         memset(vbuf, 0, sizeof(struct visit));
243
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;
248
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));
252                 cdb_free(cdbvisit);
253         }
254         else {
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;
257         }
258
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);
262         }
263 }
264
265
266 void CtdlMailboxName(char *buf, size_t n, const struct ctdluser *who, const char *prefix) {
267         snprintf(buf, n, "%010ld.%s", who->usernum, prefix);
268 }
269
270
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) {
274
275         // Do not allow twits to send Internet mail
276         if (who->axlevel <= AxProbU) return(0);
277
278         // Globally enabled?
279         if (CtdlGetConfigInt("c_restrict") == 0) return(1);
280
281         // User flagged ok?
282         if (who->flags & US_INTERNET) return(2);
283
284         // Admin level access?
285         if (who->axlevel >= AxAideU) return(3);
286
287         // No mail for you!
288         return(0);
289 }
290
291
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);
299                 return(-1);
300         }
301
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);
304                 return(-1);
305         }
306
307         if ((required_level >= ac_logged_in) && (CC->logged_in == 0)) {
308                 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
309                 return(-1);
310         }
311
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);
316                 return(-1);
317         }
318
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);
323                 return(-1);
324         }
325
326         // Do not generate any output if we succeeded -- the calling function will handle that.
327         return(0);
328 }
329
330
331 // Is the user currently logged in an Admin?
332 int is_aide(void) {
333         if (CC->user.axlevel >= AxAideU) {
334                 return(1);
335         }
336         else {
337                 return(0);
338         }
339 }
340
341
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) {
345                 return(0);
346         }
347
348         if ((CC->user.axlevel >= AxAideU) || (CC->room.QRroomaide == CC->user.usernum)) {
349                 return(1);
350         }
351         else {
352                 return(0);
353         }
354 }
355
356
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;
361         int r;
362
363         cdbun = cdb_fetch(CDB_USERSBYNUMBER, &number, sizeof(long));
364         if (cdbun == NULL) {
365                 syslog(LOG_INFO, "user_ops: %ld not found", number);
366                 return(-1);
367         }
368
369         syslog(LOG_INFO, "user_ops: %ld maps to %s", number, cdbun->ptr);
370         r = CtdlGetUser(usbuf, cdbun->ptr);
371         cdb_free(cdbun);
372         return(r);
373 }
374
375
376 // Helper function for rebuild_usersbynumber()
377 void rebuild_ubn_for_user(char *username, void *data) {
378         struct ctdluser u;
379
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);
383         }
384 }
385
386
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
391 }
392
393
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) {
397
398         struct cdbdata *cdbus;
399         struct ctdluser *usptr;
400         int return_value = (-1);
401
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;
408
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
413                 }
414         }
415
416         if (return_value != 0) {
417                 syslog(LOG_DEBUG, "user_ops: no user found with uid=%d", number);
418         }
419         return(return_value);
420 }
421
422
423 // Back end for cmd_user() and its ilk
424 int CtdlLoginExistingUser(const char *trythisname) {
425         char username[SIZ];
426         int found_user;
427
428         syslog(LOG_DEBUG, "user_ops: CtdlLoginExistingUser(%s)", trythisname);
429
430         if ((CC->logged_in)) {
431                 return login_already_logged_in;
432         }
433
434         if (trythisname == NULL) return login_not_found;
435         
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;
440         //}
441
442         // Continue attempting user validation...
443         safestrncpy(username, trythisname, sizeof (username));
444         string_trim(username);
445
446         if (IsEmptyStr(username)) {
447                 return login_not_found;
448         }
449
450         // host auth mode...
451         if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
452                 struct passwd pd;
453                 struct passwd *tempPwdPtr;
454                 char pwdbuffer[256];
455         
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!!!");
462                 tempPwdPtr = NULL;
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;
467                 }
468         
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);
474                 }
475                 syslog(LOG_DEBUG, "user_ops: found it: uid=%ld, gecos=%s here: %d", (long)pd.pw_uid, pd.pw_gecos, found_user);
476
477         }
478
479         // LDAP auth mode...
480         else if ((CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP) || (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD)) {
481
482                 uid_t ldap_uid;
483                 char ldap_cn[256];
484                 char ldap_dn[256];
485
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;
489                 }
490
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);
495                 }
496
497                 if (found_user == 0) {
498                         if (CC->ldap_dn != NULL) free(CC->ldap_dn);
499                         CC->ldap_dn = strdup(ldap_dn);
500                 }
501
502         }
503
504         // native auth mode...
505         else {
506                 struct recptypes *valid = NULL;
507         
508                 // First, try to log in as if the supplied name is a display name
509                 found_user = CtdlGetUser(&CC->user, username);
510         
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);
514                         if (valid != NULL) {
515                                 if (valid->num_local == 1) {
516                                         found_user = CtdlGetUser(&CC->user, valid->recp_local);
517                                 }
518                                 free_recipients(valid);
519                         }
520                 }
521         }
522
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;
527         }
528
529         // Did we find something?
530         if (found_user == 0) {
531                 if (((CC->nologin)) && (CC->user.axlevel < AxAideU)) {
532                         return login_too_many_users;
533                 }
534                 else {
535                         safestrncpy(CC->curr_user, CC->user.fullname, sizeof CC->curr_user);
536                         return login_ok;
537                 }
538         }
539         return login_not_found;
540 }
541
542
543 // session startup code which is common to both cmd_pass() and cmd_newu()
544 void do_login(void) {
545         CC->logged_in = 1;
546         syslog(LOG_NOTICE, "user_ops: <%s> logged in", CC->curr_user);
547
548         CtdlGetUserLock(&CC->user, CC->curr_user);
549         CC->previous_login = CC->user.lastcall;
550         time(&CC->user.lastcall);
551
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;
556         }
557
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;
562                 }
563         }
564         CtdlPutUserLock(&CC->user);
565
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);
572                         }
573                 }
574         }
575
576         // If the user does not have any email addresses assigned, generate one.
577         if (IsEmptyStr(CC->user.emailaddrs)) {
578                 AutoGenerateEmailAddressForUser(&CC->user);
579         }
580
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"));
586
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, "|");
590         if (firstsep) {
591                 strcpy(CC->cs_inet_other_emails, firstsep+1);
592                 *firstsep = 0;
593         }
594         else {
595                 CC->cs_inet_other_emails[0] = 0;
596         }
597
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);
604
605         // Run any startup routines registered by loadable modules
606         PerformSessionHooks(EVT_LOGIN);
607
608         // Enter the lobby
609         CtdlUserGoto(CtdlGetConfigStr("c_baseroom"), 0, 0, NULL, NULL, NULL, NULL);
610 }
611
612
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,
617                 CC->previous_login
618         );
619 }
620
621
622 void CtdlUserLogout(void) {
623
624         syslog(LOG_DEBUG, "user_ops: CtdlUserLogout() logging out <%s> from session %d", CC->curr_user, CC->cs_pid);
625
626         // Run any hooks registered by modules...
627         PerformSessionHooks(EVT_LOGOUT);
628         
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.
633         CC->logged_in = 0;
634
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);
638         }
639
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;
646
647         // Free any output buffers
648         unbuffer_output();
649 }
650
651
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) {
654         char buf[256];
655         int rv = 0;
656
657         if (IsEmptyStr(pass)) {
658                 syslog(LOG_DEBUG, "user_ops: refusing to chkpwd for uid=%d with empty password", uid);
659                 return 0;
660         }
661
662         syslog(LOG_DEBUG, "user_ops: validating password for uid=%d using chkpwd...", uid);
663
664         begin_critical_section(S_CHKPWD);
665         rv = write(chkpwd_write_pipe[1], &uid, sizeof(uid_t));
666         if (rv == -1) {
667                 syslog(LOG_ERR, "user_ops: communication with chkpwd broken: %m");
668                 end_critical_section(S_CHKPWD);
669                 return 0;
670         }
671         rv = write(chkpwd_write_pipe[1], pass, 256);
672         if (rv == -1) {
673                 syslog(LOG_ERR, "user_ops: communication with chkpwd broken: %m");
674                 end_critical_section(S_CHKPWD);
675                 return 0;
676         }
677         rv = read(chkpwd_read_pipe[0], buf, 4);
678         if (rv == -1) {
679                 syslog(LOG_ERR, "user_ops: ommunication with chkpwd broken: %m");
680                 end_critical_section(S_CHKPWD);
681                 return 0;
682         }
683         end_critical_section(S_CHKPWD);
684
685         if (!strncmp(buf, "PASS", 4)) {
686                 syslog(LOG_DEBUG, "user_ops: chkpwd pass");
687                 return(1);
688         }
689
690         syslog(LOG_DEBUG, "user_ops: chkpwd fail");
691         return 0;
692 }
693
694
695 // Start up the chkpwd daemon so validpw() has something to talk to
696 void start_chkpwd_daemon(void) {
697         pid_t chkpwd_pid;
698         struct stat filestats;
699         int i;
700
701         syslog(LOG_DEBUG, "user_ops: starting chkpwd daemon for host authentication mode");
702
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);
706         }
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);
710         }
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);
714         }
715
716         chkpwd_pid = fork();
717         if (chkpwd_pid < 0) {
718                 syslog(LOG_ERR, "user_ops: unable to fork chkpwd daemon: %m");
719                 exit(CTDLEXIT_CHKPWD);
720         }
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");
727                 exit(errno);
728         }
729 }
730
731
732 int CtdlTryPassword(const char *password, long len) {
733         int code;
734
735         if ((CC->logged_in)) {
736                 syslog(LOG_WARNING, "user_ops: CtdlTryPassword: already logged in");
737                 return pass_already_logged_in;
738         }
739         if (!strcmp(CC->curr_user, NLI)) {
740                 syslog(LOG_WARNING, "user_ops: CtdlTryPassword: no user selected");
741                 return pass_no_user;
742         }
743         if (CtdlGetUser(&CC->user, CC->curr_user)) {
744                 syslog(LOG_ERR, "user_ops: CtdlTryPassword: internal error");
745                 return pass_internal_error;
746         }
747         if (password == NULL) {
748                 syslog(LOG_INFO, "user_ops: CtdlTryPassword: NULL password string supplied");
749                 return pass_wrong_password;
750         }
751
752         // host auth mode...
753         else if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
754                 if (validpw(CC->user.uid, password)) {
755                         code = 0;
756
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.
762
763                         CtdlGetUserLock(&CC->user, CC->curr_user);
764                         safestrncpy(CC->user.password, password, sizeof CC->user.password);
765                         CtdlPutUserLock(&CC->user);
766
767                         // (sooper-seekrit hack ends here)
768                 }
769                 else {
770                         code = (-1);
771                 }
772         }
773
774         // LDAP auth mode...
775         else if ((CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP) || (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD)) {
776
777                 if ((CC->ldap_dn) && (!CtdlTryPasswordLDAP(CC->ldap_dn, password))) {
778                         code = 0;
779                 }
780                 else {
781                         code = (-1);
782                 }
783         }
784
785         // native auth mode...
786         else {
787                 char *pw;
788
789                 pw = (char*) malloc(len + 1);
790                 memcpy(pw, password, len + 1);
791                 strproc(pw);
792                 strproc(CC->user.password);
793                 code = strcasecmp(CC->user.password, pw);
794                 if (code != 0) {
795                         strproc(pw);
796                         strproc(CC->user.password);
797                         code = strcasecmp(CC->user.password, pw);
798                 }
799                 free (pw);
800         }
801
802         if (!code) {
803                 do_login();
804                 return pass_ok;
805         }
806         else {
807                 syslog(LOG_WARNING, "user_ops: bad password specified for <%s> Service <%s> Port <%ld> Remote <%s / %s>",
808                         CC->curr_user,
809                         CC->ServiceName,
810                         CC->tcp_port,
811                         CC->cs_host,
812                         CC->cs_addr
813                 );
814                 return pass_wrong_password;
815         }
816 }
817
818
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];
823
824         makeuserkey(usernamekey, pname);
825
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);
829         }
830
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);
834         }
835
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;
842                 CtdlPutUser(&usbuf);
843                 return(1);
844         }
845
846         syslog(LOG_NOTICE, "user_ops: deleting <%s>", pname);
847
848         // Perform any purge functions registered by server extensions
849         PerformUserHooks(&usbuf, EVT_PURGEUSER);
850
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));
857
858         // delete the users-by-number index record
859         cdb_delete(CDB_USERSBYNUMBER, &usbuf.usernum, sizeof(long));
860
861         // delete the user entry
862         cdb_delete(CDB_USERS, usernamekey, strlen(usernamekey));
863
864         return(0);
865 }
866
867
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);
872         }
873
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, "");
878         usbuf->uid = uid;
879
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);
884
885         // fetch a new user number
886         usbuf->usernum = get_new_user_number();
887
888         // add user to the database
889         CtdlPutUser(usbuf);
890         cdb_store(CDB_USERSBYNUMBER, &usbuf->usernum, sizeof(long), usbuf->fullname, strlen(usbuf->fullname)+1);
891
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);
897         }
898
899         return(0);
900 }
901
902
903 // create_user()  -  back end processing to create a new user
904 //
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];
913         char buf[SIZ];
914         int retval;
915
916         strproc(username);
917         if ((retval = internal_create_user(username, &usbuf, uid)) != 0) {
918                 return retval;
919         }
920
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);
925
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);
931         }
932
933         // Perform any create functions registered by server extensions
934         PerformUserHooks(&usbuf, EVT_NEWUSER);
935
936         // Everything below this line can be bypassed if administratively
937         // creating a user, instead of doing self-service account creation
938
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);
943                 do_login();
944         
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);
948                 }
949         }
950         
951         snprintf(buf, SIZ, 
952                 "New user account <%s> has been created, from host %s [%s].\n",
953                 username,
954                 CC->cs_host,
955                 CC->cs_addr
956         );
957         CtdlAideMessage(buf, "User Creation Notice");
958         syslog(LOG_NOTICE, "user_ops: <%s> created", username);
959         return(0);
960 }
961
962
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);
970 }
971
972
973 // API function for cmd_invt_kick() and anything else that needs to
974 // invite or kick out a user to/from a room.
975 // 
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;
979         struct visit vbuf;
980         char bbb[SIZ];
981
982         if (CtdlGetUser(&USscratch, iuser) != 0) {
983                 return(1);
984         }
985
986         CtdlGetRelationship(&vbuf, &USscratch, &CC->room);
987         if (op == 1) {
988                 vbuf.v_flags = vbuf.v_flags & ~V_FORGET & ~V_LOCKOUT;
989                 vbuf.v_flags = vbuf.v_flags | V_ACCESS;
990         }
991         if (op == 0) {
992                 vbuf.v_flags = vbuf.v_flags & ~V_ACCESS;
993                 vbuf.v_flags = vbuf.v_flags | V_FORGET | V_LOCKOUT;
994         }
995         CtdlSetRelationship(&vbuf, &USscratch, &CC->room);
996
997         // post a message in Aide> saying what we just did
998         snprintf(bbb, sizeof bbb, "%s has been %s \"%s\" by %s.\n",
999                 iuser,
1000                 ((op == 1) ? "invited to" : "kicked out of"),
1001                 CC->room.QRname,
1002                 (CC->logged_in ? CC->user.fullname : "an administrator")
1003         );
1004         CtdlAideMessage(bbb,"User Admin Message");
1005         return(0);
1006 }
1007
1008
1009 // Forget (Zap) the current room (API call)
1010 // Returns 0 on success
1011 int CtdlForgetThisRoom(void) {
1012         struct visit vbuf;
1013
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)  ) {
1017                 return(1);
1018         }
1019
1020         CtdlGetUserLock(&CC->user, CC->curr_user);
1021         CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
1022
1023         vbuf.v_flags = vbuf.v_flags | V_FORGET;
1024         vbuf.v_flags = vbuf.v_flags & ~V_ACCESS;
1025
1026         CtdlSetRelationship(&vbuf, &CC->user, &CC->room);
1027         CtdlPutUserLock(&CC->user);
1028
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);
1031         return(0);
1032 }
1033
1034
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;
1040
1041         Array *all_users = array_new(USERNAME_SIZE);
1042         if (all_users == NULL) {
1043                 syslog(LOG_ERR, "user_ops: alloc failed, ForEachUser() exiting");
1044                 return;
1045         }
1046
1047
1048         cdb_rewind(CDB_USERS);
1049
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);
1055                 }
1056         }
1057
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);
1061         }
1062
1063         // Phase 3 : free the array
1064         array_free(all_users);
1065 }
1066
1067
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;
1073         CC->newmail = 0;
1074         return(num_newmsgs);
1075 }
1076
1077
1078 // Count the number of new mail messages the user has
1079 int InitialMailCheck() {
1080         int num_newmsgs = 0;
1081         int a;
1082         char mailboxname[ROOMNAMELEN];
1083         struct ctdlroom mailbox;
1084         struct visit vbuf;
1085         long *msglist = NULL;
1086         int num_msgs = 0;
1087
1088         CtdlMailboxName(mailboxname, sizeof mailboxname, &CC->user, MAILROOM);
1089         if (CtdlGetRoom(&mailbox, mailboxname) != 0) {
1090                 return(0);
1091         }
1092         CtdlGetRelationship(&vbuf, &CC->user, &mailbox);
1093
1094         num_msgs = CtdlFetchMsgList(mailbox.QRnumber, &msglist);
1095         if (num_msgs > 0) {
1096                 for (a = 0; a < num_msgs; ++a) {
1097                         if (msglist[a] > 0L) {
1098                                 if (msglist[a] > vbuf.v_lastseen) {
1099                                         ++num_newmsgs;
1100                                 }
1101                         }
1102                 }
1103         }
1104         free(msglist);
1105         return(num_newmsgs);
1106 }
1107
1108
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);
1118         usbuf.axlevel = 6;
1119         usbuf.lastcall = time(NULL);
1120         CtdlPutUser(&usbuf);
1121 }