Refactored CtdlGetUser() API
[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)
371             || (CC->room.QRroomaide == CC->user.usernum)) {
372                 return (1);
373         } else {
374                 return (0);
375         }
376 }
377
378
379 /*
380  * CtdlGetUserByNumber() -      get user by number
381  *                      returns 0 if user was found
382  *
383  * Note: fetching a user this way requires one additional database operation.
384  */
385 int CtdlGetUserByNumber(struct ctdluser *usbuf, long number)
386 {
387         struct cdbdata *cdbun;
388         int r;
389
390         cdbun = cdb_fetch(CDB_USERSBYNUMBER, &number, sizeof(long));
391         if (cdbun == NULL) {
392                 syslog(LOG_INFO, "user_ops: %ld not found", number);
393                 return(-1);
394         }
395
396         syslog(LOG_INFO, "user_ops: %ld maps to %s", number, cdbun->ptr);
397         r = CtdlGetUser(usbuf, cdbun->ptr);
398         cdb_free(cdbun);
399         return(r);
400 }
401
402
403 /*
404  * Helper function for rebuild_usersbynumber()
405  */
406 void rebuild_ubn_for_user(struct ctdluser *usbuf, void *data) {
407
408         struct ubnlist {
409                 struct ubnlist *next;
410                 char username[USERNAME_SIZE];
411                 long usernum;
412         };
413
414         static struct ubnlist *u = NULL;
415         struct ubnlist *ptr = NULL;
416
417         /* Lazy programming here.  Call this function as a ForEachUser backend
418          * in order to queue up the room names, or call it with a null user
419          * to make it do the processing.
420          */
421         if (usbuf != NULL) {
422                 ptr = (struct ubnlist *) malloc(sizeof (struct ubnlist));
423                 if (ptr == NULL) return;
424
425                 ptr->usernum = usbuf->usernum;
426                 safestrncpy(ptr->username, usbuf->fullname, sizeof ptr->username);
427                 ptr->next = u;
428                 u = ptr;
429                 return;
430         }
431
432         while (u != NULL) {
433                 syslog(LOG_DEBUG, "user_ops: rebuilding usersbynumber index %10ld : %s", u->usernum, u->username);
434                 cdb_store(CDB_USERSBYNUMBER, &u->usernum, sizeof(long), u->username, strlen(u->username)+1);
435                 ptr = u;
436                 u = u->next;
437                 free(ptr);
438         }
439 }
440
441
442 /*
443  * Rebuild the users-by-number index
444  */
445 void rebuild_usersbynumber(void) {
446         cdb_trunc(CDB_USERSBYNUMBER);                   /* delete the old indices */
447         ForEachUser(rebuild_ubn_for_user, NULL);        /* enumerate the users */
448         rebuild_ubn_for_user(NULL, NULL);               /* and index them */
449 }
450
451
452 /*
453  * getuserbyuid()  -     get user by system uid (for PAM mode authentication)
454  *                     returns 0 if user was found
455  *
456  * WARNING:     don't use this function unless you absolutely have to.  It does
457  *              a sequential search and therefore is computationally expensive.
458  *
459  * FIXME:       build an index, dummy.
460  */
461 int getuserbyuid(struct ctdluser *usbuf, uid_t number)
462 {
463         struct cdbdata *cdbus;
464
465         cdb_rewind(CDB_USERS);
466
467         while (cdbus = cdb_next_item(CDB_USERS), cdbus != NULL) {
468                 memset(usbuf, 0, sizeof(struct ctdluser));
469                 memcpy(usbuf, cdbus->ptr,
470                        ((cdbus->len > sizeof(struct ctdluser)) ?
471                         sizeof(struct ctdluser) : cdbus->len));
472                 cdb_free(cdbus);
473                 if (usbuf->uid == number) {
474                         cdb_close_cursor(CDB_USERS);
475                         return (0);
476                 }
477         }
478         return (-1);
479 }
480
481
482 /*
483  * Back end for cmd_user() and its ilk
484  *
485  * NOTE: "authname" should only be used if we are attempting to use the "master user" feature
486  */
487 int CtdlLoginExistingUser(char *authname, const char *trythisname)
488 {
489         char username[SIZ];
490         int found_user;
491         long len;
492
493         syslog(LOG_DEBUG, "user_ops: CtdlLoginExistingUser(%s, %s)", authname, trythisname);
494
495         if ((CC->logged_in)) {
496                 return login_already_logged_in;
497         }
498
499         if (trythisname == NULL) return login_not_found;
500         
501         if (!strncasecmp(trythisname, "SYS_", 4))
502         {
503                 syslog(LOG_DEBUG, "user_ops: system user \"%s\" is not allowed to log in.", trythisname);
504                 return login_not_found;
505         }
506
507         /* If a "master user" is defined, handle its authentication if specified */
508         CC->is_master = 0;
509         if (    (!IsEmptyStr(CtdlGetConfigStr("c_master_user"))) && 
510                 (!IsEmptyStr(CtdlGetConfigStr("c_master_pass"))) &&
511                 (authname != NULL) &&
512                 (!strcasecmp(authname, CtdlGetConfigStr("c_master_user"))) )
513         {
514                 CC->is_master = 1;
515         }
516
517         /* Continue attempting user validation... */
518         safestrncpy(username, trythisname, sizeof (username));
519         striplt(username);
520         len = cutuserkey(username);
521
522         if (IsEmptyStr(username)) {
523                 return login_not_found;
524         }
525
526         if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
527
528                 /* host auth mode */
529
530                 struct passwd pd;
531                 struct passwd *tempPwdPtr;
532                 char pwdbuffer[256];
533         
534                 syslog(LOG_DEBUG, "user_ops: asking host about <%s>", username);
535 #ifdef HAVE_GETPWNAM_R
536 #ifdef SOLARIS_GETPWUID
537                 syslog(LOG_DEBUG, "user_ops: calling getpwnam_r()");
538                 tempPwdPtr = getpwnam_r(username, &pd, pwdbuffer, sizeof pwdbuffer);
539 #else // SOLARIS_GETPWUID
540                 syslog(LOG_DEBUG, "user_ops: calling getpwnam_r()");
541                 getpwnam_r(username, &pd, pwdbuffer, sizeof pwdbuffer, &tempPwdPtr);
542 #endif // SOLARIS_GETPWUID
543 #else // HAVE_GETPWNAM_R
544                 syslog(LOG_DEBUG, "user_ops: SHOULD NEVER GET HERE!!!");
545                 tempPwdPtr = NULL;
546 #endif // HAVE_GETPWNAM_R
547                 if (tempPwdPtr == NULL) {
548                         syslog(LOG_DEBUG, "user_ops: no such user <%s>", username);
549                         return login_not_found;
550                 }
551         
552                 /* Locate the associated Citadel account.
553                  * If not found, make one attempt to create it.
554                  */
555                 found_user = getuserbyuid(&CC->user, pd.pw_uid);
556                 syslog(LOG_DEBUG, "user_ops: found it: uid=%ld, gecos=%s here: %d", (long)pd.pw_uid, pd.pw_gecos, found_user);
557                 if (found_user != 0) {
558                         len = cutuserkey(username);
559                         create_user(username, len, 0);
560                         found_user = getuserbyuid(&CC->user, pd.pw_uid);
561                 }
562
563         }
564
565 #ifdef HAVE_LDAP
566         else if ((CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP) || (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD)) {
567         
568                 /* LDAP auth mode */
569
570                 uid_t ldap_uid;
571                 char ldap_cn[256];
572                 char ldap_dn[256];
573
574                 found_user = CtdlTryUserLDAP(username, ldap_dn, sizeof ldap_dn, ldap_cn, sizeof ldap_cn, &ldap_uid, 0);
575                 if (found_user != 0) {
576                         return login_not_found;
577                 }
578
579                 found_user = getuserbyuid(&CC->user, ldap_uid);
580                 if (found_user != 0) {
581                         create_user(username, len, 0);
582                         found_user = getuserbyuid(&CC->user, ldap_uid);
583                 }
584
585                 if (found_user == 0) {
586                         if (CC->ldap_dn != NULL) free(CC->ldap_dn);
587                         CC->ldap_dn = strdup(ldap_dn);
588                 }
589
590         }
591 #endif
592
593         else {
594                 /* native auth mode */
595
596                 recptypes *valid = NULL;
597         
598                 /* First, try to log in as if the supplied name is a display name */
599                 found_user = CtdlGetUser(&CC->user, username);
600         
601                 /* If that didn't work, try to log in as if the supplied name
602                 * is an e-mail address
603                 */
604                 if (found_user != 0) {
605                         valid = validate_recipients(username, NULL, 0);
606                         if (valid != NULL) {
607                                 if (valid->num_local == 1) {
608                                         found_user = CtdlGetUser(&CC->user, valid->recp_local);
609                                 }
610                                 free_recipients(valid);
611                         }
612                 }
613         }
614
615         /* Did we find something? */
616         if (found_user == 0) {
617                 if (((CC->nologin)) && (CC->user.axlevel < AxAideU)) {
618                         return login_too_many_users;
619                 } else {
620                         safestrncpy(CC->curr_user, CC->user.fullname, sizeof CC->curr_user);
621                         return login_ok;
622                 }
623         }
624         return login_not_found;
625 }
626
627
628 /*
629  * session startup code which is common to both cmd_pass() and cmd_newu()
630  */
631 void do_login(void)
632 {
633         struct CitContext *CCC = CC;
634
635         CCC->logged_in = 1;
636         syslog(LOG_NOTICE, "user_ops: <%s> logged in", CCC->curr_user);
637
638         CtdlGetUserLock(&CCC->user, CCC->curr_user);
639         ++(CCC->user.timescalled);
640         CCC->previous_login = CCC->user.lastcall;
641         time(&CCC->user.lastcall);
642
643         /* If this user's name is the name of the system administrator
644          * (as specified in setup), automatically assign access level 6.
645          */
646         if (!strcasecmp(CCC->user.fullname, CtdlGetConfigStr("c_sysadm"))) {
647                 CCC->user.axlevel = AxAideU;
648         }
649
650         /* If we're authenticating off the host system, automatically give
651          * root the highest level of access.
652          */
653         if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
654                 if (CCC->user.uid == 0) {
655                         CCC->user.axlevel = AxAideU;
656                 }
657         }
658
659         /*
660          * If we are using LDAP authentication, extract the user's email addresses from the directory.
661          * FIXME make this a site configurable setting
662          */
663         #ifdef HAVE_LDAP
664                 if ((CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP) || (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD)) {
665                         char new_emailaddrs[512];
666                         if (extract_email_addresses_from_ldap(CCC->ldap_dn, new_emailaddrs) == 0) {
667                                 strcpy(CCC->user.emailaddrs, new_emailaddrs);
668                         }
669                 }
670         #endif
671
672         /*
673          * No email address for user?  Make one up.
674          */
675         if (IsEmptyStr(CCC->user.emailaddrs)) {
676                 sprintf(CCC->user.emailaddrs, "cit%ld@%s", CCC->user.usernum, CtdlGetConfigStr("c_fqdn"));
677         }
678         
679         CtdlPutUserLock(&CCC->user);
680
681         /*
682          * Populate cs_inet_email and cs_inet_other_emails with valid email addresses from the user record
683          */
684         strcpy(CCC->cs_inet_email, CCC->user.emailaddrs);
685         char *firstsep = strstr(CCC->cs_inet_email, "|");
686         if (firstsep) {
687                 strcpy(CCC->cs_inet_other_emails, firstsep+1);
688                 *firstsep = 0;
689         }
690         else {
691                 CCC->cs_inet_other_emails[0] = 0;
692         }
693
694         /* Create any personal rooms required by the system.
695          * (Technically, MAILROOM should be there already, but just in case...)
696          */
697         CtdlCreateRoom(MAILROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
698         CtdlCreateRoom(SENTITEMS, 4, "", 0, 1, 0, VIEW_MAILBOX);
699         CtdlCreateRoom(USERTRASHROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
700         CtdlCreateRoom(USERDRAFTROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
701
702         /* Run any startup routines registered by loadable modules */
703         PerformSessionHooks(EVT_LOGIN);
704
705         /* Enter the lobby */
706         CtdlUserGoto(CtdlGetConfigStr("c_baseroom"), 0, 0, NULL, NULL, NULL, NULL);
707 }
708
709
710 void logged_in_response(void)
711 {
712         cprintf("%d %s|%d|%ld|%ld|%u|%ld|%ld\n",
713                 CIT_OK, CC->user.fullname, CC->user.axlevel,
714                 CC->user.timescalled, CC->user.posted,
715                 CC->user.flags, CC->user.usernum,
716                 CC->previous_login
717         );
718 }
719
720
721 void CtdlUserLogout(void)
722 {
723         CitContext *CCC = MyContext();
724
725         syslog(LOG_DEBUG, "user_ops: CtdlUserLogout() logging out <%s> from session %d", CCC->curr_user, CCC->cs_pid);
726
727         /* Run any hooks registered by modules... */
728         PerformSessionHooks(EVT_LOGOUT);
729         
730         /*
731          * Clear out some session data.  Most likely, the CitContext for this
732          * session is about to get nuked when the session disconnects, but
733          * since it's possible to log in again without reconnecting, we cannot
734          * make that assumption.
735          */
736         strcpy(CCC->fake_username, "");
737         strcpy(CCC->fake_hostname, "");
738         strcpy(CCC->fake_roomname, "");
739         CCC->logged_in = 0;
740
741         /* Check to see if the user was deleted whilst logged in and purge them if necessary */
742         if ((CCC->user.axlevel == AxDeleted) && (CCC->user.usernum)) {
743                 purge_user(CCC->user.fullname);
744         }
745
746         /* Clear out the user record in memory so we don't behave like a ghost */
747         memset(&CCC->user, 0, sizeof(struct ctdluser));
748         CCC->curr_user[0] = 0;
749         CCC->is_master = 0;
750         CCC->cs_inet_email[0] = 0;
751         CCC->cs_inet_other_emails[0] = 0;
752         CCC->cs_inet_fn[0] = 0;
753         CCC->fake_username[0] = 0;
754         CCC->fake_hostname[0] = 0;
755         CCC->fake_roomname[0] = 0;
756
757         /* Free any output buffers */
758         unbuffer_output();
759 }
760
761
762 /*
763  * Validate a password on the host unix system by talking to the chkpwd daemon
764  */
765 static int validpw(uid_t uid, const char *pass)
766 {
767         char buf[256];
768         int rv = 0;
769
770         if (IsEmptyStr(pass)) {
771                 syslog(LOG_DEBUG, "user_ops: refusing to chkpwd for uid=%d with empty password", uid);
772                 return 0;
773         }
774
775         syslog(LOG_DEBUG, "user_ops: validating password for uid=%d using chkpwd...", uid);
776
777         begin_critical_section(S_CHKPWD);
778         rv = write(chkpwd_write_pipe[1], &uid, sizeof(uid_t));
779         if (rv == -1) {
780                 syslog(LOG_ERR, "user_ops: communication with chkpwd broken: %m");
781                 end_critical_section(S_CHKPWD);
782                 return 0;
783         }
784         rv = write(chkpwd_write_pipe[1], pass, 256);
785         if (rv == -1) {
786                 syslog(LOG_ERR, "user_ops: communication with chkpwd broken: %m");
787                 end_critical_section(S_CHKPWD);
788                 return 0;
789         }
790         rv = read(chkpwd_read_pipe[0], buf, 4);
791         if (rv == -1) {
792                 syslog(LOG_ERR, "user_ops: ommunication with chkpwd broken: %m");
793                 end_critical_section(S_CHKPWD);
794                 return 0;
795         }
796         end_critical_section(S_CHKPWD);
797
798         if (!strncmp(buf, "PASS", 4)) {
799                 syslog(LOG_DEBUG, "user_ops: chkpwd pass");
800                 return(1);
801         }
802
803         syslog(LOG_DEBUG, "user_ops: chkpwd fail");
804         return 0;
805 }
806
807
808 /* 
809  * Start up the chkpwd daemon so validpw() has something to talk to
810  */
811 void start_chkpwd_daemon(void) {
812         pid_t chkpwd_pid;
813         struct stat filestats;
814         int i;
815
816         syslog(LOG_DEBUG, "user_ops: starting chkpwd daemon for host authentication mode");
817
818         if ((stat(file_chkpwd, &filestats)==-1) || (filestats.st_size==0)) {
819                 syslog(LOG_ERR, "user_ops: %s: %m", file_chkpwd);
820                 abort();
821         }
822         if (pipe(chkpwd_write_pipe) != 0) {
823                 syslog(LOG_ERR, "user_ops: unable to create pipe for chkpwd daemon: %m");
824                 abort();
825         }
826         if (pipe(chkpwd_read_pipe) != 0) {
827                 syslog(LOG_ERR, "user_ops: unable to create pipe for chkpwd daemon: %m");
828                 abort();
829         }
830
831         chkpwd_pid = fork();
832         if (chkpwd_pid < 0) {
833                 syslog(LOG_ERR, "user_ops: unable to fork chkpwd daemon: %m");
834                 abort();
835         }
836         if (chkpwd_pid == 0) {
837                 dup2(chkpwd_write_pipe[0], 0);
838                 dup2(chkpwd_read_pipe[1], 1);
839                 for (i=2; i<256; ++i) close(i);
840                 execl(file_chkpwd, file_chkpwd, NULL);
841                 syslog(LOG_ERR, "user_ops: unable to exec chkpwd daemon: %m");
842                 abort();
843                 exit(errno);
844         }
845 }
846
847
848 int CtdlTryPassword(const char *password, long len)
849 {
850         int code;
851         CitContext *CCC = CC;
852
853         if ((CCC->logged_in)) {
854                 syslog(LOG_WARNING, "user_ops: CtdlTryPassword: already logged in");
855                 return pass_already_logged_in;
856         }
857         if (!strcmp(CCC->curr_user, NLI)) {
858                 syslog(LOG_WARNING, "user_ops: CtdlTryPassword: no user selected");
859                 return pass_no_user;
860         }
861         if (CtdlGetUser(&CCC->user, CCC->curr_user)) {
862                 syslog(LOG_ERR, "user_ops: CtdlTryPassword: internal error");
863                 return pass_internal_error;
864         }
865         if (password == NULL) {
866                 syslog(LOG_INFO, "user_ops: CtdlTryPassword: NULL password string supplied");
867                 return pass_wrong_password;
868         }
869
870         if (CCC->is_master) {
871                 code = strcmp(password, CtdlGetConfigStr("c_master_pass"));
872         }
873
874         else if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
875
876                 /* host auth mode */
877
878                 if (validpw(CCC->user.uid, password)) {
879                         code = 0;
880
881                         /*
882                          * sooper-seekrit hack: populate the password field in the
883                          * citadel database with the password that the user typed,
884                          * if it's correct.  This allows most sites to convert from
885                          * host auth to native auth if they want to.  If you think
886                          * this is a security hazard, comment it out.
887                          */
888
889                         CtdlGetUserLock(&CCC->user, CCC->curr_user);
890                         safestrncpy(CCC->user.password, password, sizeof CCC->user.password);
891                         CtdlPutUserLock(&CCC->user);
892
893                         /*
894                          * (sooper-seekrit hack ends here)
895                          */
896                 }
897                 else {
898                         code = (-1);
899                 }
900         }
901
902 #ifdef HAVE_LDAP
903         else if ((CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP) || (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD)) {
904
905                 /* LDAP auth mode */
906
907                 if ((CCC->ldap_dn) && (!CtdlTryPasswordLDAP(CCC->ldap_dn, password))) {
908                         code = 0;
909                 }
910                 else {
911                         code = (-1);
912                 }
913         }
914 #endif
915
916         else {
917
918                 /* native auth mode */
919                 char *pw;
920
921                 pw = (char*) malloc(len + 1);
922                 memcpy(pw, password, len + 1);
923                 strproc(pw);
924                 strproc(CCC->user.password);
925                 code = strcasecmp(CCC->user.password, pw);
926                 if (code != 0) {
927                         strproc(pw);
928                         strproc(CCC->user.password);
929                         code = strcasecmp(CCC->user.password, pw);
930                 }
931                 free (pw);
932         }
933
934         if (!code) {
935                 do_login();
936                 return pass_ok;
937         }
938         else {
939                 syslog(LOG_WARNING, "user_ops: bad password specified for <%s> Service <%s> Port <%ld> Remote <%s / %s>",
940                         CCC->curr_user,
941                         CCC->ServiceName,
942                         CCC->tcp_port,
943                         CCC->cs_host,
944                         CCC->cs_addr
945                 );
946                 return pass_wrong_password;
947         }
948 }
949
950
951 /*
952  * Delete a user record *and* all of its related resources.
953  */
954 int purge_user(char pname[])
955 {
956         struct ctdluser usbuf;
957         char usernamekey[USERNAME_SIZE];
958
959         makeuserkey(usernamekey, pname, cutuserkey(pname));
960
961         /* If the name is empty we can't find them in the DB any way so just return */
962         if (IsEmptyStr(pname))
963                 return (ERROR + NO_SUCH_USER);
964
965         if (CtdlGetUser(&usbuf, pname) != 0) {
966                 syslog(LOG_ERR, "user_ops: cannot purge user <%s> - not found", pname);
967                 return (ERROR + NO_SUCH_USER);
968         }
969         /* Don't delete a user who is currently logged in.  Instead, just
970          * set the access level to 0, and let the account get swept up
971          * during the next purge.
972          */
973         if (CtdlIsUserLoggedInByNum(usbuf.usernum)) {
974                 syslog(LOG_WARNING, "user_ops: <%s> is logged in; not deleting", pname);
975                 usbuf.axlevel = AxDeleted;
976                 CtdlPutUser(&usbuf);
977                 return (1);
978         }
979         syslog(LOG_NOTICE, "user_ops: deleting <%s>", pname);
980
981 /*
982  * FIXME:
983  * This should all be wrapped in a S_USERS mutex.
984  * Without the mutex the user could log in before we get to the next function
985  * That would truly mess things up :-(
986  * I would like to see the S_USERS start before the CtdlIsUserLoggedInByNum() above
987  * and end after the user has been deleted from the database, below.
988  * Question is should we enter the EVT_PURGEUSER while S_USERS is active?
989  */
990
991         /* Perform any purge functions registered by server extensions */
992         PerformUserHooks(&usbuf, EVT_PURGEUSER);
993
994         /* delete any existing user/room relationships */
995         cdb_delete(CDB_VISIT, &usbuf.usernum, sizeof(long));
996
997         /* delete the users-by-number index record */
998         cdb_delete(CDB_USERSBYNUMBER, &usbuf.usernum, sizeof(long));
999
1000         /* delete the userlog entry */
1001         cdb_delete(CDB_USERS, usernamekey, strlen(usernamekey));
1002
1003         return (0);
1004 }
1005
1006
1007 int internal_create_user (char *username, long len, struct ctdluser *usbuf, uid_t uid)
1008 {
1009         if (!CtdlGetUser(usbuf, username)) {
1010                 return (ERROR + ALREADY_EXISTS);
1011         }
1012
1013         /* Go ahead and initialize a new user record */
1014         memset(usbuf, 0, sizeof(struct ctdluser));
1015         safestrncpy(usbuf->fullname, username, sizeof usbuf->fullname);
1016         strcpy(usbuf->password, "");
1017         usbuf->uid = uid;
1018
1019         /* These are the default flags on new accounts */
1020         usbuf->flags = US_LASTOLD | US_DISAPPEAR | US_PAGINATOR | US_FLOORS;
1021
1022         usbuf->timescalled = 0;
1023         usbuf->posted = 0;
1024         usbuf->axlevel = CtdlGetConfigInt("c_initax");
1025         usbuf->lastcall = time(NULL);
1026
1027         /* fetch a new user number */
1028         usbuf->usernum = get_new_user_number();
1029
1030         /* add user to the database */
1031         CtdlPutUser(usbuf);
1032         cdb_store(CDB_USERSBYNUMBER, &usbuf->usernum, sizeof(long), usbuf->fullname, strlen(usbuf->fullname)+1);
1033
1034         return 0;
1035 }
1036
1037
1038 /*
1039  * create_user()  -  back end processing to create a new user
1040  *
1041  * Set 'newusername' to the desired account name.
1042  * Set 'become_user' to nonzero if this is self-service account creation and we want
1043  * to actually log in as the user we just created, otherwise set it to 0.
1044  */
1045 int create_user(const char *newusername, long len, int become_user)
1046 {
1047         struct ctdluser usbuf;
1048         struct ctdlroom qrbuf;
1049         char username[256];
1050         char mailboxname[ROOMNAMELEN];
1051         char buf[SIZ];
1052         int retval;
1053         uid_t uid = (-1);
1054
1055         safestrncpy(username, newusername, sizeof username);
1056         strproc(username);
1057         
1058         if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
1059
1060                 /* host auth mode */
1061
1062                 struct passwd pd;
1063                 struct passwd *tempPwdPtr;
1064                 char pwdbuffer[SIZ];
1065         
1066 #ifdef HAVE_GETPWNAM_R
1067 #ifdef SOLARIS_GETPWUID
1068                 tempPwdPtr = getpwnam_r(username, &pd, pwdbuffer, sizeof(pwdbuffer));
1069 #else // SOLARIS_GETPWUID
1070                 getpwnam_r(username, &pd, pwdbuffer, sizeof pwdbuffer, &tempPwdPtr);
1071 #endif // SOLARIS_GETPWUID
1072 #else // HAVE_GETPWNAM_R
1073                 tempPwdPtr = NULL;
1074 #endif // HAVE_GETPWNAM_R
1075                 if (tempPwdPtr != NULL) {
1076                         extract_token(username, pd.pw_gecos, 0, ',', sizeof username);
1077                         uid = pd.pw_uid;
1078                         if (IsEmptyStr (username))
1079                         {
1080                                 safestrncpy(username, pd.pw_name, sizeof username);
1081                                 len = cutuserkey(username);
1082                         }
1083                 }
1084                 else {
1085                         return (ERROR + NO_SUCH_USER);
1086                 }
1087         }
1088
1089 #ifdef HAVE_LDAP
1090         if ((CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP) || (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD)) {
1091                 if (CtdlTryUserLDAP(username, NULL, 0, username, sizeof username, &uid, 0) != 0) {
1092                         return(ERROR + NO_SUCH_USER);
1093                 }
1094         }
1095 #endif /* HAVE_LDAP */
1096         
1097         if ((retval = internal_create_user(username, len, &usbuf, uid)) != 0)
1098                 return retval;
1099         
1100         /*
1101          * Give the user a private mailbox and a configuration room.
1102          * Make the latter an invisible system room.
1103          */
1104         CtdlMailboxName(mailboxname, sizeof mailboxname, &usbuf, MAILROOM);
1105         CtdlCreateRoom(mailboxname, 5, "", 0, 1, 1, VIEW_MAILBOX);
1106
1107         CtdlMailboxName(mailboxname, sizeof mailboxname, &usbuf, USERCONFIGROOM);
1108         CtdlCreateRoom(mailboxname, 5, "", 0, 1, 1, VIEW_BBS);
1109         if (CtdlGetRoomLock(&qrbuf, mailboxname) == 0) {
1110                 qrbuf.QRflags2 |= QR2_SYSTEM;
1111                 CtdlPutRoomLock(&qrbuf);
1112         }
1113
1114         /* Perform any create functions registered by server extensions */
1115         PerformUserHooks(&usbuf, EVT_NEWUSER);
1116
1117         /* Everything below this line can be bypassed if administratively
1118          * creating a user, instead of doing self-service account creation
1119          */
1120
1121         if (become_user) {
1122                 /* Now become the user we just created */
1123                 memcpy(&CC->user, &usbuf, sizeof(struct ctdluser));
1124                 safestrncpy(CC->curr_user, username, sizeof CC->curr_user);
1125                 do_login();
1126         
1127                 /* Check to make sure we're still who we think we are */
1128                 if (CtdlGetUser(&CC->user, CC->curr_user)) {
1129                         return (ERROR + INTERNAL_ERROR);
1130                 }
1131         }
1132         
1133         snprintf(buf, SIZ, 
1134                 "New user account <%s> has been created, from host %s [%s].\n",
1135                 username,
1136                 CC->cs_host,
1137                 CC->cs_addr
1138         );
1139         CtdlAideMessage(buf, "User Creation Notice");
1140         syslog(LOG_NOTICE, "user_ops: <%s> created", username);
1141         return (0);
1142 }
1143
1144
1145 /*
1146  * set password - back end api code
1147  */
1148 void CtdlSetPassword(char *new_pw)
1149 {
1150         CtdlGetUserLock(&CC->user, CC->curr_user);
1151         safestrncpy(CC->user.password, new_pw, sizeof(CC->user.password));
1152         CtdlPutUserLock(&CC->user);
1153         syslog(LOG_INFO, "user_ops: password changed for <%s>", CC->curr_user);
1154         PerformSessionHooks(EVT_SETPASS);
1155 }
1156
1157
1158 /*
1159  * API function for cmd_invt_kick() and anything else that needs to
1160  * invite or kick out a user to/from a room.
1161  * 
1162  * Set iuser to the name of the user, and op to 1=invite or 0=kick
1163  */
1164 int CtdlInvtKick(char *iuser, int op) {
1165         struct ctdluser USscratch;
1166         visit vbuf;
1167         char bbb[SIZ];
1168
1169         if (CtdlGetUser(&USscratch, iuser) != 0) {
1170                 return(1);
1171         }
1172
1173         CtdlGetRelationship(&vbuf, &USscratch, &CC->room);
1174         if (op == 1) {
1175                 vbuf.v_flags = vbuf.v_flags & ~V_FORGET & ~V_LOCKOUT;
1176                 vbuf.v_flags = vbuf.v_flags | V_ACCESS;
1177         }
1178         if (op == 0) {
1179                 vbuf.v_flags = vbuf.v_flags & ~V_ACCESS;
1180                 vbuf.v_flags = vbuf.v_flags | V_FORGET | V_LOCKOUT;
1181         }
1182         CtdlSetRelationship(&vbuf, &USscratch, &CC->room);
1183
1184         /* post a message in Aide> saying what we just did */
1185         snprintf(bbb, sizeof bbb, "%s has been %s \"%s\" by %s.\n",
1186                 iuser,
1187                 ((op == 1) ? "invited to" : "kicked out of"),
1188                 CC->room.QRname,
1189                 (CC->logged_in ? CC->user.fullname : "an administrator")
1190         );
1191         CtdlAideMessage(bbb,"User Admin Message");
1192
1193         return(0);
1194 }
1195
1196
1197 /*
1198  * Forget (Zap) the current room (API call)
1199  * Returns 0 on success
1200  */
1201 int CtdlForgetThisRoom(void) {
1202         visit vbuf;
1203
1204         /* On some systems, Admins are not allowed to forget rooms */
1205         if (is_aide() && (CtdlGetConfigInt("c_aide_zap") == 0)
1206            && ((CC->room.QRflags & QR_MAILBOX) == 0)  ) {
1207                 return(1);
1208         }
1209
1210         CtdlGetUserLock(&CC->user, CC->curr_user);
1211         CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
1212
1213         vbuf.v_flags = vbuf.v_flags | V_FORGET;
1214         vbuf.v_flags = vbuf.v_flags & ~V_ACCESS;
1215
1216         CtdlSetRelationship(&vbuf, &CC->user, &CC->room);
1217         CtdlPutUserLock(&CC->user);
1218
1219         /* Return to the Lobby, so we don't end up in an undefined room */
1220         CtdlUserGoto(CtdlGetConfigStr("c_baseroom"), 0, 0, NULL, NULL, NULL, NULL);
1221         return(0);
1222
1223 }
1224
1225
1226 /* 
1227  *  Traverse the user file...
1228  */
1229 void ForEachUser(void (*CallBack) (struct ctdluser * EachUser, void *out_data),
1230                  void *in_data)
1231 {
1232         struct ctdluser usbuf;
1233         struct cdbdata *cdbus;
1234
1235         cdb_rewind(CDB_USERS);
1236
1237         while (cdbus = cdb_next_item(CDB_USERS), cdbus != NULL) {
1238                 memset(&usbuf, 0, sizeof(struct ctdluser));
1239                 memcpy(&usbuf, cdbus->ptr,
1240                        ((cdbus->len > sizeof(struct ctdluser)) ?
1241                         sizeof(struct ctdluser) : cdbus->len));
1242                 cdb_free(cdbus);
1243                 (*CallBack) (&usbuf, in_data);
1244         }
1245 }
1246
1247
1248 /*
1249  * List one user (this works with cmd_list)
1250  */
1251 void ListThisUser(struct ctdluser *usbuf, void *data)
1252 {
1253         char *searchstring;
1254
1255         searchstring = (char *)data;
1256         if (bmstrcasestr(usbuf->fullname, searchstring) == NULL) {
1257                 return;
1258         }
1259
1260         if (usbuf->axlevel > AxDeleted) {
1261                 if ((CC->user.axlevel >= AxAideU)
1262                     || ((usbuf->flags & US_UNLISTED) == 0)
1263                     || ((CC->internal_pgm))) {
1264                         cprintf("%s|%d|%ld|%ld|%ld|%ld||\n",
1265                                 usbuf->fullname,
1266                                 usbuf->axlevel,
1267                                 usbuf->usernum,
1268                                 (long)usbuf->lastcall,
1269                                 usbuf->timescalled,
1270                                 usbuf->posted);
1271                 }
1272         }
1273 }
1274
1275
1276 /*
1277  * Count the number of new mail messages the user has
1278  */
1279 int NewMailCount()
1280 {
1281         int num_newmsgs = 0;
1282
1283         num_newmsgs = CC->newmail;
1284         CC->newmail = 0;
1285
1286         return (num_newmsgs);
1287 }
1288
1289
1290 /*
1291  * Count the number of new mail messages the user has
1292  */
1293 int InitialMailCheck()
1294 {
1295         int num_newmsgs = 0;
1296         int a;
1297         char mailboxname[ROOMNAMELEN];
1298         struct ctdlroom mailbox;
1299         visit vbuf;
1300         struct cdbdata *cdbfr;
1301         long *msglist = NULL;
1302         int num_msgs = 0;
1303
1304         CtdlMailboxName(mailboxname, sizeof mailboxname, &CC->user, MAILROOM);
1305         if (CtdlGetRoom(&mailbox, mailboxname) != 0)
1306                 return (0);
1307         CtdlGetRelationship(&vbuf, &CC->user, &mailbox);
1308
1309         cdbfr = cdb_fetch(CDB_MSGLISTS, &mailbox.QRnumber, sizeof(long));
1310
1311         if (cdbfr != NULL) {
1312                 msglist = malloc(cdbfr->len);
1313                 memcpy(msglist, cdbfr->ptr, cdbfr->len);
1314                 num_msgs = cdbfr->len / sizeof(long);
1315                 cdb_free(cdbfr);
1316         }
1317         if (num_msgs > 0)
1318                 for (a = 0; a < num_msgs; ++a) {
1319                         if (msglist[a] > 0L) {
1320                                 if (msglist[a] > vbuf.v_lastseen) {
1321                                         ++num_newmsgs;
1322                                 }
1323                         }
1324                 }
1325         if (msglist != NULL)
1326                 free(msglist);
1327
1328         return (num_newmsgs);
1329 }