]> code.citadel.org Git - citadel.git/blob - citadel/server/user_ops.c
Moved makeuserkey() into its own file because we need it in ctdlload
[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 // 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];
33
34         makeuserkey(k1, s1);
35         makeuserkey(k2, s2);
36         return(strcmp(k1,k2));
37 }
38
39
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;
45
46         if (usbuf != NULL) {
47                 memset(usbuf, 0, sizeof(struct ctdluser));
48         }
49
50         makeuserkey(usernamekey, name);
51         if (IsEmptyStr(usernamekey)) {
52                 return(1);      // empty user name
53         }
54         cdbus = cdb_fetch(CDB_USERS, usernamekey, strlen(usernamekey));
55
56         if (cdbus == NULL) {    // user not found
57                 return(1);
58         }
59         if (usbuf != NULL) {
60                 memcpy(usbuf, cdbus->ptr, ((cdbus->len > sizeof(struct ctdluser)) ?  sizeof(struct ctdluser) : cdbus->len));
61         }
62         cdb_free(cdbus);
63         return(0);
64 }
65
66
67 int CtdlLockGetCurrentUser(void) {
68         return CtdlGetUser(&CC->user, CC->curr_user);
69 }
70
71
72 // CtdlGetUserLock()  -  same as getuser() but locks the record
73 int CtdlGetUserLock(struct ctdluser *usbuf, char *name) {
74         int retcode;
75
76         retcode = CtdlGetUser(usbuf, name);
77         if (retcode == 0) {
78                 begin_critical_section(S_USERS);
79         }
80         return(retcode);
81 }
82
83
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));
90 }
91
92
93 void CtdlPutCurrentUserLock() {
94         CtdlPutUser(&CC->user);
95 }
96
97
98 // CtdlPutUserLock()  -  same as putuser() but locks the record
99 void CtdlPutUserLock(struct ctdluser *usbuf) {
100         CtdlPutUser(usbuf);
101         end_critical_section(S_USERS);
102 }
103
104
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;
110
111         char oldnamekey[USERNAME_SIZE];
112         char newnamekey[USERNAME_SIZE];
113
114         // Create the database keys...
115         makeuserkey(oldnamekey, oldname);
116         makeuserkey(newnamekey, newname);
117
118         // Lock up and get going
119         begin_critical_section(S_USERS);
120
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;
125         }
126
127         if (CtdlGetUser(&usbuf, newname) == 0) {
128                 retcode = RENAMEUSER_ALREADY_EXISTS;
129         }
130         else {
131
132                 if (CtdlGetUser(&usbuf, oldname) != 0) {
133                         retcode = RENAMEUSER_NOT_FOUND;
134                 }
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;
139                         }
140                         else {
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);
144                                 CtdlPutUser(&usbuf);
145                                 cdb_store(CDB_USERSBYNUMBER, &usbuf.usernum, sizeof(long), usbuf.fullname, strlen(usbuf.fullname)+1 );
146                                 retcode = RENAMEUSER_OK;
147                         }
148                 }
149         
150         }
151
152         end_critical_section(S_USERS);
153         return(retcode);
154 }
155
156
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) {
160         int i;
161
162         int len = strlen(username);
163
164         if (len >= USERNAME_SIZE) {
165                 syslog(LOG_INFO, "Username too long: %s", username);
166                 len = USERNAME_SIZE - 1; 
167         }
168         for (i=0; i<=len; ++i) {
169                 key[i] = tolower(username[i]);
170         }
171 }
172
173
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) {
177
178         char oldkey[USERNAME_SIZE];
179         char newkey[USERNAME_SIZE];
180         struct cdbdata *cdbus;
181         struct ctdluser usbuf;
182
183         makeuserkey_pre928(oldkey, username);
184         makeuserkey(newkey, username);
185
186         syslog(LOG_DEBUG, "user_ops: reindex_user_928: %s <%s> --> <%s>", username, oldkey, newkey);
187
188         // Fetch the user record using the old index format
189         cdbus = cdb_fetch(CDB_USERS, oldkey, strlen(oldkey));
190         if (cdbus == NULL) {
191                 syslog(LOG_INFO, "user_ops: <%s> not found, were they already reindexed?", username);
192                 return;
193         }
194         memcpy(&usbuf, cdbus->ptr, ((cdbus->len > sizeof(struct ctdluser)) ? sizeof(struct ctdluser) : cdbus->len));
195         cdb_free(cdbus);
196
197         // delete the old record
198         cdb_delete(CDB_USERS, oldkey, strlen(oldkey));
199
200         // write the new record
201         cdb_store(CDB_USERS, newkey, strlen(newkey), &usbuf, sizeof(struct ctdluser));
202 }
203
204
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;
211
212         memcpy(IndexBuf, &TheIndex, sizeof(TheIndex));
213         return(sizeof(TheIndex));
214 }
215
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));
219 }
220
221
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;
229
230         // Store the record
231         put_visit(newvisit);
232 }
233
234
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;
238
239         // Clear out the buffer
240         memset(vbuf, 0, sizeof(struct visit));
241
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;
246
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));
250                 cdb_free(cdbvisit);
251         }
252         else {
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;
255         }
256
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);
260         }
261 }
262
263
264 void CtdlMailboxName(char *buf, size_t n, const struct ctdluser *who, const char *prefix) {
265         snprintf(buf, n, "%010ld.%s", who->usernum, prefix);
266 }
267
268
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) {
272
273         // Do not allow twits to send Internet mail
274         if (who->axlevel <= AxProbU) return(0);
275
276         // Globally enabled?
277         if (CtdlGetConfigInt("c_restrict") == 0) return(1);
278
279         // User flagged ok?
280         if (who->flags & US_INTERNET) return(2);
281
282         // Admin level access?
283         if (who->axlevel >= AxAideU) return(3);
284
285         // No mail for you!
286         return(0);
287 }
288
289
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);
297                 return(-1);
298         }
299
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);
302                 return(-1);
303         }
304
305         if ((required_level >= ac_logged_in) && (CC->logged_in == 0)) {
306                 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
307                 return(-1);
308         }
309
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);
314                 return(-1);
315         }
316
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);
321                 return(-1);
322         }
323
324         // Do not generate any output if we succeeded -- the calling function will handle that.
325         return(0);
326 }
327
328
329 // Is the user currently logged in an Admin?
330 int is_aide(void) {
331         if (CC->user.axlevel >= AxAideU) {
332                 return(1);
333         }
334         else {
335                 return(0);
336         }
337 }
338
339
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) {
343                 return(0);
344         }
345
346         if ((CC->user.axlevel >= AxAideU) || (CC->room.QRroomaide == CC->user.usernum)) {
347                 return(1);
348         }
349         else {
350                 return(0);
351         }
352 }
353
354
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;
359         int r;
360
361         cdbun = cdb_fetch(CDB_USERSBYNUMBER, &number, sizeof(long));
362         if (cdbun == NULL) {
363                 syslog(LOG_INFO, "user_ops: %ld not found", number);
364                 return(-1);
365         }
366
367         syslog(LOG_INFO, "user_ops: %ld maps to %s", number, cdbun->ptr);
368         r = CtdlGetUser(usbuf, cdbun->ptr);
369         cdb_free(cdbun);
370         return(r);
371 }
372
373
374 // Helper function for rebuild_usersbynumber()
375 void rebuild_ubn_for_user(char *username, void *data) {
376         struct ctdluser u;
377
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);
381         }
382 }
383
384
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
389 }
390
391
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) {
395
396         struct cdbdata *cdbus;
397         struct ctdluser *usptr;
398         int return_value = (-1);
399
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;
406
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
411                 }
412         }
413
414         if (return_value != 0) {
415                 syslog(LOG_DEBUG, "user_ops: no user found with uid=%d", number);
416         }
417         return(return_value);
418 }
419
420
421 // Back end for cmd_user() and its ilk
422 int CtdlLoginExistingUser(const char *trythisname) {
423         char username[SIZ];
424         int found_user;
425
426         syslog(LOG_DEBUG, "user_ops: CtdlLoginExistingUser(%s)", trythisname);
427
428         if ((CC->logged_in)) {
429                 return login_already_logged_in;
430         }
431
432         if (trythisname == NULL) return login_not_found;
433         
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;
438         //}
439
440         // Continue attempting user validation...
441         safestrncpy(username, trythisname, sizeof (username));
442         string_trim(username);
443
444         if (IsEmptyStr(username)) {
445                 return login_not_found;
446         }
447
448         // host auth mode...
449         if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
450                 struct passwd pd;
451                 struct passwd *tempPwdPtr;
452                 char pwdbuffer[256];
453         
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!!!");
460                 tempPwdPtr = NULL;
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;
465                 }
466         
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);
472                 }
473                 syslog(LOG_DEBUG, "user_ops: found it: uid=%ld, gecos=%s here: %d", (long)pd.pw_uid, pd.pw_gecos, found_user);
474
475         }
476
477         // LDAP auth mode...
478         else if ((CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP) || (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD)) {
479
480                 uid_t ldap_uid;
481                 char ldap_cn[256];
482                 char ldap_dn[256];
483
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;
487                 }
488
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);
493                 }
494
495                 if (found_user == 0) {
496                         if (CC->ldap_dn != NULL) free(CC->ldap_dn);
497                         CC->ldap_dn = strdup(ldap_dn);
498                 }
499
500         }
501
502         // native auth mode...
503         else {
504                 struct recptypes *valid = NULL;
505         
506                 // First, try to log in as if the supplied name is a display name
507                 found_user = CtdlGetUser(&CC->user, username);
508         
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);
512                         if (valid != NULL) {
513                                 if (valid->num_local == 1) {
514                                         found_user = CtdlGetUser(&CC->user, valid->recp_local);
515                                 }
516                                 free_recipients(valid);
517                         }
518                 }
519         }
520
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;
525         }
526
527         // Did we find something?
528         if (found_user == 0) {
529                 if (((CC->nologin)) && (CC->user.axlevel < AxAideU)) {
530                         return login_too_many_users;
531                 }
532                 else {
533                         safestrncpy(CC->curr_user, CC->user.fullname, sizeof CC->curr_user);
534                         return login_ok;
535                 }
536         }
537         return login_not_found;
538 }
539
540
541 // session startup code which is common to both cmd_pass() and cmd_newu()
542 void do_login(void) {
543         CC->logged_in = 1;
544         syslog(LOG_NOTICE, "user_ops: <%s> logged in", CC->curr_user);
545
546         CtdlGetUserLock(&CC->user, CC->curr_user);
547         CC->previous_login = CC->user.lastcall;
548         time(&CC->user.lastcall);
549
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;
554         }
555
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;
560                 }
561         }
562         CtdlPutUserLock(&CC->user);
563
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);
570                         }
571                 }
572         }
573
574         // If the user does not have any email addresses assigned, generate one.
575         if (IsEmptyStr(CC->user.emailaddrs)) {
576                 AutoGenerateEmailAddressForUser(&CC->user);
577         }
578
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"));
584
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, "|");
588         if (firstsep) {
589                 strcpy(CC->cs_inet_other_emails, firstsep+1);
590                 *firstsep = 0;
591         }
592         else {
593                 CC->cs_inet_other_emails[0] = 0;
594         }
595
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);
602
603         // Run any startup routines registered by loadable modules
604         PerformSessionHooks(EVT_LOGIN);
605
606         // Enter the lobby
607         CtdlUserGoto(CtdlGetConfigStr("c_baseroom"), 0, 0, NULL, NULL, NULL, NULL);
608 }
609
610
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,
615                 CC->previous_login
616         );
617 }
618
619
620 void CtdlUserLogout(void) {
621
622         syslog(LOG_DEBUG, "user_ops: CtdlUserLogout() logging out <%s> from session %d", CC->curr_user, CC->cs_pid);
623
624         // Run any hooks registered by modules...
625         PerformSessionHooks(EVT_LOGOUT);
626         
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.
631         CC->logged_in = 0;
632
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);
636         }
637
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;
644
645         // Free any output buffers
646         unbuffer_output();
647 }
648
649
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) {
652         char buf[256];
653         int rv = 0;
654
655         if (IsEmptyStr(pass)) {
656                 syslog(LOG_DEBUG, "user_ops: refusing to chkpwd for uid=%d with empty password", uid);
657                 return 0;
658         }
659
660         syslog(LOG_DEBUG, "user_ops: validating password for uid=%d using chkpwd...", uid);
661
662         begin_critical_section(S_CHKPWD);
663         rv = write(chkpwd_write_pipe[1], &uid, sizeof(uid_t));
664         if (rv == -1) {
665                 syslog(LOG_ERR, "user_ops: communication with chkpwd broken: %m");
666                 end_critical_section(S_CHKPWD);
667                 return 0;
668         }
669         rv = write(chkpwd_write_pipe[1], pass, 256);
670         if (rv == -1) {
671                 syslog(LOG_ERR, "user_ops: communication with chkpwd broken: %m");
672                 end_critical_section(S_CHKPWD);
673                 return 0;
674         }
675         rv = read(chkpwd_read_pipe[0], buf, 4);
676         if (rv == -1) {
677                 syslog(LOG_ERR, "user_ops: ommunication with chkpwd broken: %m");
678                 end_critical_section(S_CHKPWD);
679                 return 0;
680         }
681         end_critical_section(S_CHKPWD);
682
683         if (!strncmp(buf, "PASS", 4)) {
684                 syslog(LOG_DEBUG, "user_ops: chkpwd pass");
685                 return(1);
686         }
687
688         syslog(LOG_DEBUG, "user_ops: chkpwd fail");
689         return 0;
690 }
691
692
693 // Start up the chkpwd daemon so validpw() has something to talk to
694 void start_chkpwd_daemon(void) {
695         pid_t chkpwd_pid;
696         struct stat filestats;
697         int i;
698
699         syslog(LOG_DEBUG, "user_ops: starting chkpwd daemon for host authentication mode");
700
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);
704         }
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);
708         }
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);
712         }
713
714         chkpwd_pid = fork();
715         if (chkpwd_pid < 0) {
716                 syslog(LOG_ERR, "user_ops: unable to fork chkpwd daemon: %m");
717                 exit(CTDLEXIT_CHKPWD);
718         }
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");
725                 exit(errno);
726         }
727 }
728
729
730 int CtdlTryPassword(const char *password, long len) {
731         int code;
732
733         if ((CC->logged_in)) {
734                 syslog(LOG_WARNING, "user_ops: CtdlTryPassword: already logged in");
735                 return pass_already_logged_in;
736         }
737         if (!strcmp(CC->curr_user, NLI)) {
738                 syslog(LOG_WARNING, "user_ops: CtdlTryPassword: no user selected");
739                 return pass_no_user;
740         }
741         if (CtdlGetUser(&CC->user, CC->curr_user)) {
742                 syslog(LOG_ERR, "user_ops: CtdlTryPassword: internal error");
743                 return pass_internal_error;
744         }
745         if (password == NULL) {
746                 syslog(LOG_INFO, "user_ops: CtdlTryPassword: NULL password string supplied");
747                 return pass_wrong_password;
748         }
749
750         // host auth mode...
751         else if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
752                 if (validpw(CC->user.uid, password)) {
753                         code = 0;
754
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.
760
761                         CtdlGetUserLock(&CC->user, CC->curr_user);
762                         safestrncpy(CC->user.password, password, sizeof CC->user.password);
763                         CtdlPutUserLock(&CC->user);
764
765                         // (sooper-seekrit hack ends here)
766                 }
767                 else {
768                         code = (-1);
769                 }
770         }
771
772         // LDAP auth mode...
773         else if ((CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP) || (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD)) {
774
775                 if ((CC->ldap_dn) && (!CtdlTryPasswordLDAP(CC->ldap_dn, password))) {
776                         code = 0;
777                 }
778                 else {
779                         code = (-1);
780                 }
781         }
782
783         // native auth mode...
784         else {
785                 char *pw;
786
787                 pw = (char*) malloc(len + 1);
788                 memcpy(pw, password, len + 1);
789                 strproc(pw);
790                 strproc(CC->user.password);
791                 code = strcasecmp(CC->user.password, pw);
792                 if (code != 0) {
793                         strproc(pw);
794                         strproc(CC->user.password);
795                         code = strcasecmp(CC->user.password, pw);
796                 }
797                 free (pw);
798         }
799
800         if (!code) {
801                 do_login();
802                 return pass_ok;
803         }
804         else {
805                 syslog(LOG_WARNING, "user_ops: bad password specified for <%s> Service <%s> Port <%ld> Remote <%s / %s>",
806                         CC->curr_user,
807                         CC->ServiceName,
808                         CC->tcp_port,
809                         CC->cs_host,
810                         CC->cs_addr
811                 );
812                 return pass_wrong_password;
813         }
814 }
815
816
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];
821
822         makeuserkey(usernamekey, pname);
823
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);
827         }
828
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);
832         }
833
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;
840                 CtdlPutUser(&usbuf);
841                 return(1);
842         }
843
844         syslog(LOG_NOTICE, "user_ops: deleting <%s>", pname);
845
846         // Perform any purge functions registered by server extensions
847         PerformUserHooks(&usbuf, EVT_PURGEUSER);
848
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));
855
856         // delete the users-by-number index record
857         cdb_delete(CDB_USERSBYNUMBER, &usbuf.usernum, sizeof(long));
858
859         // delete the user entry
860         cdb_delete(CDB_USERS, usernamekey, strlen(usernamekey));
861
862         return(0);
863 }
864
865
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);
870         }
871
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, "");
876         usbuf->uid = uid;
877
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);
882
883         // fetch a new user number
884         usbuf->usernum = get_new_user_number();
885
886         // add user to the database
887         CtdlPutUser(usbuf);
888         cdb_store(CDB_USERSBYNUMBER, &usbuf->usernum, sizeof(long), usbuf->fullname, strlen(usbuf->fullname)+1);
889
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);
895         }
896
897         return(0);
898 }
899
900
901 // create_user()  -  back end processing to create a new user
902 //
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];
911         char buf[SIZ];
912         int retval;
913
914         strproc(username);
915         if ((retval = internal_create_user(username, &usbuf, uid)) != 0) {
916                 return retval;
917         }
918
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);
923
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);
929         }
930
931         // Perform any create functions registered by server extensions
932         PerformUserHooks(&usbuf, EVT_NEWUSER);
933
934         // Everything below this line can be bypassed if administratively
935         // creating a user, instead of doing self-service account creation
936
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);
941                 do_login();
942         
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);
946                 }
947         }
948         
949         snprintf(buf, SIZ, 
950                 "New user account <%s> has been created, from host %s [%s].\n",
951                 username,
952                 CC->cs_host,
953                 CC->cs_addr
954         );
955         CtdlAideMessage(buf, "User Creation Notice");
956         syslog(LOG_NOTICE, "user_ops: <%s> created", username);
957         return(0);
958 }
959
960
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);
968 }
969
970
971 // API function for cmd_invt_kick() and anything else that needs to
972 // invite or kick out a user to/from a room.
973 // 
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;
977         struct visit vbuf;
978         char bbb[SIZ];
979
980         if (CtdlGetUser(&USscratch, iuser) != 0) {
981                 return(1);
982         }
983
984         CtdlGetRelationship(&vbuf, &USscratch, &CC->room);
985         if (op == 1) {
986                 vbuf.v_flags = vbuf.v_flags & ~V_FORGET & ~V_LOCKOUT;
987                 vbuf.v_flags = vbuf.v_flags | V_ACCESS;
988         }
989         if (op == 0) {
990                 vbuf.v_flags = vbuf.v_flags & ~V_ACCESS;
991                 vbuf.v_flags = vbuf.v_flags | V_FORGET | V_LOCKOUT;
992         }
993         CtdlSetRelationship(&vbuf, &USscratch, &CC->room);
994
995         // post a message in Aide> saying what we just did
996         snprintf(bbb, sizeof bbb, "%s has been %s \"%s\" by %s.\n",
997                 iuser,
998                 ((op == 1) ? "invited to" : "kicked out of"),
999                 CC->room.QRname,
1000                 (CC->logged_in ? CC->user.fullname : "an administrator")
1001         );
1002         CtdlAideMessage(bbb,"User Admin Message");
1003         return(0);
1004 }
1005
1006
1007 // Forget (Zap) the current room (API call)
1008 // Returns 0 on success
1009 int CtdlForgetThisRoom(void) {
1010         struct visit vbuf;
1011
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)  ) {
1015                 return(1);
1016         }
1017
1018         CtdlGetUserLock(&CC->user, CC->curr_user);
1019         CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
1020
1021         vbuf.v_flags = vbuf.v_flags | V_FORGET;
1022         vbuf.v_flags = vbuf.v_flags & ~V_ACCESS;
1023
1024         CtdlSetRelationship(&vbuf, &CC->user, &CC->room);
1025         CtdlPutUserLock(&CC->user);
1026
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);
1029         return(0);
1030 }
1031
1032
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;
1038
1039         Array *all_users = array_new(USERNAME_SIZE);
1040         if (all_users == NULL) {
1041                 syslog(LOG_ERR, "user_ops: alloc failed, ForEachUser() exiting");
1042                 return;
1043         }
1044
1045
1046         cdb_rewind(CDB_USERS);
1047
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);
1053                 }
1054         }
1055
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);
1059         }
1060
1061         // Phase 3 : free the array
1062         array_free(all_users);
1063 }
1064
1065
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;
1071         CC->newmail = 0;
1072         return(num_newmsgs);
1073 }
1074
1075
1076 // Count the number of new mail messages the user has
1077 int InitialMailCheck() {
1078         int num_newmsgs = 0;
1079         int a;
1080         char mailboxname[ROOMNAMELEN];
1081         struct ctdlroom mailbox;
1082         struct visit vbuf;
1083         struct cdbdata *cdbfr;
1084         long *msglist = NULL;
1085         int num_msgs = 0;
1086
1087         CtdlMailboxName(mailboxname, sizeof mailboxname, &CC->user, MAILROOM);
1088         if (CtdlGetRoom(&mailbox, mailboxname) != 0)
1089                 return(0);
1090         CtdlGetRelationship(&vbuf, &CC->user, &mailbox);
1091
1092         cdbfr = cdb_fetch(CDB_MSGLISTS, &mailbox.QRnumber, sizeof(long));
1093
1094         if (cdbfr != NULL) {
1095                 msglist = malloc(cdbfr->len);
1096                 memcpy(msglist, cdbfr->ptr, cdbfr->len);
1097                 num_msgs = cdbfr->len / sizeof(long);
1098                 cdb_free(cdbfr);
1099         }
1100         if (num_msgs > 0)
1101                 for (a = 0; a < num_msgs; ++a) {
1102                         if (msglist[a] > 0L) {
1103                                 if (msglist[a] > vbuf.v_lastseen) {
1104                                         ++num_newmsgs;
1105                                 }
1106                         }
1107                 }
1108         if (msglist != NULL)
1109                 free(msglist);
1110
1111         return(num_newmsgs);
1112 }
1113
1114
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);
1124         usbuf.axlevel = 6;
1125         usbuf.lastcall = time(NULL);
1126         CtdlPutUser(&usbuf);
1127 }