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