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