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