* make the user const
[citadel.git] / citadel / user_ops.c
1 /* 
2  * $Id$
3  *
4  * Server functions which perform operations on user objects.
5  *
6  */
7
8 #include "sysdep.h"
9 #include <errno.h>
10 #include <stdlib.h>
11 #include <unistd.h>
12 #include <stdio.h>
13 #include <fcntl.h>
14 #include <signal.h>
15 #include <pwd.h>
16 #include <ctype.h>
17 #include <sys/types.h>
18 #include <sys/wait.h>
19 #ifdef HAVE_SYS_STAT_H
20 #include <sys/stat.h>
21 #endif
22
23 #if TIME_WITH_SYS_TIME
24 # include <sys/time.h>
25 # include <time.h>
26 #else
27 # if HAVE_SYS_TIME_H
28 #  include <sys/time.h>
29 # else
30 #  include <time.h>
31 # endif
32 #endif
33
34 #include <string.h>
35 #include <limits.h>
36 #include <libcitadel.h>
37 #include "auth.h"
38 #include "citadel.h"
39 #include "server.h"
40 #include "database.h"
41 #include "user_ops.h"
42 #include "sysdep_decls.h"
43 #include "support.h"
44 #include "room_ops.h"
45 #include "file_ops.h"
46 #include "control.h"
47 #include "msgbase.h"
48 #include "config.h"
49 #include "citserver.h"
50 #include "citadel_dirs.h"
51 #include "genstamp.h"
52 #include "threads.h"
53 #include "citadel_ldap.h"
54 #include "context.h"
55
56 #include "ctdl_module.h"
57
58 /* These pipes are used to talk to the chkpwd daemon, which is forked during startup */
59 int chkpwd_write_pipe[2];
60 int chkpwd_read_pipe[2];
61
62 /*
63  * makeuserkey() - convert a username into the format used as a database key
64  *               (it's just the username converted into lower case)
65  */
66 INLINE void makeuserkey(char *key, const char *username) {
67         int i, len;
68
69         len = strlen(username);
70         if (len >= USERNAME_SIZE)
71         {
72                 CtdlLogPrintf (CTDL_EMERG, "Username to long: %s", username);
73                 cit_backtrace ();
74                 len = USERNAME_SIZE - 1; 
75                 /* WHOOPSI! whats that??? todo. */
76                 ((char*)username)[USERNAME_SIZE - 1]='\0';
77         }
78         for (i=0; i<=len; ++i) {
79                 key[i] = tolower(username[i]);
80         }
81 }
82
83
84 /*
85  * getuser()  -  retrieve named user into supplied buffer.
86  *             returns 0 on success
87  */
88 int getuser(struct ctdluser *usbuf, char name[])
89 {
90         return CtdlGetUser(usbuf, name);
91 }
92
93
94 /*
95  * CtdlGetUser()  -  retrieve named user into supplied buffer.
96  *             returns 0 on success
97  */
98 int CtdlGetUser(struct ctdluser *usbuf, const char *name)
99 {
100
101         char usernamekey[USERNAME_SIZE];
102         struct cdbdata *cdbus;
103
104         if (usbuf != NULL) {
105                 memset(usbuf, 0, sizeof(struct ctdluser));
106         }
107
108         makeuserkey(usernamekey, name);
109         cdbus = cdb_fetch(CDB_USERS, usernamekey, strlen(usernamekey));
110
111         if (cdbus == NULL) {    /* user not found */
112                 return(1);
113         }
114         if (usbuf != NULL) {
115                 memcpy(usbuf, cdbus->ptr,
116                         ((cdbus->len > sizeof(struct ctdluser)) ?
117                          sizeof(struct ctdluser) : cdbus->len));
118         }
119         cdb_free(cdbus);
120
121         return (0);
122 }
123
124
125 /*
126  * CtdlGetUserLock()  -  same as getuser() but locks the record
127  */
128 int CtdlGetUserLock(struct ctdluser *usbuf, char *name)
129 {
130         int retcode;
131
132         retcode = CtdlGetUser(usbuf, name);
133         if (retcode == 0) {
134                 begin_critical_section(S_USERS);
135         }
136         return (retcode);
137 }
138
139
140 /*
141  * lgetuser()  -  same as getuser() but locks the record
142  */
143 int lgetuser(struct ctdluser *usbuf, char *name)
144 {
145         return CtdlGetUserLock(usbuf, name);
146 }
147
148
149 /*
150  * CtdlPutUser()  -  write user buffer into the correct place on disk
151  */
152 void CtdlPutUser(struct ctdluser *usbuf)
153 {
154         char usernamekey[USERNAME_SIZE];
155
156         makeuserkey(usernamekey, usbuf->fullname);
157
158         usbuf->version = REV_LEVEL;
159         cdb_store(CDB_USERS,
160                   usernamekey, strlen(usernamekey),
161                   usbuf, sizeof(struct ctdluser));
162
163 }
164
165
166 /*
167  * putuser()  -  write user buffer into the correct place on disk
168  */
169 void putuser(struct ctdluser *usbuf)
170 {
171         CtdlPutUser(usbuf);
172 }
173
174
175 /*
176  * CtdlPutUserLock()  -  same as putuser() but locks the record
177  */
178 void CtdlPutUserLock(struct ctdluser *usbuf)
179 {
180         CtdlPutUser(usbuf);
181         end_critical_section(S_USERS);
182 }
183
184
185 /*
186  * lputuser()  -  same as putuser() but locks the record
187  */
188 void lputuser(struct ctdluser *usbuf)
189 {
190         CtdlPutUserLock(usbuf);
191 }
192
193
194 /*
195  * rename_user()  -  this is tricky because the user's display name is the database key
196  *
197  * Returns 0 on success or nonzero if there was an error...
198  *
199  */
200 int rename_user(char *oldname, char *newname) {
201         int retcode = RENAMEUSER_OK;
202         struct ctdluser usbuf;
203
204         char oldnamekey[USERNAME_SIZE];
205         char newnamekey[USERNAME_SIZE];
206
207         /* Create the database keys... */
208         makeuserkey(oldnamekey, oldname);
209         makeuserkey(newnamekey, newname);
210
211         /* Lock up and get going */
212         begin_critical_section(S_USERS);
213
214         /* We cannot rename a user who is currently logged in */
215         if (CtdlIsUserLoggedIn(oldname)) {
216                 end_critical_section(S_USERS);
217                 return RENAMEUSER_LOGGED_IN;
218         }
219
220         if (CtdlGetUser(&usbuf, newname) == 0) {
221                 retcode = RENAMEUSER_ALREADY_EXISTS;
222         }
223         else {
224
225                 if (CtdlGetUser(&usbuf, oldname) != 0) {
226                         retcode = RENAMEUSER_NOT_FOUND;
227                 }
228
229                 else {          /* Sanity checks succeeded.  Now rename the user. */
230                         if (usbuf.usernum == 0)
231                         {
232                                 CtdlLogPrintf (CTDL_DEBUG, "Can not rename user \"Citadel\".\n");
233                                 retcode = RENAMEUSER_NOT_FOUND;
234                         } else {
235                                 CtdlLogPrintf(CTDL_DEBUG, "Renaming <%s> to <%s>\n", oldname, newname);
236                                 cdb_delete(CDB_USERS, oldnamekey, strlen(oldnamekey));
237                                 safestrncpy(usbuf.fullname, newname, sizeof usbuf.fullname);
238                                 CtdlPutUser(&usbuf);
239                                 cdb_store(CDB_USERSBYNUMBER, &usbuf.usernum, sizeof(long),
240                                         usbuf.fullname, strlen(usbuf.fullname)+1 );
241
242                                 retcode = RENAMEUSER_OK;
243                         }
244                 }
245         
246         }
247
248         end_critical_section(S_USERS);
249         return(retcode);
250 }
251
252
253
254 /*
255  * Index-generating function used by Ctdl[Get|Set]Relationship
256  */
257 int GenerateRelationshipIndex(char *IndexBuf,
258                               long RoomID,
259                               long RoomGen,
260                               long UserID)
261 {
262
263         struct {
264                 long iRoomID;
265                 long iRoomGen;
266                 long iUserID;
267         } TheIndex;
268
269         TheIndex.iRoomID = RoomID;
270         TheIndex.iRoomGen = RoomGen;
271         TheIndex.iUserID = UserID;
272
273         memcpy(IndexBuf, &TheIndex, sizeof(TheIndex));
274         return (sizeof(TheIndex));
275 }
276
277
278
279 /*
280  * Back end for CtdlSetRelationship()
281  */
282 void put_visit(struct visit *newvisit)
283 {
284         char IndexBuf[32];
285         int IndexLen = 0;
286
287         memset (IndexBuf, 0, sizeof (IndexBuf));
288         /* Generate an index */
289         IndexLen = GenerateRelationshipIndex(IndexBuf,
290                                              newvisit->v_roomnum,
291                                              newvisit->v_roomgen,
292                                              newvisit->v_usernum);
293
294         /* Store the record */
295         cdb_store(CDB_VISIT, IndexBuf, IndexLen,
296                   newvisit, sizeof(struct visit)
297         );
298 }
299
300
301
302
303 /*
304  * Define a relationship between a user and a room
305  */
306 void CtdlSetRelationship(struct visit *newvisit,
307                          struct ctdluser *rel_user,
308                          struct ctdlroom *rel_room)
309 {
310
311
312         /* We don't use these in Citadel because they're implicit by the
313          * index, but they must be present if the database is exported.
314          */
315         newvisit->v_roomnum = rel_room->QRnumber;
316         newvisit->v_roomgen = rel_room->QRgen;
317         newvisit->v_usernum = rel_user->usernum;
318
319         put_visit(newvisit);
320 }
321
322 /*
323  * Locate a relationship between a user and a room
324  */
325 void CtdlGetRelationship(struct visit *vbuf,
326                          struct ctdluser *rel_user,
327                          struct ctdlroom *rel_room)
328 {
329
330         char IndexBuf[32];
331         int IndexLen;
332         struct cdbdata *cdbvisit;
333
334         /* Generate an index */
335         IndexLen = GenerateRelationshipIndex(IndexBuf,
336                                              rel_room->QRnumber,
337                                              rel_room->QRgen,
338                                              rel_user->usernum);
339
340         /* Clear out the buffer */
341         memset(vbuf, 0, sizeof(struct visit));
342
343         cdbvisit = cdb_fetch(CDB_VISIT, IndexBuf, IndexLen);
344         if (cdbvisit != NULL) {
345                 memcpy(vbuf, cdbvisit->ptr,
346                        ((cdbvisit->len > sizeof(struct visit)) ?
347                         sizeof(struct visit) : cdbvisit->len));
348                 cdb_free(cdbvisit);
349         }
350         else {
351                 /* If this is the first time the user has seen this room,
352                  * set the view to be the default for the room.
353                  */
354                 vbuf->v_view = rel_room->QRdefaultview;
355         }
356
357         /* Set v_seen if necessary */
358         if (vbuf->v_seen[0] == 0) {
359                 snprintf(vbuf->v_seen, sizeof vbuf->v_seen, "*:%ld", vbuf->v_lastseen);
360         }
361 }
362
363
364 void CtdlMailboxName(char *buf, size_t n, const struct ctdluser *who, const char *prefix)
365 {
366         snprintf(buf, n, "%010ld.%s", who->usernum, prefix);
367 }
368
369
370 void MailboxName(char *buf, size_t n, const struct ctdluser *who, const char *prefix)
371 {
372         snprintf(buf, n, "%010ld.%s", who->usernum, prefix);
373 }
374
375
376 /*
377  * Is the user currently logged in an Aide?
378  */
379 int is_aide(void)
380 {
381         if (CC->user.axlevel >= 6)
382                 return (1);
383         else
384                 return (0);
385 }
386
387
388 /*
389  * Is the user currently logged in an Aide *or* the room aide for this room?
390  */
391 int is_room_aide(void)
392 {
393
394         if (!CC->logged_in) {
395                 return (0);
396         }
397
398         if ((CC->user.axlevel >= 6)
399             || (CC->room.QRroomaide == CC->user.usernum)) {
400                 return (1);
401         } else {
402                 return (0);
403         }
404 }
405
406 /*
407  * CtdlGetUserByNumber() -      get user by number
408  *                      returns 0 if user was found
409  *
410  * Note: fetching a user this way requires one additional database operation.
411  */
412 int CtdlGetUserByNumber(struct ctdluser *usbuf, long number)
413 {
414         struct cdbdata *cdbun;
415         int r;
416
417         cdbun = cdb_fetch(CDB_USERSBYNUMBER, &number, sizeof(long));
418         if (cdbun == NULL) {
419                 CtdlLogPrintf(CTDL_INFO, "User %ld not found\n", number);
420                 return(-1);
421         }
422
423         CtdlLogPrintf(CTDL_INFO, "User %ld maps to %s\n", number, cdbun->ptr);
424         r = CtdlGetUser(usbuf, cdbun->ptr);
425         cdb_free(cdbun);
426         return(r);
427 }
428
429 /*
430  * getuserbynumber() -  get user by number
431  *                      returns 0 if user was found
432  *
433  * Note: fetching a user this way requires one additional database operation.
434  */
435 int getuserbynumber(struct ctdluser *usbuf, long number)
436 {
437         return CtdlGetUserByNumber(usbuf, number);
438 }
439
440
441
442 /*
443  * Helper function for rebuild_usersbynumber()
444  */
445 void rebuild_ubn_for_user(struct ctdluser *usbuf, void *data) {
446
447         struct ubnlist {
448                 struct ubnlist *next;
449                 char username[USERNAME_SIZE];
450                 long usernum;
451         };
452
453         static struct ubnlist *u = NULL;
454         struct ubnlist *ptr = NULL;
455
456         /* Lazy programming here.  Call this function as a ForEachUser backend
457          * in order to queue up the room names, or call it with a null user
458          * to make it do the processing.
459          */
460         if (usbuf != NULL) {
461                 ptr = (struct ubnlist *) malloc(sizeof (struct ubnlist));
462                 if (ptr == NULL) return;
463
464                 ptr->usernum = usbuf->usernum;
465                 safestrncpy(ptr->username, usbuf->fullname, sizeof ptr->username);
466                 ptr->next = u;
467                 u = ptr;
468                 return;
469         }
470
471         while (u != NULL) {
472                 CtdlLogPrintf(CTDL_DEBUG, "Rebuilding usersbynumber index %10ld : %s\n",
473                         u->usernum, u->username);
474                 cdb_store(CDB_USERSBYNUMBER, &u->usernum, sizeof(long), u->username, strlen(u->username)+1);
475
476                 ptr = u;
477                 u = u->next;
478                 free(ptr);
479         }
480 }
481
482
483
484 /*
485  * Rebuild the users-by-number index
486  */
487 void rebuild_usersbynumber(void) {
488         cdb_trunc(CDB_USERSBYNUMBER);                   /* delete the old indices */
489         ForEachUser(rebuild_ubn_for_user, NULL);        /* enumerate the users */
490         rebuild_ubn_for_user(NULL, NULL);               /* and index them */
491 }
492
493
494
495 /*
496  * getuserbyuid()  -     get user by system uid (for PAM mode authentication)
497  *                     returns 0 if user was found
498  *
499  * WARNING: don't use this function unless you absolutely have to.  It does
500  *        a sequential search and therefore is computationally expensive.
501  */
502 int getuserbyuid(struct ctdluser *usbuf, uid_t number)
503 {
504         struct cdbdata *cdbus;
505
506         cdb_rewind(CDB_USERS);
507
508         while (cdbus = cdb_next_item(CDB_USERS), cdbus != NULL) {
509                 memset(usbuf, 0, sizeof(struct ctdluser));
510                 memcpy(usbuf, cdbus->ptr,
511                        ((cdbus->len > sizeof(struct ctdluser)) ?
512                         sizeof(struct ctdluser) : cdbus->len));
513                 cdb_free(cdbus);
514                 if (usbuf->uid == number) {
515                         cdb_close_cursor(CDB_USERS);
516                         return (0);
517                 }
518         }
519         return (-1);
520 }
521
522 /*
523  * Back end for cmd_user() and its ilk
524  *
525  * NOTE: "authname" should only be used if we are attempting to use the "master user" feature
526  */
527 int CtdlLoginExistingUser(char *authname, const char *trythisname)
528 {
529         char username[SIZ];
530         int found_user;
531
532         CtdlLogPrintf(9, "CtdlLoginExistingUser(%s, %s)\n", authname, trythisname);
533
534         if ((CC->logged_in)) {
535                 return login_already_logged_in;
536         }
537
538         if (trythisname == NULL) return login_not_found;
539         
540         if (!strncasecmp(trythisname, "SYS_", 4))
541         {
542                 CtdlLogPrintf(CTDL_DEBUG, "System user \"%s\" is not allowed to log in.\n", trythisname);
543                 return login_not_found;
544         }
545
546         /* If a "master user" is defined, handle its authentication if specified */
547         CC->is_master = 0;
548         if (strlen(config.c_master_user) > 0) if (strlen(config.c_master_pass) > 0) if (authname) {
549                 if (!strcasecmp(authname, config.c_master_user)) {
550                         CC->is_master = 1;
551                 }
552         }
553
554         /* Continue attempting user validation... */
555         safestrncpy(username, trythisname, USERNAME_SIZE);
556         striplt(username);
557
558         if (IsEmptyStr(username)) {
559                 return login_not_found;
560         }
561
562         if (config.c_auth_mode == AUTHMODE_HOST) {
563
564                 /* host auth mode */
565
566                 struct passwd pd;
567                 struct passwd *tempPwdPtr;
568                 char pwdbuffer[256];
569         
570                 CtdlLogPrintf(CTDL_DEBUG, "asking host about <%s>\n", username);
571 #ifdef HAVE_GETPWNAM_R
572 #ifdef SOLARIS_GETPWUID
573                 CtdlLogPrintf(CTDL_DEBUG, "Calling getpwnam_r()\n");
574                 tempPwdPtr = getpwnam_r(username, &pd, pwdbuffer, sizeof pwdbuffer);
575 #else // SOLARIS_GETPWUID
576                 CtdlLogPrintf(CTDL_DEBUG, "Calling getpwnam_r()\n");
577                 getpwnam_r(username, &pd, pwdbuffer, sizeof pwdbuffer, &tempPwdPtr);
578 #endif // SOLARIS_GETPWUID
579 #else // HAVE_GETPWNAM_R
580                 CtdlLogPrintf(CTDL_DEBUG, "SHOULD NEVER GET HERE!!!\n");
581                 tempPwdPtr = NULL;
582 #endif // HAVE_GETPWNAM_R
583                 if (tempPwdPtr == NULL) {
584                         CtdlLogPrintf(CTDL_DEBUG, "no such user <%s>\n", username);
585                         return login_not_found;
586                 }
587         
588                 /* Locate the associated Citadel account.
589                  * If not found, make one attempt to create it.
590                  */
591                 found_user = getuserbyuid(&CC->user, pd.pw_uid);
592                 CtdlLogPrintf(CTDL_DEBUG, "found it: uid=%ld, gecos=%s here: %d\n",
593                         (long)pd.pw_uid, pd.pw_gecos, found_user);
594                 if (found_user != 0) {
595                         create_user(username, 0);
596                         found_user = getuserbyuid(&CC->user, pd.pw_uid);
597                 }
598
599         }
600
601 #ifdef HAVE_LDAP
602         else if ((config.c_auth_mode == AUTHMODE_LDAP) || (config.c_auth_mode == AUTHMODE_LDAP_AD)) {
603         
604                 /* LDAP auth mode */
605
606                 uid_t ldap_uid;
607                 char ldap_cn[256];
608                 char ldap_dn[256];
609
610                 found_user = CtdlTryUserLDAP(username, ldap_dn, sizeof ldap_dn, ldap_cn, sizeof ldap_cn, &ldap_uid);
611                 if (found_user != 0) {
612                         return login_not_found;
613                 }
614
615                 found_user = getuserbyuid(&CC->user, ldap_uid);
616                 if (found_user != 0) {
617                         create_user(trythisname, 0);
618                         found_user = getuserbyuid(&CC->user, ldap_uid);
619                 }
620
621                 if (found_user == 0) {
622                         if (CC->ldap_dn != NULL) free(CC->ldap_dn);
623                         CC->ldap_dn = strdup(ldap_dn);
624                 }
625
626         }
627 #endif
628
629         else {
630                 /* native auth mode */
631
632                 struct recptypes *valid = NULL;
633         
634                 /* First, try to log in as if the supplied name is a display name */
635                 found_user = CtdlGetUser(&CC->user, username);
636         
637                 /* If that didn't work, try to log in as if the supplied name
638                 * is an e-mail address
639                 */
640                 if (found_user != 0) {
641                         valid = validate_recipients(username, NULL, 0);
642                         if (valid != NULL) {
643                                 if (valid->num_local == 1) {
644                                         found_user = CtdlGetUser(&CC->user, valid->recp_local);
645                                 }
646                                 free_recipients(valid);
647                         }
648                 }
649         }
650
651         /* Did we find something? */
652         if (found_user == 0) {
653                 if (((CC->nologin)) && (CC->user.axlevel < 6)) {
654                         return login_too_many_users;
655                 } else {
656                         safestrncpy(CC->curr_user, CC->user.fullname,
657                                         sizeof CC->curr_user);
658                         return login_ok;
659                 }
660         }
661         return login_not_found;
662 }
663
664
665
666 /*
667  * USER cmd
668  */
669 void cmd_user(char *cmdbuf)
670 {
671         char username[256];
672         int a;
673
674         CtdlLogPrintf(CTDL_DEBUG, "cmd_user(%s)\n", cmdbuf);
675         extract_token(username, cmdbuf, 0, '|', sizeof username);
676         CtdlLogPrintf(CTDL_DEBUG, "username: %s\n", username);
677         striplt(username);
678         CtdlLogPrintf(CTDL_DEBUG, "username: %s\n", username);
679
680         a = CtdlLoginExistingUser(NULL, username);
681         switch (a) {
682         case login_already_logged_in:
683                 cprintf("%d Already logged in.\n", ERROR + ALREADY_LOGGED_IN);
684                 return;
685         case login_too_many_users:
686                 cprintf("%d %s: "
687                         "Too many users are already online "
688                         "(maximum is %d)\n",
689                         ERROR + MAX_SESSIONS_EXCEEDED,
690                         config.c_nodename, config.c_maxsessions);
691                 return;
692         case login_ok:
693                 cprintf("%d Password required for %s\n",
694                         MORE_DATA, CC->curr_user);
695                 return;
696         case login_not_found:
697                 cprintf("%d %s not found.\n", ERROR + NO_SUCH_USER, username);
698                 return;
699         default:
700                 cprintf("%d Internal error\n", ERROR + INTERNAL_ERROR);
701         }
702 }
703
704
705
706 /*
707  * session startup code which is common to both cmd_pass() and cmd_newu()
708  */
709 void do_login(void)
710 {
711         CC->logged_in = 1;
712         CtdlLogPrintf(CTDL_NOTICE, "<%s> logged in\n", CC->curr_user);
713
714         CtdlGetUserLock(&CC->user, CC->curr_user);
715         ++(CC->user.timescalled);
716         CC->previous_login = CC->user.lastcall;
717         time(&CC->user.lastcall);
718
719         /* If this user's name is the name of the system administrator
720          * (as specified in setup), automatically assign access level 6.
721          */
722         if (!strcasecmp(CC->user.fullname, config.c_sysadm)) {
723                 CC->user.axlevel = 6;
724         }
725
726         /* If we're authenticating off the host system, automatically give
727          * root the highest level of access.
728          */
729         if (config.c_auth_mode == AUTHMODE_HOST) {
730                 if (CC->user.uid == 0) {
731                         CC->user.axlevel = 6;
732                 }
733         }
734
735         CtdlPutUserLock(&CC->user);
736
737         /*
738          * Populate CC->cs_inet_email with a default address.  This will be
739          * overwritten with the user's directory address, if one exists, when
740          * the vCard module's login hook runs.
741          */
742         snprintf(CC->cs_inet_email, sizeof CC->cs_inet_email, "%s@%s",
743                 CC->user.fullname, config.c_fqdn);
744         convert_spaces_to_underscores(CC->cs_inet_email);
745
746         /* Create any personal rooms required by the system.
747          * (Technically, MAILROOM should be there already, but just in case...)
748          */
749         CtdlCreateRoom(MAILROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
750         CtdlCreateRoom(SENTITEMS, 4, "", 0, 1, 0, VIEW_MAILBOX);
751         CtdlCreateRoom(USERTRASHROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
752         /* CtdlCreateRoom(USERDRAFTROOM, 4, "", 0, 1, 0, VIEW_MAILBOX); temporarily disabled for 7.60 */
753
754         /* Run any startup routines registered by loadable modules */
755         PerformSessionHooks(EVT_LOGIN);
756
757         /* Enter the lobby */
758         CtdlUserGoto(config.c_baseroom, 0, 0, NULL, NULL);
759 }
760
761
762 void logged_in_response(void)
763 {
764         cprintf("%d %s|%d|%ld|%ld|%u|%ld|%ld\n",
765                 CIT_OK, CC->user.fullname, CC->user.axlevel,
766                 CC->user.timescalled, CC->user.posted,
767                 CC->user.flags, CC->user.usernum,
768                 CC->previous_login);
769 }
770
771
772
773 /* 
774  * misc things to be taken care of when a user is logged out
775  */
776 void logout(void)
777 {
778         CtdlUserLogout();
779 }
780
781
782 void CtdlUserLogout(void)
783 {
784         CitContext *CCC = CC;   /* CachedCitContext - performance boost */
785         /*
786          * If there is a download in progress, abort it.
787          */
788         if (CCC->download_fp != NULL) {
789                 fclose(CCC->download_fp);
790                 CCC->download_fp = NULL;
791         }
792
793         /*
794          * If there is an upload in progress, abort it.
795          */
796         if (CCC->upload_fp != NULL) {
797                 abort_upl(CCC);
798         }
799
800         /*
801          * If we were talking to a network node, we're not anymore...
802          */
803         if (!IsEmptyStr(CCC->net_node)) {
804                 network_talking_to(CCC->net_node, NTT_REMOVE);
805         }
806
807         /* Run any hooks registered by modules... */
808         PerformSessionHooks(EVT_LOGOUT);
809         
810         /*
811          * Clear out some session data.  Most likely, the CitContext for this
812          * session is about to get nuked when the session disconnects, but
813          * since it's possible to log in again without reconnecting, we cannot
814          * make that assumption.
815          */
816         strcpy(CCC->fake_username, "");
817         strcpy(CCC->fake_hostname, "");
818         strcpy(CCC->fake_roomname, "");
819         CCC->logged_in = 0;
820
821         /* Check to see if the user was deleted whilst logged in and purge them if necessary */
822         if ((CCC->user.axlevel == 0) && (CCC->user.usernum))
823                 purge_user(CCC->user.fullname);
824
825         /* Free any output buffers */
826         unbuffer_output();
827 }
828
829 /*
830  * Validate a password on the host unix system by talking to the chkpwd daemon
831  */
832 static int validpw(uid_t uid, const char *pass)
833 {
834         char buf[256];
835         int rv = 0;
836
837         if (IsEmptyStr(pass)) {
838                 CtdlLogPrintf(CTDL_DEBUG, "refusing to check empty password for uid=%d using chkpwd...\n", uid);
839                 return 0;
840         }
841
842         CtdlLogPrintf(CTDL_DEBUG, "Validating password for uid=%d using chkpwd...\n", uid);
843
844         begin_critical_section(S_CHKPWD);
845         rv = write(chkpwd_write_pipe[1], &uid, sizeof(uid_t));
846         rv = write(chkpwd_write_pipe[1], pass, 256);
847         rv = read(chkpwd_read_pipe[0], buf, 4);
848         end_critical_section(S_CHKPWD);
849
850         if (!strncmp(buf, "PASS", 4)) {
851                 CtdlLogPrintf(CTDL_DEBUG, "...pass\n");
852                 return(1);
853         }
854
855         CtdlLogPrintf(CTDL_DEBUG, "...fail\n");
856         return 0;
857 }
858
859 /* 
860  * Start up the chkpwd daemon so validpw() has something to talk to
861  */
862 void start_chkpwd_daemon(void) {
863         pid_t chkpwd_pid;
864         struct stat filestats;
865         int i;
866
867         CtdlLogPrintf(CTDL_DEBUG, "Starting chkpwd daemon for host authentication mode\n");
868
869         if ((stat(file_chkpwd, &filestats)==-1) ||
870             (filestats.st_size==0)){
871                 printf("didn't find chkpwd daemon in %s: %s\n", file_chkpwd, strerror(errno));
872                 abort();
873         }
874         if (pipe(chkpwd_write_pipe) != 0) {
875                 CtdlLogPrintf(CTDL_EMERG, "Unable to create pipe for chkpwd daemon: %s\n", strerror(errno));
876                 abort();
877         }
878         if (pipe(chkpwd_read_pipe) != 0) {
879                 CtdlLogPrintf(CTDL_EMERG, "Unable to create pipe for chkpwd daemon: %s\n", strerror(errno));
880                 abort();
881         }
882
883         chkpwd_pid = fork();
884         if (chkpwd_pid < 0) {
885                 CtdlLogPrintf(CTDL_EMERG, "Unable to fork chkpwd daemon: %s\n", strerror(errno));
886                 abort();
887         }
888         if (chkpwd_pid == 0) {
889                 CtdlLogPrintf(CTDL_DEBUG, "Now calling dup2() write\n");
890                 dup2(chkpwd_write_pipe[0], 0);
891                 CtdlLogPrintf(CTDL_DEBUG, "Now calling dup2() write\n");
892                 dup2(chkpwd_read_pipe[1], 1);
893                 CtdlLogPrintf(CTDL_DEBUG, "Now closing stuff\n");
894                 for (i=2; i<256; ++i) close(i);
895                 CtdlLogPrintf(CTDL_DEBUG, "Now calling execl(%s)\n", file_chkpwd);
896                 execl(file_chkpwd, file_chkpwd, NULL);
897                 CtdlLogPrintf(CTDL_EMERG, "Unable to exec chkpwd daemon: %s\n", strerror(errno));
898                 abort();
899                 exit(errno);
900         }
901 }
902
903
904 int CtdlTryPassword(char *password)
905 {
906         int code;
907
908         if ((CC->logged_in)) {
909                 CtdlLogPrintf(CTDL_WARNING, "CtdlTryPassword: already logged in\n");
910                 return pass_already_logged_in;
911         }
912         if (!strcmp(CC->curr_user, NLI)) {
913                 CtdlLogPrintf(CTDL_WARNING, "CtdlTryPassword: no user selected\n");
914                 return pass_no_user;
915         }
916         if (CtdlGetUser(&CC->user, CC->curr_user)) {
917                 CtdlLogPrintf(CTDL_ERR, "CtdlTryPassword: internal error\n");
918                 return pass_internal_error;
919         }
920         if (password == NULL) {
921                 CtdlLogPrintf(CTDL_INFO, "CtdlTryPassword: NULL password string supplied\n");
922                 return pass_wrong_password;
923         }
924         code = (-1);
925
926         if (CC->is_master) {
927                 code = strcmp(password, config.c_master_pass);
928         }
929
930         else if (config.c_auth_mode == AUTHMODE_HOST) {
931
932                 /* host auth mode */
933
934                 if (validpw(CC->user.uid, password)) {
935                         code = 0;
936
937                         /*
938                          * sooper-seekrit hack: populate the password field in the
939                          * citadel database with the password that the user typed,
940                          * if it's correct.  This allows most sites to convert from
941                          * host auth to native auth if they want to.  If you think
942                          * this is a security hazard, comment it out.
943                          */
944
945                         CtdlGetUserLock(&CC->user, CC->curr_user);
946                         safestrncpy(CC->user.password, password, sizeof CC->user.password);
947                         CtdlPutUserLock(&CC->user);
948
949                         /*
950                          * (sooper-seekrit hack ends here)
951                          */
952
953                 }
954                 else {
955                         code = (-1);
956                 }
957         }
958
959 #ifdef HAVE_LDAP
960         else if ((config.c_auth_mode == AUTHMODE_LDAP) || (config.c_auth_mode == AUTHMODE_LDAP_AD)) {
961
962                 /* LDAP auth mode */
963
964                 if ((CC->ldap_dn) && (!CtdlTryPasswordLDAP(CC->ldap_dn, password))) {
965                         code = 0;
966                 }
967                 else {
968                         code = (-1);
969                 }
970         }
971 #endif
972
973         else {
974
975                 /* native auth mode */
976
977                 strproc(password);
978                 strproc(CC->user.password);
979                 code = strcasecmp(CC->user.password, password);
980                 strproc(password);
981                 strproc(CC->user.password);
982                 code = strcasecmp(CC->user.password, password);
983         }
984
985         if (!code) {
986                 do_login();
987                 return pass_ok;
988         } else {
989                 CtdlLogPrintf(CTDL_WARNING, "Bad password specified for <%s>\n", CC->curr_user);
990                 return pass_wrong_password;
991         }
992 }
993
994
995 void cmd_pass(char *buf)
996 {
997         char password[256];
998         int a;
999
1000         memset(password, 0, sizeof(password));
1001         extract_token(password, buf, 0, '|', sizeof password);
1002         a = CtdlTryPassword(password);
1003
1004         switch (a) {
1005         case pass_already_logged_in:
1006                 cprintf("%d Already logged in.\n", ERROR + ALREADY_LOGGED_IN);
1007                 return;
1008         case pass_no_user:
1009                 cprintf("%d You must send a name with USER first.\n",
1010                         ERROR + USERNAME_REQUIRED);
1011                 return;
1012         case pass_wrong_password:
1013                 cprintf("%d Wrong password.\n", ERROR + PASSWORD_REQUIRED);
1014                 return;
1015         case pass_ok:
1016                 logged_in_response();
1017                 return;
1018         }
1019 }
1020
1021
1022
1023 /*
1024  * Delete a user record *and* all of its related resources.
1025  */
1026 int purge_user(char pname[])
1027 {
1028         char filename[64];
1029         struct ctdluser usbuf;
1030         char usernamekey[USERNAME_SIZE];
1031
1032         makeuserkey(usernamekey, pname);
1033
1034         /* If the name is empty we can't find them in the DB any way so just return */
1035         if (IsEmptyStr(pname))
1036                 return (ERROR + NO_SUCH_USER);
1037
1038         if (CtdlGetUser(&usbuf, pname) != 0) {
1039                 CtdlLogPrintf(CTDL_ERR, "Cannot purge user <%s> - not found\n", pname);
1040                 return (ERROR + NO_SUCH_USER);
1041         }
1042         /* Don't delete a user who is currently logged in.  Instead, just
1043          * set the access level to 0, and let the account get swept up
1044          * during the next purge.
1045          */
1046         if (CtdlIsUserLoggedInByNum(usbuf.usernum)) {
1047                 CtdlLogPrintf(CTDL_WARNING, "User <%s> is logged in; not deleting.\n", pname);
1048                 usbuf.axlevel = 0;
1049                 CtdlPutUser(&usbuf);
1050                 return (1);
1051         }
1052         CtdlLogPrintf(CTDL_NOTICE, "Deleting user <%s>\n", pname);
1053
1054 /*
1055  * FIXME:
1056  * This should all be wrapped in a S_USERS mutex.
1057  * Without the mutex the user could log in before we get to the next function
1058  * That would truly mess things up :-(
1059  * I would like to see the S_USERS start before the CtdlIsUserLoggedInByNum() above
1060  * and end after the user has been deleted from the database, below.
1061  * Question is should we enter the EVT_PURGEUSER whilst S_USERS is active?
1062  */
1063
1064         /* Perform any purge functions registered by server extensions */
1065         PerformUserHooks(&usbuf, EVT_PURGEUSER);
1066
1067         /* delete any existing user/room relationships */
1068         cdb_delete(CDB_VISIT, &usbuf.usernum, sizeof(long));
1069
1070         /* delete the users-by-number index record */
1071         cdb_delete(CDB_USERSBYNUMBER, &usbuf.usernum, sizeof(long));
1072
1073         /* delete the userlog entry */
1074         cdb_delete(CDB_USERS, usernamekey, strlen(usernamekey));
1075
1076         /* remove the user's bio file */
1077         snprintf(filename, 
1078                          sizeof filename, 
1079                          "%s/%ld",
1080                          ctdl_bio_dir,
1081                          usbuf.usernum);
1082         unlink(filename);
1083
1084         /* remove the user's picture */
1085         snprintf(filename, 
1086                          sizeof filename, 
1087                          "%s/%ld.gif",
1088                          ctdl_image_dir,
1089                          usbuf.usernum);
1090         unlink(filename);
1091
1092         return (0);
1093 }
1094
1095
1096 int internal_create_user (const char *username, struct ctdluser *usbuf, uid_t uid)
1097 {
1098         if (!CtdlGetUser(usbuf, username)) {
1099                 return (ERROR + ALREADY_EXISTS);
1100         }
1101
1102         /* Go ahead and initialize a new user record */
1103         memset(usbuf, 0, sizeof(struct ctdluser));
1104         safestrncpy(usbuf->fullname, username, sizeof usbuf->fullname);
1105         strcpy(usbuf->password, "");
1106         usbuf->uid = uid;
1107
1108         /* These are the default flags on new accounts */
1109         usbuf->flags = US_LASTOLD | US_DISAPPEAR | US_PAGINATOR | US_FLOORS;
1110
1111         usbuf->timescalled = 0;
1112         usbuf->posted = 0;
1113         usbuf->axlevel = config.c_initax;
1114         usbuf->USscreenwidth = 80;
1115         usbuf->USscreenheight = 24;
1116         usbuf->lastcall = time(NULL);
1117
1118         /* fetch a new user number */
1119         usbuf->usernum = get_new_user_number();
1120
1121         /* add user to the database */
1122         CtdlPutUser(usbuf);
1123         cdb_store(CDB_USERSBYNUMBER, &usbuf->usernum, sizeof(long), usbuf->fullname, strlen(usbuf->fullname)+1);
1124
1125         return 0;
1126 }
1127
1128
1129
1130 /*
1131  * create_user()  -  back end processing to create a new user
1132  *
1133  * Set 'newusername' to the desired account name.
1134  * Set 'become_user' to nonzero if this is self-service account creation and we want
1135  * to actually log in as the user we just created, otherwise set it to 0.
1136  */
1137 int create_user(const char *newusername, int become_user)
1138 {
1139         struct ctdluser usbuf;
1140         struct ctdlroom qrbuf;
1141         char username[256];
1142         char mailboxname[ROOMNAMELEN];
1143         char buf[SIZ];
1144         int retval;
1145         uid_t uid = (-1);
1146         
1147
1148         safestrncpy(username, newusername, sizeof username);
1149         strproc(username);
1150
1151         
1152         if (config.c_auth_mode == AUTHMODE_HOST) {
1153
1154                 /* host auth mode */
1155
1156                 struct passwd pd;
1157                 struct passwd *tempPwdPtr;
1158                 char pwdbuffer[256];
1159         
1160 #ifdef HAVE_GETPWNAM_R
1161 #ifdef SOLARIS_GETPWUID
1162                 tempPwdPtr = getpwnam_r(username, &pd, pwdbuffer, sizeof(pwdbuffer));
1163 #else // SOLARIS_GETPWUID
1164                 getpwnam_r(username, &pd, pwdbuffer, sizeof pwdbuffer, &tempPwdPtr);
1165 #endif // SOLARIS_GETPWUID
1166 #else // HAVE_GETPWNAM_R
1167                 tempPwdPtr = NULL;
1168 #endif // HAVE_GETPWNAM_R
1169                 if (tempPwdPtr != NULL) {
1170                         extract_token(username, pd.pw_gecos, 0, ',', sizeof username);
1171                         uid = pd.pw_uid;
1172                         if (IsEmptyStr (username))
1173                         {
1174                                 safestrncpy(username, pd.pw_name, sizeof username);
1175                         }
1176                 }
1177                 else {
1178                         return (ERROR + NO_SUCH_USER);
1179                 }
1180         }
1181
1182 #ifdef HAVE_LDAP
1183         if ((config.c_auth_mode == AUTHMODE_LDAP) || (config.c_auth_mode == AUTHMODE_LDAP_AD)) {
1184                 if (CtdlTryUserLDAP(username, NULL, 0, username, sizeof username, &uid) != 0) {
1185                         return(ERROR + NO_SUCH_USER);
1186                 }
1187         }
1188 #endif /* HAVE_LDAP */
1189         
1190         if ((retval = internal_create_user(username, &usbuf, uid)) != 0)
1191                 return retval;
1192         
1193         /*
1194          * Give the user a private mailbox and a configuration room.
1195          * Make the latter an invisible system room.
1196          */
1197         CtdlMailboxName(mailboxname, sizeof mailboxname, &usbuf, MAILROOM);
1198         CtdlCreateRoom(mailboxname, 5, "", 0, 1, 1, VIEW_MAILBOX);
1199
1200         CtdlMailboxName(mailboxname, sizeof mailboxname, &usbuf, USERCONFIGROOM);
1201         CtdlCreateRoom(mailboxname, 5, "", 0, 1, 1, VIEW_BBS);
1202         if (CtdlGetRoomLock(&qrbuf, mailboxname) == 0) {
1203                 qrbuf.QRflags2 |= QR2_SYSTEM;
1204                 CtdlPutRoomLock(&qrbuf);
1205         }
1206
1207         /* Perform any create functions registered by server extensions */
1208         PerformUserHooks(&usbuf, EVT_NEWUSER);
1209
1210         /* Everything below this line can be bypassed if administratively
1211          * creating a user, instead of doing self-service account creation
1212          */
1213
1214         if (become_user) {
1215                 /* Now become the user we just created */
1216                 memcpy(&CC->user, &usbuf, sizeof(struct ctdluser));
1217                 safestrncpy(CC->curr_user, username, sizeof CC->curr_user);
1218                 do_login();
1219         
1220                 /* Check to make sure we're still who we think we are */
1221                 if (CtdlGetUser(&CC->user, CC->curr_user)) {
1222                         return (ERROR + INTERNAL_ERROR);
1223                 }
1224         }
1225         
1226         snprintf(buf, SIZ, 
1227                 "New user account <%s> has been created, from host %s [%s].\n",
1228                 username,
1229                 CC->cs_host,
1230                 CC->cs_addr
1231         );
1232         CtdlAideMessage(buf, "User Creation Notice");
1233         CtdlLogPrintf(CTDL_NOTICE, "New user <%s> created\n", username);
1234         return (0);
1235 }
1236
1237
1238
1239 /*
1240  * cmd_newu()  -  create a new user account and log in as that user
1241  */
1242 void cmd_newu(char *cmdbuf)
1243 {
1244         int a;
1245         char username[26];
1246
1247         if (config.c_auth_mode != AUTHMODE_NATIVE) {
1248                 cprintf("%d This system does not use native mode authentication.\n",
1249                         ERROR + NOT_HERE);
1250                 return;
1251         }
1252
1253         if (config.c_disable_newu) {
1254                 cprintf("%d Self-service user account creation "
1255                         "is disabled on this system.\n", ERROR + NOT_HERE);
1256                 return;
1257         }
1258
1259         if (CC->logged_in) {
1260                 cprintf("%d Already logged in.\n", ERROR + ALREADY_LOGGED_IN);
1261                 return;
1262         }
1263         if (CC->nologin) {
1264                 cprintf("%d %s: Too many users are already online (maximum is %d)\n",
1265                         ERROR + MAX_SESSIONS_EXCEEDED,
1266                         config.c_nodename, config.c_maxsessions);
1267         }
1268         extract_token(username, cmdbuf, 0, '|', sizeof username);
1269         username[25] = 0;
1270         strproc(username);
1271
1272         if (IsEmptyStr(username)) {
1273                 cprintf("%d You must supply a user name.\n", ERROR + USERNAME_REQUIRED);
1274                 return;
1275         }
1276
1277         if ((!strcasecmp(username, "bbs")) ||
1278             (!strcasecmp(username, "new")) ||
1279             (!strcasecmp(username, "."))) {
1280                 cprintf("%d '%s' is an invalid login name.\n", ERROR + ILLEGAL_VALUE, username);
1281                 return;
1282         }
1283
1284         a = create_user(username, 1);
1285
1286         if (a == 0) {
1287                 logged_in_response();
1288         } else if (a == ERROR + ALREADY_EXISTS) {
1289                 cprintf("%d '%s' already exists.\n",
1290                         ERROR + ALREADY_EXISTS, username);
1291                 return;
1292         } else if (a == ERROR + INTERNAL_ERROR) {
1293                 cprintf("%d Internal error - user record disappeared?\n",
1294                         ERROR + INTERNAL_ERROR);
1295                 return;
1296         } else {
1297                 cprintf("%d unknown error\n", ERROR + INTERNAL_ERROR);
1298         }
1299 }
1300
1301
1302 /*
1303  * set password - back end api code
1304  */
1305 void CtdlSetPassword(char *new_pw)
1306 {
1307         CtdlGetUserLock(&CC->user, CC->curr_user);
1308         safestrncpy(CC->user.password, new_pw, sizeof(CC->user.password));
1309         CtdlPutUserLock(&CC->user);
1310         CtdlLogPrintf(CTDL_INFO, "Password changed for user <%s>\n", CC->curr_user);
1311         PerformSessionHooks(EVT_SETPASS);
1312 }
1313
1314
1315 /*
1316  * set password - citadel protocol implementation
1317  */
1318 void cmd_setp(char *new_pw)
1319 {
1320         int generate_random_password = 0;
1321
1322         if (CtdlAccessCheck(ac_logged_in)) {
1323                 return;
1324         }
1325         if ( (CC->user.uid != CTDLUID) && (CC->user.uid != (-1)) ) {
1326                 cprintf("%d Not allowed.  Use the 'passwd' command.\n", ERROR + NOT_HERE);
1327                 return;
1328         }
1329         if (CC->is_master) {
1330                 cprintf("%d The master prefix password cannot be changed with this command.\n",
1331                         ERROR + NOT_HERE);
1332                 return;
1333         }
1334
1335         if (!strcasecmp(new_pw, "GENERATE_RANDOM_PASSWORD")) {
1336                 char random_password[17];
1337                 generate_random_password = 1;
1338                 snprintf(random_password, sizeof random_password, "%08lx%08lx", random(), random());
1339                 CtdlSetPassword(random_password);
1340                 cprintf("%d %s\n", CIT_OK, random_password);
1341         }
1342         else {
1343                 strproc(new_pw);
1344                 if (IsEmptyStr(new_pw)) {
1345                         cprintf("%d Password unchanged.\n", CIT_OK);
1346                         return;
1347                 }
1348                 CtdlSetPassword(new_pw);
1349                 cprintf("%d Password changed.\n", CIT_OK);
1350         }
1351 }
1352
1353
1354 /*
1355  * cmd_creu() - administratively create a new user account (do not log in to it)
1356  */
1357 void cmd_creu(char *cmdbuf)
1358 {
1359         int a;
1360         char username[26];
1361         char password[32];
1362         struct ctdluser tmp;
1363
1364         if (CtdlAccessCheck(ac_aide)) {
1365                 return;
1366         }
1367
1368         extract_token(username, cmdbuf, 0, '|', sizeof username);
1369         extract_token(password, cmdbuf, 1, '|', sizeof password);
1370         username[25] = 0;
1371         password[31] = 0;
1372         strproc(username);
1373         strproc(password);
1374
1375         if (IsEmptyStr(username)) {
1376                 cprintf("%d You must supply a user name.\n", ERROR + USERNAME_REQUIRED);
1377                 return;
1378         }
1379
1380         a = create_user(username, 0);
1381
1382         if (a == 0) {
1383                 if (!IsEmptyStr(password)) {
1384                         CtdlGetUserLock(&tmp, username);
1385                         safestrncpy(tmp.password, password, sizeof(tmp.password));
1386                         CtdlPutUserLock(&tmp);
1387                 }
1388                 cprintf("%d User '%s' created %s.\n", CIT_OK, username,
1389                                 (!IsEmptyStr(password)) ? "and password set" :
1390                                 "with no password");
1391                 return;
1392         } else if (a == ERROR + ALREADY_EXISTS) {
1393                 cprintf("%d '%s' already exists.\n", ERROR + ALREADY_EXISTS, username);
1394                 return;
1395         } else if ( (config.c_auth_mode != AUTHMODE_NATIVE) && (a == ERROR + NO_SUCH_USER) ) {
1396                 cprintf("%d User accounts are not created within Citadel in host authentication mode.\n",
1397                         ERROR + NO_SUCH_USER);
1398                 return;
1399         } else {
1400                 cprintf("%d An error occurred creating the user account.\n", ERROR + INTERNAL_ERROR);
1401         }
1402 }
1403
1404
1405
1406 /*
1407  * get user parameters
1408  */
1409 void cmd_getu(char *cmdbuf)
1410 {
1411
1412         if (CtdlAccessCheck(ac_logged_in))
1413                 return;
1414
1415         CtdlGetUser(&CC->user, CC->curr_user);
1416         cprintf("%d %d|%d|%d|\n",
1417                 CIT_OK,
1418                 CC->user.USscreenwidth,
1419                 CC->user.USscreenheight,
1420                 (CC->user.flags & US_USER_SET)
1421             );
1422 }
1423
1424 /*
1425  * set user parameters
1426  */
1427 void cmd_setu(char *new_parms)
1428 {
1429         if (CtdlAccessCheck(ac_logged_in))
1430                 return;
1431
1432         if (num_parms(new_parms) < 3) {
1433                 cprintf("%d Usage error.\n", ERROR + ILLEGAL_VALUE);
1434                 return;
1435         }
1436         CtdlGetUserLock(&CC->user, CC->curr_user);
1437         CC->user.USscreenwidth = extract_int(new_parms, 0);
1438         CC->user.USscreenheight = extract_int(new_parms, 1);
1439         CC->user.flags = CC->user.flags & (~US_USER_SET);
1440         CC->user.flags = CC->user.flags |
1441             (extract_int(new_parms, 2) & US_USER_SET);
1442
1443         CtdlPutUserLock(&CC->user);
1444         cprintf("%d Ok\n", CIT_OK);
1445 }
1446
1447 /*
1448  * set last read pointer
1449  */
1450 void cmd_slrp(char *new_ptr)
1451 {
1452         long newlr;
1453         struct visit vbuf;
1454         struct visit original_vbuf;
1455
1456         if (CtdlAccessCheck(ac_logged_in)) {
1457                 return;
1458         }
1459
1460         if (!strncasecmp(new_ptr, "highest", 7)) {
1461                 newlr = CC->room.QRhighest;
1462         } else {
1463                 newlr = atol(new_ptr);
1464         }
1465
1466         CtdlGetUserLock(&CC->user, CC->curr_user);
1467
1468         CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
1469         memcpy(&original_vbuf, &vbuf, sizeof(struct visit));
1470         vbuf.v_lastseen = newlr;
1471         snprintf(vbuf.v_seen, sizeof vbuf.v_seen, "*:%ld", newlr);
1472
1473         /* Only rewrite the record if it changed */
1474         if ( (vbuf.v_lastseen != original_vbuf.v_lastseen)
1475            || (strcmp(vbuf.v_seen, original_vbuf.v_seen)) ) {
1476                 CtdlSetRelationship(&vbuf, &CC->user, &CC->room);
1477         }
1478
1479         CtdlPutUserLock(&CC->user);
1480         cprintf("%d %ld\n", CIT_OK, newlr);
1481 }
1482
1483
1484 void cmd_seen(char *argbuf) {
1485         long target_msgnum = 0L;
1486         int target_setting = 0;
1487
1488         if (CtdlAccessCheck(ac_logged_in)) {
1489                 return;
1490         }
1491
1492         if (num_parms(argbuf) != 2) {
1493                 cprintf("%d Invalid parameters\n", ERROR + ILLEGAL_VALUE);
1494                 return;
1495         }
1496
1497         target_msgnum = extract_long(argbuf, 0);
1498         target_setting = extract_int(argbuf, 1);
1499
1500         CtdlSetSeen(&target_msgnum, 1, target_setting,
1501                         ctdlsetseen_seen, NULL, NULL);
1502         cprintf("%d OK\n", CIT_OK);
1503 }
1504
1505
1506 void cmd_gtsn(char *argbuf) {
1507         char buf[SIZ];
1508
1509         if (CtdlAccessCheck(ac_logged_in)) {
1510                 return;
1511         }
1512
1513         CtdlGetSeen(buf, ctdlsetseen_seen);
1514         cprintf("%d %s\n", CIT_OK, buf);
1515 }
1516
1517
1518 /*
1519  * API function for cmd_invt_kick() and anything else that needs to
1520  * invite or kick out a user to/from a room.
1521  * 
1522  * Set iuser to the name of the user, and op to 1=invite or 0=kick
1523  */
1524 int CtdlInvtKick(char *iuser, int op) {
1525         struct ctdluser USscratch;
1526         struct visit vbuf;
1527         char bbb[SIZ];
1528
1529         if (CtdlGetUser(&USscratch, iuser) != 0) {
1530                 return(1);
1531         }
1532
1533         CtdlGetRelationship(&vbuf, &USscratch, &CC->room);
1534         if (op == 1) {
1535                 vbuf.v_flags = vbuf.v_flags & ~V_FORGET & ~V_LOCKOUT;
1536                 vbuf.v_flags = vbuf.v_flags | V_ACCESS;
1537         }
1538         if (op == 0) {
1539                 vbuf.v_flags = vbuf.v_flags & ~V_ACCESS;
1540                 vbuf.v_flags = vbuf.v_flags | V_FORGET | V_LOCKOUT;
1541         }
1542         CtdlSetRelationship(&vbuf, &USscratch, &CC->room);
1543
1544         /* post a message in Aide> saying what we just did */
1545         snprintf(bbb, sizeof bbb, "%s has been %s \"%s\" by %s.\n",
1546                 iuser,
1547                 ((op == 1) ? "invited to" : "kicked out of"),
1548                 CC->room.QRname,
1549                 CC->user.fullname);
1550         CtdlAideMessage(bbb,"User Admin Message");
1551
1552         return(0);
1553 }
1554
1555
1556 /*
1557  * INVT and KICK commands
1558  */
1559 void cmd_invt_kick(char *iuser, int op) {
1560
1561         /*
1562          * These commands are only allowed by aides, room aides,
1563          * and room namespace owners
1564          */
1565         if (is_room_aide()
1566            || (atol(CC->room.QRname) == CC->user.usernum) ) {
1567                 /* access granted */
1568         } else {
1569                 /* access denied */
1570                 cprintf("%d Higher access or room ownership required.\n",
1571                         ERROR + HIGHER_ACCESS_REQUIRED);
1572                 return;
1573         }
1574
1575         if (!strncasecmp(CC->room.QRname, config.c_baseroom,
1576                          ROOMNAMELEN)) {
1577                 cprintf("%d Can't add/remove users from this room.\n",
1578                         ERROR + NOT_HERE);
1579                 return;
1580         }
1581
1582         if (CtdlInvtKick(iuser, op) != 0) {
1583                 cprintf("%d No such user.\n", ERROR + NO_SUCH_USER);
1584                 return;
1585         }
1586
1587         cprintf("%d %s %s %s.\n",
1588                 CIT_OK, iuser,
1589                 ((op == 1) ? "invited to" : "kicked out of"),
1590                 CC->room.QRname);
1591         return;
1592 }
1593
1594 void cmd_invt(char *iuser) {cmd_invt_kick(iuser, 1);}
1595 void cmd_kick(char *iuser) {cmd_invt_kick(iuser, 0);}
1596
1597 /*
1598  * Forget (Zap) the current room (API call)
1599  * Returns 0 on success
1600  */
1601 int CtdlForgetThisRoom(void) {
1602         struct visit vbuf;
1603
1604         /* On some systems, Aides are not allowed to forget rooms */
1605         if (is_aide() && (config.c_aide_zap == 0)
1606            && ((CC->room.QRflags & QR_MAILBOX) == 0)  ) {
1607                 return(1);
1608         }
1609
1610         CtdlGetUserLock(&CC->user, CC->curr_user);
1611         CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
1612
1613         vbuf.v_flags = vbuf.v_flags | V_FORGET;
1614         vbuf.v_flags = vbuf.v_flags & ~V_ACCESS;
1615
1616         CtdlSetRelationship(&vbuf, &CC->user, &CC->room);
1617         CtdlPutUserLock(&CC->user);
1618
1619         /* Return to the Lobby, so we don't end up in an undefined room */
1620         CtdlUserGoto(config.c_baseroom, 0, 0, NULL, NULL);
1621         return(0);
1622
1623 }
1624
1625
1626 /*
1627  * forget (Zap) the current room
1628  */
1629 void cmd_forg(char *argbuf)
1630 {
1631
1632         if (CtdlAccessCheck(ac_logged_in)) {
1633                 return;
1634         }
1635
1636         if (CtdlForgetThisRoom() == 0) {
1637                 cprintf("%d Ok\n", CIT_OK);
1638         }
1639         else {
1640                 cprintf("%d You may not forget this room.\n", ERROR + NOT_HERE);
1641         }
1642 }
1643
1644 /*
1645  * Get Next Unregistered User
1646  */
1647 void cmd_gnur(char *argbuf)
1648 {
1649         struct cdbdata *cdbus;
1650         struct ctdluser usbuf;
1651
1652         if (CtdlAccessCheck(ac_aide)) {
1653                 return;
1654         }
1655
1656         if ((CitControl.MMflags & MM_VALID) == 0) {
1657                 cprintf("%d There are no unvalidated users.\n", CIT_OK);
1658                 return;
1659         }
1660
1661         /* There are unvalidated users.  Traverse the user database,
1662          * and return the first user we find that needs validation.
1663          */
1664         cdb_rewind(CDB_USERS);
1665         while (cdbus = cdb_next_item(CDB_USERS), cdbus != NULL) {
1666                 memset(&usbuf, 0, sizeof(struct ctdluser));
1667                 memcpy(&usbuf, cdbus->ptr,
1668                        ((cdbus->len > sizeof(struct ctdluser)) ?
1669                         sizeof(struct ctdluser) : cdbus->len));
1670                 cdb_free(cdbus);
1671                 if ((usbuf.flags & US_NEEDVALID)
1672                     && (usbuf.axlevel > 0)) {
1673                         cprintf("%d %s\n", MORE_DATA, usbuf.fullname);
1674                         cdb_close_cursor(CDB_USERS);
1675                         return;
1676                 }
1677         }
1678
1679         /* If we get to this point, there are no more unvalidated users.
1680          * Therefore we clear the "users need validation" flag.
1681          */
1682
1683         begin_critical_section(S_CONTROL);
1684         get_control();
1685         CitControl.MMflags = CitControl.MMflags & (~MM_VALID);
1686         put_control();
1687         end_critical_section(S_CONTROL);
1688         cprintf("%d *** End of registration.\n", CIT_OK);
1689
1690
1691 }
1692
1693
1694 /*
1695  * validate a user
1696  */
1697 void cmd_vali(char *v_args)
1698 {
1699         char user[128];
1700         int newax;
1701         struct ctdluser userbuf;
1702
1703         extract_token(user, v_args, 0, '|', sizeof user);
1704         newax = extract_int(v_args, 1);
1705
1706         if (CtdlAccessCheck(ac_aide)) {
1707                 return;
1708         }
1709
1710         if (CtdlGetUserLock(&userbuf, user) != 0) {
1711                 cprintf("%d '%s' not found.\n", ERROR + NO_SUCH_USER, user);
1712                 return;
1713         }
1714
1715         userbuf.axlevel = newax;
1716         userbuf.flags = (userbuf.flags & ~US_NEEDVALID);
1717
1718         CtdlPutUserLock(&userbuf);
1719
1720         /* If the access level was set to zero, delete the user */
1721         if (newax == 0) {
1722                 if (purge_user(user) == 0) {
1723                         cprintf("%d %s Deleted.\n", CIT_OK, userbuf.fullname);
1724                         return;
1725                 }
1726         }
1727         cprintf("%d User '%s' validated.\n", CIT_OK, userbuf.fullname);
1728 }
1729
1730
1731
1732 /* 
1733  *  Traverse the user file...
1734  */
1735 void ForEachUser(void (*CallBack) (struct ctdluser * EachUser, void *out_data),
1736                  void *in_data)
1737 {
1738         struct ctdluser usbuf;
1739         struct cdbdata *cdbus;
1740
1741         cdb_rewind(CDB_USERS);
1742
1743         while (cdbus = cdb_next_item(CDB_USERS), cdbus != NULL) {
1744                 memset(&usbuf, 0, sizeof(struct ctdluser));
1745                 memcpy(&usbuf, cdbus->ptr,
1746                        ((cdbus->len > sizeof(struct ctdluser)) ?
1747                         sizeof(struct ctdluser) : cdbus->len));
1748                 cdb_free(cdbus);
1749                 (*CallBack) (&usbuf, in_data);
1750         }
1751 }
1752
1753
1754 /*
1755  * List one user (this works with cmd_list)
1756  */
1757 void ListThisUser(struct ctdluser *usbuf, void *data)
1758 {
1759         char *searchstring;
1760
1761         searchstring = (char *)data;
1762         if (bmstrcasestr(usbuf->fullname, searchstring) == NULL) {
1763                 return;
1764         }
1765
1766         if (usbuf->axlevel > 0) {
1767                 if ((CC->user.axlevel >= 6)
1768                     || ((usbuf->flags & US_UNLISTED) == 0)
1769                     || ((CC->internal_pgm))) {
1770                         cprintf("%s|%d|%ld|%ld|%ld|%ld||\n",
1771                                 usbuf->fullname,
1772                                 usbuf->axlevel,
1773                                 usbuf->usernum,
1774                                 (long)usbuf->lastcall,
1775                                 usbuf->timescalled,
1776                                 usbuf->posted);
1777                 }
1778         }
1779 }
1780
1781 /* 
1782  *  List users (searchstring may be empty to list all users)
1783  */
1784 void cmd_list(char *cmdbuf)
1785 {
1786         char searchstring[256];
1787         extract_token(searchstring, cmdbuf, 0, '|', sizeof searchstring);
1788         striplt(searchstring);
1789         cprintf("%d \n", LISTING_FOLLOWS);
1790         ForEachUser(ListThisUser, (void *)searchstring );
1791         cprintf("000\n");
1792 }
1793
1794
1795
1796
1797 /*
1798  * assorted info we need to check at login
1799  */
1800 void cmd_chek(char *argbuf)
1801 {
1802         int mail = 0;
1803         int regis = 0;
1804         int vali = 0;
1805
1806         if (CtdlAccessCheck(ac_logged_in)) {
1807                 return;
1808         }
1809
1810         CtdlGetUser(&CC->user, CC->curr_user);  /* no lock is needed here */
1811         if ((REGISCALL != 0) && ((CC->user.flags & US_REGIS) == 0))
1812                 regis = 1;
1813
1814         if (CC->user.axlevel >= 6) {
1815                 get_control();
1816                 if (CitControl.MMflags & MM_VALID)
1817                         vali = 1;
1818         }
1819
1820         /* check for mail */
1821         mail = InitialMailCheck();
1822
1823         cprintf("%d %d|%d|%d|%s|\n", CIT_OK, mail, regis, vali, CC->cs_inet_email);
1824 }
1825
1826
1827 /*
1828  * check to see if a user exists
1829  */
1830 void cmd_qusr(char *who)
1831 {
1832         struct ctdluser usbuf;
1833
1834         if (CtdlGetUser(&usbuf, who) == 0) {
1835                 cprintf("%d %s\n", CIT_OK, usbuf.fullname);
1836         } else {
1837                 cprintf("%d No such user.\n", ERROR + NO_SUCH_USER);
1838         }
1839 }
1840
1841
1842 /*
1843  * Administrative Get User Parameters
1844  */
1845 void cmd_agup(char *cmdbuf)
1846 {
1847         struct ctdluser usbuf;
1848         char requested_user[128];
1849
1850         if (CtdlAccessCheck(ac_aide)) {
1851                 return;
1852         }
1853
1854         extract_token(requested_user, cmdbuf, 0, '|', sizeof requested_user);
1855         if (CtdlGetUser(&usbuf, requested_user) != 0) {
1856                 cprintf("%d No such user.\n", ERROR + NO_SUCH_USER);
1857                 return;
1858         }
1859         cprintf("%d %s|%s|%u|%ld|%ld|%d|%ld|%ld|%d\n",
1860                 CIT_OK,
1861                 usbuf.fullname,
1862                 usbuf.password,
1863                 usbuf.flags,
1864                 usbuf.timescalled,
1865                 usbuf.posted,
1866                 (int) usbuf.axlevel,
1867                 usbuf.usernum,
1868                 (long)usbuf.lastcall,
1869                 usbuf.USuserpurge);
1870 }
1871
1872
1873
1874 /*
1875  * Administrative Set User Parameters
1876  */
1877 void cmd_asup(char *cmdbuf)
1878 {
1879         struct ctdluser usbuf;
1880         char requested_user[128];
1881         char notify[SIZ];
1882         int np;
1883         int newax;
1884         int deleted = 0;
1885
1886         if (CtdlAccessCheck(ac_aide))
1887                 return;
1888
1889         extract_token(requested_user, cmdbuf, 0, '|', sizeof requested_user);
1890         if (CtdlGetUserLock(&usbuf, requested_user) != 0) {
1891                 cprintf("%d No such user.\n", ERROR + NO_SUCH_USER);
1892                 return;
1893         }
1894         np = num_parms(cmdbuf);
1895         if (np > 1)
1896                 extract_token(usbuf.password, cmdbuf, 1, '|', sizeof usbuf.password);
1897         if (np > 2)
1898                 usbuf.flags = extract_int(cmdbuf, 2);
1899         if (np > 3)
1900                 usbuf.timescalled = extract_int(cmdbuf, 3);
1901         if (np > 4)
1902                 usbuf.posted = extract_int(cmdbuf, 4);
1903         if (np > 5) {
1904                 newax = extract_int(cmdbuf, 5);
1905                 if ((newax >= 0) && (newax <= 6)) {
1906                         usbuf.axlevel = extract_int(cmdbuf, 5);
1907                 }
1908         }
1909         if (np > 7) {
1910                 usbuf.lastcall = extract_long(cmdbuf, 7);
1911         }
1912         if (np > 8) {
1913                 usbuf.USuserpurge = extract_int(cmdbuf, 8);
1914         }
1915         CtdlPutUserLock(&usbuf);
1916         if (usbuf.axlevel == 0) {
1917                 if (purge_user(requested_user) == 0) {
1918                         deleted = 1;
1919                 }
1920         }
1921
1922         if (deleted) {
1923                 snprintf(notify, SIZ, 
1924                          "User \"%s\" has been deleted by %s.\n",
1925                          usbuf.fullname, CC->user.fullname);
1926                 CtdlAideMessage(notify, "User Deletion Message");
1927         }
1928
1929         cprintf("%d Ok", CIT_OK);
1930         if (deleted)
1931                 cprintf(" (%s deleted)", requested_user);
1932         cprintf("\n");
1933 }
1934
1935
1936
1937 /*
1938  * Count the number of new mail messages the user has
1939  */
1940 int NewMailCount()
1941 {
1942         int num_newmsgs = 0;
1943
1944         num_newmsgs = CC->newmail;
1945         CC->newmail = 0;
1946
1947         return (num_newmsgs);
1948 }
1949
1950
1951 /*
1952  * Count the number of new mail messages the user has
1953  */
1954 int InitialMailCheck()
1955 {
1956         int num_newmsgs = 0;
1957         int a;
1958         char mailboxname[ROOMNAMELEN];
1959         struct ctdlroom mailbox;
1960         struct visit vbuf;
1961         struct cdbdata *cdbfr;
1962         long *msglist = NULL;
1963         int num_msgs = 0;
1964
1965         CtdlMailboxName(mailboxname, sizeof mailboxname, &CC->user, MAILROOM);
1966         if (CtdlGetRoom(&mailbox, mailboxname) != 0)
1967                 return (0);
1968         CtdlGetRelationship(&vbuf, &CC->user, &mailbox);
1969
1970         cdbfr = cdb_fetch(CDB_MSGLISTS, &mailbox.QRnumber, sizeof(long));
1971
1972         if (cdbfr != NULL) {
1973                 msglist = malloc(cdbfr->len);
1974                 memcpy(msglist, cdbfr->ptr, cdbfr->len);
1975                 num_msgs = cdbfr->len / sizeof(long);
1976                 cdb_free(cdbfr);
1977         }
1978         if (num_msgs > 0)
1979                 for (a = 0; a < num_msgs; ++a) {
1980                         if (msglist[a] > 0L) {
1981                                 if (msglist[a] > vbuf.v_lastseen) {
1982                                         ++num_newmsgs;
1983                                 }
1984                         }
1985                 }
1986         if (msglist != NULL)
1987                 free(msglist);
1988
1989         return (num_newmsgs);
1990 }
1991
1992
1993
1994 /*
1995  * Set the preferred view for the current user/room combination
1996  */
1997 void cmd_view(char *cmdbuf) {
1998         int requested_view;
1999         struct visit vbuf;
2000
2001         if (CtdlAccessCheck(ac_logged_in)) {
2002                 return;
2003         }
2004
2005         requested_view = extract_int(cmdbuf, 0);
2006
2007         CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
2008         vbuf.v_view = requested_view;
2009         CtdlSetRelationship(&vbuf, &CC->user, &CC->room);
2010         
2011         cprintf("%d ok\n", CIT_OK);
2012 }
2013
2014
2015 /*
2016  * Rename a user
2017  */
2018 void cmd_renu(char *cmdbuf)
2019 {
2020         int retcode;
2021         char oldname[USERNAME_SIZE];
2022         char newname[USERNAME_SIZE];
2023
2024         if (CtdlAccessCheck(ac_aide)) {
2025                 return;
2026         }
2027
2028         extract_token(oldname, cmdbuf, 0, '|', sizeof oldname);
2029         extract_token(newname, cmdbuf, 1, '|', sizeof newname);
2030
2031         retcode = rename_user(oldname, newname);
2032         switch(retcode) {
2033                 case RENAMEUSER_OK:
2034                         cprintf("%d '%s' has been renamed to '%s'.\n", CIT_OK, oldname, newname);
2035                         return;
2036                 case RENAMEUSER_LOGGED_IN:
2037                         cprintf("%d '%s' is currently logged in and cannot be renamed.\n",
2038                                 ERROR + ALREADY_LOGGED_IN , oldname);
2039                         return;
2040                 case RENAMEUSER_NOT_FOUND:
2041                         cprintf("%d '%s' does not exist.\n", ERROR + NO_SUCH_USER, oldname);
2042                         return;
2043                 case RENAMEUSER_ALREADY_EXISTS:
2044                         cprintf("%d A user named '%s' already exists.\n", ERROR + ALREADY_EXISTS, newname);
2045                         return;
2046         }
2047
2048         cprintf("%d An unknown error occurred.\n", ERROR);
2049 }
2050
2051
2052
2053 /*****************************************************************************/
2054 /*                      MODULE INITIALIZATION STUFF                          */
2055 /*****************************************************************************/
2056
2057
2058 CTDL_MODULE_INIT(user_ops)
2059 {
2060         if (!threading) {
2061                 CtdlRegisterProtoHook(cmd_user, "USER", "Autoconverted. TODO: document me.");
2062                 CtdlRegisterProtoHook(cmd_pass, "PASS", "Autoconverted. TODO: document me.");
2063                 CtdlRegisterProtoHook(cmd_creu, "CREU", "Autoconverted. TODO: document me.");
2064                 CtdlRegisterProtoHook(cmd_setp, "SETP", "Autoconverted. TODO: document me.");
2065                 CtdlRegisterProtoHook(cmd_getu, "GETU", "Autoconverted. TODO: document me.");
2066                 CtdlRegisterProtoHook(cmd_setu, "SETU", "Autoconverted. TODO: document me.");
2067                 CtdlRegisterProtoHook(cmd_slrp, "SLRP", "Autoconverted. TODO: document me.");
2068                 CtdlRegisterProtoHook(cmd_invt, "INVT", "Autoconverted. TODO: document me.");
2069                 CtdlRegisterProtoHook(cmd_kick, "KICK", "Autoconverted. TODO: document me.");
2070                 CtdlRegisterProtoHook(cmd_forg, "FORG", "Autoconverted. TODO: document me.");
2071                 CtdlRegisterProtoHook(cmd_gnur, "GNUR", "Autoconverted. TODO: document me.");
2072                 CtdlRegisterProtoHook(cmd_vali, "VALI", "Autoconverted. TODO: document me.");
2073                 CtdlRegisterProtoHook(cmd_list, "LIST", "Autoconverted. TODO: document me.");
2074                 CtdlRegisterProtoHook(cmd_chek, "CHEK", "Autoconverted. TODO: document me.");
2075                 CtdlRegisterProtoHook(cmd_qusr, "QUSR", "Autoconverted. TODO: document me.");
2076                 CtdlRegisterProtoHook(cmd_agup, "AGUP", "Autoconverted. TODO: document me.");
2077                 CtdlRegisterProtoHook(cmd_asup, "ASUP", "Autoconverted. TODO: document me.");
2078                 CtdlRegisterProtoHook(cmd_seen, "SEEN", "Autoconverted. TODO: document me.");
2079                 CtdlRegisterProtoHook(cmd_gtsn, "GTSN", "Autoconverted. TODO: document me.");
2080                 CtdlRegisterProtoHook(cmd_view, "VIEW", "Autoconverted. TODO: document me.");
2081                 CtdlRegisterProtoHook(cmd_renu, "RENU", "Autoconverted. TODO: document me.");
2082                 CtdlRegisterProtoHook(cmd_newu, "NEWU", "Autoconverted. TODO: document me.");
2083         }
2084         /* return our Subversion id for the Log */
2085         return "$Id$";
2086 }