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