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