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