int main(int argc, char** argv) { /* Create some parsers */ mpc_parser_t *Number = mpc_new("number"); mpc_parser_t *Symbol = mpc_new("symbol"); mpc_parser_t *Sexpr = mpc_new("sexpr"); mpc_parser_t *Qexpr = mpc_new("qexpr"); mpc_parser_t *Expr = mpc_new("expr"); mpc_parser_t *Lispy = mpc_new("lispy"); /* Define them with the following language */ mpca_lang(MPCA_LANG_DEFAULT, "" "number : /-?[0-9]+/ ;" "symbol : '+' | '-' | '*' | '/' | '%' | '^' " " | \"len\" | \"cons\"" " | \"list\" | \"head\" | \"tail\" | \"join\" | \"eval\" ;" "sexpr : '(' <expr>* ')' ;" "qexpr : '{' <expr>* '}' ;" "expr : <number> | <symbol> | <sexpr> | <qexpr> ;" "lispy : /^/ <expr>* /$/ ; " "", Number, Symbol, Sexpr, Qexpr, Expr, Lispy); /* Print Version and Exit Information */ puts("Lispy Version 0.0.0.0.1"); puts("Press Ctrl+c or Ctrl+d to Exit\n"); /* In a never ending loop */ while (1) { /* Output our prompt and get input */ char* input = readline("lispy> "); if (NULL == input) { /* quit with Ctrl-d */ break; } /* Add input to history */ add_history(input); /* Try to parse the user input */ mpc_result_t r; if (mpc_parse("<stdin>", input, Lispy, &r)) { /* On success evaluate AST */ lval *result = lval_eval(lval_read(r.output)); lval_println(result); lval_del(result); mpc_ast_delete(r.output); } else { mpc_err_print(r.error); mpc_err_delete(r.error); } /* Free retrieved input */ free(input); } /* Undefine and delete the parsers */ mpc_cleanup(6, Number, Symbol, Sexpr, Qexpr, Expr, Lispy); return 0; }
/* * Command parser. */ void cmdscanner (int top) { struct cmd *c; int l; if (!top) putchar ('\n'); for (;;) { if (line) { free (line); line = NULL; } line = readline (prompt); if (!line) quit (0, 0); l = strlen (line); if (l >= MAXLINE) { printf ("Line too long.\n"); break; } #if HAVE_LIBHISTORY if (line && *line) add_history (line); #endif if (l == 0) break; makeargv (); if (margc == 0) continue; c = getcmd (margv[0]); if (c == (struct cmd *) -1) { printf ("?Ambiguous command\n"); continue; } if (c == 0) { printf ("?Invalid command\n"); continue; } if (c->c_conn && !connected) { printf ("Not connected.\n"); continue; } (*c->c_handler) (margc, margv); if (bell && c->c_bell) putchar ('\007'); if (c->c_handler != help) break; } signal (SIGINT, intr); signal (SIGPIPE, lostpeer); }
char * ntp_readline( int * pcount ) { char * line; #ifdef LE_NONE char line_buf[MAXEDITLINE]; #endif #ifdef LE_EDITLINE const char * cline; #endif if (!ntp_readline_initted) return NULL; *pcount = 0; #ifdef LE_READLINE line = readline(lineedit_prompt ? lineedit_prompt : ""); if (NULL != line) { if (*line) { add_history(line); } *pcount = strlen(line); } #endif /* LE_READLINE */ #ifdef LE_EDITLINE cline = el_gets(ntp_el, pcount); if (NULL != cline) { history(ntp_hist, &hev, H_ENTER, cline); line = estrdup(cline); } else if (*pcount == -1) { line = NULL; } else { line = estrdup(""); } #endif /* LE_EDITLINE */ #ifdef LE_NONE /* stone hammers */ if (lineedit_prompt) { # ifdef VMS /* * work around problem mixing * stdout & stderr */ fputs("", stdout); # endif /* VMS */ fputs(lineedit_prompt, stderr); fflush(stderr); } line = fgets(line_buf, sizeof(line_buf), stdin); if (NULL != line && *line) { *pcount = (int)strlen(line); /* cannot overflow here */ line = estrdup(line); } else line = NULL; #endif /* LE_NONE */ if (!line) /* EOF */ fputs("\n", stderr); return line; }
int main(int argc, char *argv[]) { FUNCTION f, *fp; LHASH_OF(FUNCTION) *prog = NULL; char **copied_argv = NULL; char *p, *pname; char buf[1024]; const char *prompt; ARGS arg; int first, n, i, ret = 0; arg.argv = NULL; arg.size = 0; /* Set up some of the environment. */ default_config_file = make_config_name(); bio_in = dup_bio_in(FORMAT_TEXT); bio_out = dup_bio_out(FORMAT_TEXT); bio_err = dup_bio_err(FORMAT_TEXT); #if defined(OPENSSL_SYS_VMS) && defined(__DECC) copied_argv = argv = copy_argv(&argc, argv); #elif defined(_WIN32) /* * Replace argv[] with UTF-8 encoded strings. */ win32_utf8argv(&argc, &argv); #endif p = getenv("OPENSSL_DEBUG_MEMORY"); if (p != NULL && strcmp(p, "on") == 0) CRYPTO_set_mem_debug(1); CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON); if (getenv("OPENSSL_FIPS")) { BIO_printf(bio_err, "FIPS mode not supported.\n"); return 1; } if (!apps_startup()) { BIO_printf(bio_err, "FATAL: Startup failure (dev note: apps_startup() failed)\n"); ERR_print_errors(bio_err); ret = 1; goto end; } prog = prog_init(); pname = opt_progname(argv[0]); /* first check the program name */ f.name = pname; fp = lh_FUNCTION_retrieve(prog, &f); if (fp != NULL) { argv[0] = pname; ret = fp->func(argc, argv); goto end; } /* If there is stuff on the command line, run with that. */ if (argc != 1) { argc--; argv++; ret = do_cmd(prog, argc, argv); if (ret < 0) ret = 0; goto end; } /* ok, lets enter interactive mode */ for (;;) { ret = 0; /* Read a line, continue reading if line ends with \ */ for (p = buf, n = sizeof buf, i = 0, first = 1; n > 0; first = 0) { prompt = first ? "OpenSSL> " : "> "; p[0] = '\0'; #ifndef READLINE fputs(prompt, stdout); fflush(stdout); if (!fgets(p, n, stdin)) goto end; if (p[0] == '\0') goto end; i = strlen(p); if (i <= 1) break; if (p[i - 2] != '\\') break; i -= 2; p += i; n -= i; #else { extern char *readline(const char *); extern void add_history(const char *cp); char *text; text = readline(prompt); if (text == NULL) goto end; i = strlen(text); if (i == 0 || i > n) break; if (text[i - 1] != '\\') { p += strlen(strcpy(p, text)); free(text); add_history(buf); break; } text[i - 1] = '\0'; p += strlen(strcpy(p, text)); free(text); n -= i; } #endif } if (!chopup_args(&arg, buf)) { BIO_printf(bio_err, "Can't parse (no memory?)\n"); break; } ret = do_cmd(prog, arg.argc, arg.argv); if (ret == EXIT_THE_PROGRAM) { ret = 0; goto end; } if (ret != 0) BIO_printf(bio_err, "error in %s\n", arg.argv[0]); (void)BIO_flush(bio_out); (void)BIO_flush(bio_err); } ret = 1; end: OPENSSL_free(copied_argv); OPENSSL_free(default_config_file); lh_FUNCTION_free(prog); OPENSSL_free(arg.argv); app_RAND_write(); BIO_free(bio_in); BIO_free_all(bio_out); apps_shutdown(); #ifndef OPENSSL_NO_CRYPTO_MDEBUG if (CRYPTO_mem_leaks(bio_err) <= 0) ret = 1; #endif BIO_free(bio_err); EXIT(ret); }
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; }
int cexp_main1(int argc, char **argv, void (*callback)(int argc, char **argv, CexpContext ctx)) { CexpContextRec context; /* the public parts of this instance's context */ CexpContext myContext; char *line=0, *prompt=0, *tmp; char *symfile=0, *script=0; int rval=CEXP_MAIN_INVAL_ARG, quiet=0; MyGetOptCtxtRec oc={0}; /* must be initialized */ int opt; #ifdef HAVE_TECLA #define rl_context context.gl #else #define rl_context 0 #endif char optstr[]={ 'h', 'v', 's',':', 'a',':', 'p',':', #ifdef YYDEBUG 'd', #endif 'q', '\0' }; context.prompt = 0; context.parser = 0; while ((opt=mygetopt_r(argc, argv, optstr,&oc))>=0) { switch (opt) { default: fprintf(stderr,"Unknown Option %c\n",opt); case 'h': usage(argv[0]); case 'v': version(argv[0]); return 0; #ifdef YYDEBUG case 'd': cexpdebug=1; break; #endif case 'q': quiet=1; break; case 's': symfile=oc.optarg; break; case 'a': cexpBuiltinCpuArch = oc.optarg; break; case 'p': free(context.prompt); context.prompt = strdup(oc.optarg); break; } } if (argc>oc.optind) script=argv[oc.optind]; /* make sure vital code is initialized */ { static int initialized=0; cexpContextRunOnce(&initialized, cexpInit); } if (!cexpSystemModule) { if (!symfile) { /* try to find a builtin table */ if ( !cexpModuleLoad(0,0) ) fprintf(stderr,"No builtin symbol table -- need a symbol file argument\n"); } else if (!cexpModuleLoad(symfile,"SYSTEM")) fprintf(stderr,"Unable to load system symbol table\n"); if (!cexpSystemModule) { usage(argv[0]); return CEXP_MAIN_NO_SYMS; } } #ifdef USE_MDBG mdbgInit(); #endif /* initialize the public context */ context.next=0; #ifdef HAVE_BFD_DISASSEMBLER { extern void cexpDisassemblerInit(); cexpDisassemblerInit(&context.dinfo, stdout); } #endif cexpContextGetCurrent(&myContext); if (!myContext) { /* topmost frame */ #ifdef HAVE_TECLA context.gl = new_GetLine(200,2000); if (!context.gl) { fprintf(stderr,"Unable to create line editor\n"); return CEXP_MAIN_NO_MEM; } /* mute warnings about being unable to * read ~/.teclarc */ gl_configure_getline(context.gl,0,0,0); #endif /* register first instance running in this thread's context; */ cexpContextRegister(); if (!quiet) hello(); } else { #ifdef HAVE_TECLA /* re-use caller's line editor */ context.gl = myContext->gl; #endif } /* push our frame to the top */ context.next = myContext; myContext = &context; cexpContextSetCurrent(myContext); /* See if there is an ancestor with a local prompt * and inherit */ if ( !context.prompt && context.next && context.next->prompt ) context.prompt = strdup(context.next->prompt); do { if (!(context.parser=cexpCreateParserCtx(quiet ? 0 : stdout))) { fprintf(stderr,"Unable to create parser context\n"); usage(argv[0]); rval = CEXP_MAIN_NO_MEM; goto cleanup; } #ifdef HAVE_TECLA { CPL_MATCH_FN(cexpSymComplete); gl_customize_completion(context.gl, context.parser, cexpSymComplete); } #endif if (cexpSigHandlerInstaller) cexpSigHandlerInstaller(sighandler); if (!(rval=setjmp(context.jbuf))) { /* call them back to pass the jmpbuf */ if (callback) callback(argc, argv, &context); if (script) { if ( (rval = process_script(context.parser, script, quiet)) ) goto cleanup; } else { while ( (line=readline_r( checkPrompt( &context, &prompt, argc > 0 ? argv[0] : "Cexp" ), rl_context)) ) { /* skip empty lines */ if (*line) { if ( '<' == *(tmp=skipsp(line)) ) { process_script(context.parser,tmp+1,quiet); } else { /* interactively process this line */ cexpResetParserCtx(context.parser,line); cexpparse((void*)context.parser); add_history(line); } } free(line); line=0; } } } else { fprintf(stderr,"\nOops, exception caught\n"); /* setjmp passes 0: first time * 1: longjmp(buf,0) or longjmp(buf,1) * other: longjmp(buf,other) */ rval = (rval<2 ? -1 : CEXP_MAIN_KILLED); } cleanup: script=0; /* become interactive if script is killed */ free(line); line=0; free(prompt); prompt=0; cexpFreeParserCtx(context.parser); context.parser=0; } while (-1==rval); free(context.prompt); /* pop our stack context from the chained list anchored * at the running thread */ myContext = myContext->next; cexpContextSetCurrent(myContext); if ( ! myContext ) { /* we'll exit the topmost instance */ #ifdef HAVE_TECLA del_GetLine(context.gl); #endif cexpContextUnregister(); } return rval; }
/** * testLongSignals * To run this code : * cd storage/ndb/src/kernel * make testLongSignals * ./testLongSignals <connectstring> * */ int main(int argc, char** argv) { ndb_init(); srand(NdbTick_CurrentMillisecond()); #if 0 for(int i = 0; i<100; i++) ndbout_c("randRange(0, 3) = %d", randRange(0, 3)); return 0; #endif if (argc != 2) { ndbout << "No connectstring given, usage : " << argv[0] << " <connectstring>" << endl; return -1; } Ndb_cluster_connection con(argv[1]); ndbout << "Connecting..."; if (con.connect(12,5,1) != 0) { ndbout << "Unable to connect to management server." << endl; return -1; } if (con.wait_until_ready(30,0) < 0) { ndbout << "Cluster nodes not ready in 30 seconds." << endl; return -1; } ndbout << "done" << endl; SignalSender ss(&con); ndbout_c("Connected as block=%d node=%d", refToBlock(ss.getOwnRef()), refToNode(ss.getOwnRef())); Uint32 data[25]; Uint32 sec0[70]; Uint32 sec1[123]; Uint32 sec2[10]; data[0] = ss.getOwnRef(); data[1] = 1; data[2] = 76; data[3] = 1; data[4] = 1; data[5] = 70; data[6] = 123; data[7] = 10; const Uint32 theDataLen = 18; for(Uint32 i = 0; i<70; i++) sec0[i] = i; for(Uint32 i = 0; i<123; i++) sec1[i] = 70+i; for(Uint32 i = 0; i<10; i++) sec2[i] = (i + 1)*(i + 1); SimpleSignal signal1; signal1.set(ss, 0, CMVMI, GSN_TESTSIG, theDataLen + 2); signal1.header.m_noOfSections = 1; signal1.header.m_fragmentInfo = 1; memcpy(&signal1.theData[0], data, 4 * theDataLen ); signal1.theData[theDataLen + 0] = 0; signal1.theData[theDataLen + 1] = 7; // FragmentId signal1.ptr[0].sz = 60; signal1.ptr[0].p = &sec0[0]; SimpleSignal signal2; Uint32 idx = 0; memcpy(&signal2.theData[0], data, 4 * theDataLen ); signal2.theData[theDataLen + idx] = 0; idx++; signal2.theData[theDataLen + idx] = 1; idx++; //signal2.theData[theDataLen + idx] = 2; idx++; signal2.theData[theDataLen + idx] = 7; idx++; // FragmentId signal2.set(ss, 0, CMVMI, GSN_TESTSIG, theDataLen + idx); signal2.header.m_fragmentInfo = 3; signal2.header.m_noOfSections = idx - 1; signal2.ptr[0].sz = 10; signal2.ptr[0].p = &sec0[60]; signal2.ptr[1].sz = 123; signal2.ptr[1].p = &sec1[0]; signal2.ptr[2].sz = 10; signal2.ptr[2].p = &sec2[0]; char * buf; while((buf = readline("Enter command: "))){ add_history(buf); data[1] = atoi(buf); if(strcmp(buf, "r") == 0){ SimpleSignal * ret1 = ss.waitFor(); (* ret1).print(); continue; } if(strcmp(buf, "a") == 0){ runTest(ss, 10, true); print_help(); continue; } if(strcmp(buf, "b") == 0){ runTest(ss, 100, false); print_help(); continue; } if(strcmp(buf, "c") == 0){ runTest(ss, 1000000, false); print_help(); continue; } if(data[1] >= 1 && data[1] <= 14){ Uint32 nodeId = ss.getAliveNode(); ndbout_c("Sending 2 fragmented to node %d", nodeId); ss.sendSignal(nodeId, &signal1); ss.sendSignal(nodeId, &signal2); if(data[1] >= 5){ continue; } ndbout_c("Waiting for signal from %d", nodeId); SimpleSignal * ret1 = ss.waitFor((Uint16)nodeId); (* ret1).print(); Uint32 count = ret1->theData[4] - 1; while(count > 0){ ndbout << "Waiting for " << count << " signals... "; SimpleSignal * ret1 = ss.waitFor(); ndbout_c("received from node %d", refToNode(ret1->header.theSendersBlockRef)); (* ret1).print(); count--; } } else if (data[1] == 15) { const Uint32 count = 3500; const Uint32 loop = 1000; signal1.set(ss, 0, CMVMI, GSN_TESTSIG, 25); signal1.header.m_fragmentInfo = 0; signal1.header.m_noOfSections = 0; signal1.theData[1] = 14; signal1.theData[3] = 0; // Print signal1.theData[8] = count; signal1.theData[9] = loop; Uint32 nodeId = ss.getAliveNode(); ndbout_c("Sending 25 len signal to node %d", nodeId); ss.sendSignal(nodeId, &signal1); Uint32 total; { SimpleSignal * ret1 = ss.waitFor((Uint16)nodeId); ndbout_c("received from node %d", refToNode(ret1->header.theSendersBlockRef)); total = ret1->theData[10] - 1; } do { ndbout << "Waiting for " << total << " signals... " << flush; SimpleSignal * ret1 = ss.waitFor((Uint16)nodeId); ndbout_c("received from node %d", refToNode(ret1->header.theSendersBlockRef)); total --; } while(total > 0); } else { print_help(); } } ndbout << "Exiting" << endl; ndb_end(0); };
static void append_command_to_history(char* cmd) { add_history(cmd); write_history(FILE_HISTORY_PATH); }
int main() { printf("Variante %d: %s\n", VARIANTE, VARIANTE_STRING); #ifdef USE_GUILE scm_init_guile(); /* register "executer" function in scheme */ scm_c_define_gsubr("executer", 1, 0, 0, executer_wrapper); #endif pidTable = create_pid_list(); struct sigaction act; memset(&act, '\0', sizeof(act)); act.sa_sigaction = &terminationHandler; act.sa_flags = SA_SIGINFO | SA_NOCLDSTOP; if(sigaction(SIGCHLD, &act, NULL) == -1){ perror("sigaction"); } while (1) { char *line=0; char *prompt = "ensishell>"; /* Readline use some internal memory structure that can not be cleaned at the end of the program. Thus one memory leak per command seems unavoidable yet */ line = readline(prompt); if (line == 0 || ! strncmp(line,"exit", 4)) { terminate(line); } else if(!strncmp(line, "jobs", 4)){ clean_pid_list(&pidTable); print_pid_list(pidTable); #ifdef USE_GNU_READLINE add_history(line); #endif continue; } #ifdef USE_GNU_READLINE add_history(line); #endif #ifdef USE_GUILE /* The line is a scheme command */ if (line[0] == '(') { char catchligne[strlen(line) + 256]; sprintf(catchligne, "(catch #t (lambda () %s) (lambda (key . parameters) (display \"mauvaise expression/bug en scheme\n\")))", line); scm_eval_string(scm_from_locale_string(catchligne)); free(line); continue; } #endif executer(line); // struct cmdline *l; // int i, j; // /* parsecmd free line and set it up to 0 */ // l = parsecmd( & line); // // /* If input stream closed, normal termination */ // if (!l) { // // terminate(0); // } // // // // if (l->err) { // /* Syntax error, read another command */ // printf("error: %s\n", l->err); // continue; // } // // if (l->in) printf("in: %s\n", l->in); // if (l->out) printf("out: %s\n", l->out); // if (l->bg) printf("background (&)\n"); // // /* Display each command of the pipe */ // for (i=0; l->seq[i]!=0; i++) { // char **cmd = l->seq[i]; // printf("seq[%d]: ", i); // for (j=0; cmd[j]!=0; j++) { // printf("'%s' ", cmd[j]); // } // printf("\n"); // } } }
/* *---------- * main proc *---------- */ static int file_parse(int fd, PGconn *conn, const char *abs_path) { int ret = 0; int size = 0; int wlen = 0; char *buf = (char*)NULL; char *realcmd = (char *)NULL; char *rdlinecmd = (char *)NULL; #define TM_LEN 25 //char timebf[TM_LEN]; char *timebf = NULL; //struct timeval stamp; struct rpldsk_packet packet; struct timeval stamp; enum CMD_STATUS cmd_s = CMD_UNKNOWN; if ((timebf = malloc(TM_LEN)) == NULL) { fprintf(stderr, "malloc failed.\n"); return -1; } memset(timebf, 0, TM_LEN); while ((ret = read(fd, &packet, sizeof(struct rpldsk_packet))) == sizeof(struct rpldsk_packet)) { //dbg("<-packet->\nsize: %x\nevent: %x\nmagic: %x\n", packet.size, packet.event, packet.magic); if (packet.magic != MAGIC_SIG) { fprintf(stderr, "\n<Packet inconsistency>\n"); return -1; } size = packet.size; if (size <= 0) { fprintf(stderr, ("\n" "<Packet inconsistency>" ": bad size" "\n")); return -1; } switch (packet.event) { case EVT_WRITE: dbg("case EVT_WRITE\n"); /* read packet.size and store in outbuf */ if ((buf = malloc(size+1)) == NULL) { fprintf(stderr, "malloc error\n"); close(fd); return -1; } read(fd, buf, size); buf[size] = '\0'; #ifdef WALK_LOG dbg("\n[TTY_OUT]\n............\n%s\n............\n\n", buf); //break; #endif last_outlen = strlen(buf); // size-1 : remove '\0' in packet.data if (s_cmd == CMD_BEGIN) { outlen += last_outlen; } else { outlen = last_outlen+1; outbuf[0] = '\0'; } if (outlen >= OUT_BFMAX) { fprintf(stderr, "BUG: OUT_BFMAX to small\n"); exit(1); } strncat(outbuf, buf, size); outbuf[outlen-1] = '\0'; free(buf); buf = (char *)NULL; break; case EVT_READ: dbg("case EVT_RD: start\n"); if (PS == NULL) { if (outbuf[0] == '\0') { fprintf(stderr, "BUG: No PS but outbuf is null.\n"); //lseek(fd, size, SEEK_CUR); //break; } } char *tmp = find_ps(outbuf); if (tmp && *tmp) { //update_ps if (PS != NULL) { free(PS); PS = NULL; } PS = tmp; dbg("\nps found\n--\n%s\n--\n", PS); clear_inbuf(); stamp = packet.time; s_cmd = CMD_BEGIN; dbg("\nCMD_BEGIN...\n"); } if (s_cmd != CMD_BEGIN) { lseek(fd, size, SEEK_CUR); clear_inbuf(); clear_outbuf(); break; } //add_completion if last_inbuf is 'tab' buf = last_ttyio(inbuf, last_inlen); dbg("\n\n-inbuf-\n%s\n-lastin(%d)-\n%s\n-outbuf-\n%s\n\n", inbuf, last_inlen, buf, outbuf); if (is_last_tab(buf) == 0) { str_rm_char(outbuf, CHR_BELL); add_completion(inbuf, outbuf); dbg("**inbuf-updated:%s\n", inbuf); } myfree((void *)&buf); clear_outbuf(); //read new tty_in if ((buf = malloc(size+1)) == NULL) { fprintf(stderr, "malloc error\n"); close(fd); return -1; } read(fd, buf, size); buf[size] = '\0'; #ifdef WALK_LOG dbg("\n[TTY_IN]\n............\n%s\n............\n\n", buf); //break; #endif last_inlen = strlen(buf); // size-1 : remove '\0' in packet.data inlen += last_inlen; if (inlen >= OUT_BFMAX) { fprintf(stderr, "BUG: OUT_BFMAX to small\n"); exit(1); } strncat(inbuf, buf, size); inbuf[inlen-1] = '\0'; if (is_cmdend(inbuf) == 0) { dbg("\n...CMD_END.\n"); //get rdlinecmd from rd-pkt.data getcmd(inbuf, &rdlinecmd, rl_name); format_time(&timebf, &(stamp.tv_sec)); dbg("\n\nrdlinecmd(%s)\n-inbuf-\n%s\n--\n\n", rdlinecmd, inbuf); //output dumped log logdump(timebf, PS, rdlinecmd, abs_path, User); //fprintf(stdout, "[%s]%s%s\n", timebf, PS, rdlinecmd); if (rdlinecmd && *rdlinecmd) { if (!(PS[0] == '>')) add_history(rdlinecmd); } free(rdlinecmd); rdlinecmd = NULL; clear_inbuf(); s_cmd = CMD_END; } free(buf); buf = (char *)NULL; //get rdlinecmd from rd-pkt.data //parse_rd_pkt(fd, &rdlinecmd, &packet, rl_name, &timebf); break; case EVT_ID_USER: if ((User = malloc(size)) == NULL) { fprintf(stderr, "malloc(User) error.\n"); close(fd); exit(1); } read(fd, User, size); //fprintf(stdout, "User: %s\n", User); break; case EVT_ID_TIME: if ((Time = malloc(size)) == NULL) { fprintf(stderr, "malloc(User) error.\n"); close(fd); exit(1); } read(fd, Time, size); //fprintf(stdout, "Time: %s\n", Time); break; case EVT_LCLOSE: dbg("EVT_LCLOSE\n"); fflush(stdout); clear_inbuf(); clear_outbuf(); return 0; default: dbg("EVT: %x, lseek\n", packet.event); lseek(fd, size, SEEK_CUR); break; } } free(timebf); return 0; }
/* * do a promotion of a user that lasts only for the current session */ void temporary_promote(UR_OBJECT user) { UR_OBJECT u; enum lvl_value lvl; if (word_count < 2) { write_user(user, "Usage: tpromote <user> [<level>]\n"); return; } u = get_user_name(user, word[1]); if (!u) { write_user(user, notloggedon); return; } if (u == user) { write_user(user, "You cannot promote yourself, temporarily or otherwise.\n"); return; } /* determine what level to promote them to */ if (u->level >= user->level) { write_user(user, "You cannot temporarily promote anyone of the same or greater level than you.\n"); return; } if (word_count == 3) { lvl = get_level(word[2]); if (lvl == NUM_LEVELS) { write_user(user, "Usage: tpromote <user> [<level>]\n"); return; } if (lvl <= u->level) { vwrite_user(user, "You must specify a level higher than %s currently is.\n", u->name); return; } } else { lvl = (enum lvl_value) (u->level + 1); } if (lvl == GOD) { vwrite_user(user, "You cannot temporarily promote anyone to level %s.\n", user_level[lvl].name); return; } if (lvl >= user->level) { write_user(user, "You cannot temporarily promote anyone to a higher level than your own.\n"); return; } /* if they have already been temp promoted this session then restore normal level first */ if (u->level > u->real_level) { u->level = u->real_level; } u->real_level = u->level; u->level = lvl; vwrite_user(user, "You temporarily promote %s to %s.\n", u->name, user_level[u->level].name); vwrite_room_except(u->room, u, "~OL~FG%s~RS~OL~FG starts to glow as their power increases...\n", u->bw_recap); vwrite_user(u, "~OL~FGYou have been promoted (temporarily) to level %s.\n", user_level[u->level].name); write_syslog(SYSLOG, 1, "%s TEMPORARILY promote %s to %s.\n", user->name, u->name, user_level[u->level].name); sprintf(text, "Was temporarily to level %s.\n", user_level[u->level].name); add_history(u->name, 1, "%s", text); }
/* * nick_from_server() */ static int nick_from_server(struct Client *client_p, struct Client *source_p, int parc, char *parv[], time_t newts, char *nick) { if(IsServer(source_p)) { /* A server introducing a new client, change source */ source_p = make_client(client_p); add_client_to_list(source_p); if(parc > 2) source_p->hopcount = atoi(parv[2]); if(newts) source_p->tsinfo = newts; else { newts = source_p->tsinfo = CurrentTime; ts_warn("Remote nick %s (%s) introduced without a TS", nick, parv[0]); } /* copy the nick in place */ (void) strcpy(source_p->name, nick); (void) add_to_client_hash_table(nick, source_p); if(parc > 8) { int flag; char *m; /* parse usermodes */ m = &parv[4][1]; while (*m) { flag = user_modes_from_c_to_bitmask[(unsigned char) *m]; if(!(source_p->umodes & UMODE_INVISIBLE) && (flag & UMODE_INVISIBLE)) Count.invisi++; if(!(source_p->umodes & UMODE_OPER) && (flag & UMODE_OPER)) Count.oper++; source_p->umodes |= flag & SEND_UMODES; m++; } return do_remote_user(nick, client_p, source_p, parv[5], parv[6], parv[7], (parc > 9)? parv[8] : NULL, parv[(parc > 9)? 9 : 8]); } } else if(source_p->name[0]) { /* client changing their nick */ if(irccmp(parv[0], nick)) source_p->tsinfo = newts ? newts : CurrentTime; sendto_common_channels_local(source_p, ":%s!%s@%s NICK :%s", source_p->name, source_p->username, source_p->host, nick); if(source_p->user) { add_history(source_p, 1); sendto_server(client_p, NULL, NOCAPS, NOCAPS, ":%s NICK %s :%lu", parv[0], nick, (unsigned long) source_p->tsinfo); } } /* set the new nick name */ if(source_p->name[0]) del_from_client_hash_table(source_p->name, source_p); strcpy(source_p->name, nick); add_to_client_hash_table(nick, source_p); /* remove all accepts pointing to the client */ del_all_accepts(source_p); return 0; }
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; }
/*!***************************************************************************** ******************************************************************************* \note checkKeyboard \date July 7, 1992 \remarks checks for keyboard interaction an does appropriate functions ******************************************************************************* Function Parameters: [in]=input,[out]=output \param[in] inital_command : initial command to be executed as it were typed in the terminal -- pass NULL for nothing ******************************************************************************/ static void * checkKeyboard(void *initial_command) { int result; long nchars=0; int i=0; char prompt[1000]; char *string; char *ptr, *fptr; extern double servo_time; int rc; #ifdef __XENO__ //become a real-time process char name[100]; sprintf(name, "%s_terminal_%d", servo_name, parent_process_id); rt_task_shadow(NULL, name, 0, 0); // we want this task in non real-time mode if ((rc=rt_task_set_mode(T_PRIMARY,0,NULL))) printf("rt_task_set_mode returned %d\n",rc); #endif while (run_command_line_thread_flag) { // run initial command as soon as the task servo has started -- there is // a little trick that allows resetting the servo clock and re-run the // initial command, which is useful for simulations. // the "time_reset_detected" flag is set by the sl_readline_callback // function which detects a reset of the servo clock if (time_reset_detected && strcmp(servo_name,"task")==0 && initial_command != NULL ) { // the clock has been reset // Special LittleDog Hack -- to be removed? // if the environment variable "SL_TASK_SERVO_STANDALONE" is set, // don't wait for the servo time to start ticking: if (getenv("SL_TASK_SERVO_STANDALONE")) usleep(100000); // else wait until the servo_time goes beyond 100ms: else { while (servo_time < 0.1) usleep(10000); } if (initial_command != NULL) { checkUserCommand((char *)initial_command); } time_reset_detected = 0; } snprintf(prompt, 1000, "%s.%s> ",robot_name,servo_name); rl_event_hook = &sl_readline_callback; string = readline(prompt); if (string && *string) add_history(string); checkUserCommand(string); free(string); // this allows the user to run a command line command from a program, // and in partciular a real-time program if (strlen(user_command) > 0) { checkUserCommand(user_command); strcpy(user_command,"\0"); } } printf("Command line thread terminated\n"); return NULL; }
int main(int argc, char *argv[]) { int s; while(1) { char * line = readline("cli> "); if(!line) break; if(*line) add_history(line); char *command = line; char *token; token = strtok(command, " "); struct sockaddr_in sr; int i, slen = sizeof(sr); char buf[BUFLEN]; struct hostent *hent; int portnum; /*if (argc != 3) { printf("Correct syntax: %s <portnum> <message>", argv[0]); return 1; } portnum = atoi(argv[1]); strcpy(buf, argv[2]);*/ if(token != NULL) portnum = atoi(token); else { printf("Correct syntax: <portnum> <message>\n"); continue; } token = strtok(NULL, " "); if(token != NULL) strcpy(buf, token); else { printf("Correct syntax: <portnum> <message>\n"); continue; } #ifdef DEBUG printf("%d %s \n", portnum, buf); #endif hent = gethostbyname("localhost"); if(hent == NULL) { printf("gethostbyname failed \n"); // exit(1); } if ((s = socket(AF_INET, SOCK_STREAM, 0)) == -1) {} memset((char *) &sr, 0, sizeof(sr)); sr.sin_family = AF_INET; sr.sin_port = htons(portnum); sr.sin_addr = *(struct in_addr*)(hent ->h_addr_list[0]); if (connect(s, (struct sockaddr *) &sr, sizeof(sr)) == -1) { printf("connect error\n"); // exit(1); } /* send a message to the server PORT on machine HOST */ if (send(s, buf, BUFLEN, 0) == -1) { printf("send error\n"); // exit(1); } free(line); } close(s); return 0; }
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 main(int argc, char *argv[], char *envp[]) { char *line; int returnValue; int i, fd; char *pathString = (char *)malloc(sizeof(char) * 256); char *cmd = (char *)malloc(sizeof(char) * 256); bzero(pathString, 256); bzero(cmd, 256); /* Manage Signals */ signal(SIGINT, SIG_IGN); signal(SIGQUIT,SIG_IGN); // signal(SIGCHLD,SIG_IGN); signal(SIGKILL,SIG_IGN); signal(SIGTERM,SIG_IGN); signal(SIGINT, handleSignal); /* Extract the PATH= var from envp */ getPathString(envp, pathString); /* Insert each path to be searched into searchPath[][] */ insertPathStringToSearch(searchPath, pathString); /* Print about Slash */ clrScreen(argv, envp); printf("%s", aboutSlash); printf("PID=%d\n", getpid()); #if SLASH_DEBUG for(i=0; envp[i] != NULL; i++) printf("%s\n", envp[i]); #endif /* Bind our completer + History Feature */ initialize_readline(); while(1) { line = readline ("\x1b[96m<$lash/>\x1b[00m "); /* Print in Red! */ #if SLASH_DEBUG printf("Input: %s\n", line); #endif if(*line) { add_history (line); returnValue = execute_line (line); if(returnValue == CMD_EXIT) break; if(returnValue == CMD_UNKNOWN) { #if SLASH_DEBUG printf("CMD_UNKNOWN: %s\n", line); #endif /* Extract args to command into slashArgv[][] */ nullifyArgv(slashArgv); fillArgv(line, slashArgv); bzero(cmd, 256); strncpy(cmd, slashArgv[0], strlen(slashArgv[0])); strncat(cmd, "\0", 1); #if SLASH_DEBUG printf("arg[0]: %s\n", slashArgv[0]); printf("cmd: %s\n", cmd); #endif if(index(cmd, '/') == NULL) { if(attachPath(cmd, searchPath) == 0) { callFork(cmd, slashArgv, envp); } else printf("%s: command not found\n", cmd); } else { if((fd = open(cmd, O_RDONLY)) > 0) { close(fd); callFork(cmd, slashArgv, envp); } else printf("%s: command not found\n", cmd); } freeArgv(slashArgv); } } if(line != NULL) free(line); fflush(stdout); } free(cmd); free(pathString); for(i=0;i<50;i++) free(searchPath[i]); return 0; }
int main(int argc, char **argv) { char ruby_code[1024] = { 0 }; char last_code_line[1024] = { 0 }; #ifndef ENABLE_READLINE int last_char; int char_index; #else char *home = NULL; #endif mrbc_context *cxt; struct mrb_parser_state *parser; mrb_state *mrb; mrb_value result; struct _args args; int n; int code_block_open = FALSE; int ai; /* new interpreter instance */ mrb = mrb_open(); if (mrb == NULL) { fputs("Invalid mrb interpreter, exiting mirb\n", stderr); return EXIT_FAILURE; } mrb_define_global_const(mrb, "ARGV", mrb_ary_new_capa(mrb, 0)); n = parse_args(mrb, argc, argv, &args); if (n == EXIT_FAILURE) { cleanup(mrb, &args); usage(argv[0]); return n; } print_hint(); cxt = mrbc_context_new(mrb); cxt->capture_errors = 1; cxt->lineno = 1; mrbc_filename(mrb, cxt, "(mirb)"); if (args.verbose) cxt->dump_result = 1; ai = mrb_gc_arena_save(mrb); #ifdef ENABLE_READLINE using_history(); home = getenv("HOME"); #ifdef _WIN32 if (!home) home = getenv("USERPROFILE"); #endif if (home) { strcpy(history_path, home); strcat(history_path, "/"); strcat(history_path, history_file_name); read_history(history_path); } #endif while (TRUE) { #ifndef ENABLE_READLINE print_cmdline(code_block_open); char_index = 0; while ((last_char = getchar()) != '\n') { if (last_char == EOF) break; last_code_line[char_index++] = last_char; } if (last_char == EOF) { fputs("\n", stdout); break; } last_code_line[char_index] = '\0'; #else char* line = readline(code_block_open ? "* " : "> "); if (line == NULL) { printf("\n"); break; } strncpy(last_code_line, line, sizeof(last_code_line)-1); add_history(line); free(line); #endif if ((strcmp(last_code_line, "quit") == 0) || (strcmp(last_code_line, "exit") == 0)) { if (!code_block_open) { break; } else{ /* count the quit/exit commands as strings if in a quote block */ strcat(ruby_code, "\n"); strcat(ruby_code, last_code_line); } } else { if (code_block_open) { strcat(ruby_code, "\n"); strcat(ruby_code, last_code_line); } else { strcpy(ruby_code, last_code_line); } } /* parse code */ parser = mrb_parser_new(mrb); parser->s = ruby_code; parser->send = ruby_code + strlen(ruby_code); parser->lineno = cxt->lineno; mrb_parser_parse(parser, cxt); code_block_open = is_code_block_open(parser); if (code_block_open) { /* no evaluation of code */ } else { if (0 < parser->nerr) { /* syntax error */ printf("line %d: %s\n", parser->error_buffer[0].lineno, parser->error_buffer[0].message); } else { /* generate bytecode */ n = mrb_generate_code(mrb, parser); /* evaluate the bytecode */ result = mrb_run(mrb, /* pass a proc for evaulation */ mrb_proc_new(mrb, mrb->irep[n]), mrb_top_self(mrb)); /* did an exception occur? */ if (mrb->exc) { p(mrb, mrb_obj_value(mrb->exc), 0); mrb->exc = 0; } else { /* no */ if (!mrb_respond_to(mrb, result, mrb_intern2(mrb, "inspect", 7))){ result = mrb_any_to_s(mrb,result); } p(mrb, result, 1); } } ruby_code[0] = '\0'; last_code_line[0] = '\0'; mrb_gc_arena_restore(mrb, ai); } mrb_parser_free(parser); cxt->lineno++; } mrbc_context_free(mrb, cxt); mrb_close(mrb); #ifdef ENABLE_READLINE write_history(history_path); #endif return 0; }
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); #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) }
void tloop(int history) { using_history(); stifle_history(history); lookf(self.next); while(1){ int fail = 0; struct tobj *prev = NULL; struct tobj *noun = NULL; char *input = readline(">> "); char *verbstr = input; char *nounstr = verbstr; add_history(verbstr); /* Blank out spaces and punctuation and set the noun as the last word */ while(*input){ if(!isalpha(*input)){ *input = '\0'; if(isalpha(*(input + 1))){ nounstr = input + 1; } } ++input; } input = verbstr; /* Restore input back to where it was */ /* Do basic substition for shortcut commands */ if(tstrequals(verbstr, 2, "n", "north")){ verbstr = "go"; nounstr = "north"; } else if(tstrequals(verbstr, 2, "ne", "northeast")){ verbstr = "go"; nounstr = "northeast"; } else if(tstrequals(verbstr, 2, "e", "east")){ verbstr = "go"; nounstr = "east"; } else if(tstrequals(verbstr, 2, "se", "southeast")){ verbstr = "go"; nounstr = "southeast"; } else if(tstrequals(verbstr, 2, "s", "south")){ verbstr = "go"; nounstr = "south"; } else if(tstrequals(verbstr, 2, "sw", "southwest")){ verbstr = "go"; nounstr = "southwest"; } else if(tstrequals(verbstr, 2, "w", "west")){ verbstr = "go"; nounstr = "west"; } else if(tstrequals(verbstr, 2, "nw", "northwest")){ verbstr = "go"; nounstr = "northwest"; } else if(tstrequals(verbstr, 1, "out")){ verbstr = "go"; nounstr = "out"; } noun = tfind(&self, &prev, nounstr); if(noun == NULL){ if(verbstr != nounstr){ if(tstrequals(verbstr, 2, "go", "travel")){ printf("You can't go ``%s'' here.\n", nounstr); } else{ printf("You don't see ``%s'' here.\n", nounstr); } fail = 1; } else{ prev = NULL; noun = self.next; } } if(!fail){ if(tstrcmp(verbstr, "look") == 0){ lookf(noun); } else if(tstrequals(verbstr, 2, "i", "inventory")){ lookf(&self); } else if(tstrequals(verbstr, 3, "eat", "consume", "ingest")){ eatf(prev, noun); } else if(tstrequals(verbstr, 2, "go", "travel")){ gof(noun); } else if(tstrequals(verbstr, 3, "drop", "leave", "abandon")){ dropf(prev, noun); } else if(tstrequals(verbstr, 3, "talk", "say", "speak")){ talkf(noun); } else if(tstrequals(verbstr, 6, "break", "smash", "kick", "punch", "headbutt", "kill")){ breakf(noun); } else if(tstrcmp(verbstr, "unlock") == 0){ unlockf(noun); } else if(tstrequals(verbstr, 2, "lock", "bar")){ lockf(noun); } else if(tstrequals(verbstr, 5, "pick", "get", "take", "steal", "pack")){ pickf(prev, noun); } else{ printf("Don't know how to ``%s.''\n", verbstr); fail = 1; } } free(input); } }
/* * This function asks the user for a command and calls the dispatcher * function, dispatch, to analyze it. We use the readline library * function readline to read the command, hence all the usual readline * keys are available. The new command is saved both in the * readline's history and in our tiny one-command cache, so that only * the enter key is needed to retype it. */ void parser (void) { char *ptr,command_line [80]; int quit=0; #if 0 noecho(); cbreak(); keypad(command_win, 1); wtimeout(command_win, 100); rl_getc_function = rl_getc_replacement; #endif while (!quit) { /* Terminal screen size has changed */ if (redraw_request) { redraw_all(); redraw_request=0; } wmove (command_win,0,0); wclrtoeol (command_win); wprintw (command_win,"ext2ed > "); refresh_command_win (); /* * The ncurses library optimizes cursor movement by * keeping track of the cursor position. However, by * using the readline library I'm breaking its * assumptions. The double -1 arguments tell ncurses * to disable cursor movement optimization this * time. */ mvcur (-1,-1,LINES-COMMAND_WIN_LINES,0); /* echo (); */ ptr=readline ("ext2ed > "); /* noecho (); */ /* * Readline allocated the buffer - Copy the string * and free the allocated buffer * XXX WHY??? */ strcpy (command_line,ptr); free (ptr); if (*command_line != 0) add_history (command_line); /* If only enter was pressed, recall the last command */ if (*command_line==0) strcpy (command_line,last_command_line); /* Emulate readline's actions for ncurses */ mvcur (-1,-1,LINES-COMMAND_WIN_LINES,0); werase (command_win); wprintw (command_win,"ext2ed > "); wprintw (command_win,command_line); wprintw (command_win,"\n"); refresh_command_win (); /* Save this command in our tiny cache */ strcpy (last_command_line,command_line); /* And call dispatch to do the actual job */ quit=dispatch (command_line); } }
int lvm_shell(struct cmd_context *cmd, struct cmdline_context *cmdline) { int argc, ret; char *input = NULL, *args[MAX_ARGS], **argv; rl_readline_name = "lvm"; rl_attempted_completion_function = (CPPFunction *) _completion; _read_history(cmd); _cmdline = cmdline; _cmdline->interactive = 1; while (1) { free(input); input = readline("lvm> "); /* EOF */ if (!input) { /* readline sends prompt to stdout */ printf("\n"); break; } /* empty line */ if (!*input) continue; add_history(input); argv = args; if (lvm_split(input, &argc, argv, MAX_ARGS) == MAX_ARGS) { log_error("Too many arguments, sorry."); continue; } if (!argc) continue; if (!strcmp(argv[0], "lvm")) { argv++; argc--; } if (!argc) continue; if (!strcmp(argv[0], "quit") || !strcmp(argv[0], "exit")) { remove_history(history_length - 1); log_error("Exiting."); break; } ret = lvm_run_command(cmd, argc, argv); if (ret == ENO_SUCH_CMD) log_error("No such command '%s'. Try 'help'.", argv[0]); if ((ret != ECMD_PROCESSED) && !error_message_produced()) { log_debug(INTERNAL_ERROR "Failed command did not use log_error"); log_error("Command failed with status code %d.", ret); } _write_history(); } free(input); return 0; }
void parse_input_command(char *rl_cmd) { int i; int argc = 0; int valid_cmd = 0; char *argv[MAX_ARGS]; int last_arg_start = 0; int last_was_space = 0; int len; char *cmd; /* ^D quits */ if (rl_cmd == NULL) { run_exit_cmd(0, NULL); } cmd = strdup(rl_cmd); /* Split cmd up into args * destroying the original string mwahahahaha */ len = strlen(cmd); /* Span leading spaces */ for (i=0; cmd[i] == ' '; i++) ; last_arg_start = i; for (; i<=len; i++) { if (cmd[i] == ' ' || cmd[i] == '\0') { /* Allow multiple spaces */ if (last_was_space) { continue; } cmd[i] = '\0'; last_was_space = 1; argv[argc] = &cmd[last_arg_start]; argc++; } else { if (last_was_space) { last_arg_start = i; } last_was_space = 0; } } /* Ignore null commands */ if (strlen(argv[0]) == 0) { free(cmd); return; } #ifdef HAVE_READLINE_HISTORY_H add_history(rl_cmd); #endif /* Dispatch command */ for (i=0; i<num_cmds; i++) { if (strcasecmp(argv[0], cmd_list[i].cmd) == 0) { if (argc < cmd_list[i].min_args) { break; } cmd_list[i].cmd_runner(argc, argv); valid_cmd = 1; } } if (!valid_cmd) { do_usage(); } free(cmd); }
int main(int argc, char *argv[]) { char *temp; int did_explicit_auth = 0; char *tickets = NULL; char prompt[CHIRP_LINE_MAX]; char line[CHIRP_LINE_MAX]; char **user_argv = 0; int user_argc; signed char c; int result = 0; debug_config(argv[0]); static struct option long_options[] = { {"auth", required_argument, 0, 'a'}, {"debug", required_argument, 0, 'd'}, {"debug-file", required_argument, 0, 'o'}, {"tickets", required_argument, 0, 'i'}, {"verbose", no_argument, 0, 'l'}, {"timeout", required_argument, 0, 't'}, {"version", no_argument, 0, 'v'}, {"help", no_argument, 0, 'h'}, {0, 0, 0, 0} }; while((c = getopt_long(argc, argv, "+a:d:hi:lt:v", long_options, NULL)) > -1) { switch (c) { case 'a': auth_register_byname(optarg); did_explicit_auth = 1; break; case 'd': debug_flags_set(optarg); break; case 'o': debug_config_file(optarg); break; case 'h': show_help(argv[0]); exit(0); break; case 'i': tickets = strdup(optarg); break; case 'l': long_information = 1; break; case 't': timeout = string_time_parse(optarg); break; case 'v': cctools_version_print(stdout, argv[0]); exit(0); break; } } cctools_version_debug(D_DEBUG, argv[0]); if(!did_explicit_auth) auth_register_all(); if(tickets) { auth_ticket_load(tickets); free(tickets); } else if(getenv(CHIRP_CLIENT_TICKETS)) { auth_ticket_load(getenv(CHIRP_CLIENT_TICKETS)); } else { auth_ticket_load(NULL); } getcwd(current_local_dir, CHIRP_PATH_MAX); /* interactive mode if input is a TTY but we are not simply executing a * command from argv */ interactive_mode = isatty(0) && !((argc - optind) > 1); if(optind < argc) { stoptime = time(0) + timeout; if(do_open(1, &argv[optind - 1])) { fprintf(stderr, "couldn't open %s: %s\n", argv[optind], strerror(errno)); return 1; } } if((argc - optind) > 1) { return !process_command(argc - optind - 1, &argv[optind + 1]); } while(1) { if(interactive_mode) { sprintf(prompt, " chirp:%s:%s> ", current_host, current_remote_dir); } else { prompt[0] = 0; } #ifdef HAS_LIBREADLINE temp = readline(prompt); if(!temp) break; strcpy(line, temp); free(temp); #else printf("%s", prompt); fflush(stdout); if(!fgets(line, CHIRP_LINE_MAX, stdin)) break; #endif if(!line[0]) continue; if(!interactive_mode && (temp = strchr(line, '#'))) { /* comment? */ for(temp--; temp > line && isspace((int) *temp); temp--); /* preceding space? */ if(temp <= line) continue; /* else not comment */ } #ifdef HAS_LIBREADLINE add_history(line); #endif { char *start = line, *last = strlen(line) + line; while(*start != '\0') { /* process compound commands */ char *end = strchr(start, ';'); while(end != NULL && end != start && *(end - 1) == '\\') end = strchr(end + 1, ';'); if(end == NULL) end = start + strlen(start); *end = '\0'; if(user_argv) free(user_argv); string_split(start, &user_argc, &user_argv); if(user_argc == 0) { start++; continue; } result = process_command(user_argc, user_argv); start = end == last ? last : end + 1; } } if(!interactive_mode && !result) break; } if(result) { return 0; } else { return 1; } }
/// %Thread start void CliRunnable::run() { ///- Display the list of available CLI functions then beep //TC_LOG_INFO("server.worldserver", ""); #if PLATFORM != 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); 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("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 == PLATFORM_WINDOWS printf("HARDCORE>"); #else free(command_str); #endif continue; } std::string command; if (!consoleToUtf8(command_str, command)) // convert from console encoding to utf8 { #if PLATFORM == PLATFORM_WINDOWS printf("HARDCORE>"); #else free(command_str); #endif continue; } fflush(stdout); sWorld->QueueCliCommand(new CliCommandHolder(NULL, command.c_str(), &utf8print, &commandFinished)); #if PLATFORM != PLATFORM_WINDOWS add_history(command.c_str()); free(command_str); #endif } else if (feof(stdin)) { World::StopNow(SHUTDOWN_EXIT_CODE); } } }
/* NOTE: 1999-04-30 This is the asynchronous version of the command_line_input function. command_line_input will become obsolete once we use the event loop as the default mechanism in GDB. */ static void command_line_handler (char *rl) { static char *linebuffer = 0; static unsigned linelength = 0; char *p; char *p1; extern char *line; extern int linesize; char *nline; char got_eof = 0; int repeat = (instream == stdin); if (annotation_level > 1 && instream == stdin) { printf_unfiltered (("\n\032\032post-")); puts_unfiltered (async_annotation_suffix); printf_unfiltered (("\n")); } if (linebuffer == 0) { linelength = 80; linebuffer = (char *) xmalloc (linelength); } p = linebuffer; if (more_to_come) { strcpy (linebuffer, readline_input_state.linebuffer); p = readline_input_state.linebuffer_ptr; xfree (readline_input_state.linebuffer); more_to_come = 0; pop_prompt (); } #ifdef STOP_SIGNAL if (job_control) signal (STOP_SIGNAL, handle_stop_sig); #endif /* Make sure that all output has been output. Some machines may let you get away with leaving out some of the gdb_flush, but not all. */ wrap_here (""); gdb_flush (gdb_stdout); gdb_flush (gdb_stderr); if (source_file_name != NULL) ++source_line_number; /* If we are in this case, then command_handler will call quit and exit from gdb. */ if (!rl || rl == (char *) EOF) { got_eof = 1; command_handler (0); } if (strlen (rl) + 1 + (p - linebuffer) > linelength) { linelength = strlen (rl) + 1 + (p - linebuffer); nline = (char *) xrealloc (linebuffer, linelength); p += nline - linebuffer; linebuffer = nline; } p1 = rl; /* Copy line. Don't copy null at end. (Leaves line alone if this was just a newline) */ while (*p1) *p++ = *p1++; xfree (rl); /* Allocated in readline. */ if (p > linebuffer && *(p - 1) == '\\') { p--; /* Put on top of '\'. */ readline_input_state.linebuffer = savestring (linebuffer, strlen (linebuffer)); readline_input_state.linebuffer_ptr = p; /* We will not invoke a execute_command if there is more input expected to complete the command. So, we need to print an empty prompt here. */ more_to_come = 1; push_prompt ("", "", ""); display_gdb_prompt (0); return; } #ifdef STOP_SIGNAL if (job_control) signal (STOP_SIGNAL, SIG_DFL); #endif #define SERVER_COMMAND_LENGTH 7 server_command = (p - linebuffer > SERVER_COMMAND_LENGTH) && strncmp (linebuffer, "server ", SERVER_COMMAND_LENGTH) == 0; if (server_command) { /* Note that we don't set `line'. Between this and the check in dont_repeat, this insures that repeating will still do the right thing. */ *p = '\0'; command_handler (linebuffer + SERVER_COMMAND_LENGTH); display_gdb_prompt (0); return; } /* Do history expansion if that is wished. */ if (history_expansion_p && instream == stdin && ISATTY (instream)) { char *history_value; int expanded; *p = '\0'; /* Insert null now. */ expanded = history_expand (linebuffer, &history_value); if (expanded) { /* Print the changes. */ printf_unfiltered ("%s\n", history_value); /* If there was an error, call this function again. */ if (expanded < 0) { xfree (history_value); return; } if (strlen (history_value) > linelength) { linelength = strlen (history_value) + 1; linebuffer = (char *) xrealloc (linebuffer, linelength); } strcpy (linebuffer, history_value); p = linebuffer + strlen (linebuffer); xfree (history_value); } } /* If we just got an empty line, and that is supposed to repeat the previous command, return the value in the global buffer. */ if (repeat && p == linebuffer && *p != '\\') { command_handler (line); display_gdb_prompt (0); return; } for (p1 = linebuffer; *p1 == ' ' || *p1 == '\t'; p1++); if (repeat && !*p1) { command_handler (line); display_gdb_prompt (0); return; } *p = 0; /* Add line to history if appropriate. */ if (instream == stdin && ISATTY (stdin) && *linebuffer) add_history (linebuffer); /* Note: lines consisting solely of comments are added to the command history. This is useful when you type a command, and then realize you don't want to execute it quite yet. You can comment out the command and then later fetch it from the value history and remove the '#'. The kill ring is probably better, but some people are in the habit of commenting things out. */ if (*p1 == '#') *p1 = '\0'; /* Found a comment. */ /* Save into global buffer if appropriate. */ if (repeat) { if (linelength > linesize) { line = xrealloc (line, linelength); linesize = linelength; } strcpy (line, linebuffer); if (!more_to_come) { command_handler (line); display_gdb_prompt (0); } return; } command_handler (linebuffer); display_gdb_prompt (0); return; }
void* doInput(void* threadid) { char* commandBuffer = NULL; char toSendBuffer[USB_BYTES_AT_A_TIME]; rl_basic_word_break_characters = " \t\n\"\\'`@$><=;|&{(~!:"; rl_completion_append_character = '\0'; while(1) { if(commandBuffer != NULL) free(commandBuffer); commandBuffer = readline(NULL); if(commandBuffer && *commandBuffer) { add_history(commandBuffer); write_history(".oibc-history"); } if(!commandBuffer) break; char* fileBuffer = NULL; int len = strlen(commandBuffer); if(commandBuffer[0] == '!') { char* atLoc = strchr(&commandBuffer[1], '@'); if(atLoc != NULL) *atLoc = '\0'; FILE* file = fopen(&commandBuffer[1], "rb"); if(!file) { oibc_log("file not found: %s\n", &commandBuffer[1]); continue; } fseek(file, 0, SEEK_END); len = ftell(file); fseek(file, 0, SEEK_SET); fileBuffer = malloc(len); fread(fileBuffer, 1, len, file); fclose(file); if(atLoc != NULL) { sprintf(toSendBuffer, "sendfile %s", atLoc + 1); } else { sprintf(toSendBuffer, "sendfile 0x09000000"); } sendBuffer(toSendBuffer, strlen(toSendBuffer)); sendBuffer(fileBuffer, len); free(fileBuffer); } else if(commandBuffer[0] == '~') { if (getFile(commandBuffer+1)==1) continue; } else if (strcmp(commandBuffer,"install") == 0) { oibc_log("Backing up your NOR to current directory as norbackup.dump\n"); sprintf(toSendBuffer, "nor_read 0x09000000 0x0 1048576"); commandBuffer[len] = '\n'; sendBuffer(toSendBuffer, strlen(toSendBuffer)); sprintf(toSendBuffer,"norbackup.dump:1048576"); getFile(toSendBuffer); oibc_log("Fetching NOR backup.\n"); commandBuffer[len] = '\n'; oibc_log("NOR backed up, starting installation\n"); sprintf(toSendBuffer,"install"); sendBuffer(toSendBuffer, strlen(toSendBuffer)); } else { commandBuffer[len] = '\n'; sendBuffer(commandBuffer, len + 1); } sched_yield(); } pthread_cond_signal(&exitCond); pthread_exit(NULL); }
/// %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); } } }
int main( int argc, char ** argv) { int i; time_t timer; char *lineread = NULL; struct sigaction act, oact; extern char *optarg; extern int optind; char *line = NULL; const security_driver_t *secdrv; char *req = NULL; int response_error; struct tm *tm; config_overwrites_t *cfg_ovr; /* * Configure program for internationalization: * 1) Only set the message locale for now. * 2) Set textdomain for all amanda related programs to "amanda" * We don't want to be forced to support dozens of message catalogs. */ setlocale(LC_MESSAGES, "C"); textdomain("amanda"); safe_fd(-1, 0); set_pname("amrecover"); /* Don't die when child closes pipe */ signal(SIGPIPE, SIG_IGN); dbopen(DBG_SUBDIR_CLIENT); localhost = alloc(MAX_HOSTNAME_LENGTH+1); if (gethostname(localhost, MAX_HOSTNAME_LENGTH) != 0) { error(_("cannot determine local host name\n")); /*NOTREACHED*/ } localhost[MAX_HOSTNAME_LENGTH] = '\0'; /* load the base client configuration */ config_init(CONFIG_INIT_CLIENT, NULL); if (config_errors(NULL) >= CFGERR_WARNINGS) { config_print_errors(); if (config_errors(NULL) >= CFGERR_ERRORS) { g_critical(_("errors processing config file")); } } /* treat amrecover-specific command line options as the equivalent * -o command-line options to set configuration values */ cfg_ovr = new_config_overwrites(argc/2); /* If the first argument is not an option flag, then we assume * it is a configuration name to match the syntax of the other * Amanda utilities. */ if (argc > 1 && argv[1][0] != '-') { add_config_overwrite(cfg_ovr, "conf", argv[1]); /* remove that option from the command line */ argv[1] = argv[0]; argv++; argc--; } /* now parse regular command-line '-' options */ while ((i = getopt(argc, argv, "o:C:s:t:d:U")) != EOF) { switch (i) { case 'C': add_config_overwrite(cfg_ovr, "conf", optarg); break; case 's': add_config_overwrite(cfg_ovr, "index_server", optarg); break; case 't': add_config_overwrite(cfg_ovr, "tape_server", optarg); break; case 'd': add_config_overwrite(cfg_ovr, "tapedev", optarg); break; case 'o': add_config_overwrite_opt(cfg_ovr, optarg); break; case 'U': case '?': (void)g_printf(USAGE); return 0; } } if (optind != argc) { (void)g_fprintf(stderr, USAGE); exit(1); } /* and now try to load the configuration named in that file */ apply_config_overwrites(cfg_ovr); config_init(CONFIG_INIT_CLIENT | CONFIG_INIT_EXPLICIT_NAME | CONFIG_INIT_OVERLAY, getconf_str(CNF_CONF)); reapply_config_overwrites(); check_running_as(RUNNING_AS_ROOT); dbrename(get_config_name(), DBG_SUBDIR_CLIENT); our_features = am_init_feature_set(); our_features_string = am_feature_to_string(our_features); server_name = NULL; if (getconf_seen(CNF_INDEX_SERVER) == -2) { /* command line argument */ server_name = getconf_str(CNF_INDEX_SERVER); } if (!server_name) { server_name = getenv("AMANDA_SERVER"); if (server_name) { g_printf(_("Using index server from environment AMANDA_SERVER (%s)\n"), server_name); } } if (!server_name) { server_name = getconf_str(CNF_INDEX_SERVER); } if (!server_name) { error(_("No index server set")); /*NOTREACHED*/ } server_name = stralloc(server_name); tape_server_name = NULL; if (getconf_seen(CNF_TAPE_SERVER) == -2) { /* command line argument */ tape_server_name = getconf_str(CNF_TAPE_SERVER); } if (!tape_server_name) { tape_server_name = getenv("AMANDA_TAPE_SERVER"); if (!tape_server_name) { tape_server_name = getenv("AMANDA_TAPESERVER"); if (tape_server_name) { g_printf(_("Using tape server from environment AMANDA_TAPESERVER (%s)\n"), tape_server_name); } } else { g_printf(_("Using tape server from environment AMANDA_TAPE_SERVER (%s)\n"), tape_server_name); } } if (!tape_server_name) { tape_server_name = getconf_str(CNF_TAPE_SERVER); } if (!tape_server_name) { error(_("No tape server set")); /*NOTREACHED*/ } tape_server_name = stralloc(tape_server_name); amfree(tape_device_name); tape_device_name = getconf_str(CNF_TAPEDEV); if (!tape_device_name || strlen(tape_device_name) == 0 || !getconf_seen(CNF_TAPEDEV)) { tape_device_name = NULL; } else { tape_device_name = stralloc(tape_device_name); } authopt = stralloc(getconf_str(CNF_AUTH)); amfree(disk_name); amfree(mount_point); amfree(disk_path); dump_date[0] = '\0'; /* Don't die when child closes pipe */ signal(SIGPIPE, SIG_IGN); /* set up signal handler */ act.sa_handler = sigint_handler; sigemptyset(&act.sa_mask); act.sa_flags = 0; if (sigaction(SIGINT, &act, &oact) != 0) { error(_("error setting signal handler: %s"), strerror(errno)); /*NOTREACHED*/ } protocol_init(); /* We assume that amindexd support fe_amindexd_options_features */ /* and fe_amindexd_options_auth */ /* We should send a noop to really know */ req = vstrallocf("SERVICE amindexd\n" "OPTIONS features=%s;auth=%s;\n", our_features_string, authopt); secdrv = security_getdriver(authopt); if (secdrv == NULL) { error(_("no '%s' security driver available for host '%s'"), authopt, server_name); /*NOTREACHED*/ } protocol_sendreq(server_name, secdrv, generic_client_get_security_conf, req, STARTUP_TIMEOUT, amindexd_response, &response_error); amfree(req); protocol_run(); g_printf(_("AMRECOVER Version %s. Contacting server on %s ...\n"), version(), server_name); if(response_error != 0) { g_fprintf(stderr,"%s\n",errstr); exit(1); } /* get server's banner */ if (grab_reply(1) == -1) { aclose(server_socket); exit(1); } if (!server_happy()) { dbclose(); aclose(server_socket); exit(1); } /* try to get the features from the server */ { char *their_feature_string = NULL; indexsrv_features = NULL; line = vstrallocf("FEATURES %s", our_features_string); if(exchange(line) == 0) { their_feature_string = stralloc(server_line+13); indexsrv_features = am_string_to_feature(their_feature_string); if (!indexsrv_features) g_printf(_("Bad feature string from server: %s"), their_feature_string); } if (!indexsrv_features) indexsrv_features = am_set_default_feature_set(); amfree(their_feature_string); amfree(line); } /* set the date of extraction to be today */ (void)time(&timer); tm = localtime(&timer); if (tm) strftime(dump_date, sizeof(dump_date), "%Y-%m-%d", tm); else error(_("BAD DATE")); g_printf(_("Setting restore date to today (%s)\n"), dump_date); line = vstrallocf("DATE %s", dump_date); if (converse(line) == -1) { aclose(server_socket); exit(1); } amfree(line); line = vstrallocf("SCNF %s", get_config_name()); if (converse(line) == -1) { aclose(server_socket); exit(1); } amfree(line); if (server_happy()) { /* set host we are restoring to this host by default */ amfree(dump_hostname); set_host(localhost); if (dump_hostname) g_printf(_("Use the setdisk command to choose dump disk to recover\n")); else g_printf(_("Use the sethost command to choose a host to recover\n")); } quit_prog = 0; do { if ((lineread = readline("amrecover> ")) == NULL) { clearerr(stdin); putchar('\n'); break; } if (lineread[0] != '\0') { add_history(lineread); dbprintf(_("user command: '%s'\n"), lineread); process_line(lineread); /* act on line's content */ } amfree(lineread); } while (!quit_prog); dbclose(); aclose(server_socket); return 0; }
int vars_main(int argc, char **argv) { char *line=0; char *name,*v; unsigned long value,f; CexpSym val; int ch; cexpVarInitOnce(); { CexpVar vv; val=cexpVarLookup("hallo",1); vv = (CexpVar)((unsigned long)val - OffsetOf(CexpVar,sym)); printf("CexpVar size: %i, & 0x%08lx, &name: %08lx\n", sizeof(*vv), (unsigned long)vv, (unsigned long)&vv->sym.name); } while (free(line),line=readline("Vars Tst>")) { for (name=line+1; *name && isspace(*name); name++); for (v=name; *v && !isspace(*v); v++); if (*v) { *v=0; for (v++;*v && isspace(*v); v++); if (*v) sscanf(v,"%li",&value); } f=0; switch ((ch=toupper(line[0]))) { default: fprintf(stderr,"unknown command\n"); continue; /* dont add bad commands to history */ case 'F': cexpVarsFlush(); break; case 'P': varPrintList(); break; case 'T': strPrintList(); break; case 'A': f=1;/* find and add */ case 'S': /* find and set (dont add) */ if (!*name || !*v) { fprintf(stderr,"missing name and/or value\n"); break; } val=cexpVarLookup(name,f); if (val) { val->value.type=TULong; val->value.ptv->l=value; } printf("\n%s %s\n", f?"adding":"setting", val?"success":"failure"); break; case 'L': case 'D': if (!*name) { fprintf(stderr,"missing name\n"); break; } if ('D'==ch) { printf("Deleting %s\n", cexpVarDelete(name) ? "success" : "failure"); } else { val=cexpVarLookup(name,0); printf("Var %sfound: 0x%lx\n", val ? "" : "not ", val->value.ptv->l); } break; } add_history(line); } return 0; }