c79e87abd04dd40c86e3e23a3c61297aa1ef7bb5
[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 ((configlen.c_master_user > 0) && 
571             (configlen.c_master_pass > 0) &&
572             (authname != NULL) &&
573             (!strcasecmp(authname, config.c_master_user)))
574         {
575                 CC->is_master = 1;
576         }
577
578         /* Continue attempting user validation... */
579         safestrncpy(username, trythisname, sizeof (username));
580         striplt(username);
581         len = cutuserkey(username);
582
583         if (IsEmptyStr(username)) {
584                 return login_not_found;
585         }
586
587         if (config.c_auth_mode == AUTHMODE_HOST) {
588
589                 /* host auth mode */
590
591                 struct passwd pd;
592                 struct passwd *tempPwdPtr;
593                 char pwdbuffer[256];
594         
595                 CON_syslog(LOG_DEBUG, "asking host about <%s>\n", username);
596 #ifdef HAVE_GETPWNAM_R
597 #ifdef SOLARIS_GETPWUID
598                 CON_syslog(LOG_DEBUG, "Calling getpwnam_r()\n");
599                 tempPwdPtr = getpwnam_r(username, &pd, pwdbuffer, sizeof pwdbuffer);
600 #else // SOLARIS_GETPWUID
601                 CONM_syslog(LOG_DEBUG, "Calling getpwnam_r()\n");
602                 getpwnam_r(username, &pd, pwdbuffer, sizeof pwdbuffer, &tempPwdPtr);
603 #endif // SOLARIS_GETPWUID
604 #else // HAVE_GETPWNAM_R
605                 CON_syslog(LOG_DEBUG, "SHOULD NEVER GET HERE!!!\n");
606                 tempPwdPtr = NULL;
607 #endif // HAVE_GETPWNAM_R
608                 if (tempPwdPtr == NULL) {
609                         CON_syslog(LOG_DEBUG, "no such user <%s>\n", username);
610                         return login_not_found;
611                 }
612         
613                 /* Locate the associated Citadel account.
614                  * If not found, make one attempt to create it.
615                  */
616                 found_user = getuserbyuid(&CC->user, pd.pw_uid);
617                 CON_syslog(LOG_DEBUG, "found it: uid=%ld, gecos=%s here: %d\n",
618                         (long)pd.pw_uid, pd.pw_gecos, found_user);
619                 if (found_user != 0) {
620                         len = cutuserkey(username);
621                         create_user(username, len, 0);
622                         found_user = getuserbyuid(&CC->user, pd.pw_uid);
623                 }
624
625         }
626
627 #ifdef HAVE_LDAP
628         else if ((config.c_auth_mode == AUTHMODE_LDAP) || (config.c_auth_mode == AUTHMODE_LDAP_AD)) {
629         
630                 /* LDAP auth mode */
631
632                 uid_t ldap_uid;
633                 char ldap_cn[256];
634                 char ldap_dn[256];
635
636                 found_user = CtdlTryUserLDAP(username, ldap_dn, sizeof ldap_dn, ldap_cn, sizeof ldap_cn, &ldap_uid);
637                 if (found_user != 0) {
638                         return login_not_found;
639                 }
640
641                 found_user = getuserbyuid(&CC->user, ldap_uid);
642                 if (found_user != 0) {
643                         create_user(username, len, 0);
644                         found_user = getuserbyuid(&CC->user, ldap_uid);
645                 }
646
647                 if (found_user == 0) {
648                         if (CC->ldap_dn != NULL) free(CC->ldap_dn);
649                         CC->ldap_dn = strdup(ldap_dn);
650                 }
651
652         }
653 #endif
654
655         else {
656                 /* native auth mode */
657
658                 recptypes *valid = NULL;
659         
660                 /* First, try to log in as if the supplied name is a display name */
661                 found_user = CtdlGetUser(&CC->user, username);
662         
663                 /* If that didn't work, try to log in as if the supplied name
664                 * is an e-mail address
665                 */
666                 if (found_user != 0) {
667                         valid = validate_recipients(username, NULL, 0);
668                         if (valid != NULL) {
669                                 if (valid->num_local == 1) {
670                                         found_user = CtdlGetUser(&CC->user, valid->recp_local);
671                                 }
672                                 free_recipients(valid);
673                         }
674                 }
675         }
676
677         /* Did we find something? */
678         if (found_user == 0) {
679                 if (((CC->nologin)) && (CC->user.axlevel < AxAideU)) {
680                         return login_too_many_users;
681                 } else {
682                         safestrncpy(CC->curr_user, CC->user.fullname,
683                                         sizeof CC->curr_user);
684                         return login_ok;
685                 }
686         }
687         return login_not_found;
688 }
689
690
691
692
693
694 /*
695  * session startup code which is common to both cmd_pass() and cmd_newu()
696  */
697 void do_login(void)
698 {
699         struct CitContext *CCC = CC;
700
701         CCC->logged_in = 1;
702         CON_syslog(LOG_NOTICE, "<%s> logged in\n", CCC->curr_user);
703
704         CtdlGetUserLock(&CCC->user, CCC->curr_user);
705         ++(CCC->user.timescalled);
706         CCC->previous_login = CCC->user.lastcall;
707         time(&CCC->user.lastcall);
708
709         /* If this user's name is the name of the system administrator
710          * (as specified in setup), automatically assign access level 6.
711          */
712         if (!strcasecmp(CCC->user.fullname, config.c_sysadm)) {
713                 CCC->user.axlevel = AxAideU;
714         }
715
716         /* If we're authenticating off the host system, automatically give
717          * root the highest level of access.
718          */
719         if (config.c_auth_mode == AUTHMODE_HOST) {
720                 if (CCC->user.uid == 0) {
721                         CCC->user.axlevel = AxAideU;
722                 }
723         }
724
725         CtdlPutUserLock(&CCC->user);
726
727         /*
728          * Populate CCC->cs_inet_email with a default address.  This will be
729          * overwritten with the user's directory address, if one exists, when
730          * the vCard module's login hook runs.
731          */
732         snprintf(CCC->cs_inet_email, sizeof CCC->cs_inet_email, "%s@%s",
733                 CCC->user.fullname, config.c_fqdn);
734         convert_spaces_to_underscores(CCC->cs_inet_email);
735
736         /* Create any personal rooms required by the system.
737          * (Technically, MAILROOM should be there already, but just in case...)
738          */
739         CtdlCreateRoom(MAILROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
740         CtdlCreateRoom(SENTITEMS, 4, "", 0, 1, 0, VIEW_MAILBOX);
741         CtdlCreateRoom(USERTRASHROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
742         CtdlCreateRoom(USERDRAFTROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
743
744         /* Run any startup routines registered by loadable modules */
745         PerformSessionHooks(EVT_LOGIN);
746
747         /* Enter the lobby */
748         CtdlUserGoto(config.c_baseroom, 0, 0, NULL, NULL);
749 }
750
751
752 void logged_in_response(void)
753 {
754         cprintf("%d %s|%d|%ld|%ld|%u|%ld|%ld\n",
755                 CIT_OK, CC->user.fullname, CC->user.axlevel,
756                 CC->user.timescalled, CC->user.posted,
757                 CC->user.flags, CC->user.usernum,
758                 CC->previous_login);
759 }
760
761
762
763 void CtdlUserLogout(void)
764 {
765         CitContext *CCC = MyContext();
766
767         CON_syslog(LOG_DEBUG, "CtdlUserLogout() logging out <%s> from session %d",
768                    CCC->curr_user, CCC->cs_pid
769         );
770
771         /* Run any hooks registered by modules... */
772         PerformSessionHooks(EVT_LOGOUT);
773         
774         /*
775          * Clear out some session data.  Most likely, the CitContext for this
776          * session is about to get nuked when the session disconnects, but
777          * since it's possible to log in again without reconnecting, we cannot
778          * make that assumption.
779          */
780         strcpy(CCC->fake_username, "");
781         strcpy(CCC->fake_hostname, "");
782         strcpy(CCC->fake_roomname, "");
783         CCC->logged_in = 0;
784
785         /* Check to see if the user was deleted whilst logged in and purge them if necessary */
786         if ((CCC->user.axlevel == AxDeleted) && (CCC->user.usernum))
787                 purge_user(CCC->user.fullname);
788
789         /* Clear out the user record in memory so we don't behave like a ghost */
790         memset(&CCC->user, 0, sizeof(struct ctdluser));
791         CCC->curr_user[0] = 0;
792         CCC->is_master = 0;
793         CCC->cs_inet_email[0] = 0;
794         CCC->cs_inet_other_emails[0] = 0;
795         CCC->cs_inet_fn[0] = 0;
796         CCC->fake_username[0] = 0;
797         CCC->fake_hostname[0] = 0;
798         CCC->fake_roomname[0] = 0;
799         
800
801         /* Free any output buffers */
802         unbuffer_output();
803 }
804
805
806 /*
807  * Validate a password on the host unix system by talking to the chkpwd daemon
808  */
809 static int validpw(uid_t uid, const char *pass)
810 {
811         char buf[256];
812         int rv = 0;
813
814         if (IsEmptyStr(pass)) {
815                 CON_syslog(LOG_DEBUG, "Refusing to chkpwd for uid=%d with empty password.\n", uid);
816                 return 0;
817         }
818
819         CON_syslog(LOG_DEBUG, "Validating password for uid=%d using chkpwd...\n", uid);
820
821         begin_critical_section(S_CHKPWD);
822         rv = write(chkpwd_write_pipe[1], &uid, sizeof(uid_t));
823         if (rv == -1) {
824                 CON_syslog(LOG_EMERG, "Communicatino with chkpwd broken: %s\n", strerror(errno));
825                 end_critical_section(S_CHKPWD);
826                 return 0;
827         }
828         rv = write(chkpwd_write_pipe[1], pass, 256);
829         if (rv == -1) {
830                 CON_syslog(LOG_EMERG, "Communicatino with chkpwd broken: %s\n", strerror(errno));
831                 end_critical_section(S_CHKPWD);
832                 return 0;
833         }
834         rv = read(chkpwd_read_pipe[0], buf, 4);
835         if (rv == -1) {
836                 CON_syslog(LOG_EMERG, "Communicatino with chkpwd broken: %s\n", strerror(errno));
837                 end_critical_section(S_CHKPWD);
838                 return 0;
839         }
840         end_critical_section(S_CHKPWD);
841
842         if (!strncmp(buf, "PASS", 4)) {
843                 CONM_syslog(LOG_DEBUG, "...pass\n");
844                 return(1);
845         }
846
847         CONM_syslog(LOG_DEBUG, "...fail\n");
848         return 0;
849 }
850
851 /* 
852  * Start up the chkpwd daemon so validpw() has something to talk to
853  */
854 void start_chkpwd_daemon(void) {
855         pid_t chkpwd_pid;
856         struct stat filestats;
857         int i;
858
859         CONM_syslog(LOG_DEBUG, "Starting chkpwd daemon for host authentication mode\n");
860
861         if ((stat(file_chkpwd, &filestats)==-1) ||
862             (filestats.st_size==0)){
863                 printf("didn't find chkpwd daemon in %s: %s\n", file_chkpwd, strerror(errno));
864                 abort();
865         }
866         if (pipe(chkpwd_write_pipe) != 0) {
867                 CON_syslog(LOG_EMERG, "Unable to create pipe for chkpwd daemon: %s\n", strerror(errno));
868                 abort();
869         }
870         if (pipe(chkpwd_read_pipe) != 0) {
871                 CON_syslog(LOG_EMERG, "Unable to create pipe for chkpwd daemon: %s\n", strerror(errno));
872                 abort();
873         }
874
875         chkpwd_pid = fork();
876         if (chkpwd_pid < 0) {
877                 CON_syslog(LOG_EMERG, "Unable to fork chkpwd daemon: %s\n", strerror(errno));
878                 abort();
879         }
880         if (chkpwd_pid == 0) {
881                 CONM_syslog(LOG_DEBUG, "Now calling dup2() write\n");
882                 dup2(chkpwd_write_pipe[0], 0);
883                 CONM_syslog(LOG_DEBUG, "Now calling dup2() write\n");
884                 dup2(chkpwd_read_pipe[1], 1);
885                 CONM_syslog(LOG_DEBUG, "Now closing stuff\n");
886                 for (i=2; i<256; ++i) close(i);
887                 CON_syslog(LOG_DEBUG, "Now calling execl(%s)\n", file_chkpwd);
888                 execl(file_chkpwd, file_chkpwd, NULL);
889                 CON_syslog(LOG_EMERG, "Unable to exec chkpwd daemon: %s\n", strerror(errno));
890                 abort();
891                 exit(errno);
892         }
893 }
894
895
896 int CtdlTryPassword(const char *password, long len)
897 {
898         int code;
899         CitContext *CCC = CC;
900
901         if ((CCC->logged_in)) {
902                 CONM_syslog(LOG_WARNING, "CtdlTryPassword: already logged in\n");
903                 return pass_already_logged_in;
904         }
905         if (!strcmp(CCC->curr_user, NLI)) {
906                 CONM_syslog(LOG_WARNING, "CtdlTryPassword: no user selected\n");
907                 return pass_no_user;
908         }
909         if (CtdlGetUser(&CCC->user, CCC->curr_user)) {
910                 CONM_syslog(LOG_ERR, "CtdlTryPassword: internal error\n");
911                 return pass_internal_error;
912         }
913         if (password == NULL) {
914                 CONM_syslog(LOG_INFO, "CtdlTryPassword: NULL password string supplied\n");
915                 return pass_wrong_password;
916         }
917
918         if (CCC->is_master) {
919                 code = strcmp(password, config.c_master_pass);
920         }
921
922         else if (config.c_auth_mode == AUTHMODE_HOST) {
923
924                 /* host auth mode */
925
926                 if (validpw(CCC->user.uid, password)) {
927                         code = 0;
928
929                         /*
930                          * sooper-seekrit hack: populate the password field in the
931                          * citadel database with the password that the user typed,
932                          * if it's correct.  This allows most sites to convert from
933                          * host auth to native auth if they want to.  If you think
934                          * this is a security hazard, comment it out.
935                          */
936
937                         CtdlGetUserLock(&CCC->user, CCC->curr_user);
938                         safestrncpy(CCC->user.password, password, sizeof CCC->user.password);
939                         CtdlPutUserLock(&CCC->user);
940
941                         /*
942                          * (sooper-seekrit hack ends here)
943                          */
944
945                 }
946                 else {
947                         code = (-1);
948                 }
949         }
950
951 #ifdef HAVE_LDAP
952         else if ((config.c_auth_mode == AUTHMODE_LDAP) || (config.c_auth_mode == AUTHMODE_LDAP_AD)) {
953
954                 /* LDAP auth mode */
955
956                 if ((CCC->ldap_dn) && (!CtdlTryPasswordLDAP(CCC->ldap_dn, password))) {
957                         code = 0;
958                 }
959                 else {
960                         code = (-1);
961                 }
962         }
963 #endif
964
965         else {
966
967                 /* native auth mode */
968                 char *pw;
969
970                 pw = (char*) malloc(len + 1);
971                 memcpy(pw, password, len + 1);
972                 strproc(pw);
973                 strproc(CCC->user.password);
974                 code = strcasecmp(CCC->user.password, pw);
975                 if (code != 0) {
976                         strproc(pw);
977                         strproc(CCC->user.password);
978                         code = strcasecmp(CCC->user.password, pw);
979                 }
980                 free (pw);
981         }
982
983         if (!code) {
984                 do_login();
985                 return pass_ok;
986         } else {
987                 CON_syslog(LOG_WARNING, "Bad password specified for <%s> Service <%s> Port <%ld> Remote <%s / %s>\n",
988                            CCC->curr_user,
989                            CCC->ServiceName,
990                            CCC->tcp_port,
991                            CCC->cs_host,
992                            CCC->cs_addr);
993
994
995 //citserver[5610]: Bad password specified for <willi> Service <citadel-TCP> Remote <PotzBlitz / >
996
997                 return pass_wrong_password;
998         }
999 }
1000
1001
1002
1003
1004 /*
1005  * Delete a user record *and* all of its related resources.
1006  */
1007 int purge_user(char pname[])
1008 {
1009         char filename[64];
1010         struct ctdluser usbuf;
1011         char usernamekey[USERNAME_SIZE];
1012
1013         makeuserkey(usernamekey, pname, cutuserkey(pname));
1014
1015         /* If the name is empty we can't find them in the DB any way so just return */
1016         if (IsEmptyStr(pname))
1017                 return (ERROR + NO_SUCH_USER);
1018
1019         if (CtdlGetUser(&usbuf, pname) != 0) {
1020                 CON_syslog(LOG_ERR, "Cannot purge user <%s> - not found\n", pname);
1021                 return (ERROR + NO_SUCH_USER);
1022         }
1023         /* Don't delete a user who is currently logged in.  Instead, just
1024          * set the access level to 0, and let the account get swept up
1025          * during the next purge.
1026          */
1027         if (CtdlIsUserLoggedInByNum(usbuf.usernum)) {
1028                 CON_syslog(LOG_WARNING, "User <%s> is logged in; not deleting.\n", pname);
1029                 usbuf.axlevel = AxDeleted;
1030                 CtdlPutUser(&usbuf);
1031                 return (1);
1032         }
1033         CON_syslog(LOG_NOTICE, "Deleting user <%s>\n", pname);
1034
1035 /*
1036  * FIXME:
1037  * This should all be wrapped in a S_USERS mutex.
1038  * Without the mutex the user could log in before we get to the next function
1039  * That would truly mess things up :-(
1040  * I would like to see the S_USERS start before the CtdlIsUserLoggedInByNum() above
1041  * and end after the user has been deleted from the database, below.
1042  * Question is should we enter the EVT_PURGEUSER whilst S_USERS is active?
1043  */
1044
1045         /* Perform any purge functions registered by server extensions */
1046         PerformUserHooks(&usbuf, EVT_PURGEUSER);
1047
1048         /* delete any existing user/room relationships */
1049         cdb_delete(CDB_VISIT, &usbuf.usernum, sizeof(long));
1050
1051         /* delete the users-by-number index record */
1052         cdb_delete(CDB_USERSBYNUMBER, &usbuf.usernum, sizeof(long));
1053
1054         /* delete the userlog entry */
1055         cdb_delete(CDB_USERS, usernamekey, strlen(usernamekey));
1056
1057         /* remove the user's bio file */
1058         snprintf(filename, 
1059                          sizeof filename, 
1060                          "%s/%ld",
1061                          ctdl_bio_dir,
1062                          usbuf.usernum);
1063         unlink(filename);
1064
1065         /* remove the user's picture */
1066         snprintf(filename, 
1067                          sizeof filename, 
1068                          "%s/%ld.gif",
1069                          ctdl_image_dir,
1070                          usbuf.usernum);
1071         unlink(filename);
1072
1073         return (0);
1074 }
1075
1076
1077 int internal_create_user (const char *username, long len, struct ctdluser *usbuf, uid_t uid)
1078 {
1079         if (!CtdlGetUserLen(usbuf, username, len)) {
1080                 return (ERROR + ALREADY_EXISTS);
1081         }
1082
1083         /* Go ahead and initialize a new user record */
1084         memset(usbuf, 0, sizeof(struct ctdluser));
1085         safestrncpy(usbuf->fullname, username, sizeof usbuf->fullname);
1086         strcpy(usbuf->password, "");
1087         usbuf->uid = uid;
1088
1089         /* These are the default flags on new accounts */
1090         usbuf->flags = US_LASTOLD | US_DISAPPEAR | US_PAGINATOR | US_FLOORS;
1091
1092         usbuf->timescalled = 0;
1093         usbuf->posted = 0;
1094         usbuf->axlevel = config.c_initax;
1095         usbuf->lastcall = time(NULL);
1096
1097         /* fetch a new user number */
1098         usbuf->usernum = get_new_user_number();
1099
1100         /* add user to the database */
1101         CtdlPutUser(usbuf);
1102         cdb_store(CDB_USERSBYNUMBER, &usbuf->usernum, sizeof(long), usbuf->fullname, strlen(usbuf->fullname)+1);
1103
1104         return 0;
1105 }
1106
1107
1108
1109 /*
1110  * create_user()  -  back end processing to create a new user
1111  *
1112  * Set 'newusername' to the desired account name.
1113  * Set 'become_user' to nonzero if this is self-service account creation and we want
1114  * to actually log in as the user we just created, otherwise set it to 0.
1115  */
1116 int create_user(const char *newusername, long len, int become_user)
1117 {
1118         struct ctdluser usbuf;
1119         struct ctdlroom qrbuf;
1120         char username[256];
1121         char mailboxname[ROOMNAMELEN];
1122         char buf[SIZ];
1123         int retval;
1124         uid_t uid = (-1);
1125         
1126
1127         safestrncpy(username, newusername, sizeof username);
1128         strproc(username);
1129
1130         
1131         if (config.c_auth_mode == AUTHMODE_HOST) {
1132
1133                 /* host auth mode */
1134
1135                 struct passwd pd;
1136                 struct passwd *tempPwdPtr;
1137                 char pwdbuffer[SIZ];
1138         
1139 #ifdef HAVE_GETPWNAM_R
1140 #ifdef SOLARIS_GETPWUID
1141                 tempPwdPtr = getpwnam_r(username, &pd, pwdbuffer, sizeof(pwdbuffer));
1142 #else // SOLARIS_GETPWUID
1143                 getpwnam_r(username, &pd, pwdbuffer, sizeof pwdbuffer, &tempPwdPtr);
1144 #endif // SOLARIS_GETPWUID
1145 #else // HAVE_GETPWNAM_R
1146                 tempPwdPtr = NULL;
1147 #endif // HAVE_GETPWNAM_R
1148                 if (tempPwdPtr != NULL) {
1149                         extract_token(username, pd.pw_gecos, 0, ',', sizeof username);
1150                         uid = pd.pw_uid;
1151                         if (IsEmptyStr (username))
1152                         {
1153                                 safestrncpy(username, pd.pw_name, sizeof username);
1154                                 len = cutuserkey(username);
1155                         }
1156                 }
1157                 else {
1158                         return (ERROR + NO_SUCH_USER);
1159                 }
1160         }
1161
1162 #ifdef HAVE_LDAP
1163         if ((config.c_auth_mode == AUTHMODE_LDAP) || (config.c_auth_mode == AUTHMODE_LDAP_AD)) {
1164                 if (CtdlTryUserLDAP(username, NULL, 0, username, sizeof username, &uid) != 0) {
1165                         return(ERROR + NO_SUCH_USER);
1166                 }
1167         }
1168 #endif /* HAVE_LDAP */
1169         
1170         if ((retval = internal_create_user(username, len, &usbuf, uid)) != 0)
1171                 return retval;
1172         
1173         /*
1174          * Give the user a private mailbox and a configuration room.
1175          * Make the latter an invisible system room.
1176          */
1177         CtdlMailboxName(mailboxname, sizeof mailboxname, &usbuf, MAILROOM);
1178         CtdlCreateRoom(mailboxname, 5, "", 0, 1, 1, VIEW_MAILBOX);
1179
1180         CtdlMailboxName(mailboxname, sizeof mailboxname, &usbuf, USERCONFIGROOM);
1181         CtdlCreateRoom(mailboxname, 5, "", 0, 1, 1, VIEW_BBS);
1182         if (CtdlGetRoomLock(&qrbuf, mailboxname) == 0) {
1183                 qrbuf.QRflags2 |= QR2_SYSTEM;
1184                 CtdlPutRoomLock(&qrbuf);
1185         }
1186
1187         /* Perform any create functions registered by server extensions */
1188         PerformUserHooks(&usbuf, EVT_NEWUSER);
1189
1190         /* Everything below this line can be bypassed if administratively
1191          * creating a user, instead of doing self-service account creation
1192          */
1193
1194         if (become_user) {
1195                 /* Now become the user we just created */
1196                 memcpy(&CC->user, &usbuf, sizeof(struct ctdluser));
1197                 safestrncpy(CC->curr_user, username, sizeof CC->curr_user);
1198                 do_login();
1199         
1200                 /* Check to make sure we're still who we think we are */
1201                 if (CtdlGetUser(&CC->user, CC->curr_user)) {
1202                         return (ERROR + INTERNAL_ERROR);
1203                 }
1204         }
1205         
1206         snprintf(buf, SIZ, 
1207                 "New user account <%s> has been created, from host %s [%s].\n",
1208                 username,
1209                 CC->cs_host,
1210                 CC->cs_addr
1211         );
1212         CtdlAideMessage(buf, "User Creation Notice");
1213         CON_syslog(LOG_NOTICE, "New user <%s> created\n", username);
1214         return (0);
1215 }
1216
1217
1218
1219 /*
1220  * set password - back end api code
1221  */
1222 void CtdlSetPassword(char *new_pw)
1223 {
1224         CtdlGetUserLock(&CC->user, CC->curr_user);
1225         safestrncpy(CC->user.password, new_pw, sizeof(CC->user.password));
1226         CtdlPutUserLock(&CC->user);
1227         CON_syslog(LOG_INFO, "Password changed for user <%s>\n", CC->curr_user);
1228         PerformSessionHooks(EVT_SETPASS);
1229 }
1230
1231
1232
1233
1234 /*
1235  * API function for cmd_invt_kick() and anything else that needs to
1236  * invite or kick out a user to/from a room.
1237  * 
1238  * Set iuser to the name of the user, and op to 1=invite or 0=kick
1239  */
1240 int CtdlInvtKick(char *iuser, int op) {
1241         struct ctdluser USscratch;
1242         visit vbuf;
1243         char bbb[SIZ];
1244
1245         if (CtdlGetUser(&USscratch, iuser) != 0) {
1246                 return(1);
1247         }
1248
1249         CtdlGetRelationship(&vbuf, &USscratch, &CC->room);
1250         if (op == 1) {
1251                 vbuf.v_flags = vbuf.v_flags & ~V_FORGET & ~V_LOCKOUT;
1252                 vbuf.v_flags = vbuf.v_flags | V_ACCESS;
1253         }
1254         if (op == 0) {
1255                 vbuf.v_flags = vbuf.v_flags & ~V_ACCESS;
1256                 vbuf.v_flags = vbuf.v_flags | V_FORGET | V_LOCKOUT;
1257         }
1258         CtdlSetRelationship(&vbuf, &USscratch, &CC->room);
1259
1260         /* post a message in Aide> saying what we just did */
1261         snprintf(bbb, sizeof bbb, "%s has been %s \"%s\" by %s.\n",
1262                 iuser,
1263                 ((op == 1) ? "invited to" : "kicked out of"),
1264                 CC->room.QRname,
1265                 (CC->logged_in ? CC->user.fullname : "an administrator")
1266         );
1267         CtdlAideMessage(bbb,"User Admin Message");
1268
1269         return(0);
1270 }
1271
1272
1273 /*
1274  * Forget (Zap) the current room (API call)
1275  * Returns 0 on success
1276  */
1277 int CtdlForgetThisRoom(void) {
1278         visit vbuf;
1279
1280         /* On some systems, Admins are not allowed to forget rooms */
1281         if (is_aide() && (config.c_aide_zap == 0)
1282            && ((CC->room.QRflags & QR_MAILBOX) == 0)  ) {
1283                 return(1);
1284         }
1285
1286         CtdlGetUserLock(&CC->user, CC->curr_user);
1287         CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
1288
1289         vbuf.v_flags = vbuf.v_flags | V_FORGET;
1290         vbuf.v_flags = vbuf.v_flags & ~V_ACCESS;
1291
1292         CtdlSetRelationship(&vbuf, &CC->user, &CC->room);
1293         CtdlPutUserLock(&CC->user);
1294
1295         /* Return to the Lobby, so we don't end up in an undefined room */
1296         CtdlUserGoto(config.c_baseroom, 0, 0, NULL, NULL);
1297         return(0);
1298
1299 }
1300
1301
1302
1303
1304 /* 
1305  *  Traverse the user file...
1306  */
1307 void ForEachUser(void (*CallBack) (struct ctdluser * EachUser, void *out_data),
1308                  void *in_data)
1309 {
1310         struct ctdluser usbuf;
1311         struct cdbdata *cdbus;
1312
1313         cdb_rewind(CDB_USERS);
1314
1315         while (cdbus = cdb_next_item(CDB_USERS), cdbus != NULL) {
1316                 memset(&usbuf, 0, sizeof(struct ctdluser));
1317                 memcpy(&usbuf, cdbus->ptr,
1318                        ((cdbus->len > sizeof(struct ctdluser)) ?
1319                         sizeof(struct ctdluser) : cdbus->len));
1320                 cdb_free(cdbus);
1321                 (*CallBack) (&usbuf, in_data);
1322         }
1323 }
1324
1325
1326 /*
1327  * List one user (this works with cmd_list)
1328  */
1329 void ListThisUser(struct ctdluser *usbuf, void *data)
1330 {
1331         char *searchstring;
1332
1333         searchstring = (char *)data;
1334         if (bmstrcasestr(usbuf->fullname, searchstring) == NULL) {
1335                 return;
1336         }
1337
1338         if (usbuf->axlevel > AxDeleted) {
1339                 if ((CC->user.axlevel >= AxAideU)
1340                     || ((usbuf->flags & US_UNLISTED) == 0)
1341                     || ((CC->internal_pgm))) {
1342                         cprintf("%s|%d|%ld|%ld|%ld|%ld||\n",
1343                                 usbuf->fullname,
1344                                 usbuf->axlevel,
1345                                 usbuf->usernum,
1346                                 (long)usbuf->lastcall,
1347                                 usbuf->timescalled,
1348                                 usbuf->posted);
1349                 }
1350         }
1351 }
1352
1353
1354
1355
1356 /*
1357  * Count the number of new mail messages the user has
1358  */
1359 int NewMailCount()
1360 {
1361         int num_newmsgs = 0;
1362
1363         num_newmsgs = CC->newmail;
1364         CC->newmail = 0;
1365
1366         return (num_newmsgs);
1367 }
1368
1369
1370 /*
1371  * Count the number of new mail messages the user has
1372  */
1373 int InitialMailCheck()
1374 {
1375         int num_newmsgs = 0;
1376         int a;
1377         char mailboxname[ROOMNAMELEN];
1378         struct ctdlroom mailbox;
1379         visit vbuf;
1380         struct cdbdata *cdbfr;
1381         long *msglist = NULL;
1382         int num_msgs = 0;
1383
1384         CtdlMailboxName(mailboxname, sizeof mailboxname, &CC->user, MAILROOM);
1385         if (CtdlGetRoom(&mailbox, mailboxname) != 0)
1386                 return (0);
1387         CtdlGetRelationship(&vbuf, &CC->user, &mailbox);
1388
1389         cdbfr = cdb_fetch(CDB_MSGLISTS, &mailbox.QRnumber, sizeof(long));
1390
1391         if (cdbfr != NULL) {
1392                 msglist = malloc(cdbfr->len);
1393                 memcpy(msglist, cdbfr->ptr, cdbfr->len);
1394                 num_msgs = cdbfr->len / sizeof(long);
1395                 cdb_free(cdbfr);
1396         }
1397         if (num_msgs > 0)
1398                 for (a = 0; a < num_msgs; ++a) {
1399                         if (msglist[a] > 0L) {
1400                                 if (msglist[a] > vbuf.v_lastseen) {
1401                                         ++num_newmsgs;
1402                                 }
1403                         }
1404                 }
1405         if (msglist != NULL)
1406                 free(msglist);
1407
1408         return (num_newmsgs);
1409 }
1410
1411
1412
1413