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