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