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