static int _inp_rl_startup_hook(void) { rl_bind_keyseq("\\e1", _inp_rl_win_1_handler); rl_bind_keyseq("\\e2", _inp_rl_win_2_handler); rl_bind_keyseq("\\e3", _inp_rl_win_3_handler); rl_bind_keyseq("\\e4", _inp_rl_win_4_handler); rl_bind_keyseq("\\e5", _inp_rl_win_5_handler); rl_bind_keyseq("\\e6", _inp_rl_win_6_handler); rl_bind_keyseq("\\e7", _inp_rl_win_7_handler); rl_bind_keyseq("\\e8", _inp_rl_win_8_handler); rl_bind_keyseq("\\e9", _inp_rl_win_9_handler); rl_bind_keyseq("\\e0", _inp_rl_win_0_handler); rl_bind_keyseq("\\eOP", _inp_rl_win_1_handler); rl_bind_keyseq("\\eOQ", _inp_rl_win_2_handler); rl_bind_keyseq("\\eOR", _inp_rl_win_3_handler); rl_bind_keyseq("\\eOS", _inp_rl_win_4_handler); rl_bind_keyseq("\\e[15~", _inp_rl_win_5_handler); rl_bind_keyseq("\\e[17~", _inp_rl_win_6_handler); rl_bind_keyseq("\\e[18~", _inp_rl_win_7_handler); rl_bind_keyseq("\\e[19~", _inp_rl_win_8_handler); rl_bind_keyseq("\\e[20~", _inp_rl_win_9_handler); rl_bind_keyseq("\\e[21~", _inp_rl_win_0_handler); rl_bind_keyseq("\\e[1;9D", _inp_rl_win_prev_handler); rl_bind_keyseq("\\e[1;3D", _inp_rl_win_prev_handler); rl_bind_keyseq("\\e\\e[D", _inp_rl_win_prev_handler); rl_bind_keyseq("\\e[1;9C", _inp_rl_win_next_handler); rl_bind_keyseq("\\e[1;3C", _inp_rl_win_next_handler); rl_bind_keyseq("\\e\\e[C", _inp_rl_win_next_handler); rl_bind_keyseq("\\e\\e[5~", _inp_rl_subwin_pageup_handler); rl_bind_keyseq("\\e[5;3~", _inp_rl_subwin_pageup_handler); rl_bind_keyseq("\\e\\eOy", _inp_rl_subwin_pageup_handler); rl_bind_keyseq("\\e\\e[6~", _inp_rl_subwin_pagedown_handler); rl_bind_keyseq("\\e[6;3~", _inp_rl_subwin_pagedown_handler); rl_bind_keyseq("\\e\\eOs", _inp_rl_subwin_pagedown_handler); rl_bind_keyseq("\\e[5~", _inp_rl_win_pageup_handler); rl_bind_keyseq("\\eOy", _inp_rl_win_pageup_handler); rl_bind_keyseq("\\e[6~", _inp_rl_win_pagedown_handler); rl_bind_keyseq("\\eOs", _inp_rl_win_pagedown_handler); rl_bind_key('\t', _inp_rl_tab_handler); // unbind unwanted mappings rl_bind_keyseq("\\e=", NULL); // disable readline completion rl_variable_bind("disable-completion", "on"); // check for and load ~/.config/profanity/inputrc char *inputrc = prefs_get_inputrc(); if (inputrc) { rl_read_init_file(inputrc); free(inputrc); } return 0; }
int main(int argc, char *argv[]) { int echo = 0; #ifdef notyet int print_statistics = 0; #endif int fipsflagger = 0; int perfstats = 0; int use_encryption = 0; int chained_transactions = 0; int headers = 0; char *columnwidth = NULL; const char *colseparator = " "; const char *lineseparator = "\n"; int timeout = 0; char *username = NULL; char *password = NULL; char *server = NULL; DBCHAR *char_set = NULL; char *hostname = NULL; char *interfaces_filename = NULL; char *input_filename = NULL; char *output_filename = NULL; int logintime = -1; char *language = NULL; int size = 0; char *sybenv; LOGINREC *login; int printedlines; int i; int dbrc; int c; int errflg = 0; char *prbuf; int prbuflen; int num_cols; int selcol; int col; int collen; DBINT colid; const char *opname; char adbuf[512]; DBINT convlen; int printedcompute = 0; char adash; const char *database_name = NULL; setlocale(LC_ALL, ""); #ifdef __VMS /* Convert VMS-style arguments to Unix-style */ parse_vms_args(&argc, &argv); #endif editor = getenv("EDITOR"); if (!editor) { editor = getenv("VISUAL"); } if (!editor) { editor = "vi"; } opterr = 0; optarg = NULL; while (!errflg && (c = getopt(argc, argv, "eFgpnvXYa:c:D:E:h:H:i:I:J:l:m:o:P:s:S:t:U:w:y:z:A:")) != -1) { switch (c) { case 'e': echo = 1; break; case 'F': fipsflagger = 1; break; case 'g': errflg++; break; case 'p': errflg++; perfstats = 1; break; case 'n': no_prompt = 1; break; case 'v': puts("fisql, a free isql replacement by Nicholas S. Castellano"); return EXIT_SUCCESS; break; case 'X': /* XXX: We get a different error message than isql gives; neither seems * to work */ use_encryption = 1; break; case 'Y': chained_transactions = 1; break; case 'c': cmdend = optarg; break; case 'E': editor = optarg; break; case 'h': headers = atoi(optarg); break; case 'H': hostname = optarg; break; case 'i': input_filename = optarg; break; case 'I': interfaces_filename = optarg; break; case 'J': errflg++; break; case 'l': logintime = atoi(optarg); break; case 'm': global_errorlevel = atoi(optarg); break; case 'o': output_filename = optarg; break; case 'P': password = optarg; break; case 's': colseparator = optarg; break; case 'S': server = optarg; break; case 't': timeout = atoi(optarg); break; case 'U': username = optarg; break; case 'w': columnwidth = optarg; break; case 'y': /* XXX: this doesn't seem to be what isql does with -y...it doesn't * seem to do anything actually */ sybenv = (char *) xmalloc((strlen(optarg) + 8) * sizeof(char)); strcpy(sybenv, "SYBASE="); strcat(sybenv, optarg); putenv(sybenv); break; case 'z': language = optarg; break; case 'A': size = atoi(optarg); break; case 'D': database_name = optarg; break; default: errflg++; break; } } if (errflg) { fprintf(stderr, "usage: fisql [-e] [-F] [-g] [-p] [-n] [-v] [-X] [-Y]\n"); fprintf(stderr, "\t[-c cmdend] [-D database_name] [-E editor]\n"); fprintf(stderr, "\t[-h headers] [-H hostname] [-i inputfile]\n"); fprintf(stderr, "\t[-I interfaces_file] [-J client character set]\n"); fprintf(stderr, "\t[-l login_timeout] [-m errorlevel]\n"); fprintf(stderr, "\t[-o outputfile]\n"); fprintf(stderr, "\t[-P password] [-s colseparator] [-S server]\n"); fprintf(stderr, "\t[-t timeout] [-U username] [-w columnwidth]\n"); fprintf(stderr, "\t[-y sybase_dir] [-z language]\n"); return EXIT_FAILURE; } if (!(isatty(fileno(stdin)))) { no_prompt = 1; rl_outstream = fopen("/dev/null", "rw"); } rl_readline_name = "fisql"; rl_bind_key('\t', rl_insert); if (password == NULL) { password = (char *) xmalloc(READPASSPHRASE_MAXLEN); readpassphrase("Password: "******"r", stdin) == NULL) { /* XXX: sybase isql generates this error while parsing the options, * but doesn't redirect the input until after the Password: prompt */ /* lack of newline for bug-compatibility with isql */ fprintf(stderr, "Unable to open input file '%s'.", optarg); return EXIT_FAILURE; } } if (output_filename) { if (freopen(output_filename, "w", stdout) == NULL) { /* XXX: sybase isql generates this error while parsing the options, * but doesn't redirect the output until after the Password: prompt */ /* lack of newline for bug-compatibility with isql */ fprintf(stderr, "Unable to open output file '%s'.", output_filename); return EXIT_FAILURE; } } if (isatty(fileno(stdin))) { rl_outstream = stdout; } dbinit(); #if 0 #ifdef DBVERSION_100 dbsetversion(DBVERSION_100); #endif #endif if ((login = dblogin()) == NULL) { reset_term(); return EXIT_FAILURE; } dbmsghandle(msg_handler); dberrhandle(err_handler); DBSETLAPP(login, "fisql"); if (username) { DBSETLUSER(login, username); } DBSETLPWD(login, password); memset(password, 0, strlen(password)); if (char_set) { DBSETLCHARSET(login, char_set); } if (use_encryption) { DBSETLENCRYPT(login, TRUE); } if (hostname) { DBSETLHOST(login, hostname); } if (language) { DBSETLNATLANG(login, language); } if (size) { DBSETLPACKET(login, (short) size); } if (interfaces_filename) { dbsetifile(interfaces_filename); } dbsettime(timeout); if (logintime >= 0) { dbsetlogintime(logintime); } if (database_name) { DBSETLDBNAME(login, database_name); } if ((dbproc = dbopen(login, server)) == NULL) { fprintf(stderr, "fisql: dbopen() failed.\n"); reset_term(); return EXIT_FAILURE; } dbsetopt(dbproc, DBPRLINESEP, lineseparator, strlen(lineseparator)); if (colseparator) { dbsetopt(dbproc, DBPRCOLSEP, colseparator, strlen(colseparator)); } if (columnwidth) { dbsetopt(dbproc, DBPRLINELEN, columnwidth, 0); } if (chained_transactions) { dbsetopt(dbproc, DBCHAINXACTS, NULL, 0); } if (fipsflagger) { dbsetopt(dbproc, DBFIPSFLAG, NULL, 0); } if (perfstats) { dbsetopt(dbproc, DBSTAT, "time", 0); } while (1) { if (sigsetjmp(restart, 1)) { reset_ibuf(); fputc('\n', stdout); rl_on_new_line(); rl_reset_line_state(); } dbcancel(dbproc); signal(SIGINT, inactive_interrupt_handler); read_sql_lines(); dbfreebuf(dbproc); for (i = 0; i < ibuflines; i++) { if (echo) { puts(ibuf[i]); } dbcmd(dbproc, ibuf[i]); dbcmd(dbproc, "\n"); free(ibuf[i]); } free(ibuf); ibuf = NULL; signal(SIGINT, active_interrupt_handler); dbsetinterrupt(dbproc, (void *) active_interrupt_pending, (void *) active_interrupt_servhandler); if (dbsqlexec(dbproc) == SUCCEED) { int status_printed = 0; maybe_handle_active_interrupt(); while ((dbrc = dbresults(dbproc)) != NO_MORE_RESULTS) { printedlines = 0; #define USE_DBPRROW 0 #if USE_DBPRROW dbprhead(dbproc); dbprrow(dbproc); #else if ((dbrc == SUCCEED) && (DBROWS(dbproc) == SUCCEED)) { prbuflen = dbspr1rowlen(dbproc); prbuf = (char *) xmalloc(prbuflen * sizeof(char)); dbsprhead(dbproc, prbuf, prbuflen); fputs(prbuf, stdout); fputc('\n', stdout); dbsprline(dbproc, prbuf, prbuflen, '-'); fputs(prbuf, stdout); fputc('\n', stdout); maybe_handle_active_interrupt(); while ((dbrc = dbnextrow(dbproc)) != NO_MORE_ROWS) { if (dbrc == FAIL) { break; } if (dbrc != REG_ROW) { num_cols = dbnumalts(dbproc, dbrc); for (selcol = col = 1; col <= num_cols; col++) { colid = dbaltcolid(dbproc, dbrc, col); while (selcol < colid) { collen = get_printable_column_size(dbproc, selcol); for (i = 0; i < collen; i++) { putchar(' '); } selcol++; printf("%s", colseparator); } opname = dbprtype(dbaltop(dbproc, dbrc, col)); printf("%s", opname); collen = get_printable_column_size(dbproc, colid); collen -= strlen(opname); while (collen-- > 0) { putchar(' '); } selcol++; printf("%s", colseparator); } printf("%s", lineseparator); for (selcol = col = 1; col <= num_cols; col++) { colid = dbaltcolid(dbproc, dbrc, col); while (selcol < colid) { collen = get_printable_column_size(dbproc, selcol); for (i = 0; i < collen; i++) { putchar(' '); } selcol++; printf("%s", colseparator); } collen = get_printable_column_size(dbproc, colid); adash = '-'; for (i = 0; i < collen; i++) { putchar(adash); } selcol++; printf("%s", colseparator); } printf("%s", lineseparator); for (selcol = col = 1; col <= num_cols; col++) { colid = dbaltcolid(dbproc, dbrc, col); while (selcol < colid) { collen = get_printable_column_size(dbproc, selcol); for (i = 0; i < collen; i++) { putchar(' '); } selcol++; printf("%s", colseparator); } convlen = dbconvert(dbproc, dbalttype(dbproc, dbrc, col), dbadata(dbproc, dbrc, col), dbadlen(dbproc, dbrc, col), SYBCHAR, (BYTE *) adbuf, sizeof(adbuf)); printf("%.*s", (int) convlen, adbuf); collen = get_printable_column_size(dbproc, colid); collen -= convlen; while (collen-- > 0) { putchar(' '); } selcol++; printf("%s", colseparator); } printf("%s", lineseparator); printedcompute = 1; continue; } if (printedcompute || (headers && (printedlines >= headers) && ((printedlines % headers) == 0))) { fputc('\n', stdout); dbsprhead(dbproc, prbuf, prbuflen); fputs(prbuf, stdout); fputc('\n', stdout); dbsprline(dbproc, prbuf, prbuflen, '-'); fputs(prbuf, stdout); fputc('\n', stdout); printedcompute = 0; } printedlines++; dbspr1row(dbproc, prbuf, prbuflen); fputs(prbuf, stdout); fputc('\n', stdout); maybe_handle_active_interrupt(); } fputc('\n', stdout); free(prbuf); maybe_handle_active_interrupt(); } #endif if (dbrc != FAIL) { if ((DBCOUNT(dbproc) >= 0) || dbhasretstat(dbproc)) { if (DBCOUNT(dbproc) >= 0) { fprintf(stdout, "(%d rows affected", (int) DBCOUNT(dbproc)); if (dbhasretstat(dbproc)) { status_printed = 1; dbrc = dbretstatus(dbproc); fprintf(stdout, ", return status = %d", dbrc); } fprintf(stdout, ")\n"); } else { if (dbhasretstat(dbproc)) { status_printed = 1; dbrc = dbretstatus(dbproc); fprintf(stdout, "(return status = %d)\n", dbrc); } } } } } if (!status_printed && dbhasretstat(dbproc)) { dbrc = dbretstatus(dbproc); fprintf(stdout, "(return status = %d)\n", dbrc); } } else { /* Something failed, so change the default * exit status to reflect that. */ default_exit = EXIT_FAILURE; } } reset_term(); dbexit(); return EXIT_FAILURE; }
int main (int argc, char **argv) { char buf[256], *e, *t, *t0; int fd[2], i, j, n, n0, p, q; static char *signame[16] = { "", /*1*/ "Hangup on controlling terminal or death of controlling process", /*2*/ "Interrupt from keyboard", /*3*/ "Quit from keyboard", /*4*/ "Illegal Instruction", /*5*/ "Trace/breakpoint trap", /*6*/ "Abort signal", /*7*/ "Bus error", /*8*/ "Floating point exception", /*9*/ "Kill -9 signal", /*10*/ "Signal 10", /*11*/ "Segmentation fault (invalid memory reference)", /*12*/ "Signal 12", /*13*/ "Broken pipe", /*14*/ "Alarmm (SIGALRM)", /*15*/ "Termination signal (SIGTERM)" }; n = 0; progname = argv[0]; if (--argc <= 0) return usage(1); t = *++argv; if (*t == '-') { if (*++t == '?' && !t[1]) return usage(0); if (!strcmp(t, "-help")) return usage(0); if (*t >= '0' && *t <= '9') { n = (int)strtol(t,&t,0); if (*t) return usage(1); } else if (*t != '-' || t[1]) return usage(1); if (!(t = *++argv)) return usage(1); --argc; } if (pipe(fd)) { fprintf(stderr, "%s: pipe failure\n", progname); return 2; } if (!(q = fork())) { dup2(fd[0], 0); close(fd[0]); close(fd[1]); execvp(argv[0], argv); fprintf(stderr, "Cannot invoke %s\n", argv[0]); return 2; } signal(SIGINT, SIG_IGN); signal(SIGPIPE, catch_sigpipe); signal(SIGCHLD, catch_sigpipe); close(fd[0]); p = fd[1]; using_history(); if (n) stifle_history(n); rl_bind_key('\t', rl_insert); /* treat tab as tab */ /* history_expansion_char = 0x1b; */ /* escape: treat ! as ! */ t = t0 = 0; while(!pipegone) { if (t != t0) free(t); in_readline = 1; if (!(t = readline(0))) { pipegone = 1; write(p, buf, 0); /* try to send EOF */ write(1, "\n", 1); break; } in_readline = 0; if (pipegone) break; n0 = strlen(t); if (t[n = n0 - 1] == '\n') { if (!n) { write(p, t, n0); continue; } t[n] = 0; } else n = -1; i = history_expand(t, &e); if (i > 0) { if (i == 2) { n = strlen(e); if (n < sizeof(buf)) { memcpy(buf, e, n); buf[n++] = '\n'; write(2, buf, n); } else { write(2, e, n); if (pipegone) break; write(2, "\n", 1); } free(e); continue; } free(t); t = e; } else free(e); if (!t0 || strcmp(t,t0)) { add_history(t); if (t0) free(t0); t0 = t; } if (i >= 0) { n = strlen(t); if (n < sizeof(buf)) { memcpy(buf, t, n); buf[n++] = '\n'; write(p, buf, n); } else { write(p, t, n); if (pipegone) break; write(p, "\n", 1); } } else { if (n >= 0) t[n] = '\n'; write(p, t, n0); } } close(p); i = 0; do n = wait(&i); while(n != -1 && n != q); if (j = i & 0xff) { if (j < 16) fprintf(stderr, "%s\n", signame[j]); else fprintf(stderr, "Signal %d\n", j); return 1; } return i >> 8; }
static void setup_readline(void) { #ifdef SAVE_LOCALE char *saved_locale = strdup(setlocale(LC_CTYPE, NULL)); if (!saved_locale) Py_FatalError("not enough memory to save locale"); #endif #ifdef __APPLE__ /* the libedit readline emulation resets key bindings etc * when calling rl_initialize. So call it upfront */ if (using_libedit_emulation) rl_initialize(); /* Detect if libedit's readline emulation uses 0-based * indexing or 1-based indexing. */ add_history("1"); if (history_get(1) == NULL) { libedit_history_start = 0; } else { libedit_history_start = 1; } clear_history(); #endif /* __APPLE__ */ using_history(); rl_readline_name = "python"; #if defined(PYOS_OS2) && defined(PYCC_GCC) /* Allow $if term= in .inputrc to work */ rl_terminal_name = getenv("TERM"); #endif /* Force rebind of TAB to insert-tab */ rl_bind_key('\t', rl_insert); /* Bind both ESC-TAB and ESC-ESC to the completion function */ rl_bind_key_in_map ('\t', rl_complete, emacs_meta_keymap); rl_bind_key_in_map ('\033', rl_complete, emacs_meta_keymap); /* Set our hook functions */ rl_startup_hook = on_startup_hook; #ifdef HAVE_RL_PRE_INPUT_HOOK rl_pre_input_hook = on_pre_input_hook; #endif /* Set our completion function */ rl_attempted_completion_function = flex_complete; /* Set Python word break characters */ completer_word_break_characters = rl_completer_word_break_characters = strdup(" \t\n`~!@#$%^&*()-=+[{]}\\|;:'\",<>/?"); /* All nonalphanums except '.' */ begidx = PyInt_FromLong(0L); endidx = PyInt_FromLong(0L); /* Initialize (allows .inputrc to override) * * XXX: A bug in the readline-2.2 library causes a memory leak * inside this function. Nothing we can do about it. */ #ifdef __APPLE__ if (using_libedit_emulation) rl_read_init_file(NULL); else #endif /* __APPLE__ */ rl_initialize(); RESTORE_LOCALE(saved_locale) }
int main(int argc, char **argv) { const char *lua_init = "init.lua"; std::vector< std::pair< exec_type, std::string > > startup_cmds; // parse command line while(1) { static struct option long_options[] = { {"help", no_argument, 0, '?'}, {"quiet", no_argument, 0, 'q'}, {0, 0, 0, 0} }; int c = getopt_long(argc, argv, "?qi:e:f:", long_options, NULL); if(c == -1) break; switch(c) { case -1: break; case 'q': g_quiet = true; break; case '?': usage(); break; case 'i': lua_init = optarg; break; case 'e': startup_cmds.push_back(std::make_pair(exec_cmd, std::string(optarg))); break; case 'f': startup_cmds.push_back(std::make_pair(exec_file, std::string(optarg))); break; default: abort(); } } // load register descriptions std::vector< soc_t > socs; for(int i = optind; i < argc; i++) { socs.push_back(soc_t()); if(!soc_desc_parse_xml(argv[i], socs[socs.size() - 1])) { printf("Cannot load description '%s'\n", argv[i]); return 2; } } // create usb context libusb_context *ctx; libusb_init(&ctx); libusb_set_debug(ctx, 3); // look for device if(!g_quiet) printf("Looking for hwstub device ...\n"); // open first device libusb_device **list; ssize_t cnt = hwstub_get_device_list(ctx, &list); if(cnt <= 0) { printf("No device found\n"); return 1; } libusb_device_handle *handle; if(libusb_open(list[0], &handle) != 0) { printf("Cannot open device\n"); return 1; } libusb_free_device_list(list, 1); // admin stuff libusb_device *mydev = libusb_get_device(handle); if(!g_quiet) { printf("device found at %d:%d\n", libusb_get_bus_number(mydev), libusb_get_device_address(mydev)); } g_hwdev = hwstub_open(handle); if(g_hwdev == NULL) { printf("Cannot open device!\n"); return 1; } // get hwstub information int ret = hwstub_get_desc(g_hwdev, HWSTUB_DT_VERSION, &g_hwdev_ver, sizeof(g_hwdev_ver)); if(ret != sizeof(g_hwdev_ver)) { printf("Cannot get version!\n"); goto Lerr; } if(g_hwdev_ver.bMajor != HWSTUB_VERSION_MAJOR || g_hwdev_ver.bMinor < HWSTUB_VERSION_MINOR) { printf("Warning: this tool is possibly incompatible with your device:\n"); printf("Device version: %d.%d.%d\n", g_hwdev_ver.bMajor, g_hwdev_ver.bMinor, g_hwdev_ver.bRevision); printf("Host version: %d.%d\n", HWSTUB_VERSION_MAJOR, HWSTUB_VERSION_MINOR); } // get memory layout information ret = hwstub_get_desc(g_hwdev, HWSTUB_DT_LAYOUT, &g_hwdev_layout, sizeof(g_hwdev_layout)); if(ret != sizeof(g_hwdev_layout)) { printf("Cannot get layout: %d\n", ret); goto Lerr; } // get target ret = hwstub_get_desc(g_hwdev, HWSTUB_DT_TARGET, &g_hwdev_target, sizeof(g_hwdev_target)); if(ret != sizeof(g_hwdev_target)) { printf("Cannot get target: %d\n", ret); goto Lerr; } // get STMP specific information if(g_hwdev_target.dID == HWSTUB_TARGET_STMP) { ret = hwstub_get_desc(g_hwdev, HWSTUB_DT_STMP, &g_hwdev_stmp, sizeof(g_hwdev_stmp)); if(ret != sizeof(g_hwdev_stmp)) { printf("Cannot get stmp: %d\n", ret); goto Lerr; } } // get PP specific information if(g_hwdev_target.dID == HWSTUB_TARGET_PP) { ret = hwstub_get_desc(g_hwdev, HWSTUB_DT_PP, &g_hwdev_pp, sizeof(g_hwdev_pp)); if(ret != sizeof(g_hwdev_pp)) { printf("Cannot get pp: %d\n", ret); goto Lerr; } } /** Init lua */ // create lua state g_lua = luaL_newstate(); if(g_lua == NULL) { printf("Cannot create lua state\n"); return 1; } // import hwstub if(!my_lua_import_hwstub()) printf("Cannot import hwstub description into Lua context\n"); // open all standard libraires luaL_openlibs(g_lua); // import socs if(!my_lua_import_soc(socs)) printf("Cannot import SoC descriptions into Lua context\n"); if(luaL_dofile(g_lua, lua_init)) printf("error in init: %s\n", lua_tostring(g_lua, -1)); lua_pop(g_lua, lua_gettop(g_lua)); /** start interactive mode */ if(!g_quiet) printf("Starting interactive lua session. Type 'help()' to get some help\n"); /** run startup commands */ for(size_t i = 0; i < startup_cmds.size(); i++) { bool ret = false; if(!g_quiet) printf("Running '%s'...\n", startup_cmds[i].second.c_str()); if(startup_cmds[i].first == exec_file) ret = luaL_dofile(g_lua, startup_cmds[i].second.c_str()); else if(startup_cmds[i].first == exec_cmd) ret = luaL_dostring(g_lua, startup_cmds[i].second.c_str()); if(ret) printf("error: %s\n", lua_tostring(g_lua, -1)); } // use readline to provide some history and completion rl_bind_key('\t', rl_complete); while(!g_exit) { char *input = readline("> "); if(!input) break; add_history(input); // evaluate string if(luaL_dostring(g_lua, input)) printf("error: %s\n", lua_tostring(g_lua, -1)); // pop everything to start from a clean stack lua_pop(g_lua, lua_gettop(g_lua)); free(input); } Lerr: // display log if handled if(!g_quiet) printf("Device log:\n"); print_log(g_hwdev); hwstub_release(g_hwdev); return 1; }
int run(DCOPRef& ref) { DCOPClient *client = KApplication::dcopClient(); // Disable completion for now. We might want to add completion of JS // keywords and Kst objects at some point. rl_bind_key('\t', rl_insert); kstName = ref.app(); #ifndef SOLARIS signal(SIGALRM, &ping); itimerval tv = { { 1, 0 }, { 1, 0 } }; itimerval old; setitimer(ITIMER_REAL, &tv, &old); #endif for (;;) { if (!client->registeredApplications().contains(kstName)) { printf("%s", _T("Kst application process has terminated.\n")); return ERR_KST_TERMINATED; } char *l = 0L; const char *prompt = "kst> "; QString line; do { if (!line.isEmpty()) { // replace \ with \n line[line.length() - 1] = '\n'; } l = readline(prompt); prompt = ""; if (!l) { return 0; } line += QString(l); free(l); l = 0L; } while (line.endsWith("\\")); QString clean = line.stripWhiteSpace(); if (clean == "exit") { return ERR_NONE; } if (clean == "session") { printf("%s\n", ref.app().data()); continue; } if (clean == "help") { printf("%s", _T("Help:\n")); printf("%s", _T("session\t\t\t\tDisplay the name of the session in use\n")); printf("%s", _T("help\t\t\t\tDisplay help\n")); printf("%s", _T("exit\t\t\t\tExit the command-line interpreter\n")); continue; } if (clean.isEmpty()) { continue; } add_history(line.latin1()); DCOPReply r = ref.call("evaluate", clean); if (r.isValid()) { QString res; r.get(res); if (!res.isEmpty()) { printf("%s\n", res.latin1()); } } } }
static void Console(CYOptions &options) { CYPool pool; passwd *passwd; if (const char *username = getenv("LOGNAME")) passwd = getpwnam(username); else passwd = getpwuid(getuid()); const char *basedir(pool.strcat(passwd->pw_dir, "/.cycript", NULL)); const char *histfile(pool.strcat(basedir, "/history", NULL)); size_t histlines(0); rl_initialize(); rl_readline_name = name_; mkdir(basedir, 0700); read_history(histfile); bool bypass(false); bool debug(false); bool expand(false); bool syntax(true); out_ = &std::cout; // rl_completer_word_break_characters is broken in libedit rl_basic_word_break_characters = break_; rl_completer_word_break_characters = break_; rl_attempted_completion_function = &Complete; rl_bind_key('\t', rl_complete); struct sigaction action; sigemptyset(&action.sa_mask); action.sa_handler = &sigint; action.sa_flags = 0; sigaction(SIGINT, &action, NULL); restart: for (;;) { command_.clear(); std::vector<std::string> lines; bool extra(false); const char *prompt("cy# "); if (setjmp(ctrlc_) != 0) { mode_ = Working; *out_ << std::endl; goto restart; } read: #if RL_READLINE_VERSION >= 0x0600 if (syntax) { rl_prep_term_function = CYDisplayStart; rl_redisplay_function = CYDisplayUpdate; rl_deprep_term_function = CYDisplayFinish; } else { rl_prep_term_function = rl_prep_terminal; rl_redisplay_function = rl_redisplay; rl_deprep_term_function = rl_deprep_terminal; } #endif mode_ = Parsing; char *line(readline(prompt)); mode_ = Working; if (line == NULL) break; if (line[0] == '\0') goto read; if (!extra) { extra = true; if (line[0] == '?') { std::string data(line + 1); if (data == "bypass") { bypass = !bypass; *out_ << "bypass == " << (bypass ? "true" : "false") << std::endl; } else if (data == "debug") { debug = !debug; *out_ << "debug == " << (debug ? "true" : "false") << std::endl; } else if (data == "expand") { expand = !expand; *out_ << "expand == " << (expand ? "true" : "false") << std::endl; } else if (data == "syntax") { syntax = !syntax; *out_ << "syntax == " << (syntax ? "true" : "false") << std::endl; } add_history(line); ++histlines; goto restart; } } command_ += line; char *begin(line), *end(line + strlen(line)); while (char *nl = reinterpret_cast<char *>(memchr(begin, '\n', end - begin))) { *nl = '\0'; lines.push_back(begin); begin = nl + 1; } lines.push_back(begin); free(line); std::string code; if (bypass) code = command_; else { CYLocalPool pool; std::istringstream stream(command_); CYDriver driver(stream); cy::parser parser(driver); Setup(driver, parser); if (parser.parse() != 0 || !driver.errors_.empty()) { for (CYDriver::Errors::const_iterator error(driver.errors_.begin()); error != driver.errors_.end(); ++error) { cy::position begin(error->location_.begin); if (begin.line != lines.size() || begin.column < lines.back().size() || error->warning_) { cy::position end(error->location_.end); if (begin.line != lines.size()) { std::cerr << " | "; std::cerr << lines[begin.line - 1] << std::endl; } std::cerr << "...."; for (size_t i(0); i != begin.column; ++i) std::cerr << '.'; if (begin.line != end.line || begin.column == end.column) std::cerr << '^'; else for (size_t i(0), e(end.column - begin.column); i != e; ++i) std::cerr << '^'; std::cerr << std::endl; std::cerr << " | "; std::cerr << error->message_ << std::endl; add_history(command_.c_str()); ++histlines; goto restart; } } driver.errors_.clear(); command_ += '\n'; prompt = "cy> "; goto read; } if (driver.program_ == NULL) goto restart; if (client_ != -1) code = command_; else { std::ostringstream str; CYOutput out(str, options); Setup(out, driver, options); out << *driver.program_; code = str.str(); } } add_history(command_.c_str()); ++histlines; if (debug) { Write(syntax, code.c_str(), code.size(), std::cout); std::cout << std::endl; } Run(client_, syntax, code, out_, expand); } if (append_history$ != NULL) { _syscall(close(_syscall(open(histfile, O_CREAT | O_WRONLY, 0600)))); (*append_history$)(histlines, histfile); } else { write_history(histfile); } *out_ << std::endl; }
int main(int argc, char *argv[]) { int ch, debug = 1, rc = EXIT_FAILURE; const char *fmt = "plain"; lldpctl_conn_t *conn = NULL; const char *options = is_lldpctl(argv[0])?"hdvf:u:":"hdsvf:c:u:"; int gotinputs = 0; struct inputs inputs; TAILQ_INIT(&inputs); ctlname = lldpctl_get_default_transport(); signal(SIGHUP, SIG_IGN); /* Get and parse command line options */ optind = 1; while ((ch = getopt(argc, argv, options)) != -1) { switch (ch) { case 'd': debug++; break; case 's': debug--; break; case 'h': usage(); break; case 'u': ctlname = optarg; break; case 'v': fprintf(stdout, "%s\n", PACKAGE_VERSION); exit(0); break; case 'f': fmt = optarg; break; case 'c': if (!gotinputs) { log_init(debug, __progname); lldpctl_log_level(debug); gotinputs = 1; } input_append(optarg, &inputs, 1); break; default: usage(); } } if (!gotinputs) { log_init(debug, __progname); lldpctl_log_level(debug); } /* Disable SIGPIPE */ signal(SIGPIPE, SIG_IGN); /* Register commands */ root = register_commands(); /* Make a connection */ log_debug("lldpctl", "connect to lldpd"); conn = lldpctl_new_name(ctlname, NULL, NULL, NULL); if (conn == NULL) goto end; /* Process file inputs */ while (gotinputs && !TAILQ_EMPTY(&inputs)) { /* coverity[use_after_free] TAILQ_REMOVE does the right thing */ struct input *first = TAILQ_FIRST(&inputs); log_debug("lldpctl", "process: %s", first->name); FILE *file = fopen(first->name, "r"); if (file) { size_t len; char *line; while ((line = fgetln(file, &len))) { line = strndup(line, len); if (line[len - 1] == '\n') { line[len - 1] = '\0'; parse_and_exec(conn, fmt, line); } free(line); } fclose(file); } else { log_warn("lldpctl", "unable to open %s", first->name); } TAILQ_REMOVE(&inputs, first, next); free(first->name); free(first); } /* Process additional arguments. First if we are lldpctl (interfaces) */ if (is_lldpctl(NULL)) { char *line = NULL; for (int i = optind; i < argc; i++) { char *prev = line; if (asprintf(&line, "%s%s%s", prev?prev:"show neigh ports ", argv[i], (i == argc - 1)?" details":",") == -1) { log_warnx("lldpctl", "not enough memory to build list of interfaces"); free(prev); goto end; } free(prev); } if (line == NULL && (line = strdup("show neigh details")) == NULL) { log_warnx("lldpctl", "not enough memory to build command line"); goto end; } log_debug("lldpctl", "execute %s", line); if (parse_and_exec(conn, fmt, line) != -1) rc = EXIT_SUCCESS; free(line); goto end; } /* Then, if we are regular lldpcli (command line) */ if (optind < argc) { const char **cargv; int cargc; cargv = &((const char **)argv)[optind]; cargc = argc - optind; if (cmd_exec(conn, fmt, cargc, cargv) != -1) rc = EXIT_SUCCESS; goto end; } if (gotinputs) { rc = EXIT_SUCCESS; goto end; } /* Interactive session */ #ifdef HAVE_LIBREADLINE rl_bind_key('?', cmd_help); rl_bind_key('\t', cmd_complete); #endif const char *line; do { if ((line = readline(prompt()))) { int n = parse_and_exec(conn, fmt, line); (void)n; #ifdef HAVE_READLINE_HISTORY if (n != 0) add_history(line); #endif } } while (!must_exit && line != NULL); rc = EXIT_SUCCESS; end: while (!TAILQ_EMPTY(&inputs)) { /* coverity[use_after_free] TAILQ_REMOVE does the right thing */ struct input *first = TAILQ_FIRST(&inputs); TAILQ_REMOVE(&inputs, first, next); free(first->name); free(first); } if (conn) lldpctl_release(conn); if (root) commands_free(root); return rc; }
int main(int argc,char **argv) { ParseCtx* ctx; int i, j, ret = 0xbad; char* buf; banner(); rl_completion_entry_function = generator; if(argv[1] && !strcmp(argv[1],"--prototype")) show_proto = 1; commands = malloc( sizeof(char*) * 4 ); commands[command_index++] = strdup("quit"); commands[command_index++] = strdup("help"); commands[command_index++] = strdup("clear_ptr"); commands[command_index++] = strdup("prototype"); load_prototypes("./dynamic.xml"); specialPointer = malloc( BUFSIZ ); memset( specialPointer, 0, BUFSIZ ); while((buf = readline(">> "))) { rl_bind_key('\t',rl_complete); if( !buf[0] || buf[0] == '\n' || buf[0] == '#' ) continue; if(strstr(buf,"//")) *(char*)strstr(buf,"//") = 0; ctx = pcre_parse_string( buf ); if( !ctx ) continue; if(!strcmp( ctx->keyword, "clear_ptr" )) memset( specialPointer, 0, BUFSIZ ); else if(!strcmp( ctx->keyword, "help" )) printf( "clear_ptr()\t-\tClear the specialPointer.\n" "prototype([char*])\t-\tShow all the prototypes.\n" "help() \t-\tShow this help.\n" "quit() \t-\tQuit program.\n" ); else if(!strcmp( ctx->keyword, "prototype" )) { if(ctx->argc == 0 ) { printf("===== PROTOTYPE STARTS HERE =====\n"); for(i = 0;i < lib.sym_count;i++) { switch( lib.syms[i].proto.ret ) { case Int: printf("int "); break; case Char: printf("char "); break; case Ptr: printf("void* "); break; case Str: printf("char* "); break; case Db: printf("double "); break; default: printf("void "); break; } if( !lib.syms[i].proto.type_count ) printf("%s( );\n", lib.syms[i].name ); else { printf("%s(", lib.syms[i].name ); for(j = 0;j < lib.syms[i].proto.type_count;j++) { if(lib.syms[i].proto.types[j] == Integer) printf(" int" ); else if(lib.syms[i].proto.types[j] == Pointer) printf(" void*" ); else if(lib.syms[i].proto.types[j] == Double) printf(" double"); if( (j+1) != lib.syms[i].proto.type_count ) putchar(','); else printf(" );\n"); } } } printf("===== PROTOTYPE ENDS HERE =====\n"); } else { for(i = 0;i < lib.sym_count;i++) { if(!strcmp(lib.syms[i].name,ctx->args[0])) { switch( lib.syms[i].proto.ret ) { case Int: printf("int "); break; case Char: printf("char "); break; case Ptr: printf("void* "); break; case Str: printf("char* "); break; case Db: printf("double "); break; default: printf("void "); break; } if( !lib.syms[i].proto.type_count ) printf("%s( );\n", lib.syms[i].name ); else { printf("%s(", lib.syms[i].name ); for(j = 0;j < lib.syms[i].proto.type_count;j++) { if(lib.syms[i].proto.types[j] == Integer) printf(" int" ); else if(lib.syms[i].proto.types[j] == Pointer) printf(" void*" ); else if(lib.syms[i].proto.types[j] == Double) printf(" double"); if( (j+1) != lib.syms[i].proto.type_count ) putchar(','); else printf(" );\n"); } } } } } } else if(!strcmp( ctx->keyword, "quit" )) { free( ctx->args ); free( ctx ); exit( 0 ); } else { for(i = 0;i < lib.sym_count;i++) { if(!strcmp( lib.syms[i].name, ctx->keyword)) { ret = dlcall( lib.syms[i].pointer, ctx->args, ctx->argc, lib.syms[i].proto ); switch( lib.syms[i].proto.ret ) { case Int: printf("[return: %d]\n", ret ); break; case Ptr: printf("[return: %p]\n", (void*)ret ); break; case Str: printf("[return: %s]\n", (char*)ret ); break; case Char: printf("[return: \'%c\']\n", (char)ret ); break; case Db: printf("[return: %lf]\n", (double)ret ); break; default: printf("[return: %p]\n", (void*)ret ); break; } break; } } if( ret == 0xbad ) printf("Unknown command.\n"); } add_history( buf ); free( ctx->args ); free( ctx ); free( buf ); } return 0; }
/* * initial setup to set the readline library working */ void initialize_readline (int with_no_display_device) { //FIX ME /* Allow conditional parsing of the ~/.inputrc file. */ rl_readline_name = "fim"; //?? /* Tell the completer that we want a crack first. */ rl_attempted_completion_function = fim_completion; rl_completion_display_matches_hook=completion_display_matches_hook; if(with_no_display_device==0) { rl_catch_signals=0; rl_catch_sigwinch=0; rl_redisplay_function=redisplay; rl_event_hook=redisplay_hook; rl_pre_input_hook=redisplay_hook; } #if defined(FIM_WITH_LIBSDL) || defined(FIM_WITH_AALIB) if( g_fim_output_device=="sdl" /* only useful to bypass X11-windowed aalib (but sadly, breaks plain aalib input) */ /*|| g_fim_output_device=="aa" */ ) { rl_getc_function=rl_sdl_getc; rl_event_hook =rl_sdl_getc_hook; /* * FIXME : The following hack uses SDLK_UP, SDLK_DOWN, SDLK_LEFT, SDLK_RIGHT, all -0x100 .. * (/usr/include/SDL/SDL_keysym.h) * * Regard this as a problem. */ rl_bind_keyseq("\x11", rl_get_previous_history); // up rl_bind_keyseq("\x12", rl_get_next_history); // down rl_bind_keyseq("\x13", rl_forward_char); // right rl_bind_keyseq("\x14", rl_backward_char); // left } #endif //rl_completion_entry_function=NULL; /* * to do: * see rl_filename_quoting_function .. * */ //rl_inhibit_completion=1; //if set, TABs are read as normal characters rl_filename_quoting_desired=1; rl_filename_quote_characters="\""; //rl_reset_terminal("linux"); //rl_reset_terminal("vt100"); //rl_bind_key(0x09,fim_rl_end); //rl_bind_key(0x7F,fim_rl_end); //rl_bind_key(-1,fim_rl_end); //rl_bind_key('~',fim_rl_end); // .. //rl_bind_key('\t',rl_insert); //rl_bind_keyseq("g",fim_rl_end); //rl_set_prompt("$"); rl_bind_key(0x1B, rl_newline); //add by chris for ESC /* rl_voidfunc_t *rl_redisplay_function=redisplay; rl_hook_func_t *rl_event_hook=redisplay_hook; rl_hook_func_t *rl_pre_input_hook=redisplay_hook;*/ //std::cout << "readline initialized\n"; }
int main(int argc, char **argv) { FILE *fp = stdin; int c; if (argc == 1) { usage(0); } thiszone = gmt2local(0); while ((c = getopt(argc, argv, "acdf:HlnvxDFPphVrk?")) != -1) { switch (c) { case 'c': f_mode = MODE_STDIN; #ifdef HAVE_READLINE /* disable filename completion */ rl_bind_key('\t', rl_insert); #endif break; case 'f': f_mode = MODE_SCRIPT; if (strcmp(optarg, "-") == 0) { fp = stdin; } else if ((fp = fopen(optarg, "r")) == NULL) { err(1, "Can't open `%s'", optarg); } break; case 'D': f_mode = MODE_CMDDUMP; break; case 'F': f_mode = MODE_CMDFLUSH; break; case 'a': f_all = 1; break; case 'l': f_forever = 1; break; case 'n': f_notreally = 1; break; #ifdef __NetBSD__ case 'h': #endif case 'H': f_hexdump = 1; break; case 'x': f_mode = MODE_PROMISC; f_tflag++; break; case 'P': f_policy = 1; break; case 'p': f_withports = 1; break; case 'v': f_verbose = 1; break; case 'r': #ifdef HAVE_POLICY_FWD f_rfcmode = 1; #else rkwarn(); #endif break; case 'k': #ifdef HAVE_POLICY_FWD f_rfcmode = 0; #else rkwarn(); #endif break; case 'V': usage(1); break; #ifndef __NetBSD__ case 'h': #endif case '?': default: usage(0); } } argc -= optind; argv += optind; if (argc > 0) { while (argc--) { if (fileproc(*argv++) < 0) { err(1, "%s", argv[-1]); } } exit(0); } so = pfkey_open(); if (so < 0) { perror("pfkey_open"); exit(1); } switch (f_mode) { case MODE_CMDDUMP: sendkeyshort(f_policy ? SADB_X_SPDDUMP : SADB_DUMP); break; case MODE_CMDFLUSH: sendkeyshort(f_policy ? SADB_X_SPDFLUSH: SADB_FLUSH); break; case MODE_SCRIPT: if (get_supported() < 0) { errx(1, "%s", ipsec_strerror()); } if (parse(&fp)) exit(1); break; case MODE_STDIN: if (get_supported() < 0) { errx(1, "%s", ipsec_strerror()); } stdin_loop(); break; case MODE_PROMISC: promisc(); /* NOTREACHED */ default: usage(0); } exit(0); }
int main(int argc, char * argv[]){ char * line; pid_t c_pid; int i; char * cmd_argv[MAX_ARGS]; //NOTE: use this store your argv array, // don't go beyond MAX_ARGS char prompt[1024]; char * tok; //NOTE: This is useful for tokenizatoin //Need to ignore these signals for terminal control to work signal(SIGTTIN, SIG_IGN); signal(SIGTTOU, SIG_IGN); //for readline setup, don't edit! rl_bind_key('\t', rl_abort); while(1){ //fork/exec/wait loop //setup the prompt snprintf(prompt, 1024, "fg-shell (%d) #> ",last_pid); line = readline(prompt); //readline allocates a new line every time, need to free //read EOF, break if (line == NULL){ free(line); printf("\n"); break; } //read empty line, continue if (strcmp(line,"")==0){ free(line); continue; } //////////////////////////////////////////////////////////////// //*DO* EDIT BELOW // //FILL IN COMPLETED SOLUTION FROM LAB 5 // - parsing line using strtok into the cmd_argv array //TODO: See if user entered "fg" command // If so, try and start the background process and call my_wait() // If no last background process, report error to STDERR // Don't forget to give the foreground process control of the terminal //perform a foreground if ( strcmp(cmd_argv[0], "fg") == 0){ //TODO: FILL IN HERE free(line); //free line continue; //continue the shell after waiting } ////////////////////////////////////////////////////////////// //DO NOT EDIT BELOW // if ( (c_pid = fork()) == 0 ){ /* CHILD */ //set as it's own process group setpgrp(); execvp(cmd_argv[0],cmd_argv); perror("fg-shell"); //error _exit(2); //hard exit, don't want a fork bomb! }else if (c_pid > 0){ /* PARENT */ //give child its own process group if(setpgid(c_pid, c_pid) < 0){ perror("setpgrp"); } //give child the terminal control if( tcsetpgrp(0, c_pid) < 0){ perror("tcsetpgrp"); } //wait for a state change my_wait(); }else{ /* ERROR */ perror("fork failed"); _exit(2); } free(line); //free the current line } return 0; }
int main(int argc, char **argv) { int argval; bool quiet = false; bool done_license = false; int sockfd; uint32_t magic, needed; char *line = NULL; ssize_t len, size; char const *file = NULL; char const *name = "radiusd"; char *p, buffer[65536]; char const *input_file = NULL; FILE *inputfp = stdin; char const *output_file = NULL; char const *server = NULL; char const *radius_dir = RADIUS_DIR; char const *dict_dir = DICTDIR; char *commands[MAX_COMMANDS]; int num_commands = -1; #ifndef NDEBUG if (fr_fault_setup(getenv("PANIC_ACTION"), argv[0]) < 0) { fr_perror("radmin"); exit(EXIT_FAILURE); } #endif talloc_set_log_stderr(); outputfp = stdout; /* stdout is not a constant value... */ if ((progname = strrchr(argv[0], FR_DIR_SEP)) == NULL) { progname = argv[0]; } else { progname++; } while ((argval = getopt(argc, argv, "d:D:hi:e:Ef:n:o:qs:S")) != EOF) { switch(argval) { case 'd': if (file) { fprintf(stderr, "%s: -d and -f cannot be used together.\n", progname); exit(1); } if (server) { fprintf(stderr, "%s: -d and -s cannot be used together.\n", progname); exit(1); } radius_dir = optarg; break; case 'D': dict_dir = optarg; break; case 'e': num_commands++; /* starts at -1 */ if (num_commands >= MAX_COMMANDS) { fprintf(stderr, "%s: Too many '-e'\n", progname); exit(1); } commands[num_commands] = optarg; break; case 'E': echo = true; break; case 'f': radius_dir = NULL; file = optarg; break; default: case 'h': usage(0); break; case 'i': if (strcmp(optarg, "-") != 0) { input_file = optarg; } quiet = true; break; case 'n': name = optarg; break; case 'o': if (strcmp(optarg, "-") != 0) { output_file = optarg; } quiet = true; break; case 'q': quiet = true; break; case 's': if (file) { fprintf(stderr, "%s: -s and -f cannot be used together.\n", progname); usage(1); } radius_dir = NULL; server = optarg; break; case 'S': secret = NULL; break; } } /* * Mismatch between the binary and the libraries it depends on */ if (fr_check_lib_magic(RADIUSD_MAGIC_NUMBER) < 0) { fr_perror("radmin"); exit(1); } if (radius_dir) { int rcode; CONF_SECTION *cs, *subcs; file = NULL; /* MUST read it from the conffile now */ snprintf(buffer, sizeof(buffer), "%s/%s.conf", radius_dir, name); /* * Need to read in the dictionaries, else we may get * validation errors when we try and parse the config. */ if (dict_init(dict_dir, RADIUS_DICTIONARY) < 0) { fr_perror("radmin"); exit(64); } if (dict_read(radius_dir, RADIUS_DICTIONARY) == -1) { fr_perror("radmin"); exit(64); } cs = cf_file_read(buffer); if (!cs) { fprintf(stderr, "%s: Errors reading or parsing %s\n", progname, buffer); usage(1); } subcs = NULL; while ((subcs = cf_subsection_find_next(cs, subcs, "listen")) != NULL) { char const *value; CONF_PAIR *cp = cf_pair_find(subcs, "type"); if (!cp) continue; value = cf_pair_value(cp); if (!value) continue; if (strcmp(value, "control") != 0) continue; /* * Now find the socket name (sigh) */ rcode = cf_item_parse(subcs, "socket", FR_ITEM_POINTER(PW_TYPE_STRING, &file), NULL); if (rcode < 0) { fprintf(stderr, "%s: Failed parsing listen section\n", progname); exit(1); } if (!file) { fprintf(stderr, "%s: No path given for socket\n", progname); usage(1); } break; } if (!file) { fprintf(stderr, "%s: Could not find control socket in %s\n", progname, buffer); exit(1); } } if (input_file) { inputfp = fopen(input_file, "r"); if (!inputfp) { fprintf(stderr, "%s: Failed opening %s: %s\n", progname, input_file, strerror(errno)); exit(1); } } if (output_file) { outputfp = fopen(output_file, "w"); if (!outputfp) { fprintf(stderr, "%s: Failed creating %s: %s\n", progname, output_file, strerror(errno)); exit(1); } } if (!file && !server) { fprintf(stderr, "%s: Must use one of '-d' or '-f' or '-s'\n", progname); exit(1); } /* * Check if stdin is a TTY only if input is from stdin */ if (input_file && !quiet && !isatty(STDIN_FILENO)) quiet = true; #ifdef USE_READLINE if (!quiet) { #ifdef USE_READLINE_HISTORY using_history(); #endif rl_bind_key('\t', rl_insert); } #endif reconnect: if (file) { /* * FIXME: Get destination from command line, if possible? */ sockfd = fr_domain_socket(file); if (sockfd < 0) { exit(1); } } else { sockfd = client_socket(server); } /* * Read initial magic && version information. */ for (size = 0; size < 8; size += len) { len = read(sockfd, buffer + size, 8 - size); if (len < 0) { fprintf(stderr, "%s: Error reading initial data from socket: %s\n", progname, strerror(errno)); exit(1); } } memcpy(&magic, buffer, 4); magic = ntohl(magic); if (magic != 0xf7eead15) { fprintf(stderr, "%s: Socket %s is not FreeRADIUS administration socket\n", progname, file); exit(1); } memcpy(&magic, buffer + 4, 4); magic = ntohl(magic); if (!server) { needed = 1; } else { needed = 2; } if (magic != needed) { fprintf(stderr, "%s: Socket version mismatch: Need %d, got %d\n", progname, needed, magic); exit(1); } if (server && secret) do_challenge(sockfd); /* * Run one command. */ if (num_commands >= 0) { int i; for (i = 0; i <= num_commands; i++) { size = run_command(sockfd, commands[i], buffer, sizeof(buffer)); if (size < 0) exit(1); if (buffer[0]) { fputs(buffer, outputfp); fprintf(outputfp, "\n"); fflush(outputfp); } } exit(0); } if (!done_license && !quiet) { printf("%s - FreeRADIUS Server administration tool.\n", radmin_version); printf("Copyright (C) 2008-2014 The FreeRADIUS server project and contributors.\n"); printf("There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A\n"); printf("PARTICULAR PURPOSE.\n"); printf("You may redistribute copies of FreeRADIUS under the terms of the\n"); printf("GNU General Public License v2.\n"); done_license = true; } /* * FIXME: Do login? */ while (1) { #ifndef USE_READLINE if (!quiet) { printf("radmin> "); fflush(stdout); } #else if (!quiet) { line = readline("radmin> "); if (!line) break; if (!*line) { free(line); continue; } #ifdef USE_READLINE_HISTORY add_history(line); #endif } else /* quiet, or no readline */ #endif { line = fgets(buffer, sizeof(buffer), inputfp); if (!line) break; p = strchr(buffer, '\n'); if (!p) { fprintf(stderr, "%s: Input line too long\n", progname); exit(1); } *p = '\0'; /* * Strip off leading spaces. */ for (p = line; *p != '\0'; p++) { if ((p[0] == ' ') || (p[0] == '\t')) { line = p + 1; continue; } if (p[0] == '#') { line = NULL; break; } break; } /* * Comments: keep going. */ if (!line) continue; /* * Strip off CR / LF */ for (p = line; *p != '\0'; p++) { if ((p[0] == '\r') || (p[0] == '\n')) { p[0] = '\0'; break; } } } if (strcmp(line, "reconnect") == 0) { close(sockfd); line = NULL; goto reconnect; } if (memcmp(line, "secret ", 7) == 0) { if (!secret) { secret = line + 7; do_challenge(sockfd); } line = NULL; continue; } /* * Exit, done, etc. */ if ((strcmp(line, "exit") == 0) || (strcmp(line, "quit") == 0)) { break; } if (server && !secret) { fprintf(stderr, "ERROR: You must enter 'secret <SECRET>' before running any commands\n"); line = NULL; continue; } size = run_command(sockfd, line, buffer, sizeof(buffer)); if (size <= 0) break; /* error, or clean exit */ if (size == 1) continue; /* no output. */ fputs(buffer, outputfp); fflush(outputfp); fprintf(outputfp, "\n"); } fprintf(outputfp, "\n"); return 0; }
void * getTextInput(void *data) { static const char me[]="getTextInput"; char *buff=NULL, _buff[BUFF_SIZE+1], *cmd, *args, prompt[BUFF_SIZE+1]; rl_bind_key ('\t', rl_insert); printf("Type \"help\" for list of supported commands\n"); while (1) { if (-1 == connfd) { fprintf(stderr, "%s: server connection closed; we are done\n", me); return NULL; } sprintf(prompt, "imc(%s)> ", myself); buff = readline(prompt); if (!buff) { fprintf(stderr, "\nGot EOF; quitting\n"); exit(0); } if (strlen(buff)) { add_history(buff); } /* immediately copy buff to _buff on stack, and then free buff, so there's no memory leak even when the other thread exit()s on us */ if (strlen(buff) < BUFF_SIZE) { strcpy(_buff, buff); } else { memcpy(_buff, buff, BUFF_SIZE); _buff[BUFF_SIZE] = '\0'; } if (buff) free(buff); cmd = _buff; cmd += strspn(cmd, WHITESPACE); if (!strlen(cmd)) { continue; } args = strchr(cmd, ' '); if (args) { *args = '\0'; /* \0-terminates cmd */ args += 1; } if (!strcmp(cmd, "register") || !strcmp(cmd, "reg")) { processOp(IMP_OP_REGISTER, args); } else if (!strcmp(cmd, "login")) { processOp(IMP_OP_LOGIN, args); } else if (!strcmp(cmd, "logout")) { processOp(IMP_OP_LOGOUT, args); } else if (!strcmp(cmd, "friend_request") || !strcmp(cmd, "req")) { processOp(IMP_OP_FRIEND_REQUEST, args); } else if (!strcmp(cmd, "friend_remove") || !strcmp(cmd, "rm")) { processOp(IMP_OP_FRIEND_REMOVE, args); } else if (!strcmp(cmd, "friend_list") || !strcmp(cmd, "list")) { processOp(IMP_OP_FRIEND_LIST, args); } else if (!strcmp(cmd, "im")) { processOp(IMP_OP_IM, args); } else if (!strcmp(cmd, "raw")) { if (connfd > 0 && args) { char *rawnl = (char*)calloc(2+strlen(args), sizeof(char)); assert(rawnl); sprintf(rawnl, "%s\n", args); /* turn tabs into newlines, so that we can test server's ability to respond to multiple protocol messages at once */ size_t ll=strlen(args), ii; for (ii=0; ii<ll; ii++) { if ('\t' == rawnl[ii]) { rawnl[ii] = '\n'; } } if (0 > send(connfd, rawnl, strlen(rawnl), 0)) { fprintf(stderr, "\n%s ERROR: send() to server failed: %s\n", myself, strerror(errno)); } free(rawnl); } } else if (!strcmp(cmd, "sleep")) { int secs; if (1 != sscanf(args, "%d", &secs)) { fprintf(stderr, "%s: couldn't parse \"%s\" as integer\n", me, args); } else { printf("sleep(%d) ... \n", secs); sleep(secs); } } else if (!strcmp(cmd, "quit") || !strcmp(cmd, "q")) { printf("quitting\n"); /* have to exit, rather than return; so that the whole process (and the other thread) come down too */ exit(0); } else if (!strcmp(cmd, "help") || !strcmp(cmd, "?") || !strcmp(cmd, "h")) { printf("Commands supported:\n"); printf("\t \"register <user>\" or \"reg <user>\"\n"); printf("\t \"login <user>\"\n"); printf("\t \"logout\"\n"); printf("\t \"friend_request <user>\" or \"req <user>\"\n"); printf("\t \"friend_remove <user>\" or \"rm <user>\"\n"); printf("\t \"friend_list\" or \"list\"\n"); printf("\t \"im <user> <msg>\"\n"); printf("\t \"raw <string>\": send bare string to server\n"); printf("\t \"sleep <t>\"\n"); printf("\t \"quit\" or \"q\"\n"); } else { fprintf(stderr, "couldn't parse command \"%s%s%s\"\n", cmd, args ? " " : "", args ? args : ""); } } return NULL; }
int main(int argc,char *argv[]) { int c; int port=-1; int len=0; char *ptr; char bfr[8192]; while((c=getopt(argc,argv,"p:"))!=-1)switch(c) { case 'p': port=atoi(optarg); break; } if(port<1||port>65535) { fprintf(stderr,"Illegal port\n"); return 1; } p[0].fd=0; p[0].events=POLLIN; if((p[1].fd=mklisten(port))==-1)return 1; p[1].events=POLLIN; p[2].fd=-1; p[2].events=POLLIN; rl_bind_key ('\t',rl_insert); rl_callback_handler_install("> ",docmd); while(running) { p[2].revents=0; if(poll(p,p[2].fd==-1?2:3,-1)<=0)continue; if(p[0].revents&POLLHUP)break; if(p[0].revents&POLLIN)rl_callback_read_char(); if(p[1].revents&POLLIN) if((c=accept(p[1].fd,NULL,NULL))!=-1) { if(p[2].fd!=-1)close(p[2].fd); p[2].revents=0; p[2].fd=c; len=0; c=1; ioctl(p[2].fd,FIONBIO,&c); #if defined(TCP_KEEPCNT) && defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL) c=2; setsockopt(p[2].fd,IPPROTO_TCP,TCP_KEEPCNT, &c,sizeof(c)); c=90; setsockopt(p[2].fd,IPPROTO_TCP,TCP_KEEPIDLE, &c,sizeof(c)); c=90; setsockopt(p[2].fd,IPPROTO_TCP,TCP_KEEPINTVL, &c,sizeof(c)); c=1; setsockopt(p[2].fd,SOL_SOCKET,SO_KEEPALIVE, &c,sizeof(c)); #endif } if(p[2].revents&POLLHUP) { close(p[2].fd); p[2].fd=-1; } else if(p[2].revents&POLLIN) { if((c=read(p[2].fd,bfr+len,sizeof(bfr)-len))<=0) { close(p[2].fd); p[2].fd=-1; } else { len+=c; for(ptr=bfr,c=0;c<len;c++)if(bfr[c]=='$') { bfr[c]=0; printf("\n%s$",ptr); ptr=bfr+c+1; } if(ptr!=bfr) { printf("\n"); rl_on_new_line(); rl_redisplay(); if(ptr<bfr+len) { len=bfr+len-ptr; memmove(bfr,ptr,len); } else len=0; } if(len==sizeof(bfr)) { close(p[2].fd); p[2].fd=-1; } } } } close(p[1].fd); if(p[2].fd!=-1) { close(p[2].fd); p[2].fd=-1; } rl_set_prompt(""); rl_replace_line("",0); rl_redisplay(); rl_callback_handler_remove(); return 0; }
static void setup_readline(readlinestate *mod_state) { #ifdef SAVE_LOCALE char *saved_locale = strdup(setlocale(LC_CTYPE, NULL)); if (!saved_locale) Py_FatalError("not enough memory to save locale"); #endif #ifdef __APPLE__ /* the libedit readline emulation resets key bindings etc * when calling rl_initialize. So call it upfront */ if (using_libedit_emulation) rl_initialize(); /* Detect if libedit's readline emulation uses 0-based * indexing or 1-based indexing. */ add_history("1"); if (history_get(1) == NULL) { libedit_history_start = 0; } else { libedit_history_start = 1; } clear_history(); #endif /* __APPLE__ */ using_history(); rl_readline_name = "python"; /* Force rebind of TAB to insert-tab */ rl_bind_key('\t', rl_insert); /* Bind both ESC-TAB and ESC-ESC to the completion function */ rl_bind_key_in_map ('\t', rl_complete, emacs_meta_keymap); rl_bind_key_in_map ('\033', rl_complete, emacs_meta_keymap); /* Set our hook functions */ rl_startup_hook = on_startup_hook; #ifdef HAVE_RL_PRE_INPUT_HOOK rl_pre_input_hook = on_pre_input_hook; #endif /* Set our completion function */ rl_attempted_completion_function = flex_complete; /* Set Python word break characters */ completer_word_break_characters = rl_completer_word_break_characters = strdup(" \t\n`~!@#$%^&*()-=+[{]}\\|;:'\",<>/?"); /* All nonalphanums except '.' */ mod_state->begidx = PyLong_FromLong(0L); mod_state->endidx = PyLong_FromLong(0L); #ifndef __APPLE__ if (!isatty(STDOUT_FILENO)) { /* Issue #19884: stdout is no a terminal. Disable meta modifier keys to not write the ANSI sequence "\033[1034h" into stdout. On terminals supporting 8 bit characters like TERM=xterm-256color (which is now the default Fedora since Fedora 18), the meta key is used to enable support of 8 bit characters (ANSI sequence "\033[1034h"). With libedit, this call makes readline() crash. */ rl_variable_bind ("enable-meta-key", "off"); } #endif /* Initialize (allows .inputrc to override) * * XXX: A bug in the readline-2.2 library causes a memory leak * inside this function. Nothing we can do about it. */ #ifdef __APPLE__ if (using_libedit_emulation) rl_read_init_file(NULL); else #endif /* __APPLE__ */ rl_initialize(); RESTORE_LOCALE(saved_locale) }
int main(int argc, char *argv[]) { /* We always require a file, will guess a nick if none provided.*/ if(argc < 2) { fprintf(stderr, "%s v%s - a small chat system for multiple users\n", argv[0], VERSION); fprintf(stderr, "usage: %s file [nick]\n", argv[0]); return 1; } if(argv[2] == NULL) { /* If no nick is provided, pick based on the username. */ getlogin_r(nick, MAX_NICK_SIZE); } else { /* Copy from argv and make sure its null-terminated.*/ strncpy(nick, argv[2], MAX_NICK_SIZE); nick[MAX_NICK_SIZE-1] = '\0'; } /* Open the file. Always write at the end. */ ctrl = fopen(argv[1], "a+"); if(ctrl == NULL) { fprintf(stderr, "Unable to open %s!\n", argv[1]); return 1; } /* We don't want to see past messages, as they could be loooooong.*/ fseek(ctrl, 0L, SEEK_END); /* This is now our "last read" position. */ last_read_pos = ftell(ctrl); /* Tell readline to let us know when the user hits enter. */ rl_bind_key(RETURN, handle_enter); /* Setup the fake handler for when readline thinks we're done. */ rl_callback_handler_install(PROMPT, handle_line_fake); /* Done with setup! Now let everyone know the user has arrived. */ write_status("joined"); /* Until we decide to quit, tell readline to grab characters if they're available. */ while(cont) { get_input(); usleep(10000); check_msgs(); usleep(10000); } /* We're quitting now. Say goodbye. */ write_status("left"); /* Clean up for readline now */ rl_unbind_key(RETURN); rl_callback_handler_remove(); /* Being a good citizen. Closing file handles. */ fclose(ctrl); /* Clean up screen. */ rl_set_prompt(""); rl_redisplay(); return 0; }
/// %Thread start void CliRunnable::run() { ///- Display the list of available CLI functions then beep //sLog->outString(""); #if PLATFORM != PLATFORM_WINDOWS rl_attempted_completion_function = cli_completion; rl_event_hook = cli_hook_func; #endif if (sConfig->GetBoolDefault("BeepAtStart", true)) printf("\a"); // \a = Alert // print this here the first time // later it will be printed after command queue updates printf("TrilliumEMU>"); ///- As long as the World is running (no Trillium::m_stopEvent), get the command line and handle it while (!World::IsStopped()) { fflush(stdout); char *command_str ; // = fgets(commandbuf, sizeof(commandbuf), stdin); #if PLATFORM == PLATFORM_WINDOWS char commandbuf[256]; command_str = fgets(commandbuf, sizeof(commandbuf), stdin); #else command_str = readline("TrilliumEMU>"); rl_bind_key('\t', rl_complete); #endif if (command_str != NULL) { for (int x=0; command_str[x]; x++) if (command_str[x]=='\r'||command_str[x]=='\n') { command_str[x]=0; break; } if (!*command_str) { #if PLATFORM == PLATFORM_WINDOWS printf("TrilliumEMU>"); #endif continue; } std::string command; if (!consoleToUtf8(command_str, command)) // convert from console encoding to utf8 { #if PLATFORM == PLATFORM_WINDOWS printf("TrilliumEMU>"); #endif continue; } fflush(stdout); sWorld->QueueCliCommand(new CliCommandHolder(NULL, command.c_str(), &utf8print, &commandFinished)); #if PLATFORM != PLATFORM_WINDOWS add_history(command.c_str()); #endif } else if (feof(stdin)) { World::StopNow(SHUTDOWN_EXIT_CODE); } } }
/// %Thread start void CliThread() { ///- Display the list of available CLI functions then beep //TC_LOG_INFO("server.worldserver", ""); #if TRINITY_PLATFORM != TRINITY_PLATFORM_WINDOWS rl_attempted_completion_function = cli_completion; rl_event_hook = cli_hook_func; #endif if (sConfigMgr->GetBoolDefault("BeepAtStart", true)) printf("\a"); // \a = Alert // print this here the first time // later it will be printed after command queue updates printf("TC>"); ///- As long as the World is running (no World::m_stopEvent), get the command line and handle it while (!World::IsStopped()) { fflush(stdout); std::string command; #if TRINITY_PLATFORM == TRINITY_PLATFORM_WINDOWS wchar_t commandbuf[256]; if (fgetws(commandbuf, sizeof(commandbuf), stdin)) { if (!WStrToUtf8(commandbuf, wcslen(commandbuf), command)) { printf("TC>"); continue; } } #else char* command_str = readline("TC>"); rl_bind_key('\t', rl_complete); if (command_str != nullptr) { command = command_str; free(command_str); } #endif if (!command.empty()) { std::size_t nextLineIndex = command.find_first_of("\r\n"); if (nextLineIndex != std::string::npos) { if (nextLineIndex == 0) { #if TRINITY_PLATFORM == TRINITY_PLATFORM_WINDOWS printf("TC>"); #endif continue; } command.erase(nextLineIndex); } fflush(stdout); sWorld->QueueCliCommand(new CliCommandHolder(nullptr, command.c_str(), &utf8print, &commandFinished)); #if TRINITY_PLATFORM != TRINITY_PLATFORM_WINDOWS add_history(command.c_str()); #endif } else if (feof(stdin)) { World::StopNow(SHUTDOWN_EXIT_CODE); } } }
/// %Thread start void CliRunnable::run() { ///- Init new SQL thread for the world database (one connection call enough) WorldDatabase.ThreadStart(); // let thread do safe mySQL requests char commandbuf[256]; bool canflush = true; ///- Display the list of available CLI functions then beep sLog.outString(""); #if PLATFORM != WINDOWS rl_attempted_completion_function = cli_completion; #endif if(sConfig.GetBoolDefault("BeepAtStart", true)) printf("\a"); // \a = Alert // print this here the first time // later it will be printed after command queue updates printf("TC>"); ///- As long as the World is running (no World::m_stopEvent), get the command line and handle it while (!World::IsStopped()) { fflush(stdout); char *command_str ; // = fgets(commandbuf,sizeof(commandbuf),stdin); #if PLATFORM == WINDOWS command_str = fgets(commandbuf,sizeof(commandbuf),stdin); #else command_str = readline("TC>"); rl_bind_key('\t',rl_complete); #endif if (command_str != NULL) { for (int x=0; command_str[x]; x++) if(command_str[x]=='\r'||command_str[x]=='\n') { command_str[x]=0; break; } if(!*command_str) { #if PLATFORM == WINDOWS printf("TC>"); #endif continue; } std::string command; if(!consoleToUtf8(command_str,command)) // convert from console encoding to utf8 { #if PLATFORM == WINDOWS printf("TC>"); #endif continue; } fflush(stdout); sWorld.QueueCliCommand(&utf8print,command.c_str()); #if PLATFORM != WINDOWS add_history(command.c_str()); #endif } else if (feof(stdin)) { World::StopNow(SHUTDOWN_EXIT_CODE); } } ///- End the database thread WorldDatabase.ThreadEnd(); // free mySQL thread resources }
/* Createing and Destroying a librline context. {{{*/ struct rline *rline_initialize(int slavefd, command_cb * command, completion_cb * completion, const char *TERM) { struct rline *rline = (struct rline *) malloc(sizeof (struct rline)); static char word_break_chars[] = " \t\n!@#$%^&*()+=|~`}{[]\"';:?/>.<,-"; if (!rline) return NULL; /* Initialize each member variable */ rline->input = NULL; rline->output = NULL; rline->input = fdopen(slavefd, "r"); if (!rline->input) { rline_shutdown(rline); return NULL; } rline->output = fdopen(slavefd, "w"); if (!rline->output) { rline_shutdown(rline); return NULL; } rline->tab_completion = completion; rline->rline_rl_last_func = NULL; rline->rline_rl_completion_query_items = rl_completion_query_items; rl_readline_name = "cgdb"; rl_instream = rline->input; rl_outstream = rline->output; /* Tell readline not to put the initial prompt */ rl_already_prompted = 1; /* Tell readline not to catch signals */ rl_catch_signals = 0; rl_catch_sigwinch = 0; /* Tell readline what the prompt is if it needs to put it back */ rl_callback_handler_install("(gdb) ", command); rl_bind_key('\t', completion); /* Set the terminal type to dumb so the output of readline can be * understood by tgdb */ if (rl_reset_terminal(TERM) == -1) { rline_shutdown(rline); return NULL; } /* For some reason, readline can not deprep the terminal. * However, it doesn't matter because no other application is working on * the terminal besides readline */ rl_deprep_term_function = custom_deprep_term_function; /* These variables are here to make sure readline doesn't * attempt to query the user to determine if it wants more input. */ rl_completion_query_items = -1; rl_variable_bind("page-completions", "0"); rl_completer_word_break_characters = word_break_chars; rl_completer_quote_characters = "'"; return rline; }