Corrected Matt's name in the credits
[citadel.git] / citadel / citadel.c
1 /*
2  * $Id$
3  *
4  * Main source module for the client program.
5  */
6
7 #include "sysdep.h"
8 #include <stdlib.h>
9 #include <unistd.h>
10 #include <fcntl.h>
11 #include <stdio.h>
12 #include <ctype.h>
13 #include <string.h>
14
15 #if TIME_WITH_SYS_TIME
16 # include <sys/time.h>
17 # include <time.h>
18 #else
19 # if HAVE_SYS_TIME_H
20 #  include <sys/time.h>
21 # else
22 #  include <time.h>
23 # endif
24 #endif
25
26 #include <limits.h>
27 #include <sys/types.h>
28 #include <sys/wait.h>
29 #include <sys/stat.h>
30 #include <sys/ioctl.h>
31 #include <signal.h>
32 #include <pwd.h>
33 #include <stdarg.h>
34 #include <errno.h>
35
36 #include "citadel.h"
37 #include "citadel_ipc.h"
38 #include "axdefs.h"
39 #include "routines.h"
40 #include "routines2.h"
41 #include "rooms.h"
42 #include "messages.h"
43 #include "commands.h"
44 #include "client_chat.h"
45 #include "client_passwords.h"
46 #include "citadel_decls.h"
47 #include "tools.h"
48 #include "acconfig.h"
49 #ifndef HAVE_SNPRINTF
50 #include "snprintf.h"
51 #endif
52 #include "screen.h"
53 #include "citadel_dirs.h"
54
55 #include "md5.h"
56
57 #define IFEXPERT if (userflags&US_EXPERT)
58 #define IFNEXPERT if ((userflags&US_EXPERT)==0)
59 #define IFAIDE if (axlevel>=6)
60 #define IFNAIDE if (axlevel<6)
61
62 int rordercmp(struct ctdlroomlisting *r1, struct ctdlroomlisting *r2);
63
64 struct march *march = NULL;
65
66 /* globals associated with the client program */
67 char temp[PATH_MAX];            /* Name of general-purpose temp file */
68 char temp2[PATH_MAX];           /* Name of general-purpose temp file */
69 char tempdir[PATH_MAX];         /* Name of general-purpose temp directory */
70 char editor_paths[MAX_EDITORS][SIZ];    /* paths to external editors */
71 char printcmd[SIZ];             /* print command */
72 int editor_pid = (-1);
73 char fullname[USERNAME_SIZE];
74 int screenwidth;
75 int screenheight;
76 unsigned room_flags;
77 char room_name[ROOMNAMELEN];
78 char *uglist[UGLISTLEN]; /* size of the ungoto list */
79 long uglistlsn[UGLISTLEN]; /* current read position for all the ungoto's. Not going to make any friends with this one. */
80 int uglistsize = 0;
81 char is_mail = 0;               /* nonzero when we're in a mail room */
82 char axlevel = 0;               /* access level */
83 char is_room_aide = 0;          /* boolean flag, 1 if room aide */
84 int timescalled;
85 int posted;
86 unsigned userflags;
87 long usernum = 0L;              /* user number */
88 time_t lastcall = 0L;           /* Date/time of previous login */
89 char newnow;
90 long highest_msg_read;          /* used for <A>bandon room cmd */
91 long maxmsgnum;                 /* used for <G>oto */
92 char sigcaught = 0;
93 char have_xterm = 0;            /* are we running on an xterm? */
94 char rc_username[USERNAME_SIZE];
95 char rc_password[32];
96 char hostbuf[SIZ];
97 char portbuf[SIZ];
98 char rc_floor_mode;
99 char floor_mode;
100 char curr_floor = 0;            /* number of current floor */
101 char floorlist[128][SIZ];       /* names of floors */
102 int termn8 = 0;                 /* Set to nonzero to cause a logoff */
103 int secure;                     /* Set to nonzero when wire is encrypted */
104 int can_do_msg4 = 0;            /* Set to nonzero if the server can handle MSG4 commands */
105
106 extern char instant_msgs;       /* instant messages waiting! */
107 extern int rc_ansi_color;       /* ansi color value from citadel.rc */
108 extern int next_lazy_cmd;
109
110 CtdlIPC *ipc_for_signal_handlers;       /* KLUDGE cover your eyes */
111
112 /*
113  * here is our 'clean up gracefully and exit' routine
114  */
115 void ctdl_logoff(char *file, int line, CtdlIPC *ipc, int code)
116 {
117         int lp;
118
119         if (editor_pid > 0) {   /* kill the editor if it's running */
120                 kill(editor_pid, SIGHUP);
121         }
122
123         /* Free the ungoto list */
124         for (lp = 0; lp < uglistsize; lp++) {
125                 free(uglist[lp]);
126         }
127
128 /* Shut down the server connection ... but not if the logoff code is 3,
129  * because that means we're exiting because we already lost the server.
130  */
131         if (code != 3) {
132                 CtdlIPCQuit(ipc);
133         }
134
135 /*
136  * now clean up various things
137  */
138         screen_delete();
139
140         unlink(temp);
141         unlink(temp2);
142         nukedir(tempdir);
143
144         /* Violently kill off any child processes if Citadel is
145          * the login shell. 
146          */
147         if (getppid() == 1) {
148                 kill(0 - getpgrp(), SIGTERM);
149                 sleep(1);
150                 kill(0 - getpgrp(), SIGKILL);
151         }
152         color(ORIGINAL_PAIR);   /* Restore the old color settings */
153         stty_ctdl(SB_RESTORE);  /* return the old terminal settings */
154         /* 
155          * uncomment the following if you need to know why Citadel exited
156         printf("*** Exit code %d at %s:%d\n", code, file, line);
157         sleep(2);
158          */
159         exit(code);             /* exit with the proper exit code */
160 }
161
162
163
164 /*
165  * signal catching function for hangups...
166  */
167 void dropcarr(int signum)
168 {
169         logoff(NULL, 3);        /* No IPC when server's already gone! */
170 }
171
172
173
174 /*
175  * catch SIGCONT to reset terminal modes when were are put back into the
176  * foreground.
177  */
178 void catch_sigcont(int signum)
179 {
180         stty_ctdl(SB_LAST);
181         signal(SIGCONT, catch_sigcont);
182 }
183
184
185 /* general purpose routines */
186
187 /* display a file */
188 void formout(CtdlIPC *ipc, char *name)
189 {
190         int r;                  /* IPC return code */
191         char buf[SIZ];
192         char *text = NULL;
193
194         r = CtdlIPCSystemMessage(ipc, name, &text, buf);
195         if (r / 100 != 1) {
196                 scr_printf("%s\n", buf);
197                 return;
198         }
199         if (text) {
200                 fmout(screenwidth, NULL, text, NULL,
201                       ((userflags & US_PAGINATOR) ? 1 : 0),
202                       screenheight, 1, 1);
203                 free(text);
204         }
205 }
206
207
208 void userlist(CtdlIPC *ipc, char *patn)
209 {
210         char buf[SIZ];
211         char fl[SIZ];
212         struct tm tmbuf;
213         time_t lc;
214         int r;                          /* IPC response code */
215         char *listing = NULL;
216
217         r = CtdlIPCUserListing(ipc, patn, &listing, buf);
218         if (r / 100 != 1) {
219                 pprintf("%s\n", buf);
220                 return;
221         }
222
223         pprintf("       User Name           Num  L  LastCall  Calls Posts\n");
224         pprintf("------------------------- ----- - ---------- ----- -----\n");
225         if (listing != NULL) while (strlen(listing) > 0) {
226                 extract_token(buf, listing, 0, '\n', sizeof buf);
227                 remove_token(listing, 0, '\n');
228
229                 if (sigcaught == 0) {
230                     extract_token(fl, buf, 0, '|', sizeof fl);
231                     if (pattern(fl, patn) >= 0) {
232                         pprintf("%-25s ", fl);
233                         pprintf("%5ld %d ", extract_long(buf, 2),
234                                extract_int(buf, 1));
235                         lc = extract_long(buf, 3);
236                         localtime_r(&lc, &tmbuf);
237                         pprintf("%02d/%02d/%04d ",
238                                (tmbuf.tm_mon + 1),
239                                tmbuf.tm_mday,
240                                (tmbuf.tm_year + 1900));
241                         pprintf("%5ld %5ld\n", extract_long(buf, 4), extract_long(buf, 5));
242                     }
243
244                 }
245         }
246         free(listing);
247         pprintf("\n");
248 }
249
250
251 /*
252  * grab assorted info about the user...
253  */
254 void load_user_info(char *params)
255 {
256         extract_token(fullname, params, 0, '|', sizeof fullname);
257         axlevel = extract_int(params, 1);
258         timescalled = extract_int(params, 2);
259         posted = extract_int(params, 3);
260         userflags = extract_int(params, 4);
261         usernum = extract_long(params, 5);
262         lastcall = extract_long(params, 6);
263 }
264
265
266 /*
267  * Remove a room from the march list.  'floornum' is ignored unless
268  * 'roomname' is set to _FLOOR_, in which case all rooms on the requested
269  * floor will be removed from the march list.
270  */
271 void remove_march(char *roomname, int floornum)
272 {
273         struct march *mptr, *mptr2;
274
275         if (march == NULL)
276                 return;
277
278         if ((!strcasecmp(march->march_name, roomname))
279             || ((!strcasecmp(roomname, "_FLOOR_")) && (march->march_floor == floornum))) {
280                 mptr = march->next;
281                 free(march);
282                 march = mptr;
283                 return;
284         }
285         mptr2 = march;
286         for (mptr = march; mptr != NULL; mptr = mptr->next) {
287
288                 if ((!strcasecmp(mptr->march_name, roomname))
289                     || ((!strcasecmp(roomname, "_FLOOR_"))
290                         && (mptr->march_floor == floornum))) {
291
292                         mptr2->next = mptr->next;
293                         free(mptr);
294                         mptr = mptr2;
295                 } else {
296                         mptr2 = mptr;
297                 }
298         }
299 }
300
301
302 /*
303  * Locate the room on the march list which we most want to go to.  Each room
304  * is measured given a "weight" of preference based on various factors.
305  */
306 char *pop_march(int desired_floor, struct march *_march)
307 {
308         static char TheRoom[ROOMNAMELEN];
309         int TheFloor = 0;
310         int TheOrder = 32767;
311         int TheWeight = 0;
312         int weight;
313         struct march *mptr = NULL;
314
315         strcpy(TheRoom, "_BASEROOM_");
316         if (_march == NULL)
317                 return (TheRoom);
318
319         for (mptr = _march; mptr != NULL; mptr = mptr->next) {
320                 weight = 0;
321                 if ((strcasecmp(mptr->march_name, "_BASEROOM_")))
322                         weight = weight + 10000;
323                 if (mptr->march_floor == desired_floor)
324                         weight = weight + 5000;
325
326                 weight = weight + ((128 - (mptr->march_floor)) * 128);
327                 weight = weight + (128 - (mptr->march_order));
328
329                 if (weight > TheWeight) {
330                         TheWeight = weight;
331                         strcpy(TheRoom, mptr->march_name);
332                         TheFloor = mptr->march_floor;
333                         TheOrder = mptr->march_order;
334                 }
335         }
336         return (TheRoom);
337 }
338
339
340 /*
341  * jump directly to a room
342  */
343 void dotgoto(CtdlIPC *ipc, char *towhere, int display_name, int fromungoto)
344 {
345         char aaa[SIZ], bbb[SIZ];
346         static long ls = 0L;
347         int newmailcount = 0;
348         int partial_match, best_match;
349         char from_floor;
350         int ugpos = uglistsize;
351         int r;                          /* IPC result code */
352         struct ctdlipcroom *room = NULL;
353
354         /* store ungoto information */
355         if (fromungoto == 0) {
356                 /* sloppy slide them all down, hey it's the client, who cares. :-) */
357                 if (uglistsize >= (UGLISTLEN-1)) {
358                         int lp;
359                         free (uglist[0]);
360                         for (lp = 0; lp < (UGLISTLEN-1); lp++) {
361                                 uglist[lp] = uglist[lp+1];
362                                 uglistlsn[lp] = uglistlsn[lp+1];
363                         }
364                         ugpos--;
365                 } else {
366                         uglistsize++;
367                 }
368         
369                 uglist[ugpos] = malloc(strlen(room_name)+1);
370                 strcpy(uglist[ugpos], room_name);
371                 uglistlsn[ugpos] = ls;
372         }
373       
374         /* first try an exact match */
375         r = CtdlIPCGotoRoom(ipc, towhere, "", &room, aaa);
376         if (r / 10 == 54) {
377                 newprompt("Enter room password: ", bbb, 9);
378                 r = CtdlIPCGotoRoom(ipc, towhere, bbb, &room, aaa);
379                 if (r / 10 == 54) {
380                         scr_printf("Wrong password.\n");
381                         return;
382                 }
383         }       
384
385         /*
386          * If a match is not found, try a partial match.
387          * Partial matches anywhere in the string carry a weight of 1,
388          * left-aligned matches carry a weight of 2.  Pick the room that
389          * has the highest-weighted match.  Do not match on forgotten
390          * rooms.
391          */
392         if (r / 100 != 2) {
393                 struct march *march = NULL;
394
395                 best_match = 0;
396                 strcpy(bbb, "");
397
398                 r = CtdlIPCKnownRooms(ipc, SubscribedRooms, AllFloors, &march, aaa);
399                 if (r / 100 == 1) {
400                         /* Run the roomlist; free the data as we go */
401                         struct march *mp = march;       /* Current */
402
403                         while (mp) {
404                                 partial_match = 0;
405                                 if (pattern(mp->march_name, towhere) >= 0) {
406                                         partial_match = 1;
407                                 }
408                                 if (!strncasecmp(mp->march_name, towhere, strlen(towhere))) {
409                                         partial_match = 2;
410                                 }
411                                 if (partial_match > best_match) {
412                                         strcpy(bbb, mp->march_name);
413                                         best_match = partial_match;
414                                 }
415                                 /* Both pointers are NULL at end of list */
416                                 march = mp->next;
417                                 free(mp);
418                                 mp = march;
419                         }
420                 }
421
422                 if (strlen(bbb) == 0) {
423                         scr_printf("No room '%s'.\n", towhere);
424                         return;
425                 }
426                 room = NULL;
427                 r = CtdlIPCGotoRoom(ipc, bbb, "", &room, aaa);
428         }
429         if (r / 100 != 1 && r / 100 != 2) {
430                 scr_printf("%s\n", aaa);
431                 return;
432         }
433         safestrncpy(room_name, room->RRname, ROOMNAMELEN);
434         room_flags = room->RRflags;
435         from_floor = curr_floor;
436         curr_floor = room->RRfloor;
437
438         remove_march(room_name, 0);
439         if (!strcasecmp(towhere, "_BASEROOM_"))
440                 remove_march(towhere, 0);
441         if (!room->RRunread)
442                 next_lazy_cmd = 5;      /* Don't read new if no new msgs */
443         if ((from_floor != curr_floor) && (display_name > 0) && (floor_mode == 1)) {
444                 if (floorlist[(int) curr_floor][0] == 0)
445                         load_floorlist(ipc);
446                 scr_printf("(Entering floor: %s)\n", &floorlist[(int) curr_floor][0]);
447         }
448         if (display_name == 1) {
449                 color(BRIGHT_WHITE);
450                 scr_printf("%s ", room_name);
451                 color(DIM_WHITE);
452                 scr_printf("- ");
453         }
454         if (display_name != 2) {
455                 color(BRIGHT_YELLOW);
456                 scr_printf("%d ", room->RRunread);
457                 color(DIM_WHITE);
458                 scr_printf("new of ");
459                 color(BRIGHT_YELLOW);
460                 scr_printf("%d ", room->RRtotal);
461                 color(DIM_WHITE);
462                 scr_printf("messages.\n");
463         }
464         highest_msg_read = room->RRlastread;
465         maxmsgnum = room->RRhighest;
466         is_mail = room->RRismailbox;
467         is_room_aide = room->RRaide;
468         ls = room->RRlastread;
469
470         /* read info file if necessary */
471         if (room->RRinfoupdated > 0)
472                 readinfo(ipc);
473
474         /* check for newly arrived mail if we can */
475         newmailcount = room->RRnewmail;
476         if (newmailcount > 0) {
477                 color(BRIGHT_RED);
478                 if (newmailcount == 1) {
479                         scr_printf("*** A new mail message has arrived.\n");
480                 }
481                 else {
482                         scr_printf("*** %d new mail messages have arrived.\n",
483                                         newmailcount);
484                 }
485                 color(DIM_WHITE);
486                 if (strlen(rc_gotmail_cmd) > 0) {
487                         system(rc_gotmail_cmd);
488                 }
489         }
490         status_line(ipc->ServInfo.humannode, ipc->ServInfo.site_location,
491                         room_name, secure, newmailcount);
492 }
493
494 /* Goto next room having unread messages.
495  * We want to skip over rooms that the user has already been to, and take the
496  * user back to the lobby when done.  The room we end up in is placed in
497  * newroom - which is set to 0 (the lobby) initially.
498  */
499 void gotonext(CtdlIPC *ipc)
500 {
501         char buf[SIZ];
502         struct march *mptr, *mptr2;
503         char next_room[ROOMNAMELEN];
504         int r;                          /* IPC response code */
505
506         /* Check to see if the march-mode list is already allocated.
507          * If it is, pop the first room off the list and go there.
508          */
509         if (march == NULL) {
510                 r = CtdlIPCKnownRooms(ipc, SubscribedRoomsWithNewMessages,
511                                         AllFloors, &march, buf);
512
513 /* add _BASEROOM_ to the end of the march list, so the user will end up
514  * in the system base room (usually the Lobby>) at the end of the loop
515  */
516                 mptr = (struct march *) malloc(sizeof(struct march));
517                 mptr->next = NULL;
518                 strcpy(mptr->march_name, "_BASEROOM_");
519                 if (march == NULL) {
520                         march = mptr;
521                 } else {
522                         mptr2 = march;
523                         while (mptr2->next != NULL)
524                                 mptr2 = mptr2->next;
525                         mptr2->next = mptr;
526                 }
527 /*
528  * ...and remove the room we're currently in, so a <G>oto doesn't make us
529  * walk around in circles
530  */
531                 remove_march(room_name, 0);
532         }
533         if (march != NULL) {
534                 strcpy(next_room, pop_march(curr_floor, march));
535         } else {
536                 strcpy(next_room, "_BASEROOM_");
537         }
538         remove_march(next_room, 0);
539         dotgoto(ipc, next_room, 1, 0);
540 }
541
542 /*
543  * forget all rooms on a given floor
544  */
545 void forget_all_rooms_on(CtdlIPC *ipc, int ffloor)
546 {
547         char buf[SIZ];
548         struct march *flist = NULL;
549         struct march *fptr = NULL;
550         struct ctdlipcroom *room = NULL;
551         int r;                          /* IPC response code */
552
553         scr_printf("Forgetting all rooms on %s...\n", &floorlist[ffloor][0]);
554         scr_flush();
555         remove_march("_FLOOR_", ffloor);
556         r = CtdlIPCKnownRooms(ipc, AllAccessibleRooms, ffloor, &flist, buf);
557         if (r / 100 != 1) {
558                 scr_printf("Error %d: %s\n", r, buf);
559                 return;
560         }
561         while (flist) {
562                 r = CtdlIPCGotoRoom(ipc, flist->march_name, "", &room, buf);
563                 if (r / 100 == 2) {
564                         r = CtdlIPCForgetRoom(ipc, buf);
565                         if (r / 100 != 2) {
566                                 scr_printf("Error %d: %s\n", r, buf);
567                         }
568
569                 }
570                 fptr = flist;
571                 flist = flist->next;
572                 free(fptr);
573         }
574 }
575
576
577 /*
578  * routine called by gotofloor() to move to a new room on a new floor
579  */
580 void gf_toroom(CtdlIPC *ipc, char *towhere, int mode)
581 {
582         int floor_being_left;
583
584         floor_being_left = curr_floor;
585
586         if (mode == GF_GOTO) {          /* <;G>oto mode */
587                 updatels(ipc);
588                 dotgoto(ipc, towhere, 1, 0);
589         }
590         else if (mode == GF_SKIP) {     /* <;S>kip mode */
591                 dotgoto(ipc, towhere, 1, 0);
592                 remove_march("_FLOOR_", floor_being_left);
593         }
594         else if (mode == GF_ZAP) {      /* <;Z>ap mode */
595                 dotgoto(ipc, towhere, 1, 0);
596                 remove_march("_FLOOR_", floor_being_left);
597                 forget_all_rooms_on(ipc, floor_being_left);
598         }
599 }
600
601
602 /*
603  * go to a new floor
604  */
605 void gotofloor(CtdlIPC *ipc, char *towhere, int mode)
606 {
607         int a, tofloor;
608         int r;          /* IPC response code */
609         struct march *mptr;
610         char buf[SIZ], targ[SIZ];
611
612         if (floorlist[0][0] == 0)
613                 load_floorlist(ipc);
614         tofloor = (-1);
615         for (a = 0; a < 128; ++a)
616                 if (!strcasecmp(&floorlist[a][0], towhere))
617                         tofloor = a;
618
619         if (tofloor < 0) {
620                 for (a = 0; a < 128; ++a) {
621                         if (!strncasecmp(&floorlist[a][0], towhere, strlen(towhere))) {
622                                 tofloor = a;
623                         }
624                 }
625         }
626         if (tofloor < 0) {
627                 for (a = 0; a < 128; ++a)
628                         if (pattern(towhere, &floorlist[a][0]) > 0)
629                                 tofloor = a;
630         }
631         if (tofloor < 0) {
632                 scr_printf("No floor '%s'.\n", towhere);
633                 return;
634         }
635         for (mptr = march; mptr != NULL; mptr = mptr->next) {
636                 if ((mptr->march_floor) == tofloor) {
637                         gf_toroom(ipc, mptr->march_name, mode);
638                         return;
639                 }
640         }
641
642         /* Find first known room on the floor */
643
644         strcpy(targ, "");
645         mptr = NULL;
646         r = CtdlIPCKnownRooms(ipc, SubscribedRooms, tofloor, &mptr, buf);
647         if (r / 100 == 1) {
648                 struct march *tmp = mptr;
649
650                 /*. . . according to room order */
651                 if (mptr)
652             strcpy(targ, pop_march(tofloor, mptr));
653                 while (mptr) {
654                         tmp = mptr->next;
655                         free(mptr);
656                         mptr = tmp;
657                 }
658         }
659         if (strlen(targ) > 0) {
660                 gf_toroom(ipc, targ, mode);
661                 return;
662         }
663
664         /* No known rooms on the floor; unzap the first one then */
665
666         strcpy(targ, "");
667         mptr = NULL;
668         r = CtdlIPCKnownRooms(ipc, AllAccessibleRooms, tofloor, &mptr, buf);
669         if (r / 100 == 1) {
670                 struct march *tmp = mptr;
671                 
672         /*. . . according to room order */
673                 if (mptr)
674                         strcpy(targ, pop_march(tofloor, mptr));
675                 while (mptr) {
676                         tmp = mptr->next;
677                         free(mptr);
678                         mptr = tmp;
679                 }
680         }
681         if (strlen(targ) > 0) {
682                 gf_toroom(ipc, targ, mode);
683         } else {
684                 scr_printf("There are no rooms on '%s'.\n", &floorlist[tofloor][0]);
685         }
686 }
687
688 /*
689  * Indexing mechanism for a room list, called by gotoroomstep()
690  */
691 void room_tree_list_query(struct ctdlroomlisting *rp, char *findrmname, int findrmslot, char *rmname, int *rmslot, int *rmtotal)
692 {
693         char roomname[ROOMNAMELEN];
694         static int cur_rmslot = 0;
695
696         if (rp == NULL) {
697                 cur_rmslot = 0;
698                 return;
699         }
700
701         if (rp->lnext != NULL) {
702                 room_tree_list_query(rp->lnext, findrmname, findrmslot, rmname, rmslot, rmtotal);
703         }
704
705         if (sigcaught == 0) {
706                 strcpy(roomname, rp->rlname);
707
708                 if (rmname != NULL) {
709                         if (cur_rmslot == findrmslot) {
710                                 strcpy(rmname, roomname);
711                         }
712                 }
713                 if (rmslot != NULL) {
714                         if (!strcmp(roomname, findrmname)) {
715                                 *rmslot = cur_rmslot;
716                         }
717                 }
718                 cur_rmslot++;
719         }
720
721         if (rp->rnext != NULL) {
722                 room_tree_list_query(rp->rnext, findrmname, findrmslot, rmname, rmslot, rmtotal);
723         }
724
725         if ((rmname == NULL) && (rmslot == NULL))
726                 free(rp);
727
728         if (rmtotal != NULL) {
729                 *rmtotal = cur_rmslot;
730         }
731 }
732
733 /*
734  * step through rooms on current floor
735  */
736 void  gotoroomstep(CtdlIPC *ipc, int direction)
737 {
738         struct march *listing = NULL;
739         struct march *mptr;
740         int r;          /* IPC response code */
741         char buf[SIZ];
742         struct ctdlroomlisting *rl = NULL;
743         struct ctdlroomlisting *rp;
744         struct ctdlroomlisting *rs;
745         int list_it;
746         char rmname[ROOMNAMELEN];
747         int rmslot;
748         int rmtotal;
749
750         /* Ask the server for a room list */
751         r = CtdlIPCKnownRooms(ipc, SubscribedRooms, (-1), &listing, buf);
752         if (r / 100 != 1) {
753                 listing = NULL;
754         }
755
756         load_floorlist(ipc);
757
758         for (mptr = listing; mptr != NULL; mptr = mptr->next) {
759                 list_it = 1;
760
761                 if ( floor_mode 
762                          && (mptr->march_floor != curr_floor))
763                         list_it = 0;
764
765                 if (list_it) {
766                         rp = malloc(sizeof(struct ctdlroomlisting));
767                         strncpy(rp->rlname, mptr->march_name, ROOMNAMELEN);
768                         rp->rlflags = mptr->march_flags;
769                         rp->rlfloor = mptr->march_floor;
770                         rp->rlorder = mptr->march_order;
771                         rp->lnext = NULL;
772                         rp->rnext = NULL;
773
774                         rs = rl;
775                         if (rl == NULL) {
776                                 rl = rp;
777                         } else {
778                                 while (rp != NULL) {
779                                         if (rordercmp(rp, rs) < 0) {
780                                                 if (rs->lnext == NULL) {
781                                                         rs->lnext = rp;
782                                                         rp = NULL;
783                                                 } else {
784                                                         rs = rs->lnext;
785                                                 }
786                                         } else {
787                                                 if (rs->rnext == NULL) {
788                                                         rs->rnext = rp;
789                                                         rp = NULL;
790                                                 } else {
791                                                         rs = rs->rnext;
792                                                 }
793                                         }
794                                 }
795                         }
796                 }
797         }
798
799         /* Find position of current room */
800         room_tree_list_query(NULL, NULL, 0, NULL, NULL, NULL);
801         room_tree_list_query(rl,  room_name, 0, NULL, &rmslot, &rmtotal);
802
803         if (direction == 0) { /* Previous room */
804                 /* If we're at the first room, wrap to the last room */
805                 if (rmslot == 0) {
806                         rmslot = rmtotal - 1;
807                 } else {
808                         rmslot--;
809                 }
810         } else {                 /* Next room */
811                 /* If we're at the last room, wrap to the first room */
812                 if (rmslot == rmtotal - 1) {
813                         rmslot = 0; 
814                 } else {
815                         rmslot++;
816                 }
817         }
818
819         /* Get name of next/previous room */
820         room_tree_list_query(NULL, NULL, 0, NULL, NULL, NULL);
821         room_tree_list_query(rl,  NULL, rmslot, rmname, NULL, NULL);
822
823         /* Free the tree */
824         room_tree_list_query(rl, NULL, 0, NULL, NULL, NULL);
825
826         updatels(ipc);
827         dotgoto(ipc, rmname, 1, 0);
828 }
829
830
831 /*
832  * step through floors on system
833  */
834 void  gotofloorstep(CtdlIPC *ipc, int direction)
835 {
836         int  tofloor;
837
838         if (floorlist[0][0] == 0)
839                 load_floorlist(ipc);
840
841         if (direction == 0) { /* Previous floor */
842                 if (curr_floor) tofloor = curr_floor - 1;
843                 else tofloor = 127;
844
845                 while (!floorlist[tofloor][0]) tofloor--;
846         } else {                   /* Next floor */
847                 if (curr_floor < 127) tofloor = curr_floor + 1;
848                 else tofloor = 0;
849
850                 while (!floorlist[tofloor][0] && tofloor < 127) tofloor++;
851                 if (!floorlist[tofloor][0])     tofloor = 0;
852         }
853         /* ;g works when not in floor mode so . . . */
854         if (!floor_mode) {
855                 scr_printf("(%s)\n", floorlist[tofloor] );
856         }
857
858         gotofloor(ipc, floorlist[tofloor], GF_GOTO);
859 }
860
861
862 /*
863  * forget all rooms on current floor
864  */
865 void forget_this_floor(CtdlIPC *ipc)
866 {
867         if (curr_floor == 0) {
868                 scr_printf("Can't forget this floor.\n");
869                 return;
870         }
871         if (floorlist[0][0] == 0) {
872                 load_floorlist(ipc);
873         }
874         scr_printf("Are you sure you want to forget all rooms on %s? ",
875                &floorlist[(int) curr_floor][0]);
876         if (yesno() == 0) {
877                 return;
878         }
879
880         gf_toroom(ipc, "_BASEROOM_", GF_ZAP);
881 }
882
883
884 /* 
885  * Figure out the physical screen dimensions, if we can
886  * WARNING:  this is now called from a signal handler!
887  */
888 void check_screen_dims(void)
889 {
890 #ifdef TIOCGWINSZ
891         struct {
892                 unsigned short height;  /* rows */
893                 unsigned short width;   /* columns */
894                 unsigned short xpixels;
895                 unsigned short ypixels;         /* pixels */
896         } xwinsz;
897
898         if (have_xterm) {       /* dynamically size screen if on an xterm */
899                 if (ioctl(0, TIOCGWINSZ, &xwinsz) == 0) {
900                         if (xwinsz.height)
901                                 screenheight = is_curses_enabled() ? (int)xwinsz.height - 1 : (int) xwinsz.height;
902                         if (xwinsz.width)
903                                 screenwidth = (int) xwinsz.width;
904                 }
905         }
906 #endif
907 }
908
909
910 /*
911  * set floor mode depending on client, server, and user settings
912  */
913 void set_floor_mode(CtdlIPC* ipc)
914 {
915         if (ipc->ServInfo.ok_floors == 0) {
916                 floor_mode = 0; /* Don't use floors if the server */
917         }
918         /* doesn't support them!          */
919         else {
920                 if (rc_floor_mode == RC_NO) {   /* never use floors */
921                         floor_mode = 0;
922                 }
923                 if (rc_floor_mode == RC_YES) {  /* always use floors */
924                         floor_mode = 1;
925                 }
926                 if (rc_floor_mode == RC_DEFAULT) {      /* user choice */
927                         floor_mode = ((userflags & US_FLOORS) ? 1 : 0);
928                 }
929         }
930 }
931
932 /*
933  * Set or change the user's password
934  */
935 int set_password(CtdlIPC *ipc)
936 {
937         char pass1[20];
938         char pass2[20];
939         char buf[SIZ];
940
941         if (strlen(rc_password) > 0) {
942                 strcpy(pass1, rc_password);
943                 strcpy(pass2, rc_password);
944         } else {
945                 IFNEXPERT formout(ipc, "changepw");
946                 newprompt("Enter a new password: ", pass1, -19);
947                 newprompt("Enter it again to confirm: ", pass2, -19);
948         }
949         strproc(pass1);
950         strproc(pass2);
951         if (!strcasecmp(pass1, pass2)) {
952                 CtdlIPCChangePassword(ipc, pass1, buf);
953                 scr_printf("%s\n", buf);
954                 offer_to_remember_password(ipc, hostbuf, portbuf, fullname, pass1);
955                 return (0);
956         } else {
957                 scr_printf("*** They don't match... try again.\n");
958                 return (1);
959         }
960 }
961
962
963
964 /*
965  * get info about the server we've connected to
966  */
967 void get_serv_info(CtdlIPC *ipc, char *supplied_hostname)
968 {
969         char buf[SIZ];
970
971         CtdlIPCServerInfo(ipc, buf);
972
973         /* be nice and identify ourself to the server */
974         CtdlIPCIdentifySoftware(ipc, SERVER_TYPE, 0, REV_LEVEL,
975                  (ipc->isLocal ? "local" : CITADEL),
976                  (supplied_hostname) ? supplied_hostname : 
977                  /* Look up the , in the bible if you're confused */
978                  (locate_host(ipc, buf), buf), buf);
979
980         /*
981          * Tell the server what our preferred content formats are.
982          *
983          * Originally we preferred HTML over plain text because we can format
984          * it to the reader's screen width, but since our HTML-to-text parser
985          * isn't really all that great, it's probably better to just go with
986          * the plain text when we have it available.
987          */
988         if ((CtdlIPCSpecifyPreferredFormats(ipc, buf, "text/plain|text/html") / 100 )== 2) {
989                 can_do_msg4 = 1;
990         }
991 }
992
993
994
995 /*
996  * Record compare function for SortOnlineUsers()
997  */
998 int idlecmp(const void *rec1, const void *rec2) {
999         time_t i1, i2;
1000
1001         i1 = extract_long(rec1, 5);
1002         i2 = extract_long(rec2, 5);
1003
1004         if (i1 < i2) return(1);
1005         if (i1 > i2) return(-1);
1006         return(0);
1007 }
1008
1009
1010 /*
1011  * Sort the list of online users by idle time.
1012  * This function frees the supplied buffer, and returns a new one
1013  * to the caller.  The caller is responsible for freeing the returned buffer.
1014  */
1015 char *SortOnlineUsers(char *listing) {
1016         int rows;
1017         char *sortbuf;
1018         char *retbuf;
1019         char buf[SIZ];
1020         int i;
1021
1022         rows = num_tokens(listing, '\n');
1023         sortbuf = malloc(rows * SIZ);
1024         if (sortbuf == NULL) return(listing);
1025         retbuf = malloc(rows * SIZ);
1026         if (retbuf == NULL) {
1027                 free(sortbuf);
1028                 return(listing);
1029         }
1030
1031         /* Copy the list into a fixed-record-size array for sorting */
1032         for (i=0; i<rows; ++i) {
1033                 memset(buf, 0, SIZ);
1034                 extract_token(buf, listing, i, '\n', sizeof buf);
1035                 memcpy(&sortbuf[i*SIZ], buf, (size_t)SIZ);
1036         }
1037
1038         /* Do the sort */
1039         qsort(sortbuf, rows, SIZ, idlecmp);
1040
1041         /* Copy back to a \n delimited list */
1042         strcpy(retbuf, "");
1043         for (i=0; i<rows; ++i) {
1044                 strcat(retbuf, &sortbuf[i*SIZ]);
1045                 if (i<(rows-1)) strcat(retbuf, "\n");
1046         }
1047         return(retbuf);
1048 }
1049
1050
1051
1052 /*
1053  * Display list of users currently logged on to the server
1054  */
1055 void who_is_online(CtdlIPC *ipc, int longlist)
1056 {
1057         char buf[SIZ], username[SIZ], roomname[SIZ], fromhost[SIZ];
1058         char flags[SIZ];
1059         char actual_user[SIZ], actual_room[SIZ], actual_host[SIZ];
1060         char clientsoft[SIZ];
1061         time_t timenow = 0;
1062         time_t idletime, idlehours, idlemins, idlesecs;
1063         int last_session = (-1);
1064         int skipidle = 0;
1065         char *listing = NULL;
1066         int r;                          /* IPC response code */
1067     
1068         if (longlist == 2) {
1069                 longlist = 0;
1070                 skipidle = 1;
1071         }
1072
1073         if (!longlist) {
1074                 color(BRIGHT_WHITE);
1075                 pprintf("           User Name               Room           Idle        From host\n");
1076                 color(DIM_WHITE);
1077                 pprintf("   ------------------------- -------------------- ---- ------------------------\n");
1078         }
1079         r = CtdlIPCOnlineUsers(ipc, &listing, &timenow, buf);
1080         listing = SortOnlineUsers(listing);
1081         if (r / 100 == 1) {
1082                 while (strlen(listing) > 0) {
1083                         int isidle = 0;
1084                         
1085                         /* Get another line */
1086                         extract_token(buf, listing, 0, '\n', sizeof buf);
1087                         remove_token(listing, 0, '\n');
1088
1089                         extract_token(username, buf, 1, '|', sizeof username);
1090                         extract_token(roomname, buf, 2, '|', sizeof roomname);
1091                         extract_token(fromhost, buf, 3, '|', sizeof fromhost);
1092                         extract_token(clientsoft, buf, 4, '|', sizeof clientsoft);
1093                         extract_token(flags, buf, 7, '|', sizeof flags);
1094
1095                         idletime = timenow - extract_long(buf, 5);
1096                         idlehours = idletime / 3600;
1097                         idlemins = (idletime - (idlehours * 3600)) / 60;
1098                         idlesecs = (idletime - (idlehours * 3600) - (idlemins * 60));
1099
1100                         if (idletime > rc_idle_threshold) {
1101                                 /*
1102                                 while (strlen(roomname) < 20) {
1103                                         strcat(roomname, " ");
1104                                 }
1105                                 strcpy(&roomname[14], "[idle]");
1106                                 */
1107                                 if (skipidle)
1108                                         isidle = 1;
1109                         }
1110
1111                         if (longlist) {
1112                                 extract_token(actual_user, buf, 8, '|', sizeof actual_user);
1113                                 extract_token(actual_room, buf, 9, '|', sizeof actual_room);
1114                                 extract_token(actual_host, buf, 10, '|', sizeof actual_host);
1115
1116                                 pprintf("  Flags: %s\n", flags);
1117                                 pprintf("Session: %d\n", extract_int(buf, 0));
1118                                 pprintf("   Name: %s\n", username);
1119                                 pprintf("In room: %s\n", roomname);
1120                                 pprintf("   Host: %s\n", fromhost);
1121                                 pprintf(" Client: %s\n", clientsoft);
1122                                 pprintf("   Idle: %ld:%02ld:%02ld\n",
1123                                         (long) idlehours,
1124                                         (long) idlemins,
1125                                         (long) idlesecs);
1126
1127                                 if ( (strlen(actual_user)+strlen(actual_room)+strlen(actual_host)) > 0) {
1128                                         pprintf("(really ");
1129                                         if (strlen(actual_user)>0) pprintf("<%s> ", actual_user);
1130                                         if (strlen(actual_room)>0) pprintf("in <%s> ", actual_room);
1131                                         if (strlen(actual_host)>0) pprintf("from <%s> ", actual_host);
1132                                         pprintf(")\n");
1133                                 }
1134                                 pprintf("\n");
1135
1136                         } else {
1137                     if (isidle == 0) {
1138                                 if (extract_int(buf, 0) == last_session) {
1139                                         pprintf("        ");
1140                                 } else {
1141                                         color(BRIGHT_MAGENTA);
1142                                         pprintf("%-3s", flags);
1143                                 }
1144                                 last_session = extract_int(buf, 0);
1145                                 color(BRIGHT_CYAN);
1146                                 pprintf("%-25s ", username);
1147                                 color(BRIGHT_MAGENTA);
1148                                 roomname[20] = 0;
1149                                 pprintf("%-20s ", roomname);
1150                                 if (idletime > rc_idle_threshold) {
1151                                         /* over 1000d, must be gone fishing */
1152                                         if (idlehours > 23999) {
1153                                                 pprintf("fish");
1154                                         /* over 10 days */
1155                                         } else if (idlehours > 239) {
1156                                                 pprintf("%3ldd",
1157                                                         idlehours / 24);
1158                                         /* over 10 hours */
1159                                         } else if (idlehours > 9) {
1160                                                 pprintf("%1ldd%02ld",
1161                                                         idlehours / 24,
1162                                                         idlehours % 24);
1163                                         /* less than 10 hours */
1164                                         } else {
1165                                                 pprintf("%1ld:%02ld",
1166                                                         idlehours, idlemins);
1167                                         }
1168                                 }
1169                                 else {
1170                                         pprintf("    ");
1171                                 }
1172                                 pprintf(" ");
1173                                 color(BRIGHT_CYAN);
1174                                 fromhost[24] = '\0';
1175                                 pprintf("%-24s\n", fromhost);
1176                                 color(DIM_WHITE);
1177                         }
1178                         }
1179                 }
1180         }
1181         free(listing);
1182 }
1183
1184 void enternew(CtdlIPC *ipc, char *desc, char *buf, int maxlen)
1185 {
1186         char bbb[128];
1187         snprintf(bbb, sizeof bbb, "Enter in your new %s: ", desc);
1188         newprompt(bbb, buf, maxlen);
1189 }
1190
1191
1192
1193 int shift(int argc, char **argv, int start, int count) {
1194         int i;
1195
1196         for (i=start; i<(argc-count); ++i) {
1197                 argv[i] = argv[i+count];
1198         }
1199         argc = argc - count;
1200         return argc;
1201 }
1202
1203 static void statusHook(char *s) {
1204         sln_printf(s);
1205         sln_flush();
1206 }
1207
1208 /*
1209  * main
1210  */
1211 int main(int argc, char **argv)
1212 {
1213         int a, b, mcmd;
1214         char aaa[100], bbb[100];/* general purpose variables */
1215         char argbuf[32];        /* command line buf */
1216         char nonce[NONCE_SIZE];
1217         char *telnet_client_host = NULL;
1218         char *sptr, *sptr2;     /* USed to extract the nonce */
1219         char hexstring[MD5_HEXSTRING_SIZE];
1220         int stored_password = 0;
1221         char password[SIZ];
1222         struct ctdlipcmisc chek;
1223         struct ctdluser *myself = NULL;
1224         CtdlIPC* ipc;                   /* Our server connection */
1225         int r;                          /* IPC result code */
1226
1227         int relh=0;
1228         int home=0;
1229         char relhome[PATH_MAX]="";
1230         char ctdldir[PATH_MAX]=CTDLDIR;
1231
1232
1233
1234         calc_dirs_n_files(relh, home, relhome, ctdldir);
1235         
1236         setIPCDeathHook(screen_delete);
1237         setIPCErrorPrintf(err_printf);
1238         setCryptoStatusHook(statusHook);
1239         
1240         /* Permissions sanity check - don't run citadel setuid/setgid */
1241         if (getuid() != geteuid()) {
1242                 err_printf("Please do not run citadel setuid!\n");
1243                 logoff(NULL, 3);
1244         } else if (getgid() != getegid()) {
1245                 err_printf("Please do not run citadel setgid!\n");
1246                 logoff(NULL, 3);
1247         }
1248
1249         stty_ctdl(SB_SAVE);     /* Store the old terminal parameters */
1250         load_command_set();     /* parse the citadel.rc file */
1251         stty_ctdl(SB_NO_INTR);  /* Install the new ones */
1252         /* signal(SIGHUP, dropcarr);FIXME */    /* Cleanup gracefully if carrier is dropped */
1253         signal(SIGPIPE, dropcarr);      /* Cleanup gracefully if local conn. dropped */
1254         signal(SIGTERM, dropcarr);      /* Cleanup gracefully if terminated */
1255         signal(SIGCONT, catch_sigcont); /* Catch SIGCONT so we can reset terminal */
1256 #ifdef SIGWINCH
1257         signal(SIGWINCH, scr_winch);    /* Window resize signal */
1258 #endif
1259
1260 #ifdef HAVE_OPENSSL
1261         arg_encrypt = RC_DEFAULT;
1262 #endif
1263 #if defined(HAVE_CURSES_H) && !defined(DISABLE_CURSES)
1264         arg_screen = RC_DEFAULT;
1265 #endif
1266
1267         /* 
1268          * Handle command line options as if we were called like /bin/login
1269          * (i.e. from in.telnetd)
1270          */
1271         for (a=0; a<argc; ++a) {
1272                 if ((argc > a+1) && (!strcmp(argv[a], "-h")) ) {
1273                         telnet_client_host = argv[a+1];
1274                         argc = shift(argc, argv, a, 2);
1275                 }
1276                 if (!strcmp(argv[a], "-x")) {
1277 #ifdef HAVE_OPENSSL
1278                         arg_encrypt = RC_NO;
1279 #endif
1280                         argc = shift(argc, argv, a, 1);
1281                 }
1282                 if (!strcmp(argv[a], "-X")) {
1283 #ifdef HAVE_OPENSSL
1284                         arg_encrypt = RC_YES;
1285                         argc = shift(argc, argv, a, 1);
1286 #else
1287                         fprintf(stderr, "Not compiled with encryption support");
1288                         return 1;
1289 #endif
1290                 }
1291                 if (!strcmp(argv[a], "-s")) {
1292 #if defined(HAVE_CURSES_H) && !defined(DISABLE_CURSES)
1293                         arg_screen = RC_NO;
1294 #endif
1295                         argc = shift(argc, argv, a, 1);
1296                 }
1297                 if (!strcmp(argv[a], "-S")) {
1298 #if defined(HAVE_CURSES_H) && !defined(DISABLE_CURSES)
1299                         arg_screen = RC_YES;
1300 #endif
1301                         argc = shift(argc, argv, a, 1);
1302                 }
1303                 if (!strcmp(argv[a], "-p")) {
1304                         struct stat st;
1305                 
1306                         if (chdir(CTDLDIR) < 0) {
1307                                 perror("can't change to " CTDLDIR);
1308                                 logoff(NULL, 3);
1309                         }
1310
1311                         /*
1312                          * Drop privileges if necessary. We stat
1313                          * citadel.config to get the uid/gid since it's
1314                          * guaranteed to have the uid/gid we want.
1315                          */
1316                         if (!getuid() || !getgid()) {
1317                                 if (stat(file_citadel_config, &st) < 0) {
1318                                         perror("couldn't stat citadel.config");
1319                                         logoff(NULL, 3);
1320                                 }
1321                                 if (!getgid() && (setgid(st.st_gid) < 0)) {
1322                                         perror("couldn't change gid");
1323                                         logoff(NULL, 3);
1324                                 }
1325                                 if (!getuid() && (setuid(st.st_uid) < 0)) {
1326                                         perror("couldn't change uid");
1327                                         logoff(NULL, 3);
1328                                 }
1329                                 /*
1330                                   scr_printf("Privileges changed to uid %d gid %d\n",
1331                                   getuid(), getgid());
1332                                 */
1333                         }
1334                         argc = shift(argc, argv, a, 1);
1335                 }
1336         }
1337         
1338
1339         screen_new();
1340
1341 #ifdef __CYGWIN__
1342         newprompt("Connect to (return for local server): ", hostbuf, 64);
1343 #endif
1344
1345         sln_printf("Attaching to server... \r");
1346         sln_flush();
1347         ipc = CtdlIPC_new(argc, argv, hostbuf, portbuf);
1348         if (!ipc) {
1349                 screen_delete();
1350                 error_printf("Can't connect: %s\n", strerror(errno));
1351                 logoff(NULL, 3);
1352         }
1353 #if defined(HAVE_CURSES_H) && !defined(DISABLE_CURSES)
1354         CtdlIPC_SetNetworkStatusCallback(ipc, wait_indicator);
1355 #endif
1356         ipc_for_signal_handlers = ipc;  /* KLUDGE cover your eyes */
1357
1358         CtdlIPC_chat_recv(ipc, aaa);
1359         if (aaa[0] != '2') {
1360                 scr_printf("%s\n", &aaa[4]);
1361                 logoff(ipc, atoi(aaa));
1362         }
1363
1364         /* If there is a [nonce] at the end, put the nonce in <nonce>, else nonce
1365          * is zeroized.
1366          */
1367         
1368         if ((sptr = strchr(aaa, '<')) == NULL)
1369                 {
1370                         nonce[0] = '\0';
1371                 }
1372         else
1373                 {
1374                         if ((sptr2 = strchr(sptr, '>')) == NULL)
1375                                 {
1376                                         nonce[0] = '\0';
1377                                 }
1378                         else
1379                                 {
1380                                         sptr2++;
1381                                         *sptr2 = '\0';
1382                                         strncpy(nonce, sptr, (size_t)NONCE_SIZE);
1383                                 }
1384                 }
1385
1386 #ifdef HAVE_OPENSSL
1387         /* Evaluate encryption preferences */
1388         if (arg_encrypt != RC_NO && rc_encrypt != RC_NO) {
1389                 if (!ipc->isLocal || arg_encrypt == RC_YES || rc_encrypt == RC_YES) {
1390                         secure = (CtdlIPCStartEncryption(ipc, aaa) / 100 == 2) ? 1 : 0;
1391                         if (!secure)
1392                                 error_printf("Can't encrypt: %s\n", aaa);
1393                 }
1394         }
1395 #endif
1396
1397         get_serv_info(ipc, telnet_client_host);
1398         scr_printf("%-24s\n%s\n%s\n", ipc->ServInfo.software, ipc->ServInfo.humannode,
1399                    ipc->ServInfo.site_location);
1400         scr_flush();
1401
1402         status_line(ipc->ServInfo.humannode, ipc->ServInfo.site_location, NULL,
1403                     secure, -1);
1404
1405         screenwidth = 80;       /* default screen dimensions */
1406         screenheight = 24;
1407         
1408         scr_printf(" pause    next    stop\n");
1409         scr_printf(" ctrl-s  ctrl-o  ctrl-c\n\n");
1410         formout(ipc, "hello");  /* print the opening greeting */
1411         scr_printf("\n");
1412
1413  GSTA:  /* See if we have a username and password on disk */
1414         if (rc_remember_passwords) {
1415                 get_stored_password(hostbuf, portbuf, fullname, password);
1416                 if (strlen(fullname) > 0) {
1417                         r = CtdlIPCTryLogin(ipc, fullname, aaa);
1418                         if (r / 100 == 3) {
1419                                 if (*nonce) {
1420                                         r = CtdlIPCTryApopPassword(ipc, make_apop_string(password, nonce, hexstring, sizeof hexstring), aaa);
1421                                 } else {
1422                                         r = CtdlIPCTryPassword(ipc, password, aaa);
1423                                 }
1424                         }
1425
1426                         if (r / 100 == 2) {
1427                                 load_user_info(aaa);
1428                                 stored_password = 1;
1429                                 goto PWOK;
1430                         } else {
1431                                 set_stored_password(hostbuf, portbuf, "", "");
1432                         }
1433                 }
1434         }
1435
1436         termn8 = 0;
1437         newnow = 0;
1438         do {
1439                 if (strlen(rc_username) > 0) {
1440                         strcpy(fullname, rc_username);
1441                 } else {
1442                         newprompt("Enter your name: ", fullname, 29);
1443                 }
1444                 strproc(fullname);
1445                 if (!strcasecmp(fullname, "new")) {     /* just in case */
1446                         scr_printf("Please enter the name you wish to log in with.\n");
1447                 }
1448         } while (
1449                  (!strcasecmp(fullname, "bbs"))
1450                  || (!strcasecmp(fullname, "new"))
1451                  || (strlen(fullname) == 0));
1452
1453         if (!strcasecmp(fullname, "off")) {
1454                 mcmd = 29;
1455                 goto TERMN8;
1456         }
1457         /* sign on to the server */
1458         r = CtdlIPCTryLogin(ipc, fullname, aaa);
1459         if (r / 100 != 3)
1460                 goto NEWUSR;
1461
1462         /* password authentication */
1463         if (strlen(rc_password) > 0) {
1464                 strcpy(password, rc_password);
1465         } else {
1466                 newprompt("\rPlease enter your password: ", password, -19);
1467         }
1468         strproc(password);
1469
1470         if (*nonce) {
1471                 r = CtdlIPCTryApopPassword(ipc, make_apop_string(password, nonce, hexstring, sizeof hexstring), aaa);
1472         } else {
1473                 r = CtdlIPCTryPassword(ipc, password, aaa);
1474         }
1475         
1476         if (r / 100 == 2) {
1477                 load_user_info(aaa);
1478                 offer_to_remember_password(ipc, hostbuf, portbuf,
1479                                            fullname, password);
1480                 goto PWOK;
1481         }
1482         scr_printf("<< wrong password >>\n");
1483         if (strlen(rc_password) > 0)
1484                 logoff(ipc, 2);
1485         goto GSTA;
1486
1487 NEWUSR: if (strlen(rc_password) == 0) {
1488                 scr_printf("'%s' not found.\n", fullname);
1489                 scr_printf("Type 'off' if you would like to exit.\n");
1490                 if (ipc->ServInfo.newuser_disabled == 1) {
1491                         goto GSTA;
1492                 }
1493                 scr_printf("Do you want to create a new user account called '%s'? ",
1494                         fullname);
1495                 if (yesno() == 0) {
1496                         goto GSTA;
1497                 }
1498         }
1499
1500         r = CtdlIPCCreateUser(ipc, fullname, 1, aaa);
1501         if (r / 100 != 2) {
1502                 scr_printf("%s\n", aaa);
1503                 goto GSTA;
1504         }
1505         load_user_info(aaa);
1506
1507         while (set_password(ipc) != 0);
1508         newnow = 1;
1509
1510         enter_config(ipc, 1);
1511
1512  PWOK:
1513         /* Switch color support on or off if we're in user mode */
1514         if (rc_ansi_color == 3) {
1515                 if (userflags & US_COLOR)
1516                         enable_color = 1;
1517                 else
1518                         enable_color = 0;
1519         }
1520
1521         color(BRIGHT_WHITE);
1522         scr_printf("\n%s\nAccess level: %d (%s)\n"
1523                    "User #%ld / Login #%d",
1524                    fullname, axlevel, axdefs[(int) axlevel],
1525                    usernum, timescalled);
1526         if (lastcall > 0L) {
1527                 scr_printf(" / Last login: %s",
1528                            asctime(localtime(&lastcall)));
1529         }
1530         scr_printf("\n");
1531
1532         r = CtdlIPCMiscCheck(ipc, &chek, aaa);
1533         if (r / 100 == 2) {
1534                 b = chek.newmail;
1535                 if (b > 0) {
1536                         color(BRIGHT_RED);
1537                         if (b == 1)
1538                                 scr_printf("*** You have a new private message in Mail>\n");
1539                         if (b > 1)
1540                                 scr_printf("*** You have %d new private messages in Mail>\n", b);
1541                         color(DIM_WHITE);
1542                         if (strlen(rc_gotmail_cmd) > 0) {
1543                                 system(rc_gotmail_cmd);
1544                         }
1545                 }
1546                 if ((axlevel >= 6) && (chek.needvalid > 0)) {
1547                         scr_printf("*** Users need validation\n");
1548                 }
1549                 if (chek.needregis > 0) {
1550                         scr_printf("*** Please register.\n");
1551                         formout(ipc, "register");
1552                         entregis(ipc);
1553                 }
1554         }
1555         /* Make up some temporary filenames for use in various parts of the
1556          * program.  Don't mess with these once they've been set, because we
1557          * will be unlinking them later on in the program and we don't
1558          * want to delete something that we didn't create. */
1559         CtdlMakeTempFileName(temp, sizeof temp);
1560         CtdlMakeTempFileName(temp2, sizeof temp2);
1561         CtdlMakeTempFileName(tempdir, sizeof tempdir);
1562
1563         /* Get screen dimensions.  First we go to a default of 80x24.  Then
1564          * we try to get the user's actual screen dimensions off the server.
1565          * However, if we're running on an xterm, all this stuff is
1566          * irrelevant because we're going to dynamically size the screen
1567          * during the session.
1568          */
1569         screenwidth = 80;
1570         screenheight = 24;
1571         r = CtdlIPCGetConfig(ipc, &myself, aaa);
1572         if (r == 2) {
1573                 screenwidth = myself->USscreenwidth;
1574                 screenheight = myself->USscreenheight;
1575         }
1576         if (getenv("TERM") != NULL)
1577                 if (!strcmp(getenv("TERM"), "xterm")) {
1578                         have_xterm = 1;
1579                 }
1580 #ifdef TIOCGWINSZ
1581         check_screen_dims();
1582 #endif
1583
1584         set_floor_mode(ipc);
1585
1586         /* Enter the lobby */
1587         dotgoto(ipc, "_BASEROOM_", 1, 0);
1588
1589         /* Main loop for the system... user is logged in. */
1590         uglistsize = 0;
1591
1592         if (newnow == 1)
1593                 readmsgs(ipc, LastMessages, ReadForward, 5);
1594         else
1595                 readmsgs(ipc, NewMessages, ReadForward, 0);
1596
1597         /* MAIN COMMAND LOOP */
1598         do {
1599                 mcmd = getcmd(ipc, argbuf);     /* Get keyboard command */
1600
1601 #ifdef TIOCGWINSZ
1602                 check_screen_dims();            /* if xterm, get screen size */
1603 #endif
1604
1605                 if (termn8 == 0)
1606                         switch (mcmd) {
1607                         case 1:
1608                                 formout(ipc, "help");
1609                                 break;
1610                         case 4:
1611                                 entmsg(ipc, 0, ((userflags & US_EXTEDIT) ? 2 : 0));
1612                                 break;
1613                         case 36:
1614                                 entmsg(ipc, 0, 1);
1615                                 break;
1616                         case 46:
1617                                 entmsg(ipc, 0, 2);
1618                                 break;
1619                         case 78:
1620                                 {
1621                                         /* Only m.author is used */
1622                                         struct ctdlipcmessage m;
1623                                         newprompt("What do you want your username to be? ",
1624                                                 m.author, USERNAME_SIZE - 1);
1625                                         m.text = "";
1626                                         r = CtdlIPCPostMessage(ipc, 2, &m, aaa);
1627                                         if (r / 100 != 2)
1628                                                 scr_printf("%s\n", aaa);
1629                                         else
1630                                                 entmsg(ipc, 0, 0);
1631                                 }
1632                                 break;
1633                         case 5:                         /* <G>oto */
1634                                 updatels(ipc);
1635                                 gotonext(ipc);
1636                                 break;
1637                         case 47:                        /* <A>bandon */
1638                                 if (!rc_alt_semantics) {
1639                                         updatelsa(ipc);
1640                                 }
1641                                 gotonext(ipc);
1642                                 break;
1643                         case 90:                        /* <.A>bandon */
1644                                 if (!rc_alt_semantics)
1645                                         updatelsa(ipc);
1646                                 dotgoto(ipc, argbuf, 0, 0);
1647                                 break;
1648                         case 58:                        /* <M>ail */
1649                                 updatelsa(ipc);
1650                                 dotgoto(ipc, "_MAIL_", 1, 0);
1651                                 break;
1652                         case 20:
1653                                 if (strlen(argbuf) > 0) {
1654                                         updatels(ipc);
1655                                         dotgoto(ipc, argbuf, 0, 0);
1656                                 }
1657                                 break;
1658                         case 52:
1659                                 if (strlen(argbuf) > 0) {
1660                                         if (rc_alt_semantics) {
1661                                                 updatelsa(ipc);
1662                                         }
1663                                         dotgoto(ipc, argbuf, 0, 0);
1664                                 }
1665                                 break;
1666                         case 95: /* what exactly is the numbering scheme supposed to be anyway? --Ford, there isn't one. -IO */
1667                                 dotungoto(ipc, argbuf);
1668                                 break;
1669                         case 10:
1670                                 readmsgs(ipc, AllMessages, ReadForward, 0);
1671                                 break;
1672                         case 9:
1673                                 readmsgs(ipc, LastMessages, ReadForward, 5);
1674                                 break;
1675                         case 13:
1676                                 readmsgs(ipc, NewMessages, ReadForward, 0);
1677                                 break;
1678                         case 11:
1679                                 readmsgs(ipc, AllMessages, ReadReverse, 0);
1680                                 break;
1681                         case 12:
1682                                 readmsgs(ipc, OldMessages, ReadReverse, 0);
1683                                 break;
1684                         case 71:
1685                                 readmsgs(ipc, LastMessages, ReadForward,
1686                                                 atoi(argbuf));
1687                                 break;
1688                         case 7:
1689                                 forget(ipc);
1690                                 break;
1691                         case 18:
1692                                 subshell();
1693                                 break;
1694                         case 38:
1695                                 updatels(ipc);
1696                                 entroom(ipc);
1697                                 break;
1698                         case 22:
1699                                 killroom(ipc);
1700                                 break;
1701                         case 32:
1702                                 userlist(ipc, argbuf);
1703                                 break;
1704                         case 27:
1705                                 invite(ipc);
1706                                 break;
1707                         case 28:
1708                                 kickout(ipc);
1709                                 break;
1710                         case 23:
1711                                 editthisroom(ipc);
1712                                 break;
1713                         case 14:
1714                                 roomdir(ipc);
1715                                 break;
1716                         case 33:
1717                                 download(ipc, 0);
1718                                 break;
1719                         case 34:
1720                                 download(ipc, 1);
1721                                 break;
1722                         case 31:
1723                                 download(ipc, 2);
1724                                 break;
1725                         case 43:
1726                                 download(ipc, 3);
1727                                 break;
1728                         case 45:
1729                                 download(ipc, 4);
1730                                 break;
1731                         case 55:
1732                                 download(ipc, 5);
1733                                 break;
1734                         case 39:
1735                                 upload(ipc, 0);
1736                                 break;
1737                         case 40:
1738                                 upload(ipc, 1);
1739                                 break;
1740                         case 42:
1741                                 upload(ipc, 2);
1742                                 break;
1743                         case 44:
1744                                 upload(ipc, 3);
1745                                 break;
1746                         case 57:
1747                                 cli_upload(ipc);
1748                                 break;
1749                         case 16:
1750                                 ungoto(ipc);
1751                                 break;
1752                         case 24:
1753                                 whoknows(ipc);
1754                                 break;
1755                         case 26:
1756                                 validate(ipc);
1757                                 break;
1758                         case 29:
1759                         case 30:
1760                                 if (!rc_alt_semantics) {
1761                                         updatels(ipc);
1762                                 }
1763                                 termn8 = 1;
1764                                 break;
1765                         case 48:
1766                                 enterinfo(ipc);
1767                                 break;
1768                         case 49:
1769                                 readinfo(ipc);
1770                                 break;
1771                         case 72:
1772                                 cli_image_upload(ipc, "_userpic_");
1773                                 break;
1774                         case 73:
1775                                 cli_image_upload(ipc, "_roompic_");
1776                                 break;
1777
1778                         case 74:
1779                                 snprintf(aaa, sizeof aaa, "_floorpic_|%d", curr_floor);
1780                                 cli_image_upload(ipc, aaa);
1781                                 break;
1782
1783                         case 75:
1784                                 enternew(ipc, "roomname", aaa, 20);
1785                                 r = CtdlIPCChangeRoomname(ipc, aaa, bbb);
1786                                 if (r / 100 != 2)
1787                                         scr_printf("\n%s\n", bbb);
1788                                 break;
1789                         case 76:
1790                                 enternew(ipc, "hostname", aaa, 25);
1791                                 r = CtdlIPCChangeHostname(ipc, aaa, bbb);
1792                                 if (r / 100 != 2)
1793                                         scr_printf("\n%s\n", bbb);
1794                                 break;
1795                         case 77:
1796                                 enternew(ipc, "username", aaa, 32);
1797                                 r = CtdlIPCChangeUsername(ipc, aaa, bbb);
1798                                 if (r / 100 != 2)
1799                                         scr_printf("\n%s\n", bbb);
1800                                 break;
1801
1802                         case 35:
1803                                 set_password(ipc);
1804                                 break;
1805
1806                         case 21:
1807                                 if (argbuf[0] == 0)
1808                                         strcpy(aaa, "?");
1809                                 display_help(ipc, argbuf);
1810                                 break;
1811
1812                         case 41:
1813                                 formout(ipc, "register");
1814                                 entregis(ipc);
1815                                 break;
1816
1817                         case 15:
1818                                 scr_printf("Are you sure (y/n)? ");
1819                                 if (yesno() == 1) {
1820                                         if (!rc_alt_semantics)
1821                                                 updatels(ipc);
1822                                         a = 0;
1823                                         termn8 = 1;
1824                                 }
1825                                 break;
1826
1827                         case 85:
1828                                 scr_printf("All users will be disconnected!  "
1829                                            "Really terminate the server? ");
1830                                 if (yesno() == 1) {
1831                                         if (!rc_alt_semantics)
1832                                                 updatels(ipc);
1833                                         r = CtdlIPCTerminateServerNow(ipc, aaa);
1834                                         scr_printf("%s\n", aaa);
1835                                         if (r / 100 == 2) {
1836                                                 a = 0;
1837                                                 termn8 = 1;
1838                                         }
1839                                 }
1840                                 break;
1841
1842                         case 86:
1843                                 scr_printf("Do you really want to schedule a "
1844                                            "server shutdown? ");
1845                                 if (yesno() == 1) {
1846                                         r = CtdlIPCTerminateServerScheduled(ipc, 1, aaa);
1847                                         if (r / 100 == 2) {
1848                                                 if (atoi(aaa)) {
1849                                                         scr_printf(
1850                                                                    "The Citadel server will terminate when all users are logged off.\n"
1851                                                                    );
1852                                                 } else {
1853                                                         scr_printf(
1854                                                                    "The Citadel server will not terminate.\n"
1855                                                                    );
1856                                                 }
1857                                         }
1858                                 }
1859                                 break;
1860
1861                         case 87:
1862                                 network_config_management(ipc, "listrecp",
1863                                                           "Message-by-message mailing list recipients");
1864                                 break;
1865
1866                         case 94:
1867                                 network_config_management(ipc, "digestrecp",
1868                                                           "Digest mailing list recipients");
1869                                 break;
1870
1871                         case 89:
1872                                 network_config_management(ipc, "ignet_push_share",
1873                                                           "Nodes with which we share this room");
1874                                 break;
1875
1876                         case 88:
1877                                 do_ignet_configuration(ipc);
1878                                 break;
1879
1880                         case 92:
1881                                 do_filterlist_configuration(ipc);
1882                                 break;
1883
1884                         case 6:
1885                                 if (rc_alt_semantics) {
1886                                         updatelsa(ipc);
1887                                 }
1888                                 gotonext(ipc);
1889                                 break;
1890
1891                         case 3:
1892                                 chatmode(ipc);
1893                                 break;
1894
1895                         case 2:
1896                                 if (ipc->isLocal) {
1897                                         screen_reset();
1898                                         stty_ctdl(SB_RESTORE);
1899                                         snprintf(aaa, sizeof aaa, "USERNAME=\042%s\042; export USERNAME;"
1900                                                  "exec ./subsystem %ld %d %d", fullname,
1901                                                  usernum, screenwidth, axlevel);
1902                                         ka_system(aaa);
1903                                         stty_ctdl(SB_NO_INTR);
1904                                         screen_set();
1905                                 } else {
1906                                         scr_printf("*** Can't run doors when server is not local.\n");
1907                                 }
1908                                 break;
1909
1910                         case 17:
1911                                 who_is_online(ipc, 0);
1912                                 break;
1913
1914                         case 79:
1915                                 who_is_online(ipc, 1);
1916                                 break;
1917
1918                         case 91:
1919                                 who_is_online(ipc, 2);
1920                                 break;
1921                 
1922                         case 80:
1923                                 do_system_configuration(ipc);
1924                                 break;
1925
1926                         case 82:
1927                                 do_internet_configuration(ipc);
1928                                 break;
1929
1930                         case 83:
1931                                 check_message_base(ipc);
1932                                 break;
1933
1934                         case 84:
1935                                 quiet_mode(ipc);
1936                                 break;
1937
1938                         case 93:
1939                                 stealth_mode(ipc);
1940                                 break;
1941
1942                         case 50:
1943                                 enter_config(ipc, 2);
1944                                 break;
1945
1946                         case 37:
1947                                 enter_config(ipc, 0);
1948                                 set_floor_mode(ipc);
1949                                 break;
1950
1951                         case 59:
1952                                 enter_config(ipc, 3);
1953                                 set_floor_mode(ipc);
1954                                 break;
1955
1956                         case 60:
1957                                 gotofloor(ipc, argbuf, GF_GOTO);
1958                                 break;
1959
1960                         case 61:
1961                                 gotofloor(ipc, argbuf, GF_SKIP);
1962                                 break;
1963
1964                         case 62:
1965                                 forget_this_floor(ipc);
1966                                 break;
1967
1968                         case 63:
1969                                 create_floor(ipc);
1970                                 break;
1971
1972                         case 64:
1973                                 edit_floor(ipc);
1974                                 break;
1975
1976                         case 65:
1977                                 kill_floor(ipc);
1978                                 break;
1979
1980                         case 66:
1981                                 enter_bio(ipc);
1982                                 break;
1983
1984                         case 67:
1985                                 read_bio(ipc);
1986                                 break;
1987
1988                         case 25:
1989                                 edituser(ipc, 25);
1990                                 break;
1991
1992                         case 96:
1993                                 edituser(ipc, 96);
1994                                 break;
1995
1996                         case 8:
1997                                 knrooms(ipc, floor_mode);
1998                                 scr_printf("\n");
1999                                 break;
2000
2001                         case 68:
2002                                 knrooms(ipc, 2);
2003                                 scr_printf("\n");
2004                                 break;
2005
2006                         case 69:
2007                                 misc_server_cmd(ipc, argbuf);
2008                                 break;
2009
2010                         case 70:
2011                                 edit_system_message(ipc, argbuf);
2012                                 break;
2013
2014                         case 19:
2015                                 listzrooms(ipc);
2016                                 scr_printf("\n");
2017                                 break;
2018
2019                         case 51:
2020                                 deletefile(ipc);
2021                                 break;
2022
2023                         case 53:
2024                                 netsendfile(ipc);
2025                                 break;
2026
2027                         case 54:
2028                                 movefile(ipc);
2029                                 break;
2030
2031                         case 56:
2032                                 page_user(ipc);
2033                                 break;
2034
2035             case 110:           /* <+> Next room */
2036                  gotoroomstep(ipc, 1);
2037                              break;
2038
2039             case 111:           /* <-> Previous room */
2040                  gotoroomstep(ipc, 0);
2041                              break;
2042
2043                         case 112:           /* <>> Next floor */
2044                  gotofloorstep(ipc, 1);
2045                              break;
2046
2047                         case 113:           /* <<> Previous floor */
2048                  gotofloorstep(ipc, 0);
2049                                  break;
2050
2051                         default: /* allow some math on the command */
2052                                 /* commands 100... to 100+MAX_EDITORS-1 will
2053                                    call the appropriate editor... in other
2054                                    words, command numbers 100+ will match
2055                                    the citadel.rc keys editor0, editor1, etc.*/
2056                                 if (mcmd >= 100 && mcmd < (100+MAX_EDITORS))
2057                                 {
2058                                         /* entmsg mode >=2 select editor */
2059                                         entmsg(ipc, 0, mcmd - 100 + 2);
2060                                         break;
2061                                 }
2062                         }       /* end switch */
2063         } while (termn8 == 0);
2064
2065 TERMN8: scr_printf("%s logged out.", fullname);
2066         termn8 = 0;
2067         color(ORIGINAL_PAIR);
2068         scr_printf("\n");
2069         while (march != NULL) {
2070                 remove_march(march->march_name, 0);
2071         }
2072         if (mcmd == 30) {
2073                 sln_printf("\n\nType 'off' to disconnect, or next user...\n");
2074         }
2075         CtdlIPCLogout(ipc);
2076         if ((mcmd == 29) || (mcmd == 15)) {
2077                 screen_delete();
2078                 stty_ctdl(SB_RESTORE);
2079                 formout(ipc, "goodbye");
2080                 logoff(ipc, 0);
2081         }
2082         goto GSTA;
2083
2084 }       /* end main() */