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