1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
|
/* This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License , or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; see the file COPYING. If not, write to
the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
You may contact the author by:
e-mail: hlub@knoware.nl
*/
#include "rlwrap.h"
char slaves_working_directory[MAXPATHLEN+1];
static FILE *log_fp;
/* Give up the processor so that other processes (like command) can have their say. Especially useful with multi-line
input: if we, after writing a line to the inferior command, would return to the main select() loop immediately, we
would find more output to write, and keep blathering away without giving the poor command time to say something
back */
void
yield()
{
DPRINTF0(DEBUG_TERMIO, "yield...");
#if 0 /* If command writes some output and immediately starts a long computation, sched_yield() will not return for a
long time,and rlwrap will not see the output for all that time. The "poor mans sched_yield" with select
actually works better! */
sched_yield();
#else
{ struct timeval a_few_millisecs = { 0, 1000 };
select(0, NULL, NULL, NULL, &a_few_millisecs); /* poor man's sched_yield() */
}
#endif
}
static volatile int signal_handled = FALSE;
#ifdef HAVE_REAL_PSELECT
void zero_select_timeout () {
signal_handled = TRUE;
}
#else
#define until_hell_freezes NULL ;
static struct timeval * volatile pmy_select_timeout_tv; /* The SIGCHLD handler sets this variable (see zero_select_timeout() below) to make
select() return immediately when a child has died. gcc (4.8 and higher) may optimize it
into a register, which won't work: hence the "volatile" keyword */
static struct timeval my_select_timeout_tv;
void zero_select_timeout () {
my_select_timeout_tv.tv_sec = 0;
my_select_timeout_tv.tv_usec = 0;
pmy_select_timeout_tv = &my_select_timeout_tv;
signal_handled = TRUE;
}
#endif
/*
Even though even older linux systems HAVE PSELECT, is is non-atomic: signal handlers may (and
generally will) run between the unblocking of the signals and the select call (which will
then wait untill hell freezes over) Therefore we always convert the contents op
ptimeout_ts into to a static struct timeval my_select_timeout_tv, and use the function
zero_select_timeout to set this to {0,0} from within a signal handler, which will then
make select return immediately. (Linus Torvalds mentions this trick in
http://lkml.indiana.edu/hypermail/linux/kernel/0506.1/1191.html),
As I know of no reliable way to distiguish real pselect from fake pselect at configure
time HAVE_REAL_PSELECT will be undefined on all systems, even those that do have a genuine
pselect.
*/
int
my_pselect(int n, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, const struct timespec *ptimeout_ts, const sigset_t *sigmask) {
#ifdef HAVE_REAL_PSELECT
return pselect(n, readfds, writefds, exceptfds, ptimeout_ts, sigmask);
#else
int retval;
sigset_t oldmask;
if (ptimeout_ts) { /* convert timespec e.g {0,40000000} to timeval {0, 40000} */
pmy_select_timeout_tv = &my_select_timeout_tv;
pmy_select_timeout_tv -> tv_sec = ptimeout_ts -> tv_sec;
pmy_select_timeout_tv -> tv_usec = ptimeout_ts -> tv_nsec / 1000;
} else
pmy_select_timeout_tv = until_hell_freezes;
signal_handled = FALSE;
sigprocmask(SIG_SETMASK, sigmask, &oldmask);
/* most signals will be catched HERE (and their handlers will set my_select_timeout_tv to {0,0}) */
retval = select(n, readfds, writefds, exceptfds, pmy_select_timeout_tv);
/* but even if they are slow off the mark and get catched HERE the code 3 lines below will notice */
sigprocmask(SIG_SETMASK, &oldmask, NULL);
if (signal_handled && retval >= 0) {
errno = EINTR;
return -1;
} else {
return retval;
}
#endif
}
struct termios *
my_tcgetattr(int fd, char *which) /* the 'which' argument is only needed for error reporting */
{
struct termios *pterm =
(struct termios *)mymalloc(sizeof(struct termios));
return tcgetattr(fd, pterm) < 0 ? NULL : pterm;
}
void
do_nothing(int unused)
{
; /* yawn.... */
}
/* When using read (2) or write (2), one always has to be prepared to handle incomplete
reads or writes. The {read,write}_patiently* routines below do just that: they repeat the read
or write until the whole buffer has been filled, or an error occurs.
The {read,write}_patiently2 functions are specialised for reading/writing the input/output pipe
of a filter */
int
write_patiently(int fd, const void *buffer, int count, const char *whither) {
int nwritten = 0;
int total_written = 0;
assert(count >= 0);
if (count == 0)
return TRUE;
while(1) {
if((nwritten = write(fd, (char *)buffer + total_written, count - total_written)) <= 0) {
if (errno == EINTR)
continue;
else if (errno == EPIPE || nwritten == 0) {
return FALSE;
} else
myerror(FATAL|USE_ERRNO, "write error %s", whither);
}
total_written += nwritten;
if (total_written == count) /* done */
break;
}
return TRUE;
}
static int user_frustration_signals[] = {SIGHUP, SIGINT, SIGQUIT, SIGTERM, SIGALRM};
/* keep reading from fd and write into buffer until count bytes have been read.
for uninterruptible_msec, restart when interrupted by a signal, after this,
bail out with an error. if count < 0, returns a 0-terminated copy of buffer */
void
read_patiently2 (int fd,
void *buffer,
int count,
int uninterruptible_msec,
const char *whence) {
int nread = 0;
int total_read = 0;
int interruptible = FALSE;
assert (count >= 0);
unblock_signals(user_frustration_signals); /* allow users to use CTRL-C, but only after uninterruptible_msec */
if (count > 0) {
myalarm(uninterruptible_msec);
while (1) {
assert(count > total_read);
if((nread = read(fd, (char *) buffer + total_read, count - total_read)) <= 0) {
if (nread < 0 && errno == EINTR) {
if (interruptible)
myerror(FATAL|NOERRNO, "(user) interrupt reading %s, filter_hangs?", whence);
if (received_sigALRM) {
received_sigALRM = FALSE;
interruptible = TRUE;
}
continue;
} else if (nread == 0)
myerror(FATAL|NOERRNO, "EOF reading %s", whence);
else /* nread < 0 */
myerror(FATAL|USE_ERRNO, "error reading %s", whence);
}
total_read += nread;
if (total_read == count) /* done */
break;
}
}
myalarm(0); /* reset alarm */
block_all_signals();
DPRINTF2(DEBUG_AD_HOC, "read_patiently2 read %d bytes: %s", total_read, mangle_buffer_for_debug_log(buffer, total_read));
return;
}
void
write_patiently2(int fd,
const void *buffer,
int count,
int uninterruptible_msec,
const char* whither) {
int nwritten = 0;
int total_written = 0;
int interruptible = FALSE;
assert(count >= 0);
if (count == 0)
return; /* no-op */
unblock_signals(user_frustration_signals); /* allow impatient users to hit CTRL-C, but only after uninterruptible_msec */
myalarm(uninterruptible_msec);
while(1) {
if((nwritten = write(fd, (char *)buffer + total_written, count - total_written)) <= 0) {
if (nwritten < 0 && errno == EINTR) {
if (interruptible)
myerror(FATAL|NOERRNO, "(user) interrupt - filter hangs?");
if (received_sigALRM) {
received_sigALRM = FALSE;
interruptible = TRUE;
}
continue;
} else /* nwritten== 0 or < 0 with error other than EINTR */
myerror(FATAL|USE_ERRNO, "error writing %s", whither);
}
total_written += nwritten;
if (total_written == count) /* done */
break;
}
myalarm(0);
DPRINTF2(DEBUG_AD_HOC, "write_patiently2 wrote %d bytes: %s", total_written, mangle_buffer_for_debug_log(buffer, total_written));
block_all_signals();
return;
}
void
mysetenv(const char *name, const char *value)
{
int return_value = 0;
#ifdef HAVE_SETENV
return_value = setenv(name, value, TRUE);
#elif defined(HAVE_PUTENV)
char *name_is_value = add3strings (name, "=", value);
return_value = putenv (name_is_value);
#else /* won't happen, but anyway: */
myerror(WARNING|NOERRNO, "setting environment variable %s=%s failed, as this system has neither setenv() nor putenv()", name, value);
#endif
if (return_value != 0)
myerror(WARNING|USE_ERRNO, "setting environment variable %s=%s failed%s", name, value,
(errno ? "" : " (insufficient environment space?)")); /* will setenv(...) = -1 set errno? */
}
void set_ulimit(int resource, long value) {
#ifdef HAVE_SETRLIMIT
struct rlimit limit;
int result;
limit.rlim_cur = value;
result = setrlimit(resource, &limit);
DPRINTF4(DEBUG_ALL, "setrlim() used to set resource #%d to value %ld, result = %d (%s)",
resource, value, result, (result == 0 ? "success" : "failure"));
#endif
}
int open_unique_tempfile(const char *suffix, char **tmpfile_name) {
char **tmpdirs = list4(getenv("TMPDIR"), getenv("TMP"), getenv("TEMP"), "/tmp");
char *tmpdir = first_of(tmpdirs);
int tmpfile_fd;
if (!suffix)
suffix = "";
*tmpfile_name = mymalloc(MAXPATHLEN+1);
#ifdef HAVE_MKSTEMPS
snprintf4(*tmpfile_name, MAXPATHLEN, "%s/%s_%s_XXXXXX%s", tmpdir, program_name, command_name, suffix);
tmpfile_fd = mkstemps(*tmpfile_name, strlen(suffix)); /* this will write into *tmpfile_name */
#else
{ static int tmpfile_counter = 0;
snprintf6(*tmpfile_name, MAXPATHLEN, "%s/%s_%s_%d_%d%s", tmpdir, program_name, command_name, command_pid, tmpfile_counter++, suffix);
tmpfile_fd = open(*tmpfile_name, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR);
}
#endif
if (tmpfile_fd < 0)
myerror(FATAL|USE_ERRNO, "could not create temporary file %s", tmpfile_name);
free(tmpdirs);
return tmpfile_fd;
}
static char*
markup(const char*str)
{
if (isatty(STDOUT_FILENO) && (ansi_colour_aware || colour_the_prompt))
return add3strings("\033[1;31m", str,"\033[0m");
else
return mysavestring(str);
}
/* print error or warning message. There are two error flags,
defined in rlwrap.h
FATAL: exit(EXIT_FAILURE) after printing the message)
USE_ERRNO: print perror(errno) after the message
*/
void
myerror(int error_flags, const char *message_format, ...)
{
int saved_errno = errno;
char contents[BUFFSIZE];
int is_warning = !(error_flags & FATAL);
char *warning_or_error = is_warning ? "warning: " : "error: ";
static int warnings_given = 0;
char *message = add2strings(program_name, ": ");
va_list ap;
va_start(ap, message_format);
vsnprintf(contents, sizeof(contents) - 1, message_format, ap);
va_end(ap);
message = append_and_free_old(message, markup(warning_or_error));
message = append_and_free_old(message, contents);
if ((error_flags & USE_ERRNO) && saved_errno) {
message = append_and_free_old(message, ": ");
message = append_and_free_old(message, strerror(saved_errno));
}
message = append_and_free_old(message,"\n");
fflush(stdout);
DPRINTF2(DEBUG_ALL, "%s %s", warning_or_error, contents);
if (! (is_warning && nowarn))
fputs(message, stderr); /* @@@ error reporting (still) uses buffered I/O */
if (is_warning && !warnings_given++ && !nowarn)
fputs("\nwarnings can be silenced by the --no-warnings (-n) option\n", stderr);
fflush(stderr);
free(message);
errno = saved_errno;
if (error_flags & FATAL) {
if (!i_am_child)
cleanup_rlwrap_and_exit(EXIT_FAILURE);
else /* child: die and let parent clean up */
exit(EXIT_FAILURE);
}
}
void
open_logfile(const char *filename)
{
time_t now;
log_fp = fopen(filename, "a");
if (!log_fp)
myerror(FATAL|USE_ERRNO, "Cannot write to logfile %s", filename);
now = time(NULL);
fprintf(log_fp, "\n\n[rlwrap] %s\n", ctime(&now));
}
void
write_logfile(const char *str)
{
if (log_fp)
fputs(str, log_fp);
}
size_t
filesize(const char *filename)
{
struct stat buf;
if (stat(filename, &buf))
myerror(FATAL|USE_ERRNO, "couldn't stat file %s", filename);
return (size_t) buf.st_size;
}
void
close_logfile()
{
if (log_fp)
fclose(log_fp);
}
void
close_open_files_without_writing_buffers() /* called from child just before exec(command) */
{
if(log_fp)
close(fileno(log_fp)); /* don't flush buffers to avoid avoid double double output output */
if (debug)
close(fileno(debug_fp));
}
void
timestamp(char *buf, int size)
{
struct timeval now;
static struct timeval firsttime; /* remember when first called */
static int never_called = 1;
long diff_usec;
float diff_sec;
gettimeofday(&now, NULL);
if (never_called) {
firsttime = now;
never_called = 0;
}
diff_usec = 1000000 * (now.tv_sec -firsttime.tv_sec) + (now.tv_usec - firsttime.tv_usec);
diff_sec = diff_usec / 1000000.0;
snprintf1(buf, size, "%f ", diff_sec);
}
int killed_by(int status) {
#ifdef WTERMSIG
if (WIFSIGNALED(status))
return WTERMSIG(status);
#endif
return 0;
}
/* change_working_directory() changes rlwrap's working directory to /proc/<command_pid>/cwd
(on systems where this makes sense, like linux and Solaris) */
void
change_working_directory()
{
#ifdef HAVE_PROC_PID_CWD
static char proc_pid_cwd[MAXPATHLEN+1];
static int initialized = FALSE;
int linklen = 0;
snprintf0(slaves_working_directory, MAXPATHLEN, "?");
if (!initialized && command_pid > 0) { /* first time we're called after birth of child */
snprintf2(proc_pid_cwd, MAXPATHLEN , "%s/%d/cwd", PROC_MOUNTPOINT, command_pid);
initialized = TRUE;
}
if (chdir(proc_pid_cwd) == 0) {
#ifdef HAVE_READLINK
linklen = readlink(proc_pid_cwd, slaves_working_directory, MAXPATHLEN);
if (linklen > 0)
slaves_working_directory[linklen] = '\0';
else
snprintf1(slaves_working_directory, MAXPATHLEN, "? (%s)", strerror(errno));
#endif /* HAVE_READLINK */
}
#else /* HAVE_PROC_PID_CWD */
/* do nothing at all */
#endif
}
#define isset(flag) ((flag) ? "set" : "unset")
/* print info about terminal settings */
void log_terminal_settings(struct termios *terminal_settings) {
if (!terminal_settings)
return;
DPRINTF3(DEBUG_TERMIO, "terminal settings: clflag.ISIG: %s, cc_c[VINTR]=%d, cc_c[VEOF]=%d",
isset(terminal_settings->c_lflag | ISIG),
terminal_settings->c_cc[VINTR],
terminal_settings->c_cc[VEOF]);
}
void log_fd_info(int fd) {
struct termios terminal_settings;
if (isatty(fd)) {
if (tcgetattr(fd, &terminal_settings) < 0) {
DPRINTF1(DEBUG_TERMIO, "could not get terminal settings for fd %d", fd);
} else {
DPRINTF1(DEBUG_TERMIO, "terminal settings for fd %d:", fd);
}
log_terminal_settings(&terminal_settings);
}
}
/* some last-minute checks before we can start */
void
last_minute_checks()
{
/* flag unhealthy option combinations */
if (multiline_separator && filter_command)
myerror(WARNING|NOERRNO, "Filters don't work very well with multi-line rlwrap!");
}
/* sleep a little (for debugging cursor movement with the SHOWCURSOR macro) */
void mymicrosleep(int msec) {
int sec = msec / 1000;
struct timeval timeout;
msec -= (1000*sec);
timeout.tv_sec = sec;
timeout.tv_usec = 1000 * msec;
select (0,NULL,NULL,NULL,&timeout);
}
/* print info about option, considering whether we HAVE_GETOPT_LONG and whether GETOPT_GROKS_OPTIONAL_ARGS */
static void print_option(char shortopt, char *longopt, char*argument, int optional, char *comment) {
int long_opts, optional_args;
char *format;
char *maybe_optional = "";
char *longoptional = "";
#ifdef HAVE_GETOPT_LONG
long_opts = TRUE;
#else
long_opts = FALSE;
#endif
#ifdef GETOPT_GROKS_OPTIONAL_ARGS
optional_args = TRUE;
#else
optional_args = FALSE;
#endif
if (argument) {
maybe_optional = (optional_args && optional ? add3strings("[", argument,"]") : add3strings(" <", argument,">"));
longoptional = (optional ? add3strings("[=", argument,"]") : add3strings("=<", argument, ">"));
}
/* if we cannot use long options, use the long option as a reminder (no warnings) instead of "--no-warnings" */
if (!long_opts)
longopt = search_and_replace("-"," ", longopt, 0, NULL,NULL);
format = add2strings (" -%c%-24.24s", (long_opts ? " --%s%s" : "(%s)"));
fprintf(stderr, format, shortopt, maybe_optional, longopt, longoptional);
if (comment)
fprintf(stderr, " %s", comment);
fprintf(stderr, "\n");
/* don't free allocated strings: we'll exit() soon */
}
static void
print_debug_flag(int flag, char *explanation) {
fprintf(stderr, " %4d %s\n", flag, explanation);
}
void
usage(int status)
{
fprintf(stderr, "Usage: %s [options] command ...\n"
"\n"
"Options:\n", program_name);
print_option('a', "always-readline", "password prompt", TRUE, NULL);
print_option('A', "ansi-colour-aware", NULL, FALSE, NULL);
print_option('b', "break-chars", "chars", FALSE, NULL);
print_option('c', "complete-filenames", NULL, FALSE, NULL);
print_option('C', "command-name", "name|N", FALSE, NULL);
print_option('D', "history-no-dupes", "0|1|2", FALSE, NULL);
print_option('e', "extra-char-after-completion", "char|''", FALSE, NULL);
print_option('f', "file", "completion list", FALSE,NULL);
print_option('g', "forget-matching", "regexp", FALSE,NULL);
print_option('h', "help", NULL, FALSE, NULL);
print_option('H', "history-filename", "file", FALSE, NULL);
print_option('i', "case-insensitive", NULL, FALSE, NULL);
print_option('I', "pass-sigint-as-sigterm", NULL, FALSE, NULL);
print_option('l', "logfile", "file", FALSE, NULL);
print_option('m', "multi-line", "newline substitute", TRUE, NULL);
print_option('M', "multi-line-ext", ".ext", FALSE, NULL);
print_option('n', "no-warnings", NULL, FALSE, NULL);
print_option('N', "no-children", NULL, FALSE, NULL);
print_option('o', "one-shot", NULL, FALSE, NULL);
print_option('O', "only-cook", "regexp", FALSE, NULL);
print_option('p', "prompt-colour", "colour", TRUE, NULL);
print_option('P', "pre-given","input", FALSE, NULL);
print_option('q', "quote-characters", "chars", FALSE, NULL);
print_option('r', "remember", NULL, FALSE, NULL);
print_option('R', "renice", NULL, FALSE, NULL);
print_option('s', "histsize", "N", FALSE,"(negative: readonly)");
print_option('S', "substitute-prompt", "prompt", FALSE, NULL);
print_option('t', "set-term-name", "name", FALSE, NULL);
print_option('U', "mirror-arguments", NULL, FALSE, NULL);
print_option('v', "version", NULL, FALSE, NULL);
print_option('w', "wait-before-prompt", "N", FALSE, "(msec, <0 : patient mode)");
print_option('W', "polling", NULL, FALSE, NULL);
print_option('z', "filter", "filter command", FALSE, "(-z listing lists installed filters)");
#ifdef DEBUG
fprintf(stderr, "\n");
print_option('T', "test-terminal", NULL, FALSE, NULL);
print_option('d', "debug", "mask", TRUE, add3strings("(output sent to ", DEBUG_FILENAME,")"));
fprintf(stderr,
" \n"
"The -d or --debug option *must* come first\n"
"The debugging mask is a bitmask obtained by adding:\n");
print_debug_flag (DEBUG_TERMIO, "to debug termio,");
print_debug_flag (DEBUG_SIGNALS, "signal handling,");
print_debug_flag (DEBUG_READLINE, "readline,");
print_debug_flag (DEBUG_MEMORY_MANAGEMENT, "memory management,");
print_debug_flag (DEBUG_FILTERING, "filtering,");
print_debug_flag (DEBUG_COMPLETION, "and completion.");
/* print_debug_flag (DEBUG_AD_HOC, "to see your own DEBUG_AD_HOC results"); */
print_debug_flag (DEBUG_WITH_TIMESTAMPS, "to add (relative) timestamps,");
print_debug_flag (FORCE_HOMEGROWN_REDISPLAY, "to force the use of my_homegrown_redisplay(),");
print_debug_flag (DEBUG_LONG_STRINGS, "to not limit the length of strings in debug log (sloooow!)");
print_debug_flag (DEBUG_RACES, "add random delays to expose race conditions.");
fprintf(stderr, " default debug mask = %d (debug termio, signals and readline handling)\n"
" use the shell construct $[ ] to calculate the mask, e.g. -d$[%d+%d+%d]\n",
DEBUG_DEFAULT, DEBUG_DEFAULT, DEBUG_WITH_TIMESTAMPS, DEBUG_RACES);
#endif
fprintf(stderr,
"\n"
"bug reports, suggestions, updates:\n"
"https://github.com/hanslub42/rlwrap\n");
exit(status);
}
#ifdef DEBUG
#undef mymalloc
#endif
/* malloc with simplistic error handling: just bail out when out of memory */
void *
mymalloc(size_t size)
{
void *ptr;
ptr = malloc(size);
if (ptr == NULL) {
/* don't call myerror(), as this calls mymalloc() again */
fprintf(stderr, "Out of memory: tried in vain to allocate %d bytes\n", (int) size);
exit(EXIT_FAILURE);
}
return ptr;
}
/* free of possibly NULL pointer (only needed on very olde systems) */
void myfree(void *ptr) {
if (ptr)
free(ptr);
}
void mysetsid() {
# ifdef HAVE_SETSID /* c'mon, this is POSIX! */
pid_t ret = setsid();
DPRINTF2(DEBUG_TERMIO, "setsid() returned %d %s", (int)ret,
ERRMSG(ret < 0));
# endif
}
/* mirror_args(): look up command's command line and copy it to our own
important for commands that re-write their command lines e.g. to hide
passwords.
*/
static char ** rlwrap_command_argv; /* The slice of rlwrap's argv after all rlwrap options */
static char *argv_buffer;
static int argv_len;
static char *stored_cmdline_filename;
void mirror_args_init(char**argv) {
int i;
#ifdef ENABLE_MIRROR_ARGS
rlwrap_command_argv = argv;
stored_cmdline_filename = mymalloc(MAXPATHLEN);
*stored_cmdline_filename = '\0';
for (i = 0; argv[i]; i++) {
argv_len += strlen(argv[i]) + 1;
}
argv_buffer = mymalloc(argv_len * sizeof(char) + 1);
#else
stored_cmdline_filename = NULL;
myerror(WARNING|NOERRNO, "On this system, the -U (--mirror-arguments) option doesn't work");
#endif
}
/* C standard: "The parameters argc and argv and the strings pointed to by the argv
array shall be modifiable by the program, and retain their last-stored
values between program startup and program termination.
This doesn't guarantee that those changed values will be visible to e.g. the ps (1) command
*/
void mirror_args(command_pid) {
int cmdline_fd;
long cmdline_length;
static int been_warned = 0;
if (!stored_cmdline_filename)
return;
if (!*stored_cmdline_filename)
snprintf2(stored_cmdline_filename, MAXPATHLEN , "%s/%d/cmdline", PROC_MOUNTPOINT, command_pid);
if((cmdline_fd = open(stored_cmdline_filename, O_RDONLY)) < 1) {
stored_cmdline_filename = NULL;
if (been_warned++ == 0)
myerror(WARNING|USE_ERRNO, "cannot mirror command's command line, as %s is unreadable", stored_cmdline_filename);
return;
}
cmdline_length = read(cmdline_fd, argv_buffer,argv_len);
/* argv_buffer[cmdline_length] = '\0'; */
DPRINTF2(DEBUG_TERMIO,"read %d bytes from %s", (int) cmdline_length, stored_cmdline_filename);
if (memcmp(*rlwrap_command_argv, argv_buffer, cmdline_length)) {
char *rlwrap_argstr = mem2str(*rlwrap_command_argv, cmdline_length);
char *command_argstr = mem2str(argv_buffer, cmdline_length);
DPRINTF2(DEBUG_TERMIO, "discrepancy: rlwarp_args: %s, command_args %s", rlwrap_argstr, command_argstr);
free(rlwrap_argstr);
free(command_argstr);
memcpy(*rlwrap_command_argv, argv_buffer, cmdline_length);
}
}
|