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