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