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