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