void build_echo(t_data *d) { int i; int first; i = 4; first = 0; if (d->toexec[i]) { i = is_option(d->toexec, i); while (d->toexec[i]) { while (d->toexec[i] == ' ' || d->toexec[i] == '\t') i++; if (first == 1 && d->toexec[i] != '\0') ft_putchar(' '); if (d->toexec[i]) i = ft_print_echo(d->toexec, i); if (d->toexec[i]) i++; first = 1; } } if (is_option(d->toexec, 4) == 4) ft_putchar('\n'); }
/* * gets the next option. returns the index on data->table if the option * * Modifies internal counters (data->pt and data->i). */ static int getNextOption(struct global *data) { int nRet; assert( data ); data->arg = NULL; if( data->pt ) nRet = do_short_opt( data ); else if( !current_arg(data) ) nRet = RET_END; else if( force_end( current_arg(data) )) { data->i++; /* the user don't want the "--" stuff */ nRet = RET_END; } else if( !is_option( current_arg(data) )) nRet = RET_END; else if( is_long_opt( current_arg(data) )) nRet = do_long_option(data); else { data->pt = current_arg(data) + 1; nRet = do_short_opt( data ); } return nRet; }
// looking for nearest option or terminate sequence ('--') in argv from optind index // if no option found - return -1, else - index of found option static int look_for_option(int argc, char* const argv[], int optind) { assert(argv); for (int i = optind; i < argc; i++) if (is_option(argv[i]) || is_finish(argv[i])) return i; return -1; }
/* parse the arguments */ void argument_init( int argc, char **argv) { int i; char *option; i = 1; while (i < argc) { if( is_option("--help", argv[i]) ) { fprintf(stderr, _("Usage: %s [option ...]\nValid options are:\n"), argv[0]); fprintf(stderr, _(" -h, --help\t\tPrint a summary of the options\n")); fprintf(stderr, _(" -p, --port PORT\tBind the server to port PORT (default 2000)\n")); fprintf(stderr, _(" -s, --seed SEED\tNew seed for random\n")); fprintf(stderr, _(" -v, --version\t\tPrint the version number\n")); fprintf(stderr, _(" -c, --console BOOLEAN\tEnable the console or not (default 1)\n")); #ifdef WITH_GGZ fprintf(stderr, _(" -g, --ggz\t\tEnable the GGZ mode (default OFF)\n")); #endif /* WITH_GGZ */ fprintf(stderr, _(" -m, --metaserver BOOLEAN\tPublish this server with the metaserver (default 0)\n")); fprintf(stderr, _(" -d, --debug\tEnable verbosity in server\n")); exit(0); } else if (is_option("--version",argv[i])) { fprintf(stderr, TEG_NAME" v"VERSION"\n\n"); exit(0); } else if ((option = get_option("--port",argv,&i,argc)) != NULL) { g_server.port=atoi(option); } else if ((option = get_option("--seed",argv,&i,argc)) != NULL) { g_game.seed=atoi(option); } else if ((option = get_option("--console",argv,&i,argc)) != NULL) { g_server.with_console=atoi(option); #ifdef WITH_GGZ } else if (is_option("--ggz",argv[i])) { g_server.with_ggz=1; g_server.with_console=FALSE; #endif /* WITH_GGZ */ } else if ((option = get_option("--metaserver",argv,&i,argc)) != NULL) { g_server.metaserver_on=atoi(option); } else if ( is_option("--debug",argv[i])) { g_server.debug=1; } else { fprintf(stderr, _("Unrecognized option: \"%s\"\n"), argv[i]); exit(1); } i++; } }
void sh_applyopts(Shell_t *shp, Shopt_t newflags) { // Cannot set -n for interactive shells since there is no way out. if (sh_isoption(shp, SH_INTERACTIVE)) off_option(&newflags, SH_NOEXEC); if (is_option(&newflags, SH_PRIVILEGED)) on_option(&newflags, SH_NOUSRPROFILE); int is_privileged = is_option(&newflags, SH_PRIVILEGED) != sh_isoption(shp, SH_PRIVILEGED); int is_privileged_off = is_option(&(shp->arg_context)->sh->offoptions, SH_PRIVILEGED); if ((!sh_isstate(shp, SH_INIT) && is_privileged) || (sh_isstate(shp, SH_INIT) && is_privileged_off && shp->gd->userid != shp->gd->euserid)) { if (!is_option(&newflags, SH_PRIVILEGED)) { if (setuid(shp->gd->userid) < 0) { error(ERROR_system(0), "setuid(%d) failed", shp->gd->userid); return; } if (setgid(shp->gd->groupid) < 0) { error(ERROR_system(0), "setgid(%d) failed", shp->gd->groupid); return; } if (shp->gd->euserid == 0) { shp->gd->euserid = shp->gd->userid; shp->gd->egroupid = shp->gd->groupid; } } else if ((shp->gd->userid != shp->gd->euserid && setuid(shp->gd->euserid) < 0) || (shp->gd->groupid != shp->gd->egroupid && setgid(shp->gd->egroupid) < 0) || (shp->gd->userid == shp->gd->euserid && shp->gd->groupid == shp->gd->egroupid)) { off_option(&newflags, SH_PRIVILEGED); } } #if SHOPT_BASH on_option(&newflags, SH_CMDHIST); on_option(&newflags, SH_CHECKHASH); on_option(&newflags, SH_EXECFAIL); on_option(&newflags, SH_EXPAND_ALIASES); on_option(&newflags, SH_HISTAPPEND); on_option(&newflags, SH_INTERACTIVE_COMM); on_option(&newflags, SH_LITHIST); on_option(&newflags, SH_NOEMPTYCMDCOMPL); if (!is_option(&newflags, SH_XPG_ECHO) && sh_isoption(shp, SH_XPG_ECHO)) { astconf("UNIVERSE", 0, "ucb"); } if (is_option(&newflags, SH_XPG_ECHO) && !sh_isoption(shp, SH_XPG_ECHO)) { astconf("UNIVERSE", 0, "att"); } if (is_option(&newflags, SH_HISTORY2) && !sh_isoption(shp, SH_HISTORY2)) { sh_onstate(shp, SH_HISTORY); sh_onoption(shp, SH_HISTORY); } if (!is_option(&newflags, SH_HISTORY2) && sh_isoption(shp, SH_HISTORY2)) { sh_offstate(shp, SH_HISTORY); sh_offoption(shp, SH_HISTORY); } #endif shp->options = newflags; }
/************************************************************************** Parse freeciv-ruledit commandline. **************************************************************************/ static int re_parse_cmdline(int argc, char *argv[]) { int i = 1; bool ui_separator = FALSE; int ui_options = 0; const char *option = NULL; while (i < argc) { if (ui_separator) { argv[1 + ui_options] = argv[i]; ui_options++; } else if (is_option("--help", argv[i])) { struct cmdhelp *help = cmdhelp_new(argv[0]); cmdhelp_add(help, "h", "help", R__("Print a summary of the options")); cmdhelp_add(help, "s", /* TRANS: "source" is exactly what user must type, do not translate. */ R__("source RULESET"), R__("Load given ruleset")); cmdhelp_add(help, "v", "version", R__("Print the version number")); /* The function below prints a header and footer for the options. * Furthermore, the options are sorted. */ cmdhelp_display(help, TRUE, TRUE, TRUE); cmdhelp_destroy(help); exit(EXIT_SUCCESS); } else if ((option = get_option_malloc("--source", argv, &i, argc))) { source_rs = option; } else if (is_option("--version", argv[i])) { fc_fprintf(stderr, "%s \n", freeciv_name_version()); exit(EXIT_SUCCESS); } else if (is_option("--", argv[i])) { ui_separator = TRUE; } i++; } return ui_options; }
/************************************************************************** search for command line options. right now, it's just help semi-useless until we have options that aren't the same across all clients. **************************************************************************/ static void parse_options(int argc, char **argv) { int i = 1; char *option = NULL; while (i < argc) { if (is_option("--help", argv[i])) { print_usage(argv[0]); exit(EXIT_SUCCESS); } else if (is_option("--fullscreen",argv[i])) { gui_sdl_fullscreen = TRUE; } else if (is_option("--eventthread",argv[i])) { /* init events in other thread ( only linux and BeOS ) */ SDL_InitSubSystem(SDL_INIT_EVENTTHREAD); } else if ((option = get_option_malloc("--theme", argv, &i, argc))) { sz_strlcpy(gui_sdl_default_theme_name, option); } i++; } }
// this function is called when we need to detect next option entry in argv // return value: // true - next option entry found, retval not used // false - no more options, retval - reason (-1 no more options, 1 - argument processed as default // option with code 1) static bool detect_next_option(int argc, char* const argv[], const getopt_param& param, int& retval) { if (!is_option(argv[optind])) { // if optind points to non-option - then check it... if (is_finish(argv[optind])) { // is it terminate sequence ('--')? optind++; if(!param.posix && !param.process_all) swap_values(argc, (char**)argv, optind); retval = -1; return false; } else if (param.process_all) {// processing all elements optarg = (char*)argv[optind]; optind++; retval = 1; return false; } else if (param.posix) { retval = -1; return false; } else { int next_ind = look_for_option(argc, argv, optind); assert(next_ind != optind); // should not be same if (next_ind > 0) { add_to_swap(optind, next_ind - optind); // marking elements for swap /* NOTE: in swap_list stored indexes of elements which are not detected as options and not detected as arguments (if argv[x] is detected as option - stsrts with '-', it doesn't added to this list). later, when no more element may be detected, these stored elements are moved to end of argv vector */ optind = next_ind; } else {// no more options found swap_values(argc, (char**)argv, optind); retval = -1; return false; } } if (is_finish(argv[optind])) { optind++; if (!param.posix && !param.process_all) swap_values(argc, (char**)argv, optind); retval = -1; return false; } } return true; }
/************************************************************************** ... **************************************************************************/ static void parse_options(int argc, char **argv) { int i; i = 1; while (i < argc) { if (is_option("--help", argv[i])) { print_usage(argv[0]); exit(EXIT_SUCCESS); } i += 1; } }
static int is_option(char *str, int j) { int i; i = j; while (str[i]) { if (str[i] == '-' && str[i + 1] && str[i + 1] == 'n' && ((!str[i + 2]) || str[i + 2] == ' ' || str[i + 2] == '\t')) { i += 2; return (is_option(str, i)); } if (str[i] != ' ' && str[i] != '\t') return (j); i++; } return (j); }
/* * handle the long options. * returs <0 on error. * TODO: stinks */ static int do_long_option ( struct global *data ) { char *q,*arg ; int n; assert( data ); arg = current_arg(data)+2; data->i++; if( (q=strchr( arg , '=' )) ) /* separate --argument=something */ { q++; *(q-1)=0; if(!*q) q=NULL; } n = findLongOption ( data->table , arg); if( n<0 ) { n = RET_UNKNOW; report(data->flags,_("unknow long option `%s'"),arg); } else if( has_one_arg( data->table[n] ) ) { if( q ) /* inline option */ data->arg = q; else if( !current_arg(data) || force_end( current_arg(data) ) || ( !is_number(current_arg(data)) && is_option(current_arg(data)) ) ) { n = RET_ENOUGH; report(data->flags,_("not enough parameters for `%s'"), arg); } else { data->arg = current_arg(data); data->i++; } } else if( data->table[n].flags!=0) assert( 0 ); return n; }
int check_args(int ac, char **av, t_env *e) { int nbarg; int i; i = 1; while (i < ac && is_option(av[i], e)) i++; while (--ac >= i) { nbarg = ac; if (!is_valid_int(av[ac])) return (0); while (--nbarg) { if (ft_atoi(av[ac]) == ft_atoi(av[nbarg])) return (0); } } ac++; return (ac); }
static int check_invalid_options(char *s) { char *invalid; if (is_multi_minus(s, &invalid)) { invalid_option(invalid); ft_strclean(invalid); return (1); } while (*(++s) != '\0') { if (!is_option(*s)) { invalid = ft_strndup(s, 1); invalid_option(invalid); ft_strclean(invalid); return (1); } } return (0); }
/* * gets aditionals parameters of an option if any. * <0 error. else the position in the table of the command */ static int do_short_opt( struct global *data ) { int c; int n; assert( data ); c = *(data->pt++); if( !*data->pt ) /* we finish this arg. go to the next */ { data->pt = NULL; data->i++; } n = findShortOption( data->table,c); if( n < 0 ) { n = RET_UNKNOW; report(data->flags,_("unknow option '%c'"),c); } else if( has_one_arg( data->table[n] ) ) { if( data->pt ) /* inlined argument */ { data->arg = data->pt; data->pt = NULL; data->i++; } else if ( !current_arg(data) || force_end(current_arg(data)) || ( !is_number(current_arg(data)) && is_option(current_arg(data)) ) ) { n = RET_ENOUGH; report(data->flags,_("not enough parameters for `%c'"), c); } else { data->arg = current_arg(data); data->i++; } } return n; }
char * grub_legacy_parse (const char *buf, char **entryname, char **suffix) { const char *ptr; const char *cmdname; unsigned i, cmdnum; char *args[ARRAY_SIZE (legacy_commands[0].argt)]; *suffix = NULL; for (ptr = buf; *ptr && grub_isspace (*ptr); ptr++); if (!*ptr || *ptr == '#') { char *ret; int len = grub_strlen (buf); ret = grub_malloc (len + 2); grub_memcpy (ret, buf, len); if (len && ret[len - 1] == '\n') ret[len] = 0; else { ret[len] = '\n'; ret[len + 1] = 0; } return ret; } cmdname = ptr; for (ptr = buf; *ptr && !grub_isspace (*ptr) && *ptr != '='; ptr++); for (cmdnum = 0; cmdnum < ARRAY_SIZE (legacy_commands); cmdnum++) if (grub_strncmp (legacy_commands[cmdnum].name, cmdname, ptr - cmdname) == 0 && legacy_commands[cmdnum].name[ptr - cmdname] == 0 && (!(*entryname != NULL && (legacy_commands[cmdnum].flags & FLAG_NO_MENUENTRY))) && (!(*entryname == NULL && (legacy_commands[cmdnum].flags & FLAG_MENUENTRY_ONLY)))) break; if (cmdnum == ARRAY_SIZE (legacy_commands)) return grub_xasprintf ("# Unsupported legacy command: %s\n", buf); for (; grub_isspace (*ptr) || *ptr == '='; ptr++); if (legacy_commands[cmdnum].flags & FLAG_TITLE) { const char *ptr2; ptr2 = ptr + grub_strlen (ptr); while (ptr2 > ptr && grub_isspace (*(ptr2 - 1))) ptr2--; *entryname = grub_strndup (ptr, ptr2 - ptr); return NULL; } if (legacy_commands[cmdnum].flags & FLAG_TERMINAL) { int dumb = 0, lines = 24; #ifdef TODO int no_echo = 0, no_edit = 0; #endif int hercules = 0; int console = 0, serial = 0, graphics = 0; /* Big enough for any possible resulting command. */ char outbuf[512] = ""; char *outptr; while (*ptr) { /* "[--timeout=SECS] [--silent]" " [console] [serial] [hercules]"*/ if (grub_memcmp (ptr, "--dumb", sizeof ("--dumb") - 1) == 0) dumb = 1; #ifdef TODO if (grub_memcmp (ptr, "--no-echo", sizeof ("--no-echo") - 1) == 0) no_echo = 1; if (grub_memcmp (ptr, "--no-edit", sizeof ("--no-edit") - 1) == 0) no_edit = 1; #endif if (grub_memcmp (ptr, "--lines=", sizeof ("--lines=") - 1) == 0) { lines = grub_strtoul (ptr + sizeof ("--lines=") - 1, 0, 0); if (grub_errno) { lines = 24; grub_errno = GRUB_ERR_NONE; } } if (grub_memcmp (ptr, "console", sizeof ("console") - 1) == 0) console = 1; if (grub_memcmp (ptr, "serial", sizeof ("serial") - 1) == 0) serial = 1; if (grub_memcmp (ptr, "hercules", sizeof ("hercules") - 1) == 0) hercules = 1; if (grub_memcmp (ptr, "graphics", sizeof ("graphics") - 1) == 0) graphics = 1; while (*ptr && !grub_isspace (*ptr)) ptr++; while (*ptr && grub_isspace (*ptr)) ptr++; } if (!console && !serial && !hercules && !graphics) return grub_strdup ("terminal_input; terminal_output; terminfo\n"); outptr = outbuf; if (graphics) outptr = grub_stpcpy (outptr, "insmod all_video; "); outptr = grub_stpcpy (outptr, "terminal_input "); if (serial) outptr = grub_stpcpy (outptr, "serial "); if (console || hercules || graphics) outptr = grub_stpcpy (outptr, "console "); outptr = grub_stpcpy (outptr, "; terminal_output "); if (serial) outptr = grub_stpcpy (outptr, "serial "); if (console) outptr = grub_stpcpy (outptr, "console "); if (hercules) outptr = grub_stpcpy (outptr, "mda_text "); if (graphics) outptr = grub_stpcpy (outptr, "gfxterm "); outptr = grub_stpcpy (outptr, "; "); *outptr = '\0'; if (serial) { grub_snprintf (outptr, outbuf + sizeof (outbuf) - outptr, "terminfo serial -g 80x%d %s; ", lines, dumb ? "dumb" : "vt100"); outptr += grub_strlen (outptr); } grub_strcpy (outptr, "\n"); return grub_strdup (outbuf); } grub_memset (args, 0, sizeof (args)); { int hold_arg = 0; const char *curarg = NULL; for (i = 0; i < legacy_commands[cmdnum].argc; i++) { grub_size_t curarglen; if (hold_arg) { ptr = curarg; hold_arg = 0; } for (; grub_isspace (*ptr); ptr++); curarg = ptr; if (!*curarg) break; for (; *ptr && !grub_isspace (*ptr); ptr++); if (i != legacy_commands[cmdnum].argc - 1 || (legacy_commands[cmdnum].flags & FLAG_IGNORE_REST)) curarglen = ptr - curarg; else { curarglen = grub_strlen (curarg); while (curarglen > 0 && grub_isspace (curarg[curarglen - 1])) curarglen--; } if (*ptr) ptr++; switch (legacy_commands[cmdnum].argt[i]) { case TYPE_FILE_NO_CONSUME: hold_arg = 1; case TYPE_PARTITION: case TYPE_FILE: args[i] = adjust_file (curarg, curarglen); break; case TYPE_REST_VERBATIM: { char *outptr, *outptr0; int overhead = 3; ptr = curarg; while (*ptr) { for (; *ptr && grub_isspace (*ptr); ptr++); for (; *ptr && !grub_isspace (*ptr); ptr++) if (*ptr == '\'') overhead += 3; if (*ptr) ptr++; overhead += 3; } outptr0 = args[i] = grub_malloc (overhead + (ptr - curarg)); if (!outptr0) return NULL; ptr = curarg; outptr = outptr0; while (*ptr) { for (; *ptr && grub_isspace (*ptr); ptr++); if (outptr != outptr0) *outptr++ = ' '; *outptr++ = '\''; for (; *ptr && !grub_isspace (*ptr); ptr++) { if (*ptr == '\'') { *outptr++ = '\''; *outptr++ = '\\'; *outptr++ = '\''; *outptr++ = '\''; } else *outptr++ = *ptr; } *outptr++ = '\''; if (*ptr) ptr++; } *outptr++ = 0; } break; case TYPE_VERBATIM: args[i] = grub_legacy_escape (curarg, curarglen); break; case TYPE_WITH_CONFIGFILE_OPTION: case TYPE_FORCE_OPTION: case TYPE_NOAPM_OPTION: case TYPE_TYPE_OR_NOMEM_OPTION: case TYPE_OPTION: if (is_option (legacy_commands[cmdnum].argt[i], curarg, curarglen)) { args[i] = grub_strndup (curarg, curarglen); break; } args[i] = grub_strdup (""); hold_arg = 1; break; case TYPE_INT: { const char *brk; int base = 10; brk = curarg; if (brk[0] == '0' && brk[1] == 'x') { base = 16; brk += 2; } else if (brk[0] == '0') base = 8; for (; *brk && brk < curarg + curarglen; brk++) { if (base == 8 && (*brk == '8' || *brk == '9')) break; if (grub_isdigit (*brk)) continue; if (base != 16) break; if (!(*brk >= 'a' && *brk <= 'f') && !(*brk >= 'A' && *brk <= 'F')) break; } if (brk == curarg) args[i] = grub_strdup ("0"); else args[i] = grub_strndup (curarg, brk - curarg); } break; case TYPE_VBE_MODE: { unsigned mod; struct grub_vesa_mode_table_entry *modedesc; mod = grub_strtoul (curarg, 0, 0); if (grub_errno) { mod = 0; grub_errno = GRUB_ERR_NONE; } if (mod < GRUB_VESA_MODE_TABLE_START || mod > GRUB_VESA_MODE_TABLE_END) { args[i] = grub_strdup ("auto"); break; } modedesc = &grub_vesa_mode_table[mod - GRUB_VESA_MODE_TABLE_START]; if (!modedesc->width) { args[i] = grub_strdup ("auto"); break; } args[i] = grub_xasprintf ("%ux%ux%u", modedesc->width, modedesc->height, modedesc->depth); break; } case TYPE_BOOL: if (curarglen == 2 && curarg[0] == 'o' && curarg[1] == 'n') args[i] = grub_strdup ("1"); else args[i] = grub_strdup ("0"); break; } } } while (legacy_commands[cmdnum].argc > 0 && args[legacy_commands[cmdnum].argc - 1] == NULL && (legacy_commands[cmdnum].flags & FLAG_FALLBACK_AVAILABLE) && args[legacy_commands[cmdnum + 1].argc] == NULL) cmdnum++; for (; i < legacy_commands[cmdnum].argc; i++) switch (legacy_commands[cmdnum].argt[i]) { case TYPE_FILE_NO_CONSUME: case TYPE_PARTITION: case TYPE_FILE: case TYPE_REST_VERBATIM: case TYPE_VERBATIM: case TYPE_WITH_CONFIGFILE_OPTION: case TYPE_FORCE_OPTION: case TYPE_NOAPM_OPTION: case TYPE_TYPE_OR_NOMEM_OPTION: case TYPE_OPTION: args[i] = grub_strdup (""); break; case TYPE_BOOL: case TYPE_INT: args[i] = grub_strdup ("0"); break; case TYPE_VBE_MODE: args[i] = grub_strdup ("auto"); break; } if (legacy_commands[cmdnum].flags & FLAG_COLOR_INVERT) { char *corig = args[legacy_commands[cmdnum].argc - 1]; char *slash = grub_strchr (corig, '/'); char *invert; grub_size_t len; len = grub_strlen (corig); if (!slash) { grub_error (GRUB_ERR_BAD_ARGUMENT, N_("invalid color specification `%s'"), args[0]); return NULL; } invert = grub_malloc (len + 1); if (!invert) return NULL; grub_memcpy (invert, slash + 1, len - (slash - corig) - 1); invert[len - (slash - args[0]) - 1] = '/'; grub_memcpy (invert + len - (slash - corig), corig, slash - corig); invert[len] = 0; args[legacy_commands[cmdnum].argc] = invert; } if (legacy_commands[cmdnum].suffix) { *suffix = grub_xasprintf (legacy_commands[cmdnum].suffix, args[legacy_commands[cmdnum].suffixarg]); if (*suffix) return NULL; } { char *ret = grub_xasprintf (legacy_commands[cmdnum].map, args[0], args[1], args[2], args[3]); grub_free (args[0]); grub_free (args[1]); grub_free (args[2]); grub_free (args[3]); return ret; } }
void parse_args(int argc, const char *argv[]) { // parse command line arguments for (; option.argi < argc; option.argi++) { // not an option if (!is_option(argv[option.argi])) return; // set accumulation filename [setup] if (!strcmp(argv[option.argi], "--accum") || (!option.lgopt && !strcmp(argv[option.argi], "-a"))) { option.accum = argv[++option.argi]; debug("accumulation filename set to '%s'", option.accum); continue; } // set blank mode [setup] if (!strcmp(argv[option.argi], "--blank") || (!option.lgopt && !strcmp(argv[option.argi], "-b"))) { debug("blank spaces ignored"); option.blank = 1; continue; } // set config extension [setup] if (!strcmp(argv[option.argi], "--cfgext")) { option.cfg_e = argv[++option.argi]; debug("config extension set to '%s'", option.cfg_e); continue; } // set comment characters [setup] if (!strcmp(argv[option.argi], "--comment") || (!option.lgopt && !strcmp(argv[option.argi], "-c"))) { option.cchr = argv[++option.argi]; debug("comment characters set to '%s'", option.cchr); continue; } // set debug mode [setup] if (!strcmp(argv[option.argi], "--debug") || (!option.lgopt && !strcmp(argv[option.argi], "-d"))) { logmsg_config.level = debug_level; logmsg_config.locate = 1; debug("debug mode on"); option.debug = 1; option.check = 1; continue; } // display help [action] if (!strcmp(argv[option.argi], "--help") || (!option.lgopt && !strcmp(argv[option.argi], "-h"))) { usage(); continue; } // set info mode [setup] if (!strcmp(argv[option.argi], "--info") || (!option.lgopt && !strcmp(argv[option.argi], "-i"))) { debug("info mode on"); logmsg_config.level = inform_level; logmsg_config.locate = 0; continue; } // set keep number [setup] if (!strcmp(argv[option.argi], "--keep") || (!option.lgopt && !strcmp(argv[option.argi], "-k"))) { option.keep = strtoul(argv[++option.argi],0,0); debug("keep set to %d", option.keep); continue; } // enable left result [setup] if (!strcmp(argv[option.argi], "--lhsrec")) { debug("recycling left file enabled"); option.recycle = ndiff_recycle_left; continue; } // enable left result [setup] if (!strcmp(argv[option.argi], "--lhsres")) { debug("left results enabled"); option.lhs_res = 1; continue; } // set list mode [setup] if (!strcmp(argv[option.argi], "--list") || (!option.lgopt && !strcmp(argv[option.argi], "-l"))) { debug("list mode on"); option.list = 1; continue; } // disable short options [setup] if (!strcmp(argv[option.argi], "--long")) { debug("short options disabled"); option.lgopt = 1; continue; } // disable color [setup] if (!strcmp(argv[option.argi], "--nocolor")) { debug("color output disabled"); fail_str = "FAIL"; pass_str = "PASS"; continue; } // disable location trace [setup] if (!strcmp(argv[option.argi], "--noloc")) { debug("trace of location disabled"); logmsg_config.locate = 0; continue; } // disable warnings [setup] if (!strcmp(argv[option.argi], "--nowarn")) { debug("no warning mode on"); logmsg_config.level = error_level; logmsg_config.locate = 0; option.nowarn = 1; continue; } // set number of registers [setup] if (!strcmp(argv[option.argi], "--nregs")) { option.nregs = imin(REG_MAX, strtoul(argv[++option.argi],0,0)); debug("number of registers set to %d", option.nregs); continue; } // set output extension [setup] if (!strcmp(argv[option.argi], "--outext")) { option.out_e = argv[++option.argi]; debug("output extension set to '%s'", option.out_e); continue; } // set punctuation characters [setup] if (!strcmp(argv[option.argi], "--punct")) { option.pchr = argv[++option.argi]; debug("punctuation characters set to '%s'", option.pchr); continue; } // set quiet mode [setup] if (!strcmp(argv[option.argi], "--quiet") || (!option.lgopt && !strcmp(argv[option.argi], "-q"))) { debug("quiet mode on"); logmsg_config.level = warning_level; logmsg_config.locate = 0; continue; } // set reference extension [setup] if (!strcmp(argv[option.argi], "--refext")) { option.ref_e = argv[++option.argi]; debug("reference extension set to '%s'", option.ref_e); continue; } // set register format [setup] if (!strcmp(argv[option.argi], "--regfmt")) { option.rfmt = argv[++option.argi]; debug("register format set to '%s'", option.rfmt); continue; } // set result extension [setup] if (!strcmp(argv[option.argi], "--resext")) { option.res_e = argv[++option.argi]; debug("result extension set to '%s'", option.res_e); continue; } // reset accumulation information [action] if (!strcmp(argv[option.argi], "--reset") || (!option.lgopt && !strcmp(argv[option.argi], "-r"))) { ensure(option.accum, "no accumulation file specified"); debug("reseting file '%s'", option.accum); option.reset = 1; accum_summary(0, 0, 0, 0); continue; } // enable right result [setup] if (!strcmp(argv[option.argi], "--rhsrec")) { debug("recycling right file enabled"); option.recycle = ndiff_recycle_right; continue; } // enable right result [setup] if (!strcmp(argv[option.argi], "--rhsres")) { debug("right results enabled"); option.rhs_res = 1; continue; } // set serie mode [setup] if (!strcmp(argv[option.argi], "--serie") || (!option.lgopt && !strcmp(argv[option.argi], "-n"))) { debug("serie mode on"); option.serie = 1; continue; } // set serie format [setup] if (!strcmp(argv[option.argi], "--seriefmt")) { option.fmt = argv[++option.argi]; debug("serie format set to '%s'", option.fmt); continue; } // set suite name [setup] if (!strcmp(argv[option.argi], "--suite") || (!option.lgopt && !strcmp(argv[option.argi], "-s"))) { option.suite = argv[++option.argi]; debug("suite name set to '%s'", option.suite); continue; } // set suite format [setup] if (!strcmp(argv[option.argi], "--suitefmt")) { option.sfmt = argv[++option.argi]; debug("suite format set to '%s'", option.sfmt); continue; } // set test name [setup] if (!strcmp(argv[option.argi], "--test") || (!option.lgopt && !strcmp(argv[option.argi], "-t"))) { option.test = argv[++option.argi]; debug("test name set to '%s'", option.test); continue; } // set trace mode [setup] if (!strcmp(argv[option.argi], "--trace")) { logmsg_config.level = trace_level; logmsg_config.locate = 1; debug("trace mode on"); option.debug = 1; option.check = 1; continue; } // enable truncation [setup] if (!strcmp(argv[option.argi], "--trunc")) { debug("premature truncation allowed"); option.trunc = 1; continue; } // run utests [action] if (!strcmp(argv[option.argi], "--utest")) { run_utest(); option.utest += 1; continue; } // set check mode [setup] if (!strcmp(argv[option.argi], "--xcheck") || (!option.lgopt && !strcmp(argv[option.argi], "-x"))) { debug("check mode on"); option.check = 1; continue; } // ---- [decompression] // set tertiary unzip command [setup] if (!strcmp(argv[option.argi], "--bzip2")) { option.unzip[2] = argv[++option.argi]; debug("bzip2 command set to '%s'", option.unzip[2]); continue; } // set secondary unzip command [setup] if (!strcmp(argv[option.argi], "--gzip")) { option.unzip[1] = argv[++option.argi]; debug("gzip command set to '%s'", option.unzip[1]); continue; } // set primary unzip command [setup] if (!strcmp(argv[option.argi], "--unzip")) { option.unzip[0] = argv[++option.argi]; debug("unzip command set to '%s'", option.unzip[0]); continue; } // ---- [unknown] invalid_option(argv[option.argi]); } exit(EXIT_SUCCESS); }
int main(int argc, char **argv) { char* initial_cube = NULL; char* target_cube = NULL; char* sequence = NULL; int i; int output_limit = -1; if (argc) { if (argv[0][0] == '.' && argv[0][1] == '/') { PROGRAM_NAME = &argv[0][2]; } else { PROGRAM_NAME = argv[0]; } } while (argc-- > 1) { argv++; if (is_valid_sequence(*argv)) { if (sequence) { error("Invalid argument, already got a sequence"); } sequence = *argv; } else if (is_valid_cube_data(*argv)) { if (!initial_cube) { initial_cube = *argv; } else if (!target_cube) { target_cube = *argv; } else { error("Invalid argument, too many cube arguments"); } } else if (is_option(*argv, 'h', "help")) { usage(); } else if (is_option(*argv, 'l', "limit")) { if ((output_limit = atoi(*++argv)) <= 0) { output_limit = -1; } argc--; } else if (is_option(*argv, 'b', "best")) { output_limit = 1; } else if (is_option(*argv, 'a', "all")) { output_limit = -1; } else if (is_option(*argv, 's', "sequence")) { if ((MAX_SEQUENCE_SIZE = atoi(*++argv)) <= 0) { MAX_SEQUENCE_SIZE = DEFAULT_SEQUENCE_SIZE; } argc--; } else { error("Invalid argument"); } } if (!sequence && initial_cube && !target_cube) { target_cube = initial_cube; initial_cube = DEFAULT_CUBE; } else if (sequence && !initial_cube) { initial_cube = DEFAULT_CUBE; } if (!sequence && !initial_cube && !target_cube) { error("No arguments given"); } cube_t* cube = cube_create(initial_cube); if (sequence) { cube_transform(cube, sequence); printf("%s\n", cube->data); } else { solutions_t* solutions = brute_solutions_create(SOLUTION_LIMIT); brute_cube(solutions, cube, target_cube); brute_solutions_sort(solutions); if (output_limit < 0 || output_limit > solutions->size) { output_limit = solutions->size; } for(i = 0; i < output_limit; i++) { printf("%s\n", solutions->array[i]->sequence); } brute_solutions_free(solutions); } cube_free(cube); return 0; }
/* process command-line arguments */ int process_arguments (int argc, char **argv) { int c; int option = 0; static struct option longopts[] = { {"filename", required_argument, 0, 'F'}, {"expires", required_argument, 0, 'e'}, {"command", required_argument, 0, 'C'}, {"timeout", optional_argument, 0, 't'}, {"version", no_argument, 0, 'V'}, {"help", no_argument, 0, 'h'}, {"verbose", no_argument, 0, 'v'}, {0, 0, 0, 0} }; if (argc < 2) return ERROR; if (!is_option (argv[1])) { status_log = argv[1]; if (is_intnonneg (argv[2])) expire_minutes = atoi (argv[2]); else die (STATE_UNKNOWN, _("Expiration time must be an integer (seconds)\n")); process_string = argv[3]; return OK; } while (1) { c = getopt_long (argc, argv, "+hVvF:C:e:t:", longopts, &option); if (c == -1 || c == EOF || c == 1) break; switch (c) { case 'h': /* help */ print_help (); exit (STATE_OK); case 'V': /* version */ print_revision (progname, NP_VERSION); exit (STATE_OK); case 'F': /* status log */ status_log = optarg; break; case 'C': /* command */ process_string = optarg; break; case 'e': /* expiry time */ if (is_intnonneg (optarg)) expire_minutes = atoi (optarg); else die (STATE_UNKNOWN, _("Expiration time must be an integer (seconds)\n")); break; case 't': /* timeout */ if (is_intnonneg (optarg)) timeout_interval = atoi (optarg); else die (STATE_UNKNOWN, _("Timeout must be an integer (seconds)\n")); break; case 'v': verbose++; break; default: /* print short usage_va statement if args not parsable */ usage5(); } } if (status_log == NULL) die (STATE_UNKNOWN, _("You must provide the status_log\n")); if (process_string == NULL) die (STATE_UNKNOWN, _("You must provide a process string\n")); return OK; }
/* process command-line arguments */ static int process_arguments (int argc, char **argv) { int c; int escape = 0; int option = 0; static struct option longopts[] = { {"hostname", required_argument, 0, 'H'}, {"critical", required_argument, 0, 'c'}, {"warning", required_argument, 0, 'w'}, {"critical-codes", required_argument, 0, 'C'}, {"warning-codes", required_argument, 0, 'W'}, {"timeout", required_argument, 0, 't'}, {"protocol", required_argument, 0, 'P'}, /* FIXME: Unhandled */ {"port", required_argument, 0, 'p'}, {"escape", no_argument, 0, 'E'}, {"all", no_argument, 0, 'A'}, {"send", required_argument, 0, 's'}, {"expect", required_argument, 0, 'e'}, {"maxbytes", required_argument, 0, 'm'}, {"quit", required_argument, 0, 'q'}, {"jail", no_argument, 0, 'j'}, {"delay", required_argument, 0, 'd'}, {"refuse", required_argument, 0, 'r'}, {"mismatch", required_argument, 0, 'M'}, {"use-ipv4", no_argument, 0, '4'}, {"use-ipv6", no_argument, 0, '6'}, {"verbose", no_argument, 0, 'v'}, {"version", no_argument, 0, 'V'}, {"help", no_argument, 0, 'h'}, {"ssl", no_argument, 0, 'S'}, {"certificate", required_argument, 0, 'D'}, {0, 0, 0, 0} }; if (argc < 2) usage4 (_("No arguments found")); /* backwards compatibility */ for (c = 1; c < argc; c++) { if (strcmp ("-to", argv[c]) == 0) strcpy (argv[c], "-t"); else if (strcmp ("-wt", argv[c]) == 0) strcpy (argv[c], "-w"); else if (strcmp ("-ct", argv[c]) == 0) strcpy (argv[c], "-c"); } if (!is_option (argv[1])) { server_address = argv[1]; argv[1] = argv[0]; argv = &argv[1]; argc--; } while (1) { c = getopt_long (argc, argv, "+hVv46EAH:s:e:q:m:c:w:t:p:C:W:d:Sr:jD:M:", longopts, &option); if (c == -1 || c == EOF || c == 1) break; switch (c) { case '?': /* print short usage statement if args not parsable */ usage5 (); case 'h': /* help */ print_help (); exit (STATE_OK); case 'V': /* version */ print_revision (progname, NP_VERSION); exit (STATE_OK); case 'v': /* verbose mode */ flags |= FLAG_VERBOSE; break; case '4': address_family = AF_INET; break; case '6': #ifdef USE_IPV6 address_family = AF_INET6; #else usage4 (_("IPv6 support not available")); #endif break; case 'H': /* hostname */ server_address = optarg; break; case 'c': /* critical */ critical_time = strtod (optarg, NULL); flags |= FLAG_TIME_CRIT; break; case 'j': /* hide output */ flags |= FLAG_HIDE_OUTPUT; break; case 'w': /* warning */ warning_time = strtod (optarg, NULL); flags |= FLAG_TIME_WARN; break; case 'C': crit_codes = realloc (crit_codes, ++crit_codes_count); crit_codes[crit_codes_count - 1] = optarg; break; case 'W': warn_codes = realloc (warn_codes, ++warn_codes_count); warn_codes[warn_codes_count - 1] = optarg; break; case 't': /* timeout */ if (!is_intpos (optarg)) usage4 (_("Timeout interval must be a positive integer")); else socket_timeout = atoi (optarg); break; case 'p': /* port */ if (!is_intpos (optarg)) usage4 (_("Port must be a positive integer")); else server_port = atoi (optarg); break; case 'E': escape = 1; break; case 's': if (escape) server_send = np_escaped_string(optarg); else asprintf(&server_send, "%s", optarg); break; case 'e': /* expect string (may be repeated) */ flags &= ~FLAG_EXACT_MATCH; if (server_expect_count == 0) server_expect = malloc (sizeof (char *) * (++server_expect_count)); else server_expect = realloc (server_expect, sizeof (char *) * (++server_expect_count)); server_expect[server_expect_count - 1] = optarg; break; case 'm': if (!is_intpos (optarg)) usage4 (_("Maxbytes must be a positive integer")); else maxbytes = strtol (optarg, NULL, 0); break; case 'q': if (escape) server_quit = np_escaped_string(optarg); else asprintf(&server_quit, "%s\r\n", optarg); break; case 'r': if (!strncmp(optarg,"ok",2)) econn_refuse_state = STATE_OK; else if (!strncmp(optarg,"warn",4)) econn_refuse_state = STATE_WARNING; else if (!strncmp(optarg,"crit",4)) econn_refuse_state = STATE_CRITICAL; else usage4 (_("Refuse must be one of ok, warn, crit")); break; case 'M': if (!strncmp(optarg,"ok",2)) expect_mismatch_state = STATE_OK; else if (!strncmp(optarg,"warn",4)) expect_mismatch_state = STATE_WARNING; else if (!strncmp(optarg,"crit",4)) expect_mismatch_state = STATE_CRITICAL; else usage4 (_("Mismatch must be one of ok, warn, crit")); break; case 'd': if (is_intpos (optarg)) delay = atoi (optarg); else usage4 (_("Delay must be a positive integer")); break; case 'D': /* Check SSL cert validity - days 'til certificate expiration */ #ifdef HAVE_SSL # ifdef USE_OPENSSL /* XXX */ if (!is_intnonneg (optarg)) usage2 (_("Invalid certificate expiration period"), optarg); days_till_exp = atoi (optarg); check_cert = TRUE; flags |= FLAG_SSL; break; # endif /* USE_OPENSSL */ #endif /* fallthrough if we don't have ssl */ case 'S': #ifdef HAVE_SSL flags |= FLAG_SSL; #else die (STATE_UNKNOWN, _("Invalid option - SSL is not available")); #endif break; case 'A': flags |= FLAG_MATCH_ALL; break; } } if (server_address == NULL) usage4 (_("You must provide a server address")); else if (server_address[0] != '/' && is_host (server_address) == FALSE) die (STATE_CRITICAL, "%s %s - %s: %s\n", SERVICE, state_text(STATE_CRITICAL), _("Invalid hostname, address or socket"), server_address); return TRUE; }
/* the main application entry point */ int main(int argc, char *argv[]) { char pid_path[PATH_MAX] = ""; /* full path to the pid file */ char pid_buffer[32] = ""; /* pid string */ char old_pid_buffer[32] = ""; /* pid string */ switch_size_t pid_len, old_pid_len; const char *err = NULL; /* error value for return from freeswitch initialization */ #ifndef WIN32 switch_bool_t nf = SWITCH_FALSE; /* TRUE if we are running in nofork mode */ switch_bool_t do_wait = SWITCH_FALSE; char *runas_user = NULL; char *runas_group = NULL; int fds[2] = { 0, 0 }; #else switch_bool_t win32_service = SWITCH_FALSE; #endif switch_bool_t nc = SWITCH_FALSE; /* TRUE if we are running in noconsole mode */ pid_t pid = 0; int i, x; char *opts; char opts_str[1024] = ""; char *local_argv[1024] = { 0 }; int local_argc = argc; char *arg_argv[128] = { 0 }; int alt_dirs = 0, log_set = 0, run_set = 0, do_kill = 0; int priority = 0; #ifdef __sun switch_core_flag_t flags = SCF_USE_SQL; #else switch_core_flag_t flags = SCF_USE_SQL | SCF_USE_AUTO_NAT | SCF_USE_NAT_MAPPING | SCF_CALIBRATE_CLOCK | SCF_USE_CLOCK_RT; #endif int ret = 0; switch_status_t destroy_status; switch_file_t *fd; switch_memory_pool_t *pool = NULL; #ifdef HAVE_SETRLIMIT #ifndef FS_64BIT switch_bool_t waste = SWITCH_FALSE; #endif #endif for (x = 0; x < argc; x++) { local_argv[x] = argv[x]; } if ((opts = getenv("FREESWITCH_OPTS"))) { strncpy(opts_str, opts, sizeof(opts_str) - 1); i = switch_separate_string(opts_str, ' ', arg_argv, (sizeof(arg_argv) / sizeof(arg_argv[0]))); for (x = 0; x < i; x++) { local_argv[local_argc++] = arg_argv[x]; } } if (local_argv[0] && strstr(local_argv[0], "freeswitchd")) { nc = SWITCH_TRUE; } for (x = 1; x < local_argc; x++) { if (switch_strlen_zero(local_argv[x])) continue; if (!strcmp(local_argv[x], "-help") || !strcmp(local_argv[x], "-h") || !strcmp(local_argv[x], "-?")) { printf("%s\n", usage); exit(EXIT_SUCCESS); } #ifdef WIN32 if (x == 1 && !strcmp(local_argv[x], "-service")) { /* New installs will always have the service name specified, but keep a default for compat */ x++; if (!switch_strlen_zero(local_argv[x])) { switch_copy_string(service_name, local_argv[x], SERVICENAME_MAXLEN); } else { switch_copy_string(service_name, SERVICENAME_DEFAULT, SERVICENAME_MAXLEN); } win32_service = SWITCH_TRUE; continue; } else if (x == 1 && !strcmp(local_argv[x], "-install")) { char servicePath[PATH_MAX]; char exePath[PATH_MAX]; SC_HANDLE hService; SC_HANDLE hSCManager; SERVICE_DESCRIPTION desc; desc.lpDescription = "The FreeSWITCH service."; x++; if (!switch_strlen_zero(local_argv[x])) { switch_copy_string(service_name, local_argv[x], SERVICENAME_MAXLEN); } else { switch_copy_string(service_name, SERVICENAME_DEFAULT, SERVICENAME_MAXLEN); } GetModuleFileName(NULL, exePath, sizeof(exePath)); snprintf(servicePath, sizeof(servicePath), "%s -service %s", exePath, service_name); /* Perform service installation */ hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if (!hSCManager) { fprintf(stderr, "Could not open service manager (%u).\n", GetLastError()); exit(EXIT_FAILURE); } hService = CreateService(hSCManager, service_name, service_name, GENERIC_READ | GENERIC_EXECUTE | SERVICE_CHANGE_CONFIG, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_IGNORE, servicePath, NULL, NULL, NULL, NULL, /* Service start name */ NULL); if (!hService) { fprintf(stderr, "Error creating freeswitch service (%u).\n", GetLastError()); CloseServiceHandle(hSCManager); exit(EXIT_FAILURE); } /* Set desc, and don't care if it succeeds */ if (!ChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &desc)) { fprintf(stderr, "FreeSWITCH installed, but could not set the service description (%u).\n", GetLastError()); } CloseServiceHandle(hService); CloseServiceHandle(hSCManager); exit(EXIT_SUCCESS); } else if (x == 1 && !strcmp(local_argv[x], "-uninstall")) { SC_HANDLE hService; SC_HANDLE hSCManager; BOOL deleted; x++; if (!switch_strlen_zero(local_argv[x])) { switch_copy_string(service_name, local_argv[x], SERVICENAME_MAXLEN); } else { switch_copy_string(service_name, SERVICENAME_DEFAULT, SERVICENAME_MAXLEN); } /* Do the uninstallation */ hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if (!hSCManager) { fprintf(stderr, "Could not open service manager (%u).\n", GetLastError()); exit(EXIT_FAILURE); } hService = OpenService(hSCManager, service_name, DELETE); if (!hService) { fprintf(stderr, "Error opening service (%u).\n", GetLastError()); CloseServiceHandle(hSCManager); exit(EXIT_FAILURE); } /* remove the service! */ deleted = DeleteService(hService); if (!deleted) { fprintf(stderr, "Error deleting service (%u).\n", GetLastError()); } CloseServiceHandle(hService); CloseServiceHandle(hSCManager); exit(deleted ? EXIT_SUCCESS : EXIT_FAILURE); } else if (!strcmp(local_argv[x], "-monotonic-clock")) { flags |= SCF_USE_WIN32_MONOTONIC; } #else else if (!strcmp(local_argv[x], "-u")) { x++; if (switch_strlen_zero(local_argv[x]) || is_option(local_argv[x])) { fprintf(stderr, "Option '%s' requires an argument!\n", local_argv[x - 1]); exit(EXIT_FAILURE); } runas_user = local_argv[x]; } else if (!strcmp(local_argv[x], "-g")) { x++; if (switch_strlen_zero(local_argv[x]) || is_option(local_argv[x])) { fprintf(stderr, "Option '%s' requires an argument!\n", local_argv[x - 1]); exit(EXIT_FAILURE); } runas_group = local_argv[x]; } else if (!strcmp(local_argv[x], "-nf")) { nf = SWITCH_TRUE; } else if (!strcmp(local_argv[x], "-version")) { fprintf(stdout, "FreeSWITCH version: %s (%s)\n", SWITCH_VERSION_FULL, SWITCH_VERSION_REVISION_HUMAN); exit(EXIT_SUCCESS); } #endif #ifdef HAVE_SETRLIMIT else if (!strcmp(local_argv[x], "-core")) { struct rlimit rlp; memset(&rlp, 0, sizeof(rlp)); rlp.rlim_cur = RLIM_INFINITY; rlp.rlim_max = RLIM_INFINITY; setrlimit(RLIMIT_CORE, &rlp); } else if (!strcmp(local_argv[x], "-waste")) { #ifndef FS_64BIT fprintf(stderr, "WARNING: Wasting up to 8 megs of memory per thread.\n"); sleep(2); waste = SWITCH_TRUE; #endif } else if (!strcmp(local_argv[x], "-no-auto-stack")) { #ifndef FS_64BIT waste = SWITCH_TRUE; #endif } #endif else if (!strcmp(local_argv[x], "-hp") || !strcmp(local_argv[x], "-rp")) { priority = 2; } else if (!strcmp(local_argv[x], "-lp")) { priority = -1; } else if (!strcmp(local_argv[x], "-np")) { priority = 1; } else if (!strcmp(local_argv[x], "-nosql")) { flags &= ~SCF_USE_SQL; } else if (!strcmp(local_argv[x], "-nonat")) { flags &= ~SCF_USE_AUTO_NAT; } else if (!strcmp(local_argv[x], "-nonatmap")) { flags &= ~SCF_USE_NAT_MAPPING; } else if (!strcmp(local_argv[x], "-heavy-timer")) { flags |= SCF_USE_HEAVY_TIMING; } else if (!strcmp(local_argv[x], "-nort")) { flags &= ~SCF_USE_CLOCK_RT; } else if (!strcmp(local_argv[x], "-nocal")) { flags &= ~SCF_CALIBRATE_CLOCK; } else if (!strcmp(local_argv[x], "-vg")) { flags |= SCF_VG; } else if (!strcmp(local_argv[x], "-stop")) { do_kill = SWITCH_TRUE; } else if (!strcmp(local_argv[x], "-nc")) { nc = SWITCH_TRUE; } #ifndef WIN32 else if (!strcmp(local_argv[x], "-ncwait")) { nc = SWITCH_TRUE; do_wait = SWITCH_TRUE; } #endif else if (!strcmp(local_argv[x], "-c")) { nc = SWITCH_FALSE; } else if (!strcmp(local_argv[x], "-conf")) { x++; if (switch_strlen_zero(local_argv[x]) || is_option(local_argv[x])) { fprintf(stderr, "When using -conf you must specify a config directory\n"); return 255; } SWITCH_GLOBAL_dirs.conf_dir = (char *) malloc(strlen(local_argv[x]) + 1); if (!SWITCH_GLOBAL_dirs.conf_dir) { fprintf(stderr, "Allocation error\n"); return 255; } strcpy(SWITCH_GLOBAL_dirs.conf_dir, local_argv[x]); alt_dirs++; } else if (!strcmp(local_argv[x], "-mod")) { x++; if (switch_strlen_zero(local_argv[x]) || is_option(local_argv[x])) { fprintf(stderr, "When using -mod you must specify a module directory\n"); return 255; } SWITCH_GLOBAL_dirs.mod_dir = (char *) malloc(strlen(local_argv[x]) + 1); if (!SWITCH_GLOBAL_dirs.mod_dir) { fprintf(stderr, "Allocation error\n"); return 255; } strcpy(SWITCH_GLOBAL_dirs.mod_dir, local_argv[x]); } else if (!strcmp(local_argv[x], "-log")) { x++; if (switch_strlen_zero(local_argv[x]) || is_option(local_argv[x])) { fprintf(stderr, "When using -log you must specify a log directory\n"); return 255; } SWITCH_GLOBAL_dirs.log_dir = (char *) malloc(strlen(local_argv[x]) + 1); if (!SWITCH_GLOBAL_dirs.log_dir) { fprintf(stderr, "Allocation error\n"); return 255; } strcpy(SWITCH_GLOBAL_dirs.log_dir, local_argv[x]); alt_dirs++; log_set = SWITCH_TRUE; } else if (!strcmp(local_argv[x], "-run")) { x++; if (switch_strlen_zero(local_argv[x]) || is_option(local_argv[x])) { fprintf(stderr, "When using -run you must specify a pid directory\n"); return 255; } SWITCH_GLOBAL_dirs.run_dir = (char *) malloc(strlen(local_argv[x]) + 1); if (!SWITCH_GLOBAL_dirs.run_dir) { fprintf(stderr, "Allocation error\n"); return 255; } strcpy(SWITCH_GLOBAL_dirs.run_dir, local_argv[x]); run_set = SWITCH_TRUE; } else if (!strcmp(local_argv[x], "-db")) { x++; if (switch_strlen_zero(local_argv[x]) || is_option(local_argv[x])) { fprintf(stderr, "When using -db you must specify a db directory\n"); return 255; } SWITCH_GLOBAL_dirs.db_dir = (char *) malloc(strlen(local_argv[x]) + 1); if (!SWITCH_GLOBAL_dirs.db_dir) { fprintf(stderr, "Allocation error\n"); return 255; } strcpy(SWITCH_GLOBAL_dirs.db_dir, local_argv[x]); alt_dirs++; } else if (!strcmp(local_argv[x], "-scripts")) { x++; if (switch_strlen_zero(local_argv[x]) || is_option(local_argv[x])) { fprintf(stderr, "When using -scripts you must specify a scripts directory\n"); return 255; } SWITCH_GLOBAL_dirs.script_dir = (char *) malloc(strlen(local_argv[x]) + 1); if (!SWITCH_GLOBAL_dirs.script_dir) { fprintf(stderr, "Allocation error\n"); return 255; } strcpy(SWITCH_GLOBAL_dirs.script_dir, local_argv[x]); } else if (!strcmp(local_argv[x], "-htdocs")) { x++; if (switch_strlen_zero(local_argv[x]) || is_option(local_argv[x])) { fprintf(stderr, "When using -htdocs you must specify a htdocs directory\n"); return 255; } SWITCH_GLOBAL_dirs.htdocs_dir = (char *) malloc(strlen(local_argv[x]) + 1); if (!SWITCH_GLOBAL_dirs.htdocs_dir) { fprintf(stderr, "Allocation error\n"); return 255; } strcpy(SWITCH_GLOBAL_dirs.htdocs_dir, local_argv[x]); } else if (!strcmp(local_argv[x], "-base")) { x++; if (switch_strlen_zero(local_argv[x]) || is_option(local_argv[x])) { fprintf(stderr, "When using -base you must specify a base directory\n"); return 255; } SWITCH_GLOBAL_dirs.base_dir = (char *) malloc(strlen(local_argv[x]) + 1); if (!SWITCH_GLOBAL_dirs.base_dir) { fprintf(stderr, "Allocation error\n"); return 255; } strcpy(SWITCH_GLOBAL_dirs.base_dir, local_argv[x]); } else if (!strcmp(local_argv[x], "-temp")) { x++; if (switch_strlen_zero(local_argv[x]) || is_option(local_argv[x])) { fprintf(stderr, "When using -temp you must specify a temp directory\n"); return 255; } SWITCH_GLOBAL_dirs.temp_dir = (char *) malloc(strlen(local_argv[x]) + 1); if (!SWITCH_GLOBAL_dirs.temp_dir) { fprintf(stderr, "Allocation error\n"); return 255; } strcpy(SWITCH_GLOBAL_dirs.temp_dir, local_argv[x]); } else if (!strcmp(local_argv[x], "-storage")) { x++; if (switch_strlen_zero(local_argv[x]) || is_option(local_argv[x])) { fprintf(stderr, "When using -storage you must specify a storage directory\n"); return 255; } SWITCH_GLOBAL_dirs.storage_dir = (char *) malloc(strlen(local_argv[x]) + 1); if (!SWITCH_GLOBAL_dirs.storage_dir) { fprintf(stderr, "Allocation error\n"); return 255; } strcpy(SWITCH_GLOBAL_dirs.storage_dir, local_argv[x]); } else if (!strcmp(local_argv[x], "-recordings")) { x++; if (switch_strlen_zero(local_argv[x]) || is_option(local_argv[x])) { fprintf(stderr, "When using -recordings you must specify a recording directory\n"); return 255; } SWITCH_GLOBAL_dirs.recordings_dir = (char *) malloc(strlen(local_argv[x]) + 1); if (!SWITCH_GLOBAL_dirs.recordings_dir) { fprintf(stderr, "Allocation error\n"); return 255; } strcpy(SWITCH_GLOBAL_dirs.recordings_dir, local_argv[x]); } else if (!strcmp(local_argv[x], "-grammar")) { x++; if (switch_strlen_zero(local_argv[x]) || is_option(local_argv[x])) { fprintf(stderr, "When using -grammar you must specify a grammar directory\n"); return 255; } SWITCH_GLOBAL_dirs.grammar_dir = (char *) malloc(strlen(local_argv[x]) + 1); if (!SWITCH_GLOBAL_dirs.grammar_dir) { fprintf(stderr, "Allocation error\n"); return 255; } strcpy(SWITCH_GLOBAL_dirs.grammar_dir, local_argv[x]); } else if (!strcmp(local_argv[x], "-sounds")) { x++; if (switch_strlen_zero(local_argv[x]) || is_option(local_argv[x])) { fprintf(stderr, "When using -sounds you must specify a sounds directory\n"); return 255; } SWITCH_GLOBAL_dirs.sounds_dir = (char *) malloc(strlen(local_argv[x]) + 1); if (!SWITCH_GLOBAL_dirs.sounds_dir) { fprintf(stderr, "Allocation error\n"); return 255; } strcpy(SWITCH_GLOBAL_dirs.sounds_dir, local_argv[x]); } else if (!strcmp(local_argv[x], "-cfgname")) { x++; if (switch_strlen_zero(local_argv[x]) || is_option(local_argv[x])) { fprintf(stderr, "When using -cfgname you must specify a filename\n"); return 255; } SWITCH_GLOBAL_filenames.conf_name = (char *) malloc(strlen(local_argv[x]) + 1); if (!SWITCH_GLOBAL_filenames.conf_name) { fprintf(stderr, "Allocation error\n"); return 255; } strcpy(SWITCH_GLOBAL_filenames.conf_name, local_argv[x]); } /* Unknown option (always last!) */ else { fprintf(stderr, "Unknown option '%s', see '%s -help' for a list of valid options\n", local_argv[x], local_argv[0]); exit(EXIT_FAILURE); } } if (log_set && !run_set) { SWITCH_GLOBAL_dirs.run_dir = (char *) malloc(strlen(SWITCH_GLOBAL_dirs.log_dir) + 1); if (!SWITCH_GLOBAL_dirs.run_dir) { fprintf(stderr, "Allocation error\n"); return 255; } strcpy(SWITCH_GLOBAL_dirs.run_dir, SWITCH_GLOBAL_dirs.log_dir); } if (do_kill) { return freeswitch_kill_background(); } if (apr_initialize() != SWITCH_STATUS_SUCCESS) { fprintf(stderr, "FATAL ERROR! Could not initialize APR\n"); return 255; } if (alt_dirs && alt_dirs != 3) { fprintf(stderr, "You must specify all or none of -conf, -log, and -db\n"); return 255; } #ifndef FS_64BIT #if defined(HAVE_SETRLIMIT) && !defined(__sun) if (!waste && !(flags & SCF_VG)) { struct rlimit rlp; memset(&rlp, 0, sizeof(rlp)); getrlimit(RLIMIT_STACK, &rlp); if (rlp.rlim_cur != SWITCH_THREAD_STACKSIZE) { char buf[1024] = ""; int i = 0; memset(&rlp, 0, sizeof(rlp)); rlp.rlim_cur = SWITCH_THREAD_STACKSIZE; rlp.rlim_max = SWITCH_SYSTEM_THREAD_STACKSIZE; setrlimit(RLIMIT_STACK, &rlp); apr_terminate(); ret = (int) execv(argv[0], argv); for (i = 0; i < argc; i++) { switch_snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%s ", argv[i]); } return system(buf); } } #endif #endif signal(SIGILL, handle_SIGILL); signal(SIGTERM, handle_SIGILL); #ifndef WIN32 if (do_wait) { if (pipe(fds)) { fprintf(stderr, "System Error!\n"); exit(-1); } signal(SIGCHLD, handle_SIGCHLD); } #endif if (nc) { #ifdef WIN32 FreeConsole(); #else if (!nf) { daemonize(do_wait ? fds : NULL); } #endif } switch (priority) { case 2: set_realtime_priority(); break; case 1: set_normal_priority(); break; case -1: set_low_priority(); break; default: set_auto_priority(); break; } switch_core_setrlimits(); #ifndef WIN32 if (runas_user || runas_group) { if (change_user_group(runas_user, runas_group) < 0) { fprintf(stderr, "Failed to switch user [%s] / group [%s]\n", switch_strlen_zero(runas_user) ? "-" : runas_user, switch_strlen_zero(runas_group) ? "-" : runas_group); return 255; } } #else if (win32_service) { /* Attempt to start service */ SERVICE_TABLE_ENTRY dispatchTable[] = { {service_name, &service_main} , {NULL, NULL} }; service_flags = flags; /* copy parsed flags for service startup */ if (StartServiceCtrlDispatcher(dispatchTable) == 0) { /* Not loaded as a service */ fprintf(stderr, "Error Freeswitch loaded as a console app with -service option\n"); fprintf(stderr, "To install the service load freeswitch with -install\n"); } exit(EXIT_SUCCESS); } #endif switch_core_set_globals(); pid = getpid(); memset(pid_buffer, 0, sizeof(pid_buffer)); switch_snprintf(pid_path, sizeof(pid_path), "%s%s%s", SWITCH_GLOBAL_dirs.run_dir, SWITCH_PATH_SEPARATOR, pfile); switch_snprintf(pid_buffer, sizeof(pid_buffer), "%d", pid); pid_len = strlen(pid_buffer); apr_pool_create(&pool, NULL); switch_dir_make_recursive(SWITCH_GLOBAL_dirs.run_dir, SWITCH_DEFAULT_DIR_PERMS, pool); if (switch_file_open(&fd, pid_path, SWITCH_FOPEN_READ, SWITCH_FPROT_UREAD | SWITCH_FPROT_UWRITE, pool) == SWITCH_STATUS_SUCCESS) { old_pid_len = sizeof(old_pid_buffer); switch_file_read(fd, old_pid_buffer, &old_pid_len); switch_file_close(fd); } if (switch_file_open(&fd, pid_path, SWITCH_FOPEN_WRITE | SWITCH_FOPEN_CREATE | SWITCH_FOPEN_TRUNCATE, SWITCH_FPROT_UREAD | SWITCH_FPROT_UWRITE, pool) != SWITCH_STATUS_SUCCESS) { fprintf(stderr, "Cannot open pid file %s.\n", pid_path); return 255; } if (switch_file_lock(fd, SWITCH_FLOCK_EXCLUSIVE | SWITCH_FLOCK_NONBLOCK) != SWITCH_STATUS_SUCCESS) { fprintf(stderr, "Cannot lock pid file %s.\n", pid_path); old_pid_len = strlen(old_pid_buffer); if (strlen(old_pid_buffer)) { switch_file_write(fd, old_pid_buffer, &old_pid_len); } return 255; } switch_file_write(fd, pid_buffer, &pid_len); if (switch_core_init_and_modload(flags, nc ? SWITCH_FALSE : SWITCH_TRUE, &err) != SWITCH_STATUS_SUCCESS) { fprintf(stderr, "Cannot Initialize [%s]\n", err); return 255; } #ifndef WIN32 if (do_wait) { if (fds[1] > -1) { int i, v = 1; if ((i = write(fds[1], &v, sizeof(v))) < 0) { fprintf(stderr, "System Error [%s]\n", strerror(errno)); } else { i = read(fds[1], &v, sizeof(v)); } shutdown(fds[1], 2); close(fds[1]); fds[1] = -1; } } #endif switch_core_runtime_loop(nc); destroy_status = switch_core_destroy(); switch_file_close(fd); apr_pool_destroy(pool); if (unlink(pid_path) != 0) { fprintf(stderr, "Failed to delete pid file [%s]\n", pid_path); } if (destroy_status == SWITCH_STATUS_RESTART) { char buf[1024] = ""; int j = 0; switch_sleep(1000000); ret = (int) execv(argv[0], argv); fprintf(stderr, "Restart Failed [%s] resorting to plan b\n", strerror(errno)); for (j = 0; j < argc; j++) { switch_snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%s ", argv[j]); } ret = system(buf); } return ret; }
/* * This routine turns options on and off * The options "PDicr" are illegal from set command. * The -o option is used to set option by name * This routine returns the number of non-option arguments */ int sh_argopts(int argc,register char *argv[], void *context) { Shell_t *shp = (Shell_t*)context; register int n,o; register Arg_t *ap = (Arg_t*)(shp->arg_context); Lex_t *lp = (Lex_t*)(shp->lex_context); Shopt_t newflags; int setflag=0, action=0, trace=(int)sh_isoption(SH_XTRACE); Namval_t *np = NIL(Namval_t*); const char *cp; int verbose,f; Optdisc_t disc; newflags=ap->sh->options; memset(&disc, 0, sizeof(disc)); disc.version = OPT_VERSION; disc.infof = infof; opt_info.disc = &disc; if(argc>0) setflag = 4; else argc = -argc; while((n = optget(argv,setflag?sh_optset:sh_optksh))) { o=0; f=*opt_info.option=='-' && (opt_info.num || opt_info.arg); switch(n) { case 'A': np = nv_open(opt_info.arg,ap->sh->var_tree,NV_NOASSIGN|NV_ARRAY|NV_VARNAME); if(f) nv_unset(np); continue; #if SHOPT_BASH case 'O': /* shopt options, only in bash mode */ if(!sh_isoption(SH_BASH)) errormsg(SH_DICT,ERROR_exit(1), e_option, opt_info.name); #endif case 'o': /* set options */ byname: if(!opt_info.arg||!*opt_info.arg||*opt_info.arg=='-') { action = PRINT; /* print style: -O => shopt options * bash => print unset options also, no heading */ verbose = (f?PRINT_VERBOSE:PRINT_NO_HEADER)| (n=='O'?PRINT_SHOPT:0)| (sh_isoption(SH_BASH)?PRINT_ALL|PRINT_NO_HEADER:0)| ((opt_info.arg&&(!*opt_info.arg||*opt_info.arg=='-'))?(PRINT_TABLE|PRINT_NO_HEADER):0); continue; } o = sh_lookopt(opt_info.arg,&f); if(o<=0 || (!sh_isoption(SH_BASH) && (o&SH_BASHEXTRA)) || ((!sh_isoption(SH_BASH) || n=='o') && (o&SH_BASHOPT)) || (setflag && (o&SH_COMMANDLINE))) { errormsg(SH_DICT,2, e_option, opt_info.arg); error_info.errors++; } o &= 0xff; if(sh_isoption(SH_RESTRICTED) && !f && o==SH_RESTRICTED) errormsg(SH_DICT,ERROR_exit(1), e_restricted, opt_info.arg); break; #if SHOPT_BASH case -1: /* --rcfile */ ap->sh->gd->rcfile = opt_info.arg; continue; case -2: /* --noediting */ if (!f) { off_option(&newflags,SH_VI); off_option(&newflags,SH_EMACS); off_option(&newflags,SH_GMACS); } continue; case -3: /* --profile */ n = 'l'; goto skip; case -4: /* --posix */ /* mask lower 8 bits to find char in optksh string */ n&=0xff; goto skip; case -5: /* --version */ sfputr(sfstdout, "ksh bash emulation, version ",-1); np = nv_open("BASH_VERSION",ap->sh->var_tree,0); sfputr(sfstdout, nv_getval(np),-1); np = nv_open("MACHTYPE",ap->sh->var_tree,0); sfprintf(sfstdout, " (%s)\n", nv_getval(np)); sh_exit(0); #endif case -6: /* --default */ { register const Shtable_t *tp; for(tp=shtab_options; o = tp->sh_number; tp++) if(!(o&SH_COMMANDLINE) && is_option(&newflags,o&0xff)) off_option(&newflags,o&0xff); } continue; case -7: f = 0; goto byname; case 'D': on_option(&newflags,SH_NOEXEC); goto skip; case 'T': if (opt_info.num) ap->sh->test |= opt_info.num; else ap->sh->test = 0; continue; case 's': if(setflag) { action = SORT; continue; } #if SHOPT_KIA goto skip; case 'R': if(setflag) n = ':'; else { ap->kiafile = opt_info.arg; n = 'n'; } /*FALLTHROUGH*/ #endif /* SHOPT_KIA */ #if SHOPT_REGRESS goto skip; case 'I': continue; #endif /* SHOPT_REGRESS */ skip: default: if(cp=strchr(optksh,n)) o = flagval[cp-optksh]; break; case ':': if(opt_info.name[0]=='-'&&opt_info.name[1]=='-') { opt_info.arg = argv[opt_info.index-1] + 2; f = 1; goto byname; } errormsg(SH_DICT,2, "%s", opt_info.arg); continue; case '?': errormsg(SH_DICT,ERROR_usage(0), "%s", opt_info.arg); return(-1); } if(f) { if(o==SH_VI || o==SH_EMACS || o==SH_GMACS) { off_option(&newflags,SH_VI); off_option(&newflags,SH_EMACS); off_option(&newflags,SH_GMACS); } on_option(&newflags,o); off_option(&ap->sh->offoptions,o); } else { if(o==SH_XTRACE) trace = 0; off_option(&newflags,o); if(setflag==0) on_option(&ap->sh->offoptions,o); } } if(error_info.errors) errormsg(SH_DICT,ERROR_usage(2),"%s",optusage(NIL(char*))); /* check for '-' or '+' argument */ if((cp=argv[opt_info.index]) && cp[1]==0 && (*cp=='+' || *cp=='-') && strcmp(argv[opt_info.index-1],"--")) { opt_info.index++; off_option(&newflags,SH_XTRACE); off_option(&newflags,SH_VERBOSE); trace = 0; } if(trace) sh_trace(shp,argv,1); argc -= opt_info.index; argv += opt_info.index; if(action==PRINT) sh_printopts(newflags,verbose,0); if(setflag) { if(action==SORT) { if(argc>0) strsort(argv,argc,strcoll); else strsort(ap->sh->st.dolv+1,ap->sh->st.dolc,strcoll); } if(np) { nv_setvec(np,0,argc,argv); nv_close(np); } else if(argc>0 || ((cp=argv[-1]) && strcmp(cp,"--")==0)) sh_argset(ap,argv-1); } else if(is_option(&newflags,SH_CFLAG)) { if(!(ap->sh->comdiv = *argv++)) { errormsg(SH_DICT,2,e_cneedsarg); errormsg(SH_DICT,ERROR_usage(2),optusage(NIL(char*))); } argc--; }
UpoptStatus upopt_next(UpoptContext* context, int* constant, const char** value, char** error) { const char* arg; const char* val = NULL; const UpoptOptionInfo* info = NULL; if (context->index >= context->argc) return UPOPT_STATUS_DONE; arg = context->argv[context->index++]; if (!context->only_normal) { if (is_long(arg)) { if (!arg[2]) { context->only_normal = 1; return upopt_next(context, constant, value, error); } else { char* equal = strchr(arg, '='); if (equal) { *equal = '\0'; val = equal + 1; } info = find_long(context->options, arg+2); if (equal) { *equal = '='; } if (!info) { *error = format("Unrecognized option: %s\n", arg); return UPOPT_STATUS_ERROR; } } } else if (is_short(arg)) { if (arg[2]) { val = arg+2; } info = find_short(context->options, arg[1]); if (!info) { *error = format("Unrecognized option: %s\n", arg); return UPOPT_STATUS_ERROR; } } } if (info) { if (val && !info->argument) { if (is_long(arg)) { *error = format("Did not expect an argument after --%s\n", info->longname); } else { *error = format("Did not expect an argument after -%c\n", info->shortname); } return UPOPT_STATUS_ERROR; } else if (!val && info->argument) { if ((context->index >= context->argc || (!context->only_normal && is_option(context->argv[context->index])))) { *error = format("Expected argument after %s\n", arg); return UPOPT_STATUS_ERROR; } val = context->argv[context->index++]; } *constant = info->constant; *value = val; *error = NULL; return UPOPT_STATUS_NORMAL; } else { *constant = UPOPT_ARG_NORMAL; *value = arg; *error = NULL; return UPOPT_STATUS_NORMAL; } }
// Print option settings on standard output. // If mode is inclusive or of PRINT_*. // If <mask> is set, only options with this mask value are displayed. void sh_printopts(Shell_t *shp, Shopt_t oflags, int mode, Shopt_t *mask) { const Shtable_t *tp; const char *name; int on; int value; if (!(mode & PRINT_NO_HEADER)) sfputr(sfstdout, sh_translate(e_heading), '\n'); if (mode & PRINT_TABLE) { size_t w; int c; int r; int i; c = 0; for (tp = shtab_options; (value = tp->sh_number); tp++) { if (mask && !is_option(mask, value & 0xff)) continue; name = tp->sh_name; if (name[0] == 'n' && name[1] == 'o' && name[2] != 't') name += 2; if (c < (w = strlen(name))) c = w; } c += 4; w = ed_window(); if (w < 2 * c) w = 2 * c; r = w / c; i = 0; for (tp = shtab_options; (value = tp->sh_number); tp++) { if (mask && !is_option(mask, value & 0xff)) continue; on = is_option(&oflags, value); name = tp->sh_name; if (name[0] == 'n' && name[1] == 'o' && name[2] != 't') { name += 2; on = !on; } if (++i >= r) { i = 0; sfprintf(sfstdout, "%s%s\n", on ? "" : "no", name); } else { sfprintf(sfstdout, "%s%-*s", on ? "" : "no", on ? c : (c - 2), name); } } if (i) sfputc(sfstdout, '\n'); return; } if (!(mode & (PRINT_ALL | PRINT_VERBOSE))) { // only print set options if (mode & PRINT_SHOPT) { sfwrite(sfstdout, "shopt -s", 3); } else { sfwrite(sfstdout, "set --default", 13); } } for (tp = shtab_options; (value = tp->sh_number); tp++) { if (mask && !is_option(mask, value & 0xff)) continue; if (sh_isoption(shp, SH_BASH)) { if (!(mode & PRINT_SHOPT) != !(value & SH_BASHOPT)) continue; } else if (value & (SH_BASHEXTRA | SH_BASHOPT)) { continue; } on = is_option(&oflags, value); name = tp->sh_name; if (name[0] == 'n' && name[1] == 'o' && name[2] != 't') { name += 2; on = !on; } if (mode & PRINT_VERBOSE) { sfputr(sfstdout, name, ' '); sfnputc(sfstdout, ' ', 24 - strlen(name)); sfputr(sfstdout, on ? sh_translate(e_on) : sh_translate(e_off), '\n'); } else if (mode & PRINT_ALL) { // print unset options also if (mode & PRINT_SHOPT) { sfprintf(sfstdout, "shopt -%c %s\n", on ? 's' : 'u', name); } else { sfprintf(sfstdout, "set %co %s\n", on ? '-' : '+', name); } } else if (!(value & SH_COMMANDLINE) && is_option(&oflags, value & 0xff)) { sfprintf(sfstdout, " %s%s%s", (mode & PRINT_SHOPT) ? "" : "--", on ? "" : "no", name); } } if (!(mode & (PRINT_VERBOSE | PRINT_ALL))) sfputc(sfstdout, '\n'); }
// This routine turns options on and off. // The options "PDicr" are illegal from set command. // The -o option is used to set option by name. // This routine returns the number of non-option arguments. int sh_argopts(int argc, char *argv[], void *context) { Shell_t *shp = context; int n, o; Arg_t *ap = shp->arg_context; Lex_t *lp = shp->lex_context; Shopt_t newflags; int setflag = 0, action = 0, trace = (int)sh_isoption(shp, SH_XTRACE); Namval_t *np = NULL; const char *sp; char *keylist = NULL; int verbose, f, unsetnp = 0; Optdisc_t disc; newflags = shp->options; memset(&disc, 0, sizeof(disc)); disc.version = OPT_VERSION; disc.infof = infof; opt_info.disc = &disc; if (argc > 0) { setflag = 4; } else { argc = -argc; } while ((n = optget(argv, setflag ? sh_optset : sh_optksh))) { o = 0; f = *opt_info.option == '-' && (opt_info.num || opt_info.arg); switch (n) { case 'A': { np = nv_open(opt_info.arg, shp->var_tree, NV_ARRAY | NV_VARNAME); if (f) unsetnp = 1; continue; } case 'K': { keylist = opt_info.arg; continue; } #if SHOPT_BASH case 'O': { // shopt options, only in bash mode if (!sh_isoption(shp, SH_BASH)) { errormsg(SH_DICT, ERROR_exit(1), e_option, opt_info.name); __builtin_unreachable(); } } #endif // FALLTHRU case 'o': { // set options byname: if (!opt_info.arg || !*opt_info.arg || *opt_info.arg == '-') { action = PRINT; // print style: -O => shopt options. // bash => print unset options also, no heading. verbose = (f ? PRINT_VERBOSE : PRINT_NO_HEADER) | (n == 'O' ? PRINT_SHOPT : 0) | (sh_isoption(shp, SH_BASH) ? PRINT_ALL | PRINT_NO_HEADER : 0) | ((opt_info.arg && (!*opt_info.arg || *opt_info.arg == '-')) ? (PRINT_TABLE | PRINT_NO_HEADER) : 0); continue; } o = sh_lookopt(opt_info.arg, &f); if (o <= 0 || (!sh_isoption(shp, SH_BASH) && (o & SH_BASHEXTRA)) || ((!sh_isoption(shp, SH_BASH) || n == 'o') && (o & SH_BASHOPT)) || (setflag && (o & SH_COMMANDLINE))) { errormsg(SH_DICT, 2, e_option, opt_info.arg); error_info.errors++; } o &= 0xff; if (sh_isoption(shp, SH_RESTRICTED) && !f && o == SH_RESTRICTED) { errormsg(SH_DICT, ERROR_exit(1), e_restricted, opt_info.arg); __builtin_unreachable(); } break; } #if SHOPT_BASH case -1: { // --rcfile shp->gd->rcfile = opt_info.arg; continue; } case -2: { // --noediting if (!f) { off_option(&newflags, SH_VI); off_option(&newflags, SH_EMACS); off_option(&newflags, SH_GMACS); } continue; } case -3: { // --profile n = 'l'; sp = strchr(optksh, n); if (sp) o = flagval[sp - optksh]; break; } case -4: { // --posix // Mask lower 8 bits to find char in optksh string. n &= 0xff; sp = strchr(optksh, n); if (sp) o = flagval[sp - optksh]; break; } case -5: { // --version sfputr(sfstdout, "ksh bash emulation, version ", -1); np = nv_open("BASH_VERSION", shp->var_tree, 0); sfputr(sfstdout, nv_getval(np), -1); np = nv_open("MACHTYPE", shp->var_tree, 0); sfprintf(sfstdout, " (%s)\n", nv_getval(np)); sh_exit(shp, 0); } #endif case -6: { // --default const Shtable_t *tp; for (tp = shtab_options; (o = tp->sh_number); tp++) { if (!(o & SH_COMMANDLINE) && is_option(&newflags, o & 0xff)) { off_option(&newflags, o & 0xff); } } continue; } case -7: { f = 0; goto byname; } case 'D': { on_option(&newflags, SH_NOEXEC); // Cppcheck doesn't recognize the "goto" in the preceding case and thus thinks we // might fall through and call strchr() with n == -7. Even though this it // technically a bug in cppcheck it is one reason why `goto` shouldn't be used; at // least inside `switch` blocks. // cppcheck-suppress invalidFunctionArg sp = strchr(optksh, n); if (sp) o = flagval[sp - optksh]; break; } case 'T': { if (opt_info.num) { shp->test |= opt_info.num; } else { shp->test = 0; } continue; } case 's': { if (setflag) { action = SORT; continue; } sp = strchr(optksh, n); if (sp) o = flagval[sp - optksh]; break; } case 'R': { if (setflag) { n = ':'; } else { ap->kiafile = opt_info.arg; n = 'n'; } sp = strchr(optksh, n); if (sp) o = flagval[sp - optksh]; break; } case ':': { if (opt_info.name[0] == '-' && opt_info.name[1] == '-') { opt_info.arg = argv[opt_info.index - 1] + 2; f = 1; goto byname; } errormsg(SH_DICT, 2, "%s", opt_info.arg); continue; } case '?': { errormsg(SH_DICT, ERROR_usage(0), "%s", opt_info.arg); return -1; } default: { sp = strchr(optksh, n); if (sp) o = flagval[sp - optksh]; break; } } if (f) { if (o == SH_VI || o == SH_EMACS || o == SH_GMACS) { off_option(&newflags, SH_VI); off_option(&newflags, SH_EMACS); off_option(&newflags, SH_GMACS); } on_option(&newflags, o); off_option(&shp->offoptions, o); } else { if (o == SH_RESTRICTED && sh_isoption(shp, SH_RESTRICTED)) { errormsg(SH_DICT, ERROR_exit(1), e_restricted, "r"); __builtin_unreachable(); } if (o == SH_XTRACE) trace = 0; off_option(&newflags, o); if (setflag == 0) on_option(&shp->offoptions, o); } } if (error_info.errors) { errormsg(SH_DICT, ERROR_usage(2), "%s", optusage(NULL)); __builtin_unreachable(); } // Check for '-' or '+' argument. sp = argv[opt_info.index]; if (sp && sp[1] == 0 && (*sp == '+' || *sp == '-') && strcmp(argv[opt_info.index - 1], "--")) { opt_info.index++; off_option(&newflags, SH_XTRACE); off_option(&newflags, SH_VERBOSE); trace = 0; } if (trace) sh_trace(shp, argv, 1); argc -= opt_info.index; argv += opt_info.index; if (action == PRINT) sh_printopts(shp, newflags, verbose, 0); if (setflag) { if (action == SORT) { int (*sortfn)(const char *, const char *) = strcoll; Namarr_t *arp; struct Value *args; unsigned char *bits; if (argc > 0) { strsort(argv, argc, sortfn); } else if (np && (arp = nv_arrayptr(np)) && (args = nv_aivec(np, &bits))) { char *cp; int i, c, keys = 0; if (keylist) { for (cp = keylist; (c = *cp); cp++) { if (c == ',') keys++; } keys++; } else { keylist = ""; } arp->nelem = nv_aipack(arp); cp = nv_name(np); c = strlen(cp); // This used to multiply by `(keys - 1)` but `keys` can be zero which means the // nodesize can be less than `sizeof(struct Node)` which is obviously wrong. // Whether multiplying by `keys` is correct is unclear. // See issue #824. size_t nodesize = sizeof(struct Node) + keys * sizeof(Namval_t *); struct Sort *sp = malloc(sizeof(struct Sort) + strlen(keylist) + (sizeof(char *) + 1) * keys + (arp->nelem + 1) * (nodesize + sizeof(void *)) + c + 3); sp->shp = shp; sp->np = np; if (!(sp->root = shp->last_root)) sp->root = shp->var_tree; sp->vp = args; sp->cur = 0; sp->nodes = (struct Node *)&sp->keys[keys + 2]; memset(sp->nodes, 0, arp->nelem * nodesize); sp->nptrs = (struct Node **)((char *)sp->nodes + arp->nelem * nodesize); sp->flags = (char *)&sp->nptrs[arp->nelem + 1]; memset(sp->flags, 0, keys + 1); sp->name = sp->flags + keys + 1; memcpy(sp->name, cp, c + 1); sp->keys[0] = sp->name + c + 1; strcpy(sp->keys[0], keylist); cp = (char *)sp->nodes; for (c = 0; c < arp->nelem; c++) { if (*keylist && *keylist != ':') { struct Namval *np = FETCH_VT(args[c], np); ((struct Node *)cp)->index = strtol(np->nvname, NULL, 10); ((struct Node *)cp)->bits = bits[c]; } else { ((struct Node *)cp)->index = c; } ((struct Node *)cp)->vp = args[c]; sp->nptrs[c] = (struct Node *)cp; cp += nodesize; } if (!(cp = sp->keys[0])) cp = keylist; for (keys = 0; (c = *cp); cp++) { if (c == ',') { *cp++ = 0; sp->keys[++keys] = cp; sp->flags[keys] = 0; } else if (c == ':') { again: *cp++ = 0; c = *cp; if (c == 'r') { sp->flags[keys] |= SORT_reverse; c = cp[1]; } else if (c == 'n') { sp->flags[keys] |= SORT_numeric; c = cp[1]; } if (c == 'n' || c == 'r') goto again; } } sp->keys[++keys] = 0; Sp = sp; if (sp->keys[0] && *sp->keys[0]) { sortfn = arraysort; } else if (sp->flags[0] & SORT_numeric) { sortfn = numsort; } else { sortfn = alphasort; } strsort((char **)sp->nptrs, arp->nelem, sortfn); cp = (char *)sp->nodes; for (c = 0; c < arp->nelem; c++) { i = (char *)sp->nptrs[c] - (char *)&sp->nodes[0]; if (i / nodesize != c) { args[c] = ((struct Node *)(cp + i))->vp; bits[c] = ((struct Node *)(cp + i))->bits; } } free(sp); nv_close(np); np = NULL; } else { strsort(shp->st.dolv + 1, shp->st.dolc, sortfn); } } if (np) { if (unsetnp) nv_unset(np); nv_setvec(np, 0, argc, argv); nv_close(np); } else if (argc > 0 || ((sp = argv[-1]) && strcmp(sp, "--") == 0)) { sh_argset(ap, argv - 1); } } else if (is_option(&newflags, SH_CFLAG)) { if (!(shp->comdiv = *argv++)) { errormsg(SH_DICT, 2, e_cneedsarg); errormsg(SH_DICT, ERROR_usage(2), optusage(NULL)); __builtin_unreachable(); } argc--; } // Handling SH_INTERACTIVE and SH_PRIVILEGED has been moved to // sh_applyopts(), so that the code can be reused from b_shopt(), too. sh_applyopts(shp, newflags); if (!ap->kiafile) return argc; if (!argv[0]) { errormsg(SH_DICT, ERROR_usage(2), "-R requires scriptname"); __builtin_unreachable(); } if (!(lp->kiafile = sfopen(NULL, ap->kiafile, "w+"))) { errormsg(SH_DICT, ERROR_system(3), e_create, ap->kiafile); __builtin_unreachable(); } if (!(lp->kiatmp = sftmp(2 * SF_BUFSIZE))) { errormsg(SH_DICT, ERROR_system(3), e_tmpcreate); __builtin_unreachable(); } sfputr(lp->kiafile, ";vdb;CIAO/ksh", '\n'); lp->kiabegin = sftell(lp->kiafile); lp->entity_tree = dtopen(&_Nvdisc, Dtbag); lp->scriptname = strdup(sh_fmtq(argv[0])); lp->script = kiaentity(lp, lp->scriptname, -1, 'p', -1, 0, 0, 's', 0, ""); lp->fscript = kiaentity(lp, lp->scriptname, -1, 'f', -1, 0, 0, 's', 0, ""); lp->unknown = kiaentity(lp, "<unknown>", -1, 'p', -1, 0, 0, '0', 0, ""); kiaentity(lp, "<unknown>", -1, 'p', 0, 0, lp->unknown, '0', 0, ""); lp->current = lp->script; ap->kiafile = NULL; return argc; }
int b_shopt(int argc,register char *argv[],void *extra) { Shell_t *shp = (Shell_t*)extra; int n, f, ret=0; Shopt_t newflags=shp->options, opt; int verbose=PRINT_SHOPT|PRINT_ALL|PRINT_NO_HEADER|PRINT_VERBOSE; int setflag=0, quietflag=0, oflag=0; memset(&opt,0,sizeof(opt)); #if SHOPT_RAWONLY on_option(&newflags,SH_VIRAW); #endif while((n = optget(argv,sh_optshopt))) { switch(n) { case 'p': verbose&=~PRINT_VERBOSE; break; case 's': case 'u': setflag|=n=='s'?SET_SET:SET_UNSET; if(setflag==(SET_SET|SET_UNSET)) { errormsg(SH_DICT,ERROR_ERROR,"cannot set and unset options simultaneously"); error_info.errors++; } break; case 'q': quietflag=1; break; case 'o': oflag=1; verbose&=~PRINT_SHOPT; break; case ':': errormsg(SH_DICT,2, "%s", opt_info.arg); continue; case '?': errormsg(SH_DICT,ERROR_usage(0), "%s", opt_info.arg); return(-1); } } if(error_info.errors) errormsg(SH_DICT,ERROR_usage(2),"%s",optusage(NIL(char*))); argc -= opt_info.index; if(argc==0) { /* no args, -s => mask=current options, -u mask=~(current options) else mask=all bits */ if(setflag&SET_SET) opt=newflags; else if(setflag&SET_UNSET) for(n=0;n<4;n++) opt.v[n]=~newflags.v[n]; else memset(&opt,0xff,sizeof(opt)); setflag=SET_NOARGS; } while(argc>0) { f=1; n=sh_lookopt(argv[opt_info.index],&f); if(n<=0||(setflag && (is_option(&opt,SH_INTERACTIVE) || is_option(&opt,SH_RESTRICTED) || is_option(&opt,SH_RESTRICTED2) || is_option(&opt,SH_BASH) || is_option(&opt,SH_LOGIN_SHELL))) ||(oflag&&(n&SH_BASHOPT))) { errormsg(SH_DICT,ERROR_ERROR, e_option, argv[opt_info.index]); error_info.errors++; ret=1; } else if(f) on_option(&opt,n&0xff); else off_option(&opt,n&0xff); opt_info.index++; argc--; } if(setflag&(SET_SET|SET_UNSET)) { if(setflag&SET_SET) { if(sh_isoption(SH_INTERACTIVE)) off_option(&opt,SH_NOEXEC); if(is_option(&opt,SH_VI)||is_option(&opt,SH_EMACS)||is_option(&opt,SH_GMACS)) { off_option(&newflags,SH_VI); off_option(&newflags,SH_EMACS); off_option(&newflags,SH_GMACS); } for(n=0;n<4;n++) newflags.v[n] |= opt.v[n]; } else if(setflag&SET_UNSET) for(n=0;n<4;n++) newflags.v[n] &= ~opt.v[n]; sh_applyopts(shp,newflags); shp->options = newflags; if(is_option(&newflags,SH_XTRACE)) sh_trace(argv,1); } else if(!(setflag&SET_NOARGS)) /* no -s,-u but args, ret=0 if opt&mask==mask */ { for(n=0;n<4;n++) ret+=((newflags.v[n]&opt.v[n])!=opt.v[n]); } if(!quietflag&&!(setflag&(SET_SET|SET_UNSET))) sh_printopts(newflags,verbose,&opt); return(ret); }
/************************************************************************** Parse commandline parameters. Modified argv[] so it contains only ui-specific options afterwards. Number of those ui-specific options is returned. Currently this is implemented in a way that it never fails. Either it returns with success or exit()s. Implementation can be changhed so that this returns with value -1 in case program should be shut down instead of exiting itself. Callers are prepared for such implementation. **************************************************************************/ int fcmp_parse_cmdline(int argc, char *argv[]) { int i = 1; bool ui_separator = FALSE; int ui_options = 0; const char *option = NULL; while (i < argc) { if (ui_separator) { argv[1 + ui_options] = argv[i]; ui_options++; } else if (is_option("--help", argv[i])) { struct cmdhelp *help = cmdhelp_new(argv[0]); cmdhelp_add(help, "h", "help", _("Print a summary of the options")); cmdhelp_add(help, "L", /* TRANS: "List" is exactly what user must type, do not translate. */ _("List URL"), _("Load modpack list from given URL")); cmdhelp_add(help, "p", /* TRANS: "prefix" is exactly what user must type, do not translate. */ _("prefix DIR"), _("Install modpacks to given directory hierarchy")); cmdhelp_add(help, "v", "version", _("Print the version number")); /* The function below prints a header and footer for the options. * Furthermore, the options are sorted. */ cmdhelp_display(help, TRUE, TRUE, TRUE); cmdhelp_destroy(help); exit(EXIT_SUCCESS); } else if ((option = get_option_malloc("--List", argv, &i, argc))) { fcmp.list_url = option; } else if ((option = get_option_malloc("--prefix", argv, &i, argc))) { fcmp.inst_prefix = option; } else if (is_option("--version", argv[i])) { fc_fprintf(stderr, "%s \n", freeciv_name_version()); exit(EXIT_SUCCESS); } else if (is_option("--", argv[i])) { ui_separator = TRUE; } i++; } if (fcmp.inst_prefix == NULL) { const char *home = user_home_dir(); if (home == NULL) { log_error("Cannot determine user home directory"); } else { static char pfx_buf[500]; snprintf(pfx_buf, sizeof(pfx_buf), "%s/.freeciv", home); fcmp.inst_prefix = pfx_buf; } } return ui_options; }
/* * This routine turns options on and off * The options "PDicr" are illegal from set command. * The -o option is used to set option by name * This routine returns the number of non-option arguments */ int sh_argopts(int argc,register char *argv[], void *context) { Shell_t *shp = (Shell_t*)context; register int n,o; register Arg_t *ap = (Arg_t*)(shp->arg_context); Lex_t *lp = (Lex_t*)(shp->lex_context); Shopt_t newflags; int setflag=0, action=0, trace=(int)sh_isoption(shp,SH_XTRACE); Namval_t *np = NIL(Namval_t*); const char *sp; char *keylist=0; int verbose,f,unsetnp=0; Optdisc_t disc; newflags=shp->options; memset(&disc, 0, sizeof(disc)); disc.version = OPT_VERSION; disc.infof = infof; opt_info.disc = &disc; if(argc>0) setflag = 4; else argc = -argc; while((n = optget(argv,setflag?sh_optset:sh_optksh))) { o=0; f=*opt_info.option=='-' && (opt_info.num || opt_info.arg); switch(n) { case 'A': np = nv_open(opt_info.arg,shp->var_tree,NV_NOASSIGN|NV_ARRAY|NV_VARNAME); if(f) unsetnp=1; continue; case 'K': keylist = opt_info.arg; continue; #if SHOPT_BASH case 'O': /* shopt options, only in bash mode */ if(!sh_isoption(shp,SH_BASH)) errormsg(SH_DICT,ERROR_exit(1), e_option, opt_info.name); #endif case 'o': /* set options */ byname: if(!opt_info.arg||!*opt_info.arg||*opt_info.arg=='-') { action = PRINT; /* print style: -O => shopt options * bash => print unset options also, no heading */ verbose = (f?PRINT_VERBOSE:PRINT_NO_HEADER)| (n=='O'?PRINT_SHOPT:0)| (sh_isoption(shp,SH_BASH)?PRINT_ALL|PRINT_NO_HEADER:0)| ((opt_info.arg&&(!*opt_info.arg||*opt_info.arg=='-'))?(PRINT_TABLE|PRINT_NO_HEADER):0); continue; } o = sh_lookopt(opt_info.arg,&f); if(o<=0 || (!sh_isoption(shp,SH_BASH) && (o&SH_BASHEXTRA)) || ((!sh_isoption(shp,SH_BASH) || n=='o') && (o&SH_BASHOPT)) || (setflag && (o&SH_COMMANDLINE))) { errormsg(SH_DICT,2, e_option, opt_info.arg); error_info.errors++; } o &= 0xff; if(sh_isoption(shp,SH_RESTRICTED) && !f && o==SH_RESTRICTED) errormsg(SH_DICT,ERROR_exit(1), e_restricted, opt_info.arg); break; #if SHOPT_BASH case -1: /* --rcfile */ shp->gd->rcfile = opt_info.arg; continue; case -2: /* --noediting */ if (!f) { off_option(&newflags,SH_VI); off_option(&newflags,SH_EMACS); off_option(&newflags,SH_GMACS); } continue; case -3: /* --profile */ n = 'l'; goto skip; case -4: /* --posix */ /* mask lower 8 bits to find char in optksh string */ n&=0xff; goto skip; case -5: /* --version */ sfputr(sfstdout, "ksh bash emulation, version ",-1); np = nv_open("BASH_VERSION",shp->var_tree,0); sfputr(sfstdout, nv_getval(np),-1); np = nv_open("MACHTYPE",shp->var_tree,0); sfprintf(sfstdout, " (%s)\n", nv_getval(np)); sh_exit(shp,0); #endif case -6: /* --default */ { register const Shtable_t *tp; for(tp=shtab_options; o = tp->sh_number; tp++) if(!(o&SH_COMMANDLINE) && is_option(&newflags,o&0xff)) off_option(&newflags,o&0xff); } continue; case -7: f = 0; goto byname; case 'D': on_option(&newflags,SH_NOEXEC); goto skip; case 'T': if (opt_info.num) shp->test |= opt_info.num; else shp->test = 0; continue; case 's': if(setflag) { action = SORT; continue; } #if SHOPT_KIA goto skip; case 'R': if(setflag) n = ':'; else { ap->kiafile = opt_info.arg; n = 'n'; } /*FALLTHROUGH*/ #endif /* SHOPT_KIA */ #if SHOPT_REGRESS goto skip; case 'I': continue; #endif /* SHOPT_REGRESS */ skip: default: if(sp=strchr(optksh,n)) o = flagval[sp-optksh]; break; case ':': if(opt_info.name[0]=='-'&&opt_info.name[1]=='-') { opt_info.arg = argv[opt_info.index-1] + 2; f = 1; goto byname; } errormsg(SH_DICT,2, "%s", opt_info.arg); continue; case '?': errormsg(SH_DICT,ERROR_usage(0), "%s", opt_info.arg); return(-1); } if(f) { if(o==SH_VI || o==SH_EMACS || o==SH_GMACS) { off_option(&newflags,SH_VI); off_option(&newflags,SH_EMACS); off_option(&newflags,SH_GMACS); } on_option(&newflags,o); off_option(&shp->offoptions,o); } else { if(o==SH_XTRACE) trace = 0; off_option(&newflags,o); if(setflag==0) on_option(&shp->offoptions,o); } } if(error_info.errors) errormsg(SH_DICT,ERROR_usage(2),"%s",optusage(NIL(char*))); /* check for '-' or '+' argument */ if((sp=argv[opt_info.index]) && sp[1]==0 && (*sp=='+' || *sp=='-') && strcmp(argv[opt_info.index-1],"--")) { opt_info.index++; off_option(&newflags,SH_XTRACE); off_option(&newflags,SH_VERBOSE); trace = 0; } if(trace) sh_trace(shp,argv,1); argc -= opt_info.index; argv += opt_info.index; if(action==PRINT) sh_printopts(shp,newflags,verbose,0); if(setflag) { if(action==SORT) { int (*sortfn)(const char*,const char*) = strcoll; Namarr_t *arp; union Value *args; unsigned char *bits; if(argc>0) strsort(argv,argc,sortfn); else if(np && (arp=nv_arrayptr(np)) && (args = nv_aivec(np,&bits))) { struct Sort *sp; char *cp; int i, c, keys=0; size_t nodesize; if(keylist) { for(cp=keylist;c= *cp; cp++) { if(c==',') keys++; } keys++; } else keylist = Empty; arp->nelem = nv_aipack(arp);; cp = nv_name(np); c = strlen(cp); nodesize = sizeof(struct Node)+(keys-1)*sizeof(Namval_t*); sp = (struct Sort*)malloc(sizeof(struct Sort)+strlen(keylist)+(sizeof(char*)+1)*keys+(arp->nelem+1)*(nodesize+sizeof(void*))+c+3); sp->shp = shp; sp->np = np; if(!(sp->root = shp->last_root)) sp->root = shp->var_tree; sp->vp = args; sp->cur = 0; sp->nodes = (struct Node*)&sp->keys[keys+2]; memset(sp->nodes, 0, arp->nelem*nodesize); sp->nptrs = (struct Node**)((char*)sp->nodes+arp->nelem*nodesize); sp->flags = (char*)&sp->nptrs[arp->nelem+1]; memset(sp->flags,0,keys+1); sp->name = sp->flags + keys+1; memcpy(sp->name,cp,c+1); sp->keys[0] = sp->name+c+1; strcpy(sp->keys[0],keylist); cp = (char*)sp->nodes; for(c=0; c < arp->nelem; c++) { if(keylist!=Empty && *keylist!=':') { ((struct Node*)cp)->index = strtol(args[c].np->nvname,NULL,10); ((struct Node*)cp)->bits = bits[c]; } else ((struct Node*)cp)->index = c; ((struct Node*)cp)->vp = args[c]; sp->nptrs[c] = (struct Node*)cp; cp += nodesize; } if(!(cp = sp->keys[0])) cp = keylist; for(keys=0;c= *cp; cp++) { if(c==',') { *cp++ = 0; sp->keys[++keys] = cp; sp->flags[keys] = 0; } else if(c==':') { again: *cp++ = 0; if((c= *cp) == 'r') { sp->flags[keys] |= SORT_reverse; c = cp[1]; } else if(c=='n') { sp->flags[keys] |= SORT_numeric; c = cp[1]; } if(c=='n' || c=='r') goto again; } } sp->keys[++keys] = 0; Sp = sp; if(sp->keys[0] && *sp->keys[0]) sortfn = arraysort; else if(sp->flags[0]&SORT_numeric) sortfn = numsort; else sortfn = alphasort; strsort((char**)sp->nptrs,arp->nelem,sortfn); cp = (char*)sp->nodes; for(c=0; c < arp->nelem; c++) { i = (char*)sp->nptrs[c]-(char*)&sp->nodes[0]; if(i/nodesize !=c) { args[c] = ((struct Node*)(cp+i))->vp; bits[c] = ((struct Node*)(cp+i))->bits; } } free(sp); nv_close(np); np = 0; } else strsort(shp->st.dolv+1,shp->st.dolc,sortfn); } if(np) { if(unsetnp) nv_unset(np); nv_setvec(np,0,argc,argv); nv_close(np); } else if(argc>0 || ((sp=argv[-1]) && strcmp(sp,"--")==0)) sh_argset(ap,argv-1); } else if(is_option(&newflags,SH_CFLAG)) { if(!(shp->comdiv = *argv++)) { errormsg(SH_DICT,2,e_cneedsarg); errormsg(SH_DICT,ERROR_usage(2),optusage(NIL(char*))); } argc--; }
/* process command-line arguments */ int process_arguments(int argc, char **argv){ int c; int option = 0; static struct option longopts[] = { {"port", required_argument,0,'p'}, {"timeout", required_argument,0,'t'}, {"critical", required_argument,0,'c'}, {"warning", required_argument,0,'w'}, {"variable", required_argument,0,'v'}, {"hostname", required_argument,0,'H'}, {"params", required_argument,0,'l'}, {"secret", required_argument,0,'s'}, {"display", required_argument,0,'d'}, {"unknown-timeout", no_argument, 0, 'u'}, {"version", no_argument, 0,'V'}, {"help", no_argument, 0,'h'}, {0,0,0,0} }; /* no options were supplied */ if(argc<2) return ERROR; /* backwards compatibility */ if (! is_option(argv[1])) { server_address = strdup(argv[1]); argv[1]=argv[0]; argv=&argv[1]; argc--; } for (c=1;c<argc;c++) { if(strcmp("-to",argv[c])==0) strcpy(argv[c],"-t"); else if (strcmp("-wv",argv[c])==0) strcpy(argv[c],"-w"); else if (strcmp("-cv",argv[c])==0) strcpy(argv[c],"-c"); } while (1) { c = getopt_long(argc,argv,"+hVH:t:c:w:p:v:l:s:d:u",longopts,&option); if (c==-1||c==EOF||c==1) break; switch (c) { case '?': /* print short usage statement if args not parsable */ usage5 (); case 'h': /* help */ print_help(); exit(STATE_OK); case 'V': /* version */ print_revision(progname, NP_VERSION); exit(STATE_OK); case 'H': /* hostname */ server_address = optarg; break; case 's': /* password */ req_password = optarg; break; case 'p': /* port */ if (is_intnonneg(optarg)) server_port=atoi(optarg); else die(STATE_UNKNOWN,_("Server port must be an integer\n")); break; case 'v': if(strlen(optarg)<4) return ERROR; if(!strcmp(optarg,"CLIENTVERSION")) vars_to_check=CHECK_CLIENTVERSION; else if(!strcmp(optarg,"CPULOAD")) vars_to_check=CHECK_CPULOAD; else if(!strcmp(optarg,"UPTIME")) vars_to_check=CHECK_UPTIME; else if(!strcmp(optarg,"USEDDISKSPACE")) vars_to_check=CHECK_USEDDISKSPACE; else if(!strcmp(optarg,"SERVICESTATE")) vars_to_check=CHECK_SERVICESTATE; else if(!strcmp(optarg,"PROCSTATE")) vars_to_check=CHECK_PROCSTATE; else if(!strcmp(optarg,"MEMUSE")) vars_to_check=CHECK_MEMUSE; else if(!strcmp(optarg,"COUNTER")) vars_to_check=CHECK_COUNTER; else if(!strcmp(optarg,"FILEAGE")) vars_to_check=CHECK_FILEAGE; else if(!strcmp(optarg,"INSTANCES")) vars_to_check=CHECK_INSTANCES; else return ERROR; break; case 'l': /* value list */ value_list = optarg; break; case 'w': /* warning threshold */ warning_value=strtoul(optarg,NULL,10); check_warning_value=TRUE; break; case 'c': /* critical threshold */ critical_value=strtoul(optarg,NULL,10); check_critical_value=TRUE; break; case 'd': /* Display select for services */ if (!strcmp(optarg,"SHOWALL")) show_all = TRUE; break; case 'u': socket_timeout_state=STATE_UNKNOWN; break; case 't': /* timeout */ socket_timeout=atoi(optarg); if(socket_timeout<=0) return ERROR; } } if (server_address == NULL) usage4 (_("You must provide a server address or host name")); if (vars_to_check==CHECK_NONE) return ERROR; if (req_password == NULL) req_password = strdup (_("None")); return OK; }
int main(int argc, char *argv[]) { timer t; t.set_print_mode(HMS_MODE); bencrypt=false; bdecrypt=false; bgen_pk=false; bfind_point=false; btest_point=false; bwipe_file=false; bhelp=false; bfile=false; buser=false; bversion=false; bks=false; for(int i=1;i<argc;i++) { if((strcmp(argv[i],"-e")==0) || (strcmp(argv[i],"--encrypt")==0)) { if (i+1 < argc) if(!is_option(argv[i+1])) { bencrypt=true; filename=argv[i+1]; bfile=true; i++; continue; } banner(); cerr<<"\nAZTECC ERROR : No filename given."<<endl; exit(1); } if((strcmp(argv[i],"-d")==0) || (strcmp(argv[i],"--decrypt")==0)) { if (i+1 < argc) if(!is_option(argv[i+1])) { bdecrypt=true; filename=argv[i+1]; bfile=true; i++; continue; } banner(); cerr<<"\nAZTECC ERROR : No filename given."<<endl; exit(1); } if((strcmp(argv[i],"-g")==0) || (strcmp(argv[i],"--genkey")==0)) bgen_pk=true; if((strcmp(argv[i],"-k")==0) || (strcmp(argv[i],"--keysize")==0)) { if (i+1 < argc) if(!is_option(argv[i+1])) { bks=true; keysize=argv[i+1]; i++; continue; } banner(); cerr<<"\nAZTECC ERROR : No valid keysize given."<<endl; exit(1); } if((strcmp(argv[i],"-u")==0) || (strcmp(argv[i],"--user")==0)) { if (i+1 < argc) if(!is_option(argv[i+1])) { username=argv[i+1]; buser=true; i++; continue; } banner(); cerr<<"\nAZTECC ERROR : No valid username given."<<endl; exit(1); } if((strcmp(argv[i],"-pk")==0) || (strcmp(argv[i],"--pubkey")==0)) { if(!is_option(argv[i+1])) { pubkey=argv[i+1]; i++; continue; } banner(); cerr<<"\nAZTECC ERROR : No public key filename given."<<endl; exit(1); } // find and test point if((strcmp(argv[i],"-f")==0) || (strcmp(argv[i],"--find")==0)) bfind_point=true; if((strcmp(argv[i],"-t")==0) || (strcmp(argv[i],"--test")==0)) btest_point=true; if((strcmp(argv[i],"-h")==0) || (strcmp(argv[i],"--help")==0)) bhelp=true; if((strcmp(argv[i],"-v")==0) || (strcmp(argv[i],"--version")==0)) bversion=true; if((strcmp(argv[i],"-w")==0) || (strcmp(argv[i],"--wipe")==0)) { if (i+1 < argc) if(!is_option(argv[i+1])) { filename=argv[i+1]; bwipe_file=true; bfile=true; i++; continue; } banner(); cerr<<"\nAZTECC ERROR : No filename given."<<endl; exit(1); } } if((bencrypt) && (buser) && (bfile) && (!bdecrypt) && (!bgen_pk) && (!bfind_point) && (!btest_point) && (!bhelp) && (!bwipe_file) && (!bversion) && (!bks)) { t.start_timer(); encrypt_file(pubkey,username,filename); t.stop_timer(); cout<<"\nElapsed time : "<<t<<endl; exit(0); } if((bdecrypt) && (bfile) && (!buser) && (!bencrypt) && (!bgen_pk) && (!bfind_point) && (!btest_point) && (!bhelp) && (!bwipe_file) && (!bversion) && (!bks)) { t.start_timer(); decrypt_file(pubkey,filename); t.stop_timer(); cout<<"\nElapsed time : "<<t<<endl; exit(0); } if((bgen_pk) && (bks) && (!buser) && (!bencrypt) && (!bdecrypt) && (!bfind_point) && (!btest_point) && (!bhelp) && (!bwipe_file) && (!bversion)) { if(strcmp(keysize,"160")==0) blocksize=20; else if(strcmp(keysize,"192")==0) blocksize=24; else { banner(); cerr<<"\nAZTECC ERROR : Keysize not valid.\n"; exit(1); } gen_pubkey(pubkey,blocksize); exit(0); } if((bfind_point) && (!bencrypt) && (!bdecrypt) && (!bgen_pk) && (!btest_point) && (!bhelp) && (!bwipe_file) && (!bversion) && (!buser) && (!bks)) { find_point(); exit(0); } if((btest_point) && (!bencrypt) && (!bdecrypt) && (!bgen_pk) && (!bfind_point) && (!bhelp) && (!bwipe_file) && (!bversion) && (!buser) && (!bks)) { test_point(); exit(0); } if((bwipe_file) && (bfile) && (!bencrypt) && (!bdecrypt) && (!bgen_pk) && (!bfind_point) && (!btest_point) && (!bhelp) && (!bversion) && (!buser) && (!bks)) { wipe_file(filename); exit(0); } if((bversion) && (!bencrypt) && (!bdecrypt) && (!bgen_pk) && (!bfind_point) && (!btest_point) && (!bhelp) && (!bwipe_file) && (!buser) && (!bks)) { version(); exit(0); } if(bhelp) { usage(); exit(0); } else usage(); return 0; }
/* process command-line arguments */ int process_arguments (int argc, char **argv) { int c; char *rv[2]; int option = 0; static struct option longopts[] = { {"hostname", required_argument, 0, 'H'}, {"sourceip", required_argument, 0, 'S'}, {"sourceif", required_argument, 0, 'I'}, {"critical", required_argument, 0, 'c'}, {"warning", required_argument, 0, 'w'}, {"bytes", required_argument, 0, 'b'}, {"number", required_argument, 0, 'n'}, {"target-timeout", required_argument, 0, 'T'}, {"interval", required_argument, 0, 'i'}, {"verbose", no_argument, 0, 'v'}, {"version", no_argument, 0, 'V'}, {"help", no_argument, 0, 'h'}, {"use-ipv4", no_argument, 0, '4'}, {"use-ipv6", no_argument, 0, '6'}, {0, 0, 0, 0} }; rv[PL] = NULL; rv[RTA] = NULL; if (argc < 2) return ERROR; if (!is_option (argv[1])) { server_name = argv[1]; argv[1] = argv[0]; argv = &argv[1]; argc--; } while (1) { c = getopt_long (argc, argv, "+hVvH:S:c:w:b:n:T:i:I:46", longopts, &option); if (c == -1 || c == EOF || c == 1) break; switch (c) { case '?': /* print short usage statement if args not parsable */ usage5 (); case 'h': /* help */ print_help (); exit (STATE_OK); case 'V': /* version */ print_revision (progname, NP_VERSION); exit (STATE_OK); case 'v': /* verbose mode */ verbose = TRUE; break; case 'H': /* hostname */ if (is_host (optarg) == FALSE) { usage2 (_("Invalid hostname/address"), optarg); } server_name = strscpy (server_name, optarg); break; case 'S': /* sourceip */ if (is_host (optarg) == FALSE) { usage2 (_("Invalid hostname/address"), optarg); } sourceip = strscpy (sourceip, optarg); break; case 'I': /* sourceip */ sourceif = strscpy (sourceif, optarg); case '4': /* IPv4 only */ address_family = AF_INET; break; case '6': /* IPv6 only */ #ifdef USE_IPV6 address_family = AF_INET6; #else usage (_("IPv6 support not available\n")); #endif break; case 'c': get_threshold (optarg, rv); if (rv[RTA]) { crta = strtod (rv[RTA], NULL); crta_p = TRUE; rv[RTA] = NULL; } if (rv[PL]) { cpl = atoi (rv[PL]); cpl_p = TRUE; rv[PL] = NULL; } break; case 'w': get_threshold (optarg, rv); if (rv[RTA]) { wrta = strtod (rv[RTA], NULL); wrta_p = TRUE; rv[RTA] = NULL; } if (rv[PL]) { wpl = atoi (rv[PL]); wpl_p = TRUE; rv[PL] = NULL; } break; case 'b': /* bytes per packet */ if (is_intpos (optarg)) packet_size = atoi (optarg); else usage (_("Packet size must be a positive integer")); break; case 'n': /* number of packets */ if (is_intpos (optarg)) packet_count = atoi (optarg); else usage (_("Packet count must be a positive integer")); break; case 'T': /* timeout in msec */ if (is_intpos (optarg)) target_timeout = atoi (optarg); else usage (_("Target timeout must be a positive integer")); break; case 'i': /* interval in msec */ if (is_intpos (optarg)) packet_interval = atoi (optarg); else usage (_("Interval must be a positive integer")); break; } } if (server_name == NULL) usage4 (_("Hostname was not supplied")); return OK; }