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