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