b43c7bb2af46a9b7833f49e645b3c90e54834ec3
[citadel.git] / citadel / user_ops.c
1 /* 
2  * $Id$
3  *
4  * Server functions which perform operations on user objects.
5  *
6  */
7
8 #ifdef DLL_EXPORT
9 #define IN_LIBCIT
10 #endif
11
12 #include "sysdep.h"
13 #include <errno.h>
14 #include <stdlib.h>
15 #include <unistd.h>
16 #include <stdio.h>
17 #include <fcntl.h>
18 #include <signal.h>
19 #include <pwd.h>
20 #include <ctype.h>
21 #include <sys/types.h>
22 #include <sys/wait.h>
23
24 #if TIME_WITH_SYS_TIME
25 # include <sys/time.h>
26 # include <time.h>
27 #else
28 # if HAVE_SYS_TIME_H
29 #  include <sys/time.h>
30 # else
31 #  include <time.h>
32 # endif
33 #endif
34
35 #include <string.h>
36 #include <limits.h>
37 #ifndef ENABLE_CHKPWD
38 #include "auth.h"
39 #endif
40 #include "citadel.h"
41 #include "server.h"
42 #include "database.h"
43 #include "user_ops.h"
44 #include "serv_extensions.h"
45 #include "sysdep_decls.h"
46 #include "support.h"
47 #include "room_ops.h"
48 #include "file_ops.h"
49 #include "control.h"
50 #include "msgbase.h"
51 #include "config.h"
52 #include "tools.h"
53 #include "citserver.h"
54
55
56 /*
57  * makeuserkey() - convert a username into the format used as a database key
58  *                 (it's just the username converted into lower case)
59  */
60 static INLINE void makeuserkey(char *key, char *username) {
61         int i, len;
62
63         len = strlen(username);
64         for (i=0; i<=len; ++i) {
65                 key[i] = tolower(username[i]);
66         }
67 }
68
69
70 /*
71  * getuser()  -  retrieve named user into supplied buffer.
72  *               returns 0 on success
73  */
74 int getuser(struct ctdluser *usbuf, char name[])
75 {
76
77         char usernamekey[USERNAME_SIZE];
78         char sysuser_name[USERNAME_SIZE];
79         struct cdbdata *cdbus;
80         int using_sysuser = 0;
81
82         memset(usbuf, 0, sizeof(struct ctdluser));
83
84 #ifdef ENABLE_AUTOLOGIN
85         if (CtdlAssociateSystemUser(sysuser_name, name) == 0) {
86                 ++using_sysuser;
87         }
88 #endif
89
90         if (using_sysuser) {
91                 makeuserkey(usernamekey, sysuser_name);
92         }
93         else {
94                 makeuserkey(usernamekey, name);
95         }
96
97         cdbus = cdb_fetch(CDB_USERS, usernamekey, strlen(usernamekey));
98         if (cdbus == NULL) {    /* user not found */
99                 return(1);
100         }
101         memcpy(usbuf, cdbus->ptr,
102                ((cdbus->len > sizeof(struct ctdluser)) ?
103                 sizeof(struct ctdluser) : cdbus->len));
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         struct passwd *p = NULL;
356
357         if (trythisname == NULL) return login_not_found;
358         safestrncpy(username, trythisname, sizeof username);
359         strproc(username);
360
361         if ((CC->logged_in)) {
362                 return login_already_logged_in;
363         }
364
365         /* First, try to log in as if the supplied name is a display name */
366         found_user = getuser(&CC->user, username);
367
368         /* If that didn't work, try to log in as if the supplied name
369          * is an e-mail address
370          */
371         if (found_user != 0) {
372                 valid = validate_recipients(trythisname);
373                 if (valid != NULL) {
374                         if (valid->num_local == 1) {
375                                 found_user = getuser(&CC->user,
376                                                 valid->recp_local);
377                         }
378                         phree(valid);
379                 }
380         }
381
382 #ifdef ENABLE_AUTOLOGIN
383         /* If we haven't found the account yet, and the supplied name
384          * is a login name on the underlying host system, create the
385          * account.
386          */
387         if (found_user != 0) {
388                 p = (struct passwd *) getpwnam(username);
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[SIZ];
417         int a;
418
419         extract(username, cmdbuf, 0);
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                 cprintf("%d Internal error\n", ERROR + INTERNAL_ERROR);
442         }
443 }
444
445
446
447 /*
448  * session startup code which is common to both cmd_pass() and cmd_newu()
449  */
450 void session_startup(void)
451 {
452         int i;
453
454         lprintf(CTDL_NOTICE, "<%s> logged in\n", CC->curr_user);
455
456         lgetuser(&CC->user, CC->curr_user);
457         ++(CC->user.timescalled);
458         CC->previous_login = CC->user.lastcall;
459         time(&CC->user.lastcall);
460
461         /* If this user's name is the name of the system administrator
462          * (as specified in setup), automatically assign access level 6.
463          */
464         if (!strcasecmp(CC->user.fullname, config.c_sysadm)) {
465                 CC->user.axlevel = 6;
466         }
467         lputuser(&CC->user);
468
469         /*
470          * Populate CC->cs_inet_email with a default address.  This will be
471          * overwritten with the user's directory address, if one exists, when
472          * the vCard module's login hook runs.
473          */
474         snprintf(CC->cs_inet_email, sizeof CC->cs_inet_email, "%s@%s",
475                 CC->user.fullname, config.c_fqdn);
476         for (i=0; i<strlen(CC->cs_inet_email); ++i) {
477                 if (isspace(CC->cs_inet_email[i])) {
478                         CC->cs_inet_email[i] = '_';
479                 }
480         }
481
482         /* Create any personal rooms required by the system.
483          * (Technically, MAILROOM should be there already, but just in case...)
484          */
485         create_room(MAILROOM, 4, "", 0, 1, 0);
486         create_room(SENTITEMS, 4, "", 0, 1, 0);
487
488         /* Run any startup routines registered by loadable modules */
489         PerformSessionHooks(EVT_LOGIN);
490
491         /* Enter the lobby */
492         usergoto(config.c_baseroom, 0, 0, NULL, NULL);
493 }
494
495
496 void logged_in_response(void)
497 {
498         cprintf("%d %s|%d|%ld|%ld|%u|%ld|%ld\n",
499                 CIT_OK, CC->user.fullname, CC->user.axlevel,
500                 CC->user.timescalled, CC->user.posted,
501                 CC->user.flags, CC->user.usernum,
502                 CC->previous_login);
503 }
504
505
506
507 /* 
508  * misc things to be taken care of when a user is logged out
509  */
510 void logout(struct CitContext *who)
511 {
512         /*
513          * Clear out some session data.  Most likely, the CitContext for this
514          * session is about to get nuked when the session disconnects, but
515          * since it's possible to log in again without reconnecting, we cannot
516          * make that assumption.
517          */
518         strcpy(who->fake_username, "");
519         strcpy(who->fake_postname, "");
520         strcpy(who->fake_hostname, "");
521         strcpy(who->fake_roomname, "");
522         who->logged_in = 0;
523
524         /*
525          * If there is a download in progress, abort it.
526          */
527         if (who->download_fp != NULL) {
528                 fclose(who->download_fp);
529                 who->download_fp = NULL;
530         }
531
532         /*
533          * If there is an upload in progress, abort it.
534          */
535         if (who->upload_fp != NULL) {
536                 abort_upl(who);
537         }
538
539         /*
540          * If we were talking to a network node, we're not anymore...
541          */
542         if (strlen(who->net_node) > 0) {
543                 network_talking_to(who->net_node, NTT_REMOVE);
544         }
545
546         /* Do modular stuff... */
547         PerformSessionHooks(EVT_LOGOUT);
548
549         /* Free any output buffers */
550         if (who->output_buffer != NULL) {
551                 unbuffer_output();
552         }
553 }
554
555 #ifdef ENABLE_CHKPWD
556 /*
557  * an alternate version of validpw() which executes `chkpwd' instead of
558  * verifying the password directly
559  */
560 static int validpw(uid_t uid, const char *pass)
561 {
562         pid_t pid;
563         int status, pipev[2];
564         char buf[24];
565
566         if (pipe(pipev)) {
567                 lprintf(CTDL_ERR, "pipe failed (%s): denying autologin access for "
568                         "uid %ld\n", strerror(errno), (long)uid);
569                 return 0;
570         }
571         switch (pid = fork()) {
572         case -1:
573                 lprintf(CTDL_ERR, "fork failed (%s): denying autologin access for "
574                         "uid %ld\n", strerror(errno), (long)uid);
575                 close(pipev[0]);
576                 close(pipev[1]);
577                 return 0;
578
579         case 0:
580                 close(pipev[1]);
581                 if (dup2(pipev[0], 0) == -1) {
582                         perror("dup2");
583                         exit(1);
584                 }
585                 close(pipev[0]);
586
587                 execl(BBSDIR "/chkpwd", BBSDIR "/chkpwd", NULL);
588                 perror(BBSDIR "/chkpwd");
589                 exit(1);
590         }
591
592         close(pipev[0]);
593         write(pipev[1], buf,
594               snprintf(buf, sizeof buf, "%lu\n", (unsigned long) uid));
595         write(pipev[1], pass, strlen(pass));
596         write(pipev[1], "\n", 1);
597         close(pipev[1]);
598
599         while (waitpid(pid, &status, 0) == -1)
600                 if (errno != EINTR) {
601                         lprintf(CTDL_ERR, "waitpid failed (%s): denying autologin "
602                                 "access for uid %ld\n",
603                                 strerror(errno), (long)uid);
604                         return 0;
605                 }
606         if (WIFEXITED(status) && !WEXITSTATUS(status))
607                 return 1;
608
609         return 0;
610 }
611 #endif
612
613 void do_login()
614 {
615         (CC->logged_in) = 1;
616         session_startup();
617 }
618
619
620 int CtdlTryPassword(char *password)
621 {
622         int code;
623
624         if ((CC->logged_in)) {
625                 lprintf(CTDL_WARNING, "CtdlTryPassword: already logged in\n");
626                 return pass_already_logged_in;
627         }
628         if (!strcmp(CC->curr_user, NLI)) {
629                 lprintf(CTDL_WARNING, "CtdlTryPassword: no user selected\n");
630                 return pass_no_user;
631         }
632         if (getuser(&CC->user, CC->curr_user)) {
633                 lprintf(CTDL_ERR, "CtdlTryPassword: internal error\n");
634                 return pass_internal_error;
635         }
636         if (password == NULL) {
637                 lprintf(CTDL_INFO, "CtdlTryPassword: NULL password string supplied\n");
638                 return pass_wrong_password;
639         }
640         code = (-1);
641
642
643 #ifdef ENABLE_AUTOLOGIN
644         /* A uid of BBSUID or -1 indicates that this user exists only in
645          * Citadel, not in the underlying operating system.
646          */
647         if ( (CC->user.uid == BBSUID) || (CC->user.uid == (-1)) ) {
648                 strproc(password);
649                 strproc(CC->user.password);
650                 code = strcasecmp(CC->user.password, password);
651         }
652         /* Any other uid means we have to check the system password database */
653         else {
654                 if (validpw(CC->user.uid, password)) {
655                         code = 0;
656                         lgetuser(&CC->user, CC->curr_user);
657                         safestrncpy(CC->user.password, password,
658                                     sizeof CC->user.password);
659                         lputuser(&CC->user);
660                 }
661         }
662
663 #else /* ENABLE_AUTOLOGIN */
664         strproc(password);
665         strproc(CC->user.password);
666         code = strcasecmp(CC->user.password, password);
667
668 #endif /* ENABLE_AUTOLOGIN */
669
670         if (!code) {
671                 do_login();
672                 return pass_ok;
673         } else {
674                 lprintf(CTDL_WARNING, "Bad password specified for <%s>\n", CC->curr_user);
675                 return pass_wrong_password;
676         }
677 }
678
679
680 void cmd_pass(char *buf)
681 {
682         char password[SIZ];
683         int a;
684
685         extract(password, buf, 0);
686         a = CtdlTryPassword(password);
687
688         switch (a) {
689         case pass_already_logged_in:
690                 cprintf("%d Already logged in.\n", ERROR + ALREADY_LOGGED_IN);
691                 return;
692         case pass_no_user:
693                 cprintf("%d You must send a name with USER first.\n",
694                         ERROR + USERNAME_REQUIRED);
695                 return;
696         case pass_wrong_password:
697                 cprintf("%d Wrong password.\n", ERROR + PASSWORD_REQUIRED);
698                 return;
699         case pass_ok:
700                 logged_in_response();
701                 return;
702                 cprintf("%d Can't find user record!\n",
703                         ERROR + INTERNAL_ERROR);
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.fullname, usbuf.usernum, 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, sizeof filename, "./bio/%ld", usbuf.usernum);
757         unlink(filename);
758
759         /* remove the user's picture */
760         snprintf(filename, sizeof filename, "./userpics/%ld.gif", usbuf.usernum);
761         unlink(filename);
762
763         return (0);
764 }
765
766
767 /*
768  * create_user()  -  back end processing to create a new user
769  *
770  * Set 'newusername' to the desired account name.
771  * Set 'become_user' to nonzero if this is self-service account creation and we want
772  * to actually log in as the user we just created, otherwise set it to 0.
773  */
774 int create_user(char *newusername, int become_user)
775 {
776         struct ctdluser usbuf;
777         struct ctdlroom qrbuf;
778         struct passwd *p = NULL;
779         char username[SIZ];
780         char mailboxname[ROOMNAMELEN];
781         uid_t uid;
782
783         safestrncpy(username, newusername, sizeof username);
784         strproc(username);
785
786 #ifdef ENABLE_AUTOLOGIN
787         p = (struct passwd *) getpwnam(username);
788         if (p != NULL) {
789                 extract_token(username, p->pw_gecos, 0, ',');
790                 uid = p->pw_uid;
791         } else {
792                 uid = (-1);
793         }
794 #else
795         uid = (-1);
796 #endif
797
798         if (!getuser(&usbuf, username)) {
799                 return (ERROR + ALREADY_EXISTS);
800         }
801
802         /* Go ahead and initialize a new user record */
803         memset(&usbuf, 0, sizeof(struct ctdluser));
804         safestrncpy(usbuf.fullname, username, sizeof usbuf.fullname);
805         strcpy(usbuf.password, "");
806         usbuf.uid = uid;
807
808         /* These are the default flags on new accounts */
809         usbuf.flags = US_LASTOLD | US_DISAPPEAR | US_PAGINATOR | US_FLOORS;
810
811         usbuf.timescalled = 0;
812         usbuf.posted = 0;
813         usbuf.axlevel = config.c_initax;
814         usbuf.USscreenwidth = 80;
815         usbuf.USscreenheight = 24;
816         usbuf.lastcall = time(NULL);
817
818         /* fetch a new user number */
819         usbuf.usernum = get_new_user_number();
820
821         /* The very first user created on the system will always be an Aide */
822         if (usbuf.usernum == 1L) {
823                 usbuf.axlevel = 6;
824         }
825
826         /* add user to userlog */
827         putuser(&usbuf);
828
829         /*
830          * Give the user a private mailbox and a configuration room.
831          * Make the latter an invisible system room.
832          */
833         MailboxName(mailboxname, sizeof mailboxname, &usbuf, MAILROOM);
834         create_room(mailboxname, 5, "", 0, 1, 1);
835
836         MailboxName(mailboxname, sizeof mailboxname, &usbuf, USERCONFIGROOM);
837         create_room(mailboxname, 5, "", 0, 1, 1);
838         if (lgetroom(&qrbuf, mailboxname) == 0) {
839                 qrbuf.QRflags2 |= QR2_SYSTEM;
840                 lputroom(&qrbuf);
841         }
842
843         /* Everything below this line can be bypassed if administratively
844            creating a user, instead of doing self-service account creation
845          */
846
847         if (become_user) {
848                 /* Now become the user we just created */
849                 memcpy(&CC->user, &usbuf, sizeof(struct ctdluser));
850                 safestrncpy(CC->curr_user, username, sizeof CC->curr_user);
851                 CC->logged_in = 1;
852         
853                 /* Check to make sure we're still who we think we are */
854                 if (getuser(&CC->user, CC->curr_user)) {
855                         return (ERROR + INTERNAL_ERROR);
856                 }
857         }
858
859         lprintf(CTDL_NOTICE, "New user <%s> created\n", username);
860         return (0);
861 }
862
863
864
865
866 /*
867  * cmd_newu()  -  create a new user account and log in as that user
868  */
869 void cmd_newu(char *cmdbuf)
870 {
871         int a;
872         char username[SIZ];
873
874         if (config.c_disable_newu) {
875                 cprintf("%d Self-service user account creation "
876                         "is disabled on this system.\n", ERROR + NOT_HERE);
877                 return;
878         }
879
880         if (CC->logged_in) {
881                 cprintf("%d Already logged in.\n", ERROR + ALREADY_LOGGED_IN);
882                 return;
883         }
884         if (CC->nologin) {
885                 cprintf("%d %s: Too many users are already online (maximum is %d)\n",
886                         ERROR + MAX_SESSIONS_EXCEEDED,
887                         config.c_nodename, config.c_maxsessions);
888         }
889         extract(username, cmdbuf, 0);
890         username[25] = 0;
891         strproc(username);
892
893         if (strlen(username) == 0) {
894                 cprintf("%d You must supply a user name.\n", ERROR + USERNAME_REQUIRED);
895                 return;
896         }
897
898         if ((!strcasecmp(username, "bbs")) ||
899             (!strcasecmp(username, "new")) ||
900             (!strcasecmp(username, "."))) {
901                 cprintf("%d '%s' is an invalid login name.\n", ERROR + ILLEGAL_VALUE, username);
902                 return;
903         }
904
905         a = create_user(username, 1);
906
907         if (a == 0) {
908                 session_startup();
909                 logged_in_response();
910         } else if (a == ERROR + ALREADY_EXISTS) {
911                 cprintf("%d '%s' already exists.\n",
912                         ERROR + ALREADY_EXISTS, username);
913                 return;
914         } else if (a == ERROR + INTERNAL_ERROR) {
915                 cprintf("%d Internal error - user record disappeared?\n",
916                         ERROR + INTERNAL_ERROR);
917                 return;
918         } else {
919                 cprintf("%d unknown error\n", ERROR + INTERNAL_ERROR);
920         }
921 }
922
923
924
925 /*
926  * set password
927  */
928 void cmd_setp(char *new_pw)
929 {
930         if (CtdlAccessCheck(ac_logged_in)) {
931                 return;
932         }
933         if ( (CC->user.uid != BBSUID) && (CC->user.uid != (-1)) ) {
934                 cprintf("%d Not allowed.  Use the 'passwd' command.\n", ERROR + NOT_HERE);
935                 return;
936         }
937         strproc(new_pw);
938         if (strlen(new_pw) == 0) {
939                 cprintf("%d Password unchanged.\n", CIT_OK);
940                 return;
941         }
942         lgetuser(&CC->user, CC->curr_user);
943         safestrncpy(CC->user.password, new_pw, sizeof(CC->user.password));
944         lputuser(&CC->user);
945         cprintf("%d Password changed.\n", CIT_OK);
946         lprintf(CTDL_INFO, "Password changed for user <%s>\n", CC->curr_user);
947         PerformSessionHooks(EVT_SETPASS);
948 }
949
950
951 /*
952  * cmd_creu() - administratively create a new user account (do not log in to it)
953  */
954 void cmd_creu(char *cmdbuf)
955 {
956         int a;
957         char username[SIZ];
958         char password[SIZ];
959         struct ctdluser tmp;
960
961         if (CtdlAccessCheck(ac_aide)) {
962                 return;
963         }
964
965         extract(username, cmdbuf, 0);
966         extract(password, cmdbuf, 1);
967         username[25] = 0;
968         password[31] = 0;
969         strproc(username);
970         strproc(password);
971
972         if (strlen(username) == 0) {
973                 cprintf("%d You must supply a user name.\n", ERROR + USERNAME_REQUIRED);
974                 return;
975         }
976
977         a = create_user(username, 0);
978
979         if (a == 0) {
980                 if (strlen(password) > 0) {
981                         lgetuser(&tmp, username);
982                         safestrncpy(tmp.password, password, sizeof(tmp.password));
983                         lputuser(&tmp);
984                 }
985                 cprintf("%d User '%s' created %s.\n", CIT_OK, username,
986                                 (strlen(password) > 0) ? "and password set" :
987                                 "with no password");
988                 return;
989         } else if (a == ERROR + ALREADY_EXISTS) {
990                 cprintf("%d '%s' already exists.\n",
991                         ERROR + ALREADY_EXISTS, username);
992                 return;
993         } else {
994                 cprintf("%d An error occured creating the user account.\n", ERROR + INTERNAL_ERROR);
995         }
996 }
997
998
999
1000 /*
1001  * get user parameters
1002  */
1003 void cmd_getu(void)
1004 {
1005
1006         if (CtdlAccessCheck(ac_logged_in))
1007                 return;
1008
1009         getuser(&CC->user, CC->curr_user);
1010         cprintf("%d %d|%d|%d|\n",
1011                 CIT_OK,
1012                 CC->user.USscreenwidth,
1013                 CC->user.USscreenheight,
1014                 (CC->user.flags & US_USER_SET)
1015             );
1016 }
1017
1018 /*
1019  * set user parameters
1020  */
1021 void cmd_setu(char *new_parms)
1022 {
1023         if (CtdlAccessCheck(ac_logged_in))
1024                 return;
1025
1026         if (num_parms(new_parms) < 3) {
1027                 cprintf("%d Usage error.\n", ERROR + ILLEGAL_VALUE);
1028                 return;
1029         }
1030         lgetuser(&CC->user, CC->curr_user);
1031         CC->user.USscreenwidth = extract_int(new_parms, 0);
1032         CC->user.USscreenheight = extract_int(new_parms, 1);
1033         CC->user.flags = CC->user.flags & (~US_USER_SET);
1034         CC->user.flags = CC->user.flags |
1035             (extract_int(new_parms, 2) & US_USER_SET);
1036
1037         lputuser(&CC->user);
1038         cprintf("%d Ok\n", CIT_OK);
1039 }
1040
1041 /*
1042  * set last read pointer
1043  */
1044 void cmd_slrp(char *new_ptr)
1045 {
1046         long newlr;
1047         struct visit vbuf;
1048         struct visit original_vbuf;
1049
1050         if (CtdlAccessCheck(ac_logged_in)) {
1051                 return;
1052         }
1053
1054         if (!strncasecmp(new_ptr, "highest", 7)) {
1055                 newlr = CC->room.QRhighest;
1056         } else {
1057                 newlr = atol(new_ptr);
1058         }
1059
1060         lgetuser(&CC->user, CC->curr_user);
1061
1062         CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
1063         memcpy(&original_vbuf, &vbuf, sizeof(struct visit));
1064         vbuf.v_lastseen = newlr;
1065         snprintf(vbuf.v_seen, sizeof vbuf.v_seen, "*:%ld", newlr);
1066
1067         /* Only rewrite the record if it changed */
1068         if ( (vbuf.v_lastseen != original_vbuf.v_lastseen)
1069            || (strcmp(vbuf.v_seen, original_vbuf.v_seen)) ) {
1070                 CtdlSetRelationship(&vbuf, &CC->user, &CC->room);
1071         }
1072
1073         lputuser(&CC->user);
1074         cprintf("%d %ld\n", CIT_OK, newlr);
1075 }
1076
1077
1078 void cmd_seen(char *argbuf) {
1079         long target_msgnum = 0L;
1080         int target_setting = 0;
1081
1082         if (CtdlAccessCheck(ac_logged_in)) {
1083                 return;
1084         }
1085
1086         if (num_parms(argbuf) != 2) {
1087                 cprintf("%d Invalid parameters\n", ERROR + ILLEGAL_VALUE);
1088                 return;
1089         }
1090
1091         target_msgnum = extract_long(argbuf, 0);
1092         target_setting = extract_int(argbuf, 1);
1093
1094         CtdlSetSeen(target_msgnum, target_setting, ctdlsetseen_seen);
1095         cprintf("%d OK\n", CIT_OK);
1096 }
1097
1098
1099 void cmd_gtsn(char *argbuf) {
1100         char buf[SIZ];
1101
1102         if (CtdlAccessCheck(ac_logged_in)) {
1103                 return;
1104         }
1105
1106         CtdlGetSeen(buf, ctdlsetseen_seen);
1107         cprintf("%d %s\n", CIT_OK, buf);
1108 }
1109
1110
1111 /*
1112  * API function for cmd_invt_kick() and anything else that needs to
1113  * invite or kick out a user to/from a room.
1114  * 
1115  * Set iuser to the name of the user, and op to 1=invite or 0=kick
1116  */
1117 int CtdlInvtKick(char *iuser, int op) {
1118         struct ctdluser USscratch;
1119         struct visit vbuf;
1120         char bbb[SIZ];
1121
1122         if (getuser(&USscratch, iuser) != 0) {
1123                 return(1);
1124         }
1125
1126         CtdlGetRelationship(&vbuf, &USscratch, &CC->room);
1127         if (op == 1) {
1128                 vbuf.v_flags = vbuf.v_flags & ~V_FORGET & ~V_LOCKOUT;
1129                 vbuf.v_flags = vbuf.v_flags | V_ACCESS;
1130         }
1131         if (op == 0) {
1132                 vbuf.v_flags = vbuf.v_flags & ~V_ACCESS;
1133                 vbuf.v_flags = vbuf.v_flags | V_FORGET | V_LOCKOUT;
1134         }
1135         CtdlSetRelationship(&vbuf, &USscratch, &CC->room);
1136
1137         /* post a message in Aide> saying what we just did */
1138         snprintf(bbb, sizeof bbb, "%s %s %s> by %s\n",
1139                 iuser,
1140                 ((op == 1) ? "invited to" : "kicked out of"),
1141                 CC->room.QRname,
1142                 CC->user.fullname);
1143         aide_message(bbb);
1144
1145         return(0);
1146 }
1147
1148
1149 /*
1150  * INVT and KICK commands
1151  */
1152 void cmd_invt_kick(char *iuser, int op) {
1153
1154         /*
1155          * These commands are only allowed by aides, room aides,
1156          * and room namespace owners
1157          */
1158         if (is_room_aide()
1159            || (atol(CC->room.QRname) == CC->user.usernum) ) {
1160                 /* access granted */
1161         } else {
1162                 /* access denied */
1163                 cprintf("%d Higher access or room ownership required.\n",
1164                         ERROR + HIGHER_ACCESS_REQUIRED);
1165                 return;
1166         }
1167
1168         if (!strncasecmp(CC->room.QRname, config.c_baseroom,
1169                          ROOMNAMELEN)) {
1170                 cprintf("%d Can't add/remove users from this room.\n",
1171                         ERROR + NOT_HERE);
1172                 return;
1173         }
1174
1175         if (CtdlInvtKick(iuser, op) != 0) {
1176                 cprintf("%d No such user.\n", ERROR + NO_SUCH_USER);
1177                 return;
1178         }
1179
1180         cprintf("%d %s %s %s.\n",
1181                 CIT_OK, iuser,
1182                 ((op == 1) ? "invited to" : "kicked out of"),
1183                 CC->room.QRname);
1184         return;
1185 }
1186
1187
1188 /*
1189  * Forget (Zap) the current room (API call)
1190  * Returns 0 on success
1191  */
1192 int CtdlForgetThisRoom(void) {
1193         struct visit vbuf;
1194
1195         /* On some systems, Aides are not allowed to forget rooms */
1196         if (is_aide() && (config.c_aide_zap == 0)
1197            && ((CC->room.QRflags & QR_MAILBOX) == 0)  ) {
1198                 return(1);
1199         }
1200
1201         lgetuser(&CC->user, CC->curr_user);
1202         CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
1203
1204         vbuf.v_flags = vbuf.v_flags | V_FORGET;
1205         vbuf.v_flags = vbuf.v_flags & ~V_ACCESS;
1206
1207         CtdlSetRelationship(&vbuf, &CC->user, &CC->room);
1208         lputuser(&CC->user);
1209
1210         /* Return to the Lobby, so we don't end up in an undefined room */
1211         usergoto(config.c_baseroom, 0, 0, NULL, NULL);
1212         return(0);
1213
1214 }
1215
1216
1217 /*
1218  * forget (Zap) the current room
1219  */
1220 void cmd_forg(void)
1221 {
1222
1223         if (CtdlAccessCheck(ac_logged_in)) {
1224                 return;
1225         }
1226
1227         if (CtdlForgetThisRoom() == 0) {
1228                 cprintf("%d Ok\n", CIT_OK);
1229         }
1230         else {
1231                 cprintf("%d You may not forget this room.\n", ERROR + NOT_HERE);
1232         }
1233 }
1234
1235 /*
1236  * Get Next Unregistered User
1237  */
1238 void cmd_gnur(void)
1239 {
1240         struct cdbdata *cdbus;
1241         struct ctdluser usbuf;
1242
1243         if (CtdlAccessCheck(ac_aide)) {
1244                 return;
1245         }
1246
1247         if ((CitControl.MMflags & MM_VALID) == 0) {
1248                 cprintf("%d There are no unvalidated users.\n", CIT_OK);
1249                 return;
1250         }
1251
1252         /* There are unvalidated users.  Traverse the user database,
1253          * and return the first user we find that needs validation.
1254          */
1255         cdb_rewind(CDB_USERS);
1256         while (cdbus = cdb_next_item(CDB_USERS), cdbus != NULL) {
1257                 memset(&usbuf, 0, sizeof(struct ctdluser));
1258                 memcpy(&usbuf, cdbus->ptr,
1259                        ((cdbus->len > sizeof(struct ctdluser)) ?
1260                         sizeof(struct ctdluser) : cdbus->len));
1261                 cdb_free(cdbus);
1262                 if ((usbuf.flags & US_NEEDVALID)
1263                     && (usbuf.axlevel > 0)) {
1264                         cprintf("%d %s\n", MORE_DATA, usbuf.fullname);
1265                         cdb_close_cursor(CDB_USERS);
1266                         return;
1267                 }
1268         }
1269
1270         /* If we get to this point, there are no more unvalidated users.
1271          * Therefore we clear the "users need validation" flag.
1272          */
1273
1274         begin_critical_section(S_CONTROL);
1275         get_control();
1276         CitControl.MMflags = CitControl.MMflags & (~MM_VALID);
1277         put_control();
1278         end_critical_section(S_CONTROL);
1279         cprintf("%d *** End of registration.\n", CIT_OK);
1280
1281
1282 }
1283
1284
1285 /*
1286  * validate a user
1287  */
1288 void cmd_vali(char *v_args)
1289 {
1290         char user[SIZ];
1291         int newax;
1292         struct ctdluser userbuf;
1293
1294         extract(user, v_args, 0);
1295         newax = extract_int(v_args, 1);
1296
1297         if (CtdlAccessCheck(ac_aide)) {
1298                 return;
1299         }
1300
1301         if (lgetuser(&userbuf, user) != 0) {
1302                 cprintf("%d '%s' not found.\n", ERROR + NO_SUCH_USER, user);
1303                 return;
1304         }
1305
1306         userbuf.axlevel = newax;
1307         userbuf.flags = (userbuf.flags & ~US_NEEDVALID);
1308
1309         lputuser(&userbuf);
1310
1311         /* If the access level was set to zero, delete the user */
1312         if (newax == 0) {
1313                 if (purge_user(user) == 0) {
1314                         cprintf("%d %s Deleted.\n", CIT_OK, userbuf.fullname);
1315                         return;
1316                 }
1317         }
1318         cprintf("%d User '%s' validated.\n", CIT_OK, userbuf.fullname);
1319 }
1320
1321
1322
1323 /* 
1324  *  Traverse the user file...
1325  */
1326 void ForEachUser(void (*CallBack) (struct ctdluser * EachUser, void *out_data),
1327                  void *in_data)
1328 {
1329         struct ctdluser usbuf;
1330         struct cdbdata *cdbus;
1331
1332         cdb_rewind(CDB_USERS);
1333
1334         while (cdbus = cdb_next_item(CDB_USERS), cdbus != NULL) {
1335                 memset(&usbuf, 0, sizeof(struct ctdluser));
1336                 memcpy(&usbuf, cdbus->ptr,
1337                        ((cdbus->len > sizeof(struct ctdluser)) ?
1338                         sizeof(struct ctdluser) : cdbus->len));
1339                 cdb_free(cdbus);
1340                 (*CallBack) (&usbuf, in_data);
1341         }
1342 }
1343
1344
1345 /*
1346  * List one user (this works with cmd_list)
1347  */
1348 void ListThisUser(struct ctdluser *usbuf, void *data)
1349 {
1350         if (usbuf->axlevel > 0) {
1351                 if ((CC->user.axlevel >= 6)
1352                     || ((usbuf->flags & US_UNLISTED) == 0)
1353                     || ((CC->internal_pgm))) {
1354                         cprintf("%s|%d|%ld|%ld|%ld|%ld|",
1355                                 usbuf->fullname,
1356                                 usbuf->axlevel,
1357                                 usbuf->usernum,
1358                                 (long)usbuf->lastcall,
1359                                 usbuf->timescalled,
1360                                 usbuf->posted);
1361                         if (CC->user.axlevel >= 6)
1362                                 cprintf("%s", usbuf->password);
1363                         cprintf("\n");
1364                 }
1365         }
1366 }
1367
1368 /* 
1369  *  List users
1370  */
1371 void cmd_list(void)
1372 {
1373         cprintf("%d \n", LISTING_FOLLOWS);
1374         ForEachUser(ListThisUser, NULL);
1375         cprintf("000\n");
1376 }
1377
1378
1379
1380
1381 /*
1382  * assorted info we need to check at login
1383  */
1384 void cmd_chek(void)
1385 {
1386         int mail = 0;
1387         int regis = 0;
1388         int vali = 0;
1389
1390         if (CtdlAccessCheck(ac_logged_in)) {
1391                 return;
1392         }
1393
1394         getuser(&CC->user, CC->curr_user);      /* no lock is needed here */
1395         if ((REGISCALL != 0) && ((CC->user.flags & US_REGIS) == 0))
1396                 regis = 1;
1397
1398         if (CC->user.axlevel >= 6) {
1399                 get_control();
1400                 if (CitControl.MMflags & MM_VALID)
1401                         vali = 1;
1402         }
1403
1404         /* check for mail */
1405         mail = InitialMailCheck();
1406
1407         cprintf("%d %d|%d|%d|%s|\n", CIT_OK, mail, regis, vali, CC->cs_inet_email);
1408 }
1409
1410
1411 /*
1412  * check to see if a user exists
1413  */
1414 void cmd_qusr(char *who)
1415 {
1416         struct ctdluser usbuf;
1417
1418         if (getuser(&usbuf, who) == 0) {
1419                 cprintf("%d %s\n", CIT_OK, usbuf.fullname);
1420         } else {
1421                 cprintf("%d No such user.\n", ERROR + NO_SUCH_USER);
1422         }
1423 }
1424
1425
1426 /*
1427  * Administrative Get User Parameters
1428  */
1429 void cmd_agup(char *cmdbuf)
1430 {
1431         struct ctdluser usbuf;
1432         char requested_user[SIZ];
1433
1434         if (CtdlAccessCheck(ac_aide)) {
1435                 return;
1436         }
1437
1438         extract(requested_user, cmdbuf, 0);
1439         if (getuser(&usbuf, requested_user) != 0) {
1440                 cprintf("%d No such user.\n", ERROR + NO_SUCH_USER);
1441                 return;
1442         }
1443         cprintf("%d %s|%s|%u|%ld|%ld|%d|%ld|%ld|%d\n",
1444                 CIT_OK,
1445                 usbuf.fullname,
1446                 usbuf.password,
1447                 usbuf.flags,
1448                 usbuf.timescalled,
1449                 usbuf.posted,
1450                 (int) usbuf.axlevel,
1451                 usbuf.usernum,
1452                 (long)usbuf.lastcall,
1453                 usbuf.USuserpurge);
1454 }
1455
1456
1457
1458 /*
1459  * Administrative Set User Parameters
1460  */
1461 void cmd_asup(char *cmdbuf)
1462 {
1463         struct ctdluser usbuf;
1464         char requested_user[SIZ];
1465         char notify[SIZ];
1466         int np;
1467         int newax;
1468         int deleted = 0;
1469
1470         if (CtdlAccessCheck(ac_aide))
1471                 return;
1472
1473         extract(requested_user, cmdbuf, 0);
1474         if (lgetuser(&usbuf, requested_user) != 0) {
1475                 cprintf("%d No such user.\n", ERROR + NO_SUCH_USER);
1476                 return;
1477         }
1478         np = num_parms(cmdbuf);
1479         if (np > 1)
1480                 extract(usbuf.password, cmdbuf, 1);
1481         if (np > 2)
1482                 usbuf.flags = extract_int(cmdbuf, 2);
1483         if (np > 3)
1484                 usbuf.timescalled = extract_int(cmdbuf, 3);
1485         if (np > 4)
1486                 usbuf.posted = extract_int(cmdbuf, 4);
1487         if (np > 5) {
1488                 newax = extract_int(cmdbuf, 5);
1489                 if ((newax >= 0) && (newax <= 6)) {
1490                         usbuf.axlevel = extract_int(cmdbuf, 5);
1491                 }
1492         }
1493         if (np > 7) {
1494                 usbuf.lastcall = extract_long(cmdbuf, 7);
1495         }
1496         if (np > 8) {
1497                 usbuf.USuserpurge = extract_int(cmdbuf, 8);
1498         }
1499         lputuser(&usbuf);
1500         if (usbuf.axlevel == 0) {
1501                 if (purge_user(requested_user) == 0) {
1502                         deleted = 1;
1503                 }
1504         }
1505
1506         if (deleted) {
1507                 sprintf(notify, "User <%s> deleted by %s\n",
1508                         usbuf.fullname, CC->user.fullname);
1509                 aide_message(notify);
1510         }
1511
1512         cprintf("%d Ok", CIT_OK);
1513         if (deleted)
1514                 cprintf(" (%s deleted)", requested_user);
1515         cprintf("\n");
1516 }
1517
1518
1519
1520 /*
1521  * Check to see if the user who we just sent mail to is logged in.  If yes,
1522  * bump the 'new mail' counter for their session.  That enables them to
1523  * receive a new mail notification without having to hit the database.
1524  */
1525 void BumpNewMailCounter(long which_user) {
1526         struct CitContext *ptr;
1527
1528         begin_critical_section(S_SESSION_TABLE);
1529
1530         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1531                 if (ptr->user.usernum == which_user) {
1532                         ptr->newmail += 1;
1533                 }
1534         }
1535
1536         end_critical_section(S_SESSION_TABLE);
1537 }
1538
1539
1540 /*
1541  * Count the number of new mail messages the user has
1542  */
1543 int NewMailCount()
1544 {
1545         int num_newmsgs = 0;
1546
1547         num_newmsgs = CC->newmail;
1548         CC->newmail = 0;
1549
1550         return (num_newmsgs);
1551 }
1552
1553
1554 /*
1555  * Count the number of new mail messages the user has
1556  */
1557 int InitialMailCheck()
1558 {
1559         int num_newmsgs = 0;
1560         int a;
1561         char mailboxname[ROOMNAMELEN];
1562         struct ctdlroom mailbox;
1563         struct visit vbuf;
1564         struct cdbdata *cdbfr;
1565         long *msglist = NULL;
1566         int num_msgs = 0;
1567
1568         MailboxName(mailboxname, sizeof mailboxname, &CC->user, MAILROOM);
1569         if (getroom(&mailbox, mailboxname) != 0)
1570                 return (0);
1571         CtdlGetRelationship(&vbuf, &CC->user, &mailbox);
1572
1573         cdbfr = cdb_fetch(CDB_MSGLISTS, &mailbox.QRnumber, sizeof(long));
1574
1575         if (cdbfr != NULL) {
1576                 msglist = mallok(cdbfr->len);
1577                 memcpy(msglist, cdbfr->ptr, cdbfr->len);
1578                 num_msgs = cdbfr->len / sizeof(long);
1579                 cdb_free(cdbfr);
1580         }
1581         if (num_msgs > 0)
1582                 for (a = 0; a < num_msgs; ++a) {
1583                         if (msglist[a] > 0L) {
1584                                 if (msglist[a] > vbuf.v_lastseen) {
1585                                         ++num_newmsgs;
1586                                 }
1587                         }
1588                 }
1589         if (msglist != NULL)
1590                 phree(msglist);
1591
1592         return (num_newmsgs);
1593 }
1594
1595
1596
1597 /*
1598  * Set the preferred view for the current user/room combination
1599  */
1600 void cmd_view(char *cmdbuf) {
1601         int requested_view;
1602         struct visit vbuf;
1603
1604         if (CtdlAccessCheck(ac_logged_in)) {
1605                 return;
1606         }
1607
1608         requested_view = extract_int(cmdbuf, 0);
1609
1610         CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
1611         vbuf.v_view = requested_view;
1612         CtdlSetRelationship(&vbuf, &CC->user, &CC->room);
1613         
1614         cprintf("%d ok\n", CIT_OK);
1615 }