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