Replaced some of the 'autoconverted - document me' strings
[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(9, "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         /* Free any output buffers */
816         unbuffer_output();
817 }
818
819 /*
820  * Validate a password on the host unix system by talking to the chkpwd daemon
821  */
822 static int validpw(uid_t uid, const char *pass)
823 {
824         char buf[256];
825         int rv = 0;
826
827         if (IsEmptyStr(pass)) {
828                 CtdlLogPrintf(CTDL_DEBUG, "refusing to check empty password for uid=%d using chkpwd...\n", uid);
829                 return 0;
830         }
831
832         CtdlLogPrintf(CTDL_DEBUG, "Validating password for uid=%d using chkpwd...\n", uid);
833
834         begin_critical_section(S_CHKPWD);
835         rv = write(chkpwd_write_pipe[1], &uid, sizeof(uid_t));
836         rv = write(chkpwd_write_pipe[1], pass, 256);
837         rv = read(chkpwd_read_pipe[0], buf, 4);
838         end_critical_section(S_CHKPWD);
839
840         if (!strncmp(buf, "PASS", 4)) {
841                 CtdlLogPrintf(CTDL_DEBUG, "...pass\n");
842                 return(1);
843         }
844
845         CtdlLogPrintf(CTDL_DEBUG, "...fail\n");
846         return 0;
847 }
848
849 /* 
850  * Start up the chkpwd daemon so validpw() has something to talk to
851  */
852 void start_chkpwd_daemon(void) {
853         pid_t chkpwd_pid;
854         struct stat filestats;
855         int i;
856
857         CtdlLogPrintf(CTDL_DEBUG, "Starting chkpwd daemon for host authentication mode\n");
858
859         if ((stat(file_chkpwd, &filestats)==-1) ||
860             (filestats.st_size==0)){
861                 printf("didn't find chkpwd daemon in %s: %s\n", file_chkpwd, strerror(errno));
862                 abort();
863         }
864         if (pipe(chkpwd_write_pipe) != 0) {
865                 CtdlLogPrintf(CTDL_EMERG, "Unable to create pipe for chkpwd daemon: %s\n", strerror(errno));
866                 abort();
867         }
868         if (pipe(chkpwd_read_pipe) != 0) {
869                 CtdlLogPrintf(CTDL_EMERG, "Unable to create pipe for chkpwd daemon: %s\n", strerror(errno));
870                 abort();
871         }
872
873         chkpwd_pid = fork();
874         if (chkpwd_pid < 0) {
875                 CtdlLogPrintf(CTDL_EMERG, "Unable to fork chkpwd daemon: %s\n", strerror(errno));
876                 abort();
877         }
878         if (chkpwd_pid == 0) {
879                 CtdlLogPrintf(CTDL_DEBUG, "Now calling dup2() write\n");
880                 dup2(chkpwd_write_pipe[0], 0);
881                 CtdlLogPrintf(CTDL_DEBUG, "Now calling dup2() write\n");
882                 dup2(chkpwd_read_pipe[1], 1);
883                 CtdlLogPrintf(CTDL_DEBUG, "Now closing stuff\n");
884                 for (i=2; i<256; ++i) close(i);
885                 CtdlLogPrintf(CTDL_DEBUG, "Now calling execl(%s)\n", file_chkpwd);
886                 execl(file_chkpwd, file_chkpwd, NULL);
887                 CtdlLogPrintf(CTDL_EMERG, "Unable to exec chkpwd daemon: %s\n", strerror(errno));
888                 abort();
889                 exit(errno);
890         }
891 }
892
893
894 int CtdlTryPassword(const char *password, long len)
895 {
896         int code;
897
898         if ((CC->logged_in)) {
899                 CtdlLogPrintf(CTDL_WARNING, "CtdlTryPassword: already logged in\n");
900                 return pass_already_logged_in;
901         }
902         if (!strcmp(CC->curr_user, NLI)) {
903                 CtdlLogPrintf(CTDL_WARNING, "CtdlTryPassword: no user selected\n");
904                 return pass_no_user;
905         }
906         if (CtdlGetUser(&CC->user, CC->curr_user)) {
907                 CtdlLogPrintf(CTDL_ERR, "CtdlTryPassword: internal error\n");
908                 return pass_internal_error;
909         }
910         if (password == NULL) {
911                 CtdlLogPrintf(CTDL_INFO, "CtdlTryPassword: NULL password string supplied\n");
912                 return pass_wrong_password;
913         }
914         code = (-1);
915
916         if (CC->is_master) {
917                 code = strcmp(password, config.c_master_pass);
918         }
919
920         else if (config.c_auth_mode == AUTHMODE_HOST) {
921
922                 /* host auth mode */
923
924                 if (validpw(CC->user.uid, password)) {
925                         code = 0;
926
927                         /*
928                          * sooper-seekrit hack: populate the password field in the
929                          * citadel database with the password that the user typed,
930                          * if it's correct.  This allows most sites to convert from
931                          * host auth to native auth if they want to.  If you think
932                          * this is a security hazard, comment it out.
933                          */
934
935                         CtdlGetUserLock(&CC->user, CC->curr_user);
936                         safestrncpy(CC->user.password, password, sizeof CC->user.password);
937                         CtdlPutUserLock(&CC->user);
938
939                         /*
940                          * (sooper-seekrit hack ends here)
941                          */
942
943                 }
944                 else {
945                         code = (-1);
946                 }
947         }
948
949 #ifdef HAVE_LDAP
950         else if ((config.c_auth_mode == AUTHMODE_LDAP) || (config.c_auth_mode == AUTHMODE_LDAP_AD)) {
951
952                 /* LDAP auth mode */
953
954                 if ((CC->ldap_dn) && (!CtdlTryPasswordLDAP(CC->ldap_dn, password))) {
955                         code = 0;
956                 }
957                 else {
958                         code = (-1);
959                 }
960         }
961 #endif
962
963         else {
964
965                 /* native auth mode */
966                 char *pw;
967
968                 pw = (char*) malloc(len + 1);
969                 memcpy(pw, password, len + 1);
970                 strproc(pw);
971                 strproc(CC->user.password);
972                 code = strcasecmp(CC->user.password, pw);
973                 strproc(pw);
974                 strproc(CC->user.password);
975                 code = strcasecmp(CC->user.password, pw);
976                 free (pw);
977         }
978
979         if (!code) {
980                 do_login();
981                 return pass_ok;
982         } else {
983                 CtdlLogPrintf(CTDL_WARNING, "Bad password specified for <%s>\n", CC->curr_user);
984                 return pass_wrong_password;
985         }
986 }
987
988
989 void cmd_pass(char *buf)
990 {
991         char password[SIZ];
992         int a;
993         long len;
994
995         memset(password, 0, sizeof(password));
996         len = extract_token(password, buf, 0, '|', sizeof password);
997         a = CtdlTryPassword(password, len);
998
999         switch (a) {
1000         case pass_already_logged_in:
1001                 cprintf("%d Already logged in.\n", ERROR + ALREADY_LOGGED_IN);
1002                 return;
1003         case pass_no_user:
1004                 cprintf("%d You must send a name with USER first.\n",
1005                         ERROR + USERNAME_REQUIRED);
1006                 return;
1007         case pass_wrong_password:
1008                 cprintf("%d Wrong password.\n", ERROR + PASSWORD_REQUIRED);
1009                 return;
1010         case pass_ok:
1011                 logged_in_response();
1012                 return;
1013         }
1014 }
1015
1016
1017
1018 /*
1019  * Delete a user record *and* all of its related resources.
1020  */
1021 int purge_user(char pname[])
1022 {
1023         char filename[64];
1024         struct ctdluser usbuf;
1025         char usernamekey[USERNAME_SIZE];
1026
1027         makeuserkey(usernamekey, pname, cutuserkey(pname));
1028
1029         /* If the name is empty we can't find them in the DB any way so just return */
1030         if (IsEmptyStr(pname))
1031                 return (ERROR + NO_SUCH_USER);
1032
1033         if (CtdlGetUser(&usbuf, pname) != 0) {
1034                 CtdlLogPrintf(CTDL_ERR, "Cannot purge user <%s> - not found\n", pname);
1035                 return (ERROR + NO_SUCH_USER);
1036         }
1037         /* Don't delete a user who is currently logged in.  Instead, just
1038          * set the access level to 0, and let the account get swept up
1039          * during the next purge.
1040          */
1041         if (CtdlIsUserLoggedInByNum(usbuf.usernum)) {
1042                 CtdlLogPrintf(CTDL_WARNING, "User <%s> is logged in; not deleting.\n", pname);
1043                 usbuf.axlevel = AxDeleted;
1044                 CtdlPutUser(&usbuf);
1045                 return (1);
1046         }
1047         CtdlLogPrintf(CTDL_NOTICE, "Deleting user <%s>\n", pname);
1048
1049 /*
1050  * FIXME:
1051  * This should all be wrapped in a S_USERS mutex.
1052  * Without the mutex the user could log in before we get to the next function
1053  * That would truly mess things up :-(
1054  * I would like to see the S_USERS start before the CtdlIsUserLoggedInByNum() above
1055  * and end after the user has been deleted from the database, below.
1056  * Question is should we enter the EVT_PURGEUSER whilst S_USERS is active?
1057  */
1058
1059         /* Perform any purge functions registered by server extensions */
1060         PerformUserHooks(&usbuf, EVT_PURGEUSER);
1061
1062         /* delete any existing user/room relationships */
1063         cdb_delete(CDB_VISIT, &usbuf.usernum, sizeof(long));
1064
1065         /* delete the users-by-number index record */
1066         cdb_delete(CDB_USERSBYNUMBER, &usbuf.usernum, sizeof(long));
1067
1068         /* delete the userlog entry */
1069         cdb_delete(CDB_USERS, usernamekey, strlen(usernamekey));
1070
1071         /* remove the user's bio file */
1072         snprintf(filename, 
1073                          sizeof filename, 
1074                          "%s/%ld",
1075                          ctdl_bio_dir,
1076                          usbuf.usernum);
1077         unlink(filename);
1078
1079         /* remove the user's picture */
1080         snprintf(filename, 
1081                          sizeof filename, 
1082                          "%s/%ld.gif",
1083                          ctdl_image_dir,
1084                          usbuf.usernum);
1085         unlink(filename);
1086
1087         return (0);
1088 }
1089
1090
1091 int internal_create_user (const char *username, long len, struct ctdluser *usbuf, uid_t uid)
1092 {
1093         if (!CtdlGetUserLen(usbuf, username, len)) {
1094                 return (ERROR + ALREADY_EXISTS);
1095         }
1096
1097         /* Go ahead and initialize a new user record */
1098         memset(usbuf, 0, sizeof(struct ctdluser));
1099         safestrncpy(usbuf->fullname, username, sizeof usbuf->fullname);
1100         strcpy(usbuf->password, "");
1101         usbuf->uid = uid;
1102
1103         /* These are the default flags on new accounts */
1104         usbuf->flags = US_LASTOLD | US_DISAPPEAR | US_PAGINATOR | US_FLOORS;
1105
1106         usbuf->timescalled = 0;
1107         usbuf->posted = 0;
1108         usbuf->axlevel = config.c_initax;
1109         usbuf->lastcall = time(NULL);
1110
1111         /* fetch a new user number */
1112         usbuf->usernum = get_new_user_number();
1113
1114         /* add user to the database */
1115         CtdlPutUser(usbuf);
1116         cdb_store(CDB_USERSBYNUMBER, &usbuf->usernum, sizeof(long), usbuf->fullname, strlen(usbuf->fullname)+1);
1117
1118         return 0;
1119 }
1120
1121
1122
1123 /*
1124  * create_user()  -  back end processing to create a new user
1125  *
1126  * Set 'newusername' to the desired account name.
1127  * Set 'become_user' to nonzero if this is self-service account creation and we want
1128  * to actually log in as the user we just created, otherwise set it to 0.
1129  */
1130 int create_user(const char *newusername, long len, int become_user)
1131 {
1132         struct ctdluser usbuf;
1133         struct ctdlroom qrbuf;
1134         char username[256];
1135         char mailboxname[ROOMNAMELEN];
1136         char buf[SIZ];
1137         int retval;
1138         uid_t uid = (-1);
1139         
1140
1141         safestrncpy(username, newusername, sizeof username);
1142         strproc(username);
1143
1144         
1145         if (config.c_auth_mode == AUTHMODE_HOST) {
1146
1147                 /* host auth mode */
1148
1149                 struct passwd pd;
1150                 struct passwd *tempPwdPtr;
1151                 char pwdbuffer[SIZ];
1152         
1153 #ifdef HAVE_GETPWNAM_R
1154 #ifdef SOLARIS_GETPWUID
1155                 tempPwdPtr = getpwnam_r(username, &pd, pwdbuffer, sizeof(pwdbuffer));
1156 #else // SOLARIS_GETPWUID
1157                 getpwnam_r(username, &pd, pwdbuffer, sizeof pwdbuffer, &tempPwdPtr);
1158 #endif // SOLARIS_GETPWUID
1159 #else // HAVE_GETPWNAM_R
1160                 tempPwdPtr = NULL;
1161 #endif // HAVE_GETPWNAM_R
1162                 if (tempPwdPtr != NULL) {
1163                         extract_token(username, pd.pw_gecos, 0, ',', sizeof username);
1164                         uid = pd.pw_uid;
1165                         if (IsEmptyStr (username))
1166                         {
1167                                 safestrncpy(username, pd.pw_name, sizeof username);
1168                                 len = cutuserkey(username);
1169                         }
1170                 }
1171                 else {
1172                         return (ERROR + NO_SUCH_USER);
1173                 }
1174         }
1175
1176 #ifdef HAVE_LDAP
1177         if ((config.c_auth_mode == AUTHMODE_LDAP) || (config.c_auth_mode == AUTHMODE_LDAP_AD)) {
1178                 if (CtdlTryUserLDAP(username, NULL, 0, username, sizeof username, &uid) != 0) {
1179                         return(ERROR + NO_SUCH_USER);
1180                 }
1181         }
1182 #endif /* HAVE_LDAP */
1183         
1184         if ((retval = internal_create_user(username, len, &usbuf, uid)) != 0)
1185                 return retval;
1186         
1187         /*
1188          * Give the user a private mailbox and a configuration room.
1189          * Make the latter an invisible system room.
1190          */
1191         CtdlMailboxName(mailboxname, sizeof mailboxname, &usbuf, MAILROOM);
1192         CtdlCreateRoom(mailboxname, 5, "", 0, 1, 1, VIEW_MAILBOX);
1193
1194         CtdlMailboxName(mailboxname, sizeof mailboxname, &usbuf, USERCONFIGROOM);
1195         CtdlCreateRoom(mailboxname, 5, "", 0, 1, 1, VIEW_BBS);
1196         if (CtdlGetRoomLock(&qrbuf, mailboxname) == 0) {
1197                 qrbuf.QRflags2 |= QR2_SYSTEM;
1198                 CtdlPutRoomLock(&qrbuf);
1199         }
1200
1201         /* Perform any create functions registered by server extensions */
1202         PerformUserHooks(&usbuf, EVT_NEWUSER);
1203
1204         /* Everything below this line can be bypassed if administratively
1205          * creating a user, instead of doing self-service account creation
1206          */
1207
1208         if (become_user) {
1209                 /* Now become the user we just created */
1210                 memcpy(&CC->user, &usbuf, sizeof(struct ctdluser));
1211                 safestrncpy(CC->curr_user, username, sizeof CC->curr_user);
1212                 do_login();
1213         
1214                 /* Check to make sure we're still who we think we are */
1215                 if (CtdlGetUser(&CC->user, CC->curr_user)) {
1216                         return (ERROR + INTERNAL_ERROR);
1217                 }
1218         }
1219         
1220         snprintf(buf, SIZ, 
1221                 "New user account <%s> has been created, from host %s [%s].\n",
1222                 username,
1223                 CC->cs_host,
1224                 CC->cs_addr
1225         );
1226         CtdlAideMessage(buf, "User Creation Notice");
1227         CtdlLogPrintf(CTDL_NOTICE, "New user <%s> created\n", username);
1228         return (0);
1229 }
1230
1231
1232
1233 /*
1234  * cmd_newu()  -  create a new user account and log in as that user
1235  */
1236 void cmd_newu(char *cmdbuf)
1237 {
1238         int a;
1239         long len;
1240         char username[26];
1241
1242         if (config.c_auth_mode != AUTHMODE_NATIVE) {
1243                 cprintf("%d This system does not use native mode authentication.\n",
1244                         ERROR + NOT_HERE);
1245                 return;
1246         }
1247
1248         if (config.c_disable_newu) {
1249                 cprintf("%d Self-service user account creation "
1250                         "is disabled on this system.\n", ERROR + NOT_HERE);
1251                 return;
1252         }
1253
1254         if (CC->logged_in) {
1255                 cprintf("%d Already logged in.\n", ERROR + ALREADY_LOGGED_IN);
1256                 return;
1257         }
1258         if (CC->nologin) {
1259                 cprintf("%d %s: Too many users are already online (maximum is %d)\n",
1260                         ERROR + MAX_SESSIONS_EXCEEDED,
1261                         config.c_nodename, config.c_maxsessions);
1262         }
1263         extract_token(username, cmdbuf, 0, '|', sizeof username);
1264         strproc(username);
1265         len = cutuserkey(username);
1266
1267         if (IsEmptyStr(username)) {
1268                 cprintf("%d You must supply a user name.\n", ERROR + USERNAME_REQUIRED);
1269                 return;
1270         }
1271
1272         if ((!strcasecmp(username, "bbs")) ||
1273             (!strcasecmp(username, "new")) ||
1274             (!strcasecmp(username, "."))) {
1275                 cprintf("%d '%s' is an invalid login name.\n", ERROR + ILLEGAL_VALUE, username);
1276                 return;
1277         }
1278
1279         a = create_user(username, len, 1);
1280
1281         if (a == 0) {
1282                 logged_in_response();
1283         } else if (a == ERROR + ALREADY_EXISTS) {
1284                 cprintf("%d '%s' already exists.\n",
1285                         ERROR + ALREADY_EXISTS, username);
1286                 return;
1287         } else if (a == ERROR + INTERNAL_ERROR) {
1288                 cprintf("%d Internal error - user record disappeared?\n",
1289                         ERROR + INTERNAL_ERROR);
1290                 return;
1291         } else {
1292                 cprintf("%d unknown error\n", ERROR + INTERNAL_ERROR);
1293         }
1294 }
1295
1296
1297 /*
1298  * set password - back end api code
1299  */
1300 void CtdlSetPassword(char *new_pw)
1301 {
1302         CtdlGetUserLock(&CC->user, CC->curr_user);
1303         safestrncpy(CC->user.password, new_pw, sizeof(CC->user.password));
1304         CtdlPutUserLock(&CC->user);
1305         CtdlLogPrintf(CTDL_INFO, "Password changed for user <%s>\n", CC->curr_user);
1306         PerformSessionHooks(EVT_SETPASS);
1307 }
1308
1309
1310 /*
1311  * set password - citadel protocol implementation
1312  */
1313 void cmd_setp(char *new_pw)
1314 {
1315         int generate_random_password = 0;
1316
1317         if (CtdlAccessCheck(ac_logged_in)) {
1318                 return;
1319         }
1320         if ( (CC->user.uid != CTDLUID) && (CC->user.uid != (-1)) ) {
1321                 cprintf("%d Not allowed.  Use the 'passwd' command.\n", ERROR + NOT_HERE);
1322                 return;
1323         }
1324         if (CC->is_master) {
1325                 cprintf("%d The master prefix password cannot be changed with this command.\n",
1326                         ERROR + NOT_HERE);
1327                 return;
1328         }
1329
1330         if (!strcasecmp(new_pw, "GENERATE_RANDOM_PASSWORD")) {
1331                 char random_password[17];
1332                 generate_random_password = 1;
1333                 snprintf(random_password, sizeof random_password, "%08lx%08lx", random(), random());
1334                 CtdlSetPassword(random_password);
1335                 cprintf("%d %s\n", CIT_OK, random_password);
1336         }
1337         else {
1338                 strproc(new_pw);
1339                 if (IsEmptyStr(new_pw)) {
1340                         cprintf("%d Password unchanged.\n", CIT_OK);
1341                         return;
1342                 }
1343                 CtdlSetPassword(new_pw);
1344                 cprintf("%d Password changed.\n", CIT_OK);
1345         }
1346 }
1347
1348
1349 /*
1350  * cmd_creu() - administratively create a new user account (do not log in to it)
1351  */
1352 void cmd_creu(char *cmdbuf)
1353 {
1354         int a;
1355         long len;
1356         char username[SIZ];
1357         char password[SIZ];
1358         struct ctdluser tmp;
1359
1360         if (CtdlAccessCheck(ac_aide)) {
1361                 return;
1362         }
1363
1364         extract_token(username, cmdbuf, 0, '|', sizeof username);
1365         extract_token(password, cmdbuf, 1, '|', sizeof password);
1366         ////username[25] = 0;
1367         //password[31] = 0;
1368         strproc(username);
1369         strproc(password);
1370         len = cutuserkey(username);
1371
1372         if (IsEmptyStr(username)) {
1373                 cprintf("%d You must supply a user name.\n", ERROR + USERNAME_REQUIRED);
1374                 return;
1375         }
1376
1377         a = create_user(username, len, 0);
1378
1379         if (a == 0) {
1380                 if (!IsEmptyStr(password)) {
1381                         CtdlGetUserLock(&tmp, username);
1382                         safestrncpy(tmp.password, password, sizeof(tmp.password));
1383                         CtdlPutUserLock(&tmp);
1384                 }
1385                 cprintf("%d User '%s' created %s.\n", CIT_OK, username,
1386                                 (!IsEmptyStr(password)) ? "and password set" :
1387                                 "with no password");
1388                 return;
1389         } else if (a == ERROR + ALREADY_EXISTS) {
1390                 cprintf("%d '%s' already exists.\n", ERROR + ALREADY_EXISTS, username);
1391                 return;
1392         } else if ( (config.c_auth_mode != AUTHMODE_NATIVE) && (a == ERROR + NO_SUCH_USER) ) {
1393                 cprintf("%d User accounts are not created within Citadel in host authentication mode.\n",
1394                         ERROR + NO_SUCH_USER);
1395                 return;
1396         } else {
1397                 cprintf("%d An error occurred creating the user account.\n", ERROR + INTERNAL_ERROR);
1398         }
1399 }
1400
1401
1402
1403 /*
1404  * get user parameters
1405  */
1406 void cmd_getu(char *cmdbuf)
1407 {
1408
1409         if (CtdlAccessCheck(ac_logged_in))
1410                 return;
1411
1412         CtdlGetUser(&CC->user, CC->curr_user);
1413         cprintf("%d 80|24|%d|\n",
1414                 CIT_OK,
1415                 (CC->user.flags & US_USER_SET)
1416         );
1417 }
1418
1419 /*
1420  * set user parameters
1421  */
1422 void cmd_setu(char *new_parms)
1423 {
1424         if (CtdlAccessCheck(ac_logged_in))
1425                 return;
1426
1427         if (num_parms(new_parms) < 3) {
1428                 cprintf("%d Usage error.\n", ERROR + ILLEGAL_VALUE);
1429                 return;
1430         }
1431         CtdlGetUserLock(&CC->user, CC->curr_user);
1432         CC->user.flags = CC->user.flags & (~US_USER_SET);
1433         CC->user.flags = CC->user.flags | (extract_int(new_parms, 2) & US_USER_SET);
1434         CtdlPutUserLock(&CC->user);
1435         cprintf("%d Ok\n", CIT_OK);
1436 }
1437
1438 /*
1439  * set last read pointer
1440  */
1441 void cmd_slrp(char *new_ptr)
1442 {
1443         long newlr;
1444         visit vbuf;
1445         visit original_vbuf;
1446
1447         if (CtdlAccessCheck(ac_logged_in)) {
1448                 return;
1449         }
1450
1451         if (!strncasecmp(new_ptr, "highest", 7)) {
1452                 newlr = CC->room.QRhighest;
1453         } else {
1454                 newlr = atol(new_ptr);
1455         }
1456
1457         CtdlGetUserLock(&CC->user, CC->curr_user);
1458
1459         CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
1460         memcpy(&original_vbuf, &vbuf, sizeof(visit));
1461         vbuf.v_lastseen = newlr;
1462         snprintf(vbuf.v_seen, sizeof vbuf.v_seen, "*:%ld", newlr);
1463
1464         /* Only rewrite the record if it changed */
1465         if ( (vbuf.v_lastseen != original_vbuf.v_lastseen)
1466            || (strcmp(vbuf.v_seen, original_vbuf.v_seen)) ) {
1467                 CtdlSetRelationship(&vbuf, &CC->user, &CC->room);
1468         }
1469
1470         CtdlPutUserLock(&CC->user);
1471         cprintf("%d %ld\n", CIT_OK, newlr);
1472 }
1473
1474
1475 void cmd_seen(char *argbuf) {
1476         long target_msgnum = 0L;
1477         int target_setting = 0;
1478
1479         if (CtdlAccessCheck(ac_logged_in)) {
1480                 return;
1481         }
1482
1483         if (num_parms(argbuf) != 2) {
1484                 cprintf("%d Invalid parameters\n", ERROR + ILLEGAL_VALUE);
1485                 return;
1486         }
1487
1488         target_msgnum = extract_long(argbuf, 0);
1489         target_setting = extract_int(argbuf, 1);
1490
1491         CtdlSetSeen(&target_msgnum, 1, target_setting,
1492                         ctdlsetseen_seen, NULL, NULL);
1493         cprintf("%d OK\n", CIT_OK);
1494 }
1495
1496
1497 void cmd_gtsn(char *argbuf) {
1498         visit vbuf;
1499
1500         if (CtdlAccessCheck(ac_logged_in)) {
1501                 return;
1502         }
1503
1504         /* Learn about the user and room in question */
1505         CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
1506
1507         cprintf("%d ", CIT_OK);
1508         client_write(vbuf.v_seen, strlen(vbuf.v_seen));
1509         client_write(HKEY("\n"));
1510 }
1511
1512
1513 /*
1514  * API function for cmd_invt_kick() and anything else that needs to
1515  * invite or kick out a user to/from a room.
1516  * 
1517  * Set iuser to the name of the user, and op to 1=invite or 0=kick
1518  */
1519 int CtdlInvtKick(char *iuser, int op) {
1520         struct ctdluser USscratch;
1521         visit vbuf;
1522         char bbb[SIZ];
1523
1524         if (CtdlGetUser(&USscratch, iuser) != 0) {
1525                 return(1);
1526         }
1527
1528         CtdlGetRelationship(&vbuf, &USscratch, &CC->room);
1529         if (op == 1) {
1530                 vbuf.v_flags = vbuf.v_flags & ~V_FORGET & ~V_LOCKOUT;
1531                 vbuf.v_flags = vbuf.v_flags | V_ACCESS;
1532         }
1533         if (op == 0) {
1534                 vbuf.v_flags = vbuf.v_flags & ~V_ACCESS;
1535                 vbuf.v_flags = vbuf.v_flags | V_FORGET | V_LOCKOUT;
1536         }
1537         CtdlSetRelationship(&vbuf, &USscratch, &CC->room);
1538
1539         /* post a message in Aide> saying what we just did */
1540         snprintf(bbb, sizeof bbb, "%s has been %s \"%s\" by %s.\n",
1541                 iuser,
1542                 ((op == 1) ? "invited to" : "kicked out of"),
1543                 CC->room.QRname,
1544                 CC->user.fullname);
1545         CtdlAideMessage(bbb,"User Admin Message");
1546
1547         return(0);
1548 }
1549
1550
1551 /*
1552  * INVT and KICK commands
1553  */
1554 void cmd_invt_kick(char *iuser, int op) {
1555
1556         /*
1557          * These commands are only allowed by aides, room aides,
1558          * and room namespace owners
1559          */
1560         if (is_room_aide()) {
1561                 /* access granted */
1562         } else if ( ((atol(CC->room.QRname) == CC->user.usernum) ) && (CC->user.usernum != 0) ) {
1563                 /* access granted */
1564         } else {
1565                 /* access denied */
1566                 cprintf("%d Higher access or room ownership required.\n",
1567                         ERROR + HIGHER_ACCESS_REQUIRED);
1568                 return;
1569         }
1570
1571         if (!strncasecmp(CC->room.QRname, config.c_baseroom,
1572                          ROOMNAMELEN)) {
1573                 cprintf("%d Can't add/remove users from this room.\n",
1574                         ERROR + NOT_HERE);
1575                 return;
1576         }
1577
1578         if (CtdlInvtKick(iuser, op) != 0) {
1579                 cprintf("%d No such user.\n", ERROR + NO_SUCH_USER);
1580                 return;
1581         }
1582
1583         cprintf("%d %s %s %s.\n",
1584                 CIT_OK, iuser,
1585                 ((op == 1) ? "invited to" : "kicked out of"),
1586                 CC->room.QRname);
1587         return;
1588 }
1589
1590 void cmd_invt(char *iuser) {cmd_invt_kick(iuser, 1);}
1591 void cmd_kick(char *iuser) {cmd_invt_kick(iuser, 0);}
1592
1593 /*
1594  * Forget (Zap) the current room (API call)
1595  * Returns 0 on success
1596  */
1597 int CtdlForgetThisRoom(void) {
1598         visit vbuf;
1599
1600         /* On some systems, Aides are not allowed to forget rooms */
1601         if (is_aide() && (config.c_aide_zap == 0)
1602            && ((CC->room.QRflags & QR_MAILBOX) == 0)  ) {
1603                 return(1);
1604         }
1605
1606         CtdlGetUserLock(&CC->user, CC->curr_user);
1607         CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
1608
1609         vbuf.v_flags = vbuf.v_flags | V_FORGET;
1610         vbuf.v_flags = vbuf.v_flags & ~V_ACCESS;
1611
1612         CtdlSetRelationship(&vbuf, &CC->user, &CC->room);
1613         CtdlPutUserLock(&CC->user);
1614
1615         /* Return to the Lobby, so we don't end up in an undefined room */
1616         CtdlUserGoto(config.c_baseroom, 0, 0, NULL, NULL);
1617         return(0);
1618
1619 }
1620
1621
1622 /*
1623  * forget (Zap) the current room
1624  */
1625 void cmd_forg(char *argbuf)
1626 {
1627
1628         if (CtdlAccessCheck(ac_logged_in)) {
1629                 return;
1630         }
1631
1632         if (CtdlForgetThisRoom() == 0) {
1633                 cprintf("%d Ok\n", CIT_OK);
1634         }
1635         else {
1636                 cprintf("%d You may not forget this room.\n", ERROR + NOT_HERE);
1637         }
1638 }
1639
1640 /*
1641  * Get Next Unregistered User
1642  */
1643 void cmd_gnur(char *argbuf)
1644 {
1645         struct cdbdata *cdbus;
1646         struct ctdluser usbuf;
1647
1648         if (CtdlAccessCheck(ac_aide)) {
1649                 return;
1650         }
1651
1652         if ((CitControl.MMflags & MM_VALID) == 0) {
1653                 cprintf("%d There are no unvalidated users.\n", CIT_OK);
1654                 return;
1655         }
1656
1657         /* There are unvalidated users.  Traverse the user database,
1658          * and return the first user we find that needs validation.
1659          */
1660         cdb_rewind(CDB_USERS);
1661         while (cdbus = cdb_next_item(CDB_USERS), cdbus != NULL) {
1662                 memset(&usbuf, 0, sizeof(struct ctdluser));
1663                 memcpy(&usbuf, cdbus->ptr,
1664                        ((cdbus->len > sizeof(struct ctdluser)) ?
1665                         sizeof(struct ctdluser) : cdbus->len));
1666                 cdb_free(cdbus);
1667                 if ((usbuf.flags & US_NEEDVALID)
1668                     && (usbuf.axlevel > AxDeleted)) {
1669                         cprintf("%d %s\n", MORE_DATA, usbuf.fullname);
1670                         cdb_close_cursor(CDB_USERS);
1671                         return;
1672                 }
1673         }
1674
1675         /* If we get to this point, there are no more unvalidated users.
1676          * Therefore we clear the "users need validation" flag.
1677          */
1678
1679         begin_critical_section(S_CONTROL);
1680         get_control();
1681         CitControl.MMflags = CitControl.MMflags & (~MM_VALID);
1682         put_control();
1683         end_critical_section(S_CONTROL);
1684         cprintf("%d *** End of registration.\n", CIT_OK);
1685
1686
1687 }
1688
1689
1690 /*
1691  * validate a user
1692  */
1693 void cmd_vali(char *v_args)
1694 {
1695         char user[128];
1696         int newax;
1697         struct ctdluser userbuf;
1698
1699         extract_token(user, v_args, 0, '|', sizeof user);
1700         newax = extract_int(v_args, 1);
1701
1702         if (CtdlAccessCheck(ac_aide) || 
1703             (newax > AxAideU) ||
1704             (newax < AxDeleted)) {
1705                 return;
1706         }
1707
1708         if (CtdlGetUserLock(&userbuf, user) != 0) {
1709                 cprintf("%d '%s' not found.\n", ERROR + NO_SUCH_USER, user);
1710                 return;
1711         }
1712
1713         userbuf.axlevel = newax;
1714         userbuf.flags = (userbuf.flags & ~US_NEEDVALID);
1715
1716         CtdlPutUserLock(&userbuf);
1717
1718         /* If the access level was set to zero, delete the user */
1719         if (newax == 0) {
1720                 if (purge_user(user) == 0) {
1721                         cprintf("%d %s Deleted.\n", CIT_OK, userbuf.fullname);
1722                         return;
1723                 }
1724         }
1725         cprintf("%d User '%s' validated.\n", CIT_OK, userbuf.fullname);
1726 }
1727
1728
1729
1730 /* 
1731  *  Traverse the user file...
1732  */
1733 void ForEachUser(void (*CallBack) (struct ctdluser * EachUser, void *out_data),
1734                  void *in_data)
1735 {
1736         struct ctdluser usbuf;
1737         struct cdbdata *cdbus;
1738
1739         cdb_rewind(CDB_USERS);
1740
1741         while (cdbus = cdb_next_item(CDB_USERS), cdbus != NULL) {
1742                 memset(&usbuf, 0, sizeof(struct ctdluser));
1743                 memcpy(&usbuf, cdbus->ptr,
1744                        ((cdbus->len > sizeof(struct ctdluser)) ?
1745                         sizeof(struct ctdluser) : cdbus->len));
1746                 cdb_free(cdbus);
1747                 (*CallBack) (&usbuf, in_data);
1748         }
1749 }
1750
1751
1752 /*
1753  * List one user (this works with cmd_list)
1754  */
1755 void ListThisUser(struct ctdluser *usbuf, void *data)
1756 {
1757         char *searchstring;
1758
1759         searchstring = (char *)data;
1760         if (bmstrcasestr(usbuf->fullname, searchstring) == NULL) {
1761                 return;
1762         }
1763
1764         if (usbuf->axlevel > AxDeleted) {
1765                 if ((CC->user.axlevel >= AxAideU)
1766                     || ((usbuf->flags & US_UNLISTED) == 0)
1767                     || ((CC->internal_pgm))) {
1768                         cprintf("%s|%d|%ld|%ld|%ld|%ld||\n",
1769                                 usbuf->fullname,
1770                                 usbuf->axlevel,
1771                                 usbuf->usernum,
1772                                 (long)usbuf->lastcall,
1773                                 usbuf->timescalled,
1774                                 usbuf->posted);
1775                 }
1776         }
1777 }
1778
1779 /* 
1780  *  List users (searchstring may be empty to list all users)
1781  */
1782 void cmd_list(char *cmdbuf)
1783 {
1784         char searchstring[256];
1785         extract_token(searchstring, cmdbuf, 0, '|', sizeof searchstring);
1786         striplt(searchstring);
1787         cprintf("%d \n", LISTING_FOLLOWS);
1788         ForEachUser(ListThisUser, (void *)searchstring );
1789         cprintf("000\n");
1790 }
1791
1792
1793
1794
1795 /*
1796  * assorted info we need to check at login
1797  */
1798 void cmd_chek(char *argbuf)
1799 {
1800         int mail = 0;
1801         int regis = 0;
1802         int vali = 0;
1803
1804         if (CtdlAccessCheck(ac_logged_in)) {
1805                 return;
1806         }
1807
1808         CtdlGetUser(&CC->user, CC->curr_user);  /* no lock is needed here */
1809         if ((REGISCALL != 0) && ((CC->user.flags & US_REGIS) == 0))
1810                 regis = 1;
1811
1812         if (CC->user.axlevel >= AxAideU) {
1813                 get_control();
1814                 if (CitControl.MMflags & MM_VALID)
1815                         vali = 1;
1816         }
1817
1818         /* check for mail */
1819         mail = InitialMailCheck();
1820
1821         cprintf("%d %d|%d|%d|%s|\n", CIT_OK, mail, regis, vali, CC->cs_inet_email);
1822 }
1823
1824
1825 /*
1826  * check to see if a user exists
1827  */
1828 void cmd_qusr(char *who)
1829 {
1830         struct ctdluser usbuf;
1831
1832         if (CtdlGetUser(&usbuf, who) == 0) {
1833                 cprintf("%d %s\n", CIT_OK, usbuf.fullname);
1834         } else {
1835                 cprintf("%d No such user.\n", ERROR + NO_SUCH_USER);
1836         }
1837 }
1838
1839
1840 /*
1841  * Administrative Get User Parameters
1842  */
1843 void cmd_agup(char *cmdbuf)
1844 {
1845         struct ctdluser usbuf;
1846         char requested_user[128];
1847
1848         if (CtdlAccessCheck(ac_aide)) {
1849                 return;
1850         }
1851
1852         extract_token(requested_user, cmdbuf, 0, '|', sizeof requested_user);
1853         if (CtdlGetUser(&usbuf, requested_user) != 0) {
1854                 cprintf("%d No such user.\n", ERROR + NO_SUCH_USER);
1855                 return;
1856         }
1857         cprintf("%d %s|%s|%u|%ld|%ld|%d|%ld|%ld|%d\n",
1858                 CIT_OK,
1859                 usbuf.fullname,
1860                 usbuf.password,
1861                 usbuf.flags,
1862                 usbuf.timescalled,
1863                 usbuf.posted,
1864                 (int) usbuf.axlevel,
1865                 usbuf.usernum,
1866                 (long)usbuf.lastcall,
1867                 usbuf.USuserpurge);
1868 }
1869
1870
1871
1872 /*
1873  * Administrative Set User Parameters
1874  */
1875 void cmd_asup(char *cmdbuf)
1876 {
1877         struct ctdluser usbuf;
1878         char requested_user[128];
1879         char notify[SIZ];
1880         int np;
1881         int newax;
1882         int deleted = 0;
1883
1884         if (CtdlAccessCheck(ac_aide))
1885                 return;
1886
1887         extract_token(requested_user, cmdbuf, 0, '|', sizeof requested_user);
1888         if (CtdlGetUserLock(&usbuf, requested_user) != 0) {
1889                 cprintf("%d No such user.\n", ERROR + NO_SUCH_USER);
1890                 return;
1891         }
1892         np = num_parms(cmdbuf);
1893         if (np > 1)
1894                 extract_token(usbuf.password, cmdbuf, 1, '|', sizeof usbuf.password);
1895         if (np > 2)
1896                 usbuf.flags = extract_int(cmdbuf, 2);
1897         if (np > 3)
1898                 usbuf.timescalled = extract_int(cmdbuf, 3);
1899         if (np > 4)
1900                 usbuf.posted = extract_int(cmdbuf, 4);
1901         if (np > 5) {
1902                 newax = extract_int(cmdbuf, 5);
1903                 if ((newax >= AxDeleted) && (newax <= AxAideU)) {
1904                         usbuf.axlevel = newax;
1905                 }
1906         }
1907         if (np > 7) {
1908                 usbuf.lastcall = extract_long(cmdbuf, 7);
1909         }
1910         if (np > 8) {
1911                 usbuf.USuserpurge = extract_int(cmdbuf, 8);
1912         }
1913         CtdlPutUserLock(&usbuf);
1914         if (usbuf.axlevel == AxDeleted) {
1915                 if (purge_user(requested_user) == 0) {
1916                         deleted = 1;
1917                 }
1918         }
1919
1920         if (deleted) {
1921                 snprintf(notify, SIZ, 
1922                          "User \"%s\" has been deleted by %s.\n",
1923                          usbuf.fullname, CC->user.fullname);
1924                 CtdlAideMessage(notify, "User Deletion Message");
1925         }
1926
1927         cprintf("%d Ok", CIT_OK);
1928         if (deleted)
1929                 cprintf(" (%s deleted)", requested_user);
1930         cprintf("\n");
1931 }
1932
1933
1934
1935 /*
1936  * Count the number of new mail messages the user has
1937  */
1938 int NewMailCount()
1939 {
1940         int num_newmsgs = 0;
1941
1942         num_newmsgs = CC->newmail;
1943         CC->newmail = 0;
1944
1945         return (num_newmsgs);
1946 }
1947
1948
1949 /*
1950  * Count the number of new mail messages the user has
1951  */
1952 int InitialMailCheck()
1953 {
1954         int num_newmsgs = 0;
1955         int a;
1956         char mailboxname[ROOMNAMELEN];
1957         struct ctdlroom mailbox;
1958         visit vbuf;
1959         struct cdbdata *cdbfr;
1960         long *msglist = NULL;
1961         int num_msgs = 0;
1962
1963         CtdlMailboxName(mailboxname, sizeof mailboxname, &CC->user, MAILROOM);
1964         if (CtdlGetRoom(&mailbox, mailboxname) != 0)
1965                 return (0);
1966         CtdlGetRelationship(&vbuf, &CC->user, &mailbox);
1967
1968         cdbfr = cdb_fetch(CDB_MSGLISTS, &mailbox.QRnumber, sizeof(long));
1969
1970         if (cdbfr != NULL) {
1971                 msglist = malloc(cdbfr->len);
1972                 memcpy(msglist, cdbfr->ptr, cdbfr->len);
1973                 num_msgs = cdbfr->len / sizeof(long);
1974                 cdb_free(cdbfr);
1975         }
1976         if (num_msgs > 0)
1977                 for (a = 0; a < num_msgs; ++a) {
1978                         if (msglist[a] > 0L) {
1979                                 if (msglist[a] > vbuf.v_lastseen) {
1980                                         ++num_newmsgs;
1981                                 }
1982                         }
1983                 }
1984         if (msglist != NULL)
1985                 free(msglist);
1986
1987         return (num_newmsgs);
1988 }
1989
1990
1991
1992 /*
1993  * Set the preferred view for the current user/room combination
1994  */
1995 void cmd_view(char *cmdbuf) {
1996         int requested_view;
1997         visit vbuf;
1998
1999         if (CtdlAccessCheck(ac_logged_in)) {
2000                 return;
2001         }
2002
2003         requested_view = extract_int(cmdbuf, 0);
2004
2005         CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
2006         vbuf.v_view = requested_view;
2007         CtdlSetRelationship(&vbuf, &CC->user, &CC->room);
2008         
2009         cprintf("%d ok\n", CIT_OK);
2010 }
2011
2012
2013 /*
2014  * Rename a user
2015  */
2016 void cmd_renu(char *cmdbuf)
2017 {
2018         int retcode;
2019         char oldname[USERNAME_SIZE];
2020         char newname[USERNAME_SIZE];
2021
2022         if (CtdlAccessCheck(ac_aide)) {
2023                 return;
2024         }
2025
2026         extract_token(oldname, cmdbuf, 0, '|', sizeof oldname);
2027         extract_token(newname, cmdbuf, 1, '|', sizeof newname);
2028
2029         retcode = rename_user(oldname, newname);
2030         switch(retcode) {
2031                 case RENAMEUSER_OK:
2032                         cprintf("%d '%s' has been renamed to '%s'.\n", CIT_OK, oldname, newname);
2033                         return;
2034                 case RENAMEUSER_LOGGED_IN:
2035                         cprintf("%d '%s' is currently logged in and cannot be renamed.\n",
2036                                 ERROR + ALREADY_LOGGED_IN , oldname);
2037                         return;
2038                 case RENAMEUSER_NOT_FOUND:
2039                         cprintf("%d '%s' does not exist.\n", ERROR + NO_SUCH_USER, oldname);
2040                         return;
2041                 case RENAMEUSER_ALREADY_EXISTS:
2042                         cprintf("%d A user named '%s' already exists.\n", ERROR + ALREADY_EXISTS, newname);
2043                         return;
2044         }
2045
2046         cprintf("%d An unknown error occurred.\n", ERROR);
2047 }
2048
2049
2050
2051 /*****************************************************************************/
2052 /*                      MODULE INITIALIZATION STUFF                          */
2053 /*****************************************************************************/
2054
2055
2056 CTDL_MODULE_INIT(user_ops)
2057 {
2058         if (!threading) {
2059                 CtdlRegisterProtoHook(cmd_user, "USER", "Submit username for login");
2060                 CtdlRegisterProtoHook(cmd_pass, "PASS", "Complete login by submitting a password");
2061                 CtdlRegisterProtoHook(cmd_creu, "CREU", "Create User");
2062                 CtdlRegisterProtoHook(cmd_setp, "SETP", "Set the password for an account");
2063                 CtdlRegisterProtoHook(cmd_getu, "GETU", "Get User parameters");
2064                 CtdlRegisterProtoHook(cmd_setu, "SETU", "Set User parameters");
2065                 CtdlRegisterProtoHook(cmd_slrp, "SLRP", "Set Last Read Pointer");
2066                 CtdlRegisterProtoHook(cmd_invt, "INVT", "Invite a user to a room");
2067                 CtdlRegisterProtoHook(cmd_kick, "KICK", "Kick a user out of a room");
2068                 CtdlRegisterProtoHook(cmd_forg, "FORG", "Forget a room");
2069                 CtdlRegisterProtoHook(cmd_gnur, "GNUR", "Autoconverted. TODO: document me.");
2070                 CtdlRegisterProtoHook(cmd_vali, "VALI", "Validate new users");
2071                 CtdlRegisterProtoHook(cmd_list, "LIST", "List users");
2072                 CtdlRegisterProtoHook(cmd_chek, "CHEK", "Autoconverted. TODO: document me.");
2073                 CtdlRegisterProtoHook(cmd_qusr, "QUSR", "Autoconverted. TODO: document me.");
2074                 CtdlRegisterProtoHook(cmd_agup, "AGUP", "Autoconverted. TODO: document me.");
2075                 CtdlRegisterProtoHook(cmd_asup, "ASUP", "Autoconverted. TODO: document me.");
2076                 CtdlRegisterProtoHook(cmd_seen, "SEEN", "Autoconverted. TODO: document me.");
2077                 CtdlRegisterProtoHook(cmd_gtsn, "GTSN", "Autoconverted. TODO: document me.");
2078                 CtdlRegisterProtoHook(cmd_view, "VIEW", "Autoconverted. TODO: document me.");
2079                 CtdlRegisterProtoHook(cmd_renu, "RENU", "Autoconverted. TODO: document me.");
2080                 CtdlRegisterProtoHook(cmd_newu, "NEWU", "Autoconverted. TODO: document me.");
2081         }
2082         /* return our Subversion id for the Log */
2083         return "user_ops";
2084 }