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