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