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