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