Example #1
0
File: AlARM_SET.c Project: JXLF/SCM
void shift_cursor()
{
	uchar i,cursor=0;
	while(keysix_flag==1)
	{
		keysix_flag=0;
		for(i=0;i<5;i++)
		{
			lcd_writecommand(0x80+0x46+cursor);
			lcd_writedata('_');
			delayms(500);
			lcd_writecommand(0x80+0x46+cursor);
			lcd_writedata(' ');
			delayms(500);
			keysix_scan();
			keyseven_scan();
			keyeight_scan();
			if(keysix_flag==1)
				break;
			if(keyseven_flag==1||keyeight_flag==1)
			{
				set_limit(cursor);
			    break;
			}
		}
		cursor+=7;
		if(cursor==14)
			cursor=0;
	}



}
Example #2
0
int set_max_connections(int n)
{
    if(set_limit(RLIMIT_FD_MAX, n))
    {
        log_message_level(LOG_LEVEL_ERROR, "set_max_connections: unable to set resource limit");
        return -1;
    }
    log_message_level(LOG_LEVEL_SERVER, "set_max_connections: max connections set to %d", n);
    return 0;
}
Example #3
0
int set_rss_size(int n)
{
    if(set_limit(RLIMIT_RSS, n))
    {
        log_message_level(LOG_LEVEL_ERROR, "set_rss_size: unable to set resource limit");
        return -1;
    }
    log_message_level(LOG_LEVEL_SERVER,  "set_rss_size: max rss segment size set to %d", n);
    return 0;
}
Example #4
0
static void
checksum (char *word[], void *userdata)
{
	if (!g_ascii_strcasecmp ("GET", word[2]))
	{
		print_limit ();
	}
	else if (!g_ascii_strcasecmp ("SET", word[2]))
	{
		set_limit (word[3]);
	}
	else
	{
		xchat_printf (ph, "Usage: /CHECKSUM GET|INC|DEC\n");
		xchat_printf (ph, "  GET - print the maximum file size (in MiB) to be hashed\n");
		xchat_printf (ph, "  SET <filesize> - set the maximum file size (in MiB) to be hashed\n");
	}
}
Example #5
0
static int
checksum (char *word[], char *word_eol[], void *userdata)
{
	if (!g_ascii_strcasecmp ("GET", word[2]))
	{
		print_limit ();
	}
	else if (!g_ascii_strcasecmp ("SET", word[2]))
	{
		set_limit (word[3]);
	}
	else
	{
		hexchat_printf (ph, "Usage: /CHECKSUM GET|SET\n");
		hexchat_printf (ph, "  GET - print the maximum file size (in MiB) to be hashed\n");
		hexchat_printf (ph, "  SET <filesize> - set the maximum file size (in MiB) to be hashed\n");
	}

	return HEXCHAT_EAT_NONE;
}
Example #6
0
static void do_limit(s_event * event)
{
	s_event_after_fork_data *data;

	int ret = 0;

	assert(event->event_type == &EVENT_AFTER_FORK);
	assert(event->data);

	data = event->data;

	assert(data->service);
	assert(data->service->name);
	assert(data->process);

	D_("do_limit!\n");

	/* Handle RLIMIT_AS */
	ret += set_limit(&RLIMIT_AS_SOFT, &RLIMIT_AS_HARD, data->service,
			 RLIMIT_AS, 1024);

	/* Handle RLIMIT_CORE */
	ret += set_limit(&RLIMIT_CORE_SOFT, &RLIMIT_CORE_HARD, data->service,
			 RLIMIT_CORE, 1024);

	/* Handle RLIMIT_CPU */
	ret += set_limit(&RLIMIT_CPU_SOFT, &RLIMIT_CPU_HARD, data->service,
			 RLIMIT_CPU, 1);

	/* Handle RLIMIT_DATA */
	ret += set_limit(&RLIMIT_DATA_SOFT, &RLIMIT_DATA_HARD, data->service,
			 RLIMIT_DATA, 1024);

	/* Handle RLIMIT_FSIZE */
	ret += set_limit(&RLIMIT_FSIZE_SOFT, &RLIMIT_FSIZE_HARD,
			 data->service, RLIMIT_FSIZE, 1024);

	/* Handle RLIMIT_MEMLOCK */
	ret += set_limit(&RLIMIT_MEMLOCK_SOFT, &RLIMIT_MEMLOCK_HARD,
			 data->service, RLIMIT_MEMLOCK, 1024);

	/* Handle RLIMIT_NOFILE */
	ret += set_limit(&RLIMIT_NOFILE_SOFT, &RLIMIT_NOFILE_HARD,
			 data->service, RLIMIT_NOFILE, 1);

	/* Handle RLIMIT_NPROC */
	ret += set_limit(&RLIMIT_NPROC_SOFT, &RLIMIT_NPROC_HARD,
			 data->service, RLIMIT_NPROC, 1);

	/* Handle RLIMIT_RSS */
	ret += set_limit(&RLIMIT_RSS_SOFT, &RLIMIT_RSS_HARD, data->service,
			 RLIMIT_RSS, 1024);

#ifdef RLIMIT_SIGPENDING
	/* for some reason, this seems missing on some systems */
	/* Handle RLIMIT_SIGPENDING */
	ret += set_limit(&RLIMIT_SIGPENDING_SOFT, &RLIMIT_SIGPENDING_HARD,
			 data->service, RLIMIT_SIGPENDING, 1);
#endif

	/* Handle RLIMIT_STACK */
	ret += set_limit(&RLIMIT_STACK_SOFT, &RLIMIT_STACK_HARD,
			 data->service, RLIMIT_STACK, 1024);

	/* make sure every rlimit suceeded */
	if (ret != 0)
		event->status = FAILED;
}
Example #7
0
File: pip.c Project: smokeless/eotl
void
extra_create()
{
    set_limit(1); //just in case

    speech =
    ({
      "Pleased to meet you, %s.",
      "Name's Francis Pumphandle, but everyone calls me Pip.",
      "",
      "Cheese balls are one of my all-time favorite foods.",
      "I always seem to meet the most interesting people when I'm around them, too.",
      "In fact, cheese balls bring to mind the time I met Bob Barker.",
      "",
      "Bob Barker.  Star of the most popular morning game show.",
      "He's an emcee, a host, and a celebrity all rolled into one.",
      "Anyway, eight months ago --",
      "-- it was Tuesday the 17th, I believe --",
      "-- or it might have been the 18th ...",
      "...  no, no, it was definitely the 17th, because it was precisely one week after my aunt Lucretia's birthday, which is the 10th.",
      "Aunt Lucretia's quite a woman.  Loves to cook.",
      "She prepares a fabulous war shu a.  That's a Chinese duck dish.",
      "I love Chinese food.",
      "I once went to a party where they served Chinese food and cheese balls.",
      "Now that was a Catch-22 situation.",
      "Catch-22 was a movie, you know.",
      "It was long, very long.",
      "They say the book was better, but it was a novel and I never finish reading those things.",
      "",
      "Of course, a lot of people don't read much nowadays.  They watch television.",
      "I caught a program on PBS last night.  A very good show on chimpanzees in the media.",
      "They had a clip of J. Fred Muggs, the chimp from the TODAY show.",
      "But it was Fred's chimpanzee girlfriend that had me stumped.",
      "I couldn't remember her name, so I looked it up.  Her name was Phoebe B. Beebe.",
      "",
      "Anyway, as I was saying, eight months ago, Tuesday the 17th, I went downtown on a nice, relaxing stroll.",
      "I love to relax.",
      "In fact, relaxing is a pastime of mine.",
      "Some people play golf.",
      "Others like tennis, horseshoes, bridge, canasta, and other such fancy hobbies.",
      "",
      "Now, another hobby enjoyed by many is knitting.",
      "My grandmother was a great knitter.",
      "Knitted this sweater I'm wearing.  It's red, which is not my favorite color.",
      "I prefer mauve or mustard yellow.",
      "Now, don't get me wrong: red is okay for ties and suspenders, but with sweaters I prefer more neutral colors.",
      "",
      "But when I'm relaxing, I don't care what I wear: long pants, Bermuda shorts, T-shirts, or formal attire.",
      "You name it, anything goes.",
      "Now, on the 17th, during my relaxing stroll, I recall wearing my herringbone jacket, my Laughlin, Nevada, souvenir tie, and my charcoal gray slacks.",
      "Or was it the navy slacks?",
      "Oh, I suppose it doesn't really matter.",
      "What matters is comfort.",
      "You know, I love comfort.",
      "It goes along with that pastime of mine, relaxing.",
      "Now, for me, there is nothing more relaxing than a nice leisurely stroll, like the one I took eight months ago on the 17th.",
      "It was a bright, sunny day, which of course is the optimum condition for relaxed strolling.",
      "And as I walked along, I found myself humming a haunting melody.",
      "I kept humming and humming and humming and humming.  I couldn't get the tune out of my head.",
      "",
      "I racked my brains to come up with the title, but to no avail.",
      "You see, I'm not terribly musical.",
      "And yet, I'd always wanted to play an instrument and be like my musical hero, Leo Sayer",
      "",
      "But who can compete with Leo?  I think I was just scared that I'd fail.",
      "",
      "Well, I decided right then and there to go buy a musical instrument.",
      "So on the particular Tuesday the 17th to which I was referring, I went down to the Sixth Street Music Emporium to buy a new tambourine, a terribly soothing instrument, contrary to popular opinion.",
      "And as I was strolling along, I detected a wonderful scent in the morning air.",
      "What could it be, I asked myself.",
      "",
      "",
      "",
      "So I went toward that marvelous scent, distracted by its aroma from my musical mission.",
      "The odor was a mix of orchid flowers and bologna, which of course is one of the world's most under-appreciated luncheon meats.",
      "That and pimento loaf.",
      "I _love_ a good pimento loaf and mayo sandwich -- the more pimentos, the better.",
      "Why, just the mention of pimentos makes my taste buds stand up and say, \"Howdy.\"",
      "Now there's an interesting word: \"Howdy.\"",
      "Is it from \"How are you\" or maybe \"How you doing\"?",
      "\"Howdy\"'s one of those strange words that really has no origin.",
      "I like saying \"How do\" more than \"Howdy\" -- more formal, I think.",
      "Not too flowery.",
      "But the flowery aroma of that particular morning carried me on my fragrant quest.",
      "",
      "Now, the smell was actually less bologna and more orchid -- the beautiful flower found on the island state of Hawaii.",
      "Of course, I wasn't in Hawaii, so I needed to search out the location of the nearest orchid.",
      "So, I visited every florist shop in town.",
      "Well, to make a long story short, not a single flower shop in town had any orchids in stock, which seemed mighty curious to me.",
      "Now, as we all know, curiosity killed the cat, but since I'm not a feline, I wasn't too worried.",
      "Felines are funny creatures, don't you think?",
      "I had a cat once.",
      "It used its claws to tear my living room couch to shreds.",
      "It was a comfy couch, too.",
      "Had a sleep-away bed in it with a foam rubber mattress.",
      "Now, I bought the couch and the mattress at Levine's Department Store on Third Avenue, the very same afternoon of that relaxing stroll aforementioned.",
      "I also bought myself a lovely tambourine on that same shopping expedition.",
      "Anyway, I didn't want to pay extra for the delivery of the couch, so I decided to carry the couch home myself.",
      "It was quite cumbersome.",
      "And getting it through the store's revolving doors was a bit of a challenge.",
      "And just as I emerged onto the street, by accident I bumped into a well-dressed man with an orchid in his lapel.",
      "It was Bob Barker and he was eating a bologna and cheese balls sandwich.",
      "",
      "Well, it's been nice chatting with you.",
    });
Example #8
0
R_API int r_run_start(RRunProfile *p) {
#if __APPLE__
	posix_spawnattr_t attr = {0};
	pid_t pid = -1;
#endif
	int ret;
	if (!p->_program && !p->_system) {
		printf ("No program or system rule defined\n");
		return 1;
	}
	if (p->_stdin) {
		int f = open (p->_stdin, O_RDONLY);
		if (f < 0)
			return 1;
		close (0);
		dup2 (f, 0);
	}
	if (p->_stdout) {
		int f = open (p->_stdout, O_WRONLY);
		if (f < 0)
			return 1;
		close (1);
		dup2 (f, 1);
	}
	if (p->_stderr) {
		int f = open (p->_stderr, O_WRONLY);
		if (f < 0)
			return 1;
		close (2);
		dup2 (f, 2);
	}
	if (p->_aslr != -1)
		setASLR (p->_aslr);
#if __UNIX__
	set_limit (p->_docore, RLIMIT_CORE, RLIM_INFINITY);
	if (p->_maxfd)
		set_limit (p->_maxfd, RLIMIT_NOFILE, p->_maxfd);
#ifdef RLIMIT_NPROC
	if (p->_maxproc)
		set_limit (p->_maxproc, RLIMIT_NPROC, p->_maxproc);
#endif
	if (p->_maxstack)
		set_limit (p->_maxstack, RLIMIT_STACK, p->_maxstack);
#else
	if (p->_docore || p->_maxfd || p->_maxproc || p->_maxstack)
		eprintf ("Warning: setrlimits not supported for this platform\n");
#endif

	if (p->_connect) {
		char *q = strchr (p->_connect, ':');
		if (q) {
			RSocket *fd = r_socket_new (0);
			*q = 0;
			if (!r_socket_connect_tcp (fd, p->_connect, q+1, 30)) {
				eprintf ("Cannot connect\n");
				return 1;
			}
			eprintf ("connected\n");
			close (0);
			close (1);
			close (2);
			dup2 (fd->fd, 0);
			dup2 (fd->fd, 1);
			dup2 (fd->fd, 2);
		} else {
			eprintf ("Invalid format for connect. missing ':'\n");
			return 1;
		}
	}
	if (p->_listen) {
		RSocket *child, *fd = r_socket_new (0);
		if (!r_socket_listen (fd, p->_listen, NULL)) {
			eprintf ("rarun2: cannot listen\n");
			r_socket_free (fd);
			return 1;
		}
		child = r_socket_accept (fd);
		if (child) {
			eprintf ("connected\n");
			close (0);
			close (1);
			close (2);
			dup2 (child->fd, 0);
			dup2 (child->fd, 1);
			dup2 (child->fd, 2);
		}
	}
	if (p->_r2sleep != 0) {
		r_sys_sleep (p->_r2sleep);
	}
	if (p->_chgdir) {
		ret = chdir (p->_chgdir);
		if (ret < 0)
			return 1;
	}
	if (p->_chroot) {
		ret = chdir (p->_chroot);
		if (ret < 0)
			return 1;
	}
#if __UNIX__
	if (p->_chroot) {
		if (chroot (p->_chroot)) {
			eprintf ("rarun2: cannot chroot\n");
			return 1;
		}
		chdir("/");
	}
	if (p->_setuid) {
		ret = setgroups(0, NULL);
		if (ret < 0)
			return 1;
		ret = setuid (atoi (p->_setuid));
		if (ret < 0)
			return 1;
	}
	if (p->_seteuid) {
		ret = seteuid (atoi (p->_seteuid));
		if (ret < 0)
			return 1;
	}
	if (p->_setgid) {
		ret = setgid (atoi (p->_setgid));
		if (ret < 0)
			return 1;
	}
	if (p->_input) {
		int f2[2];
		pipe (f2);
		close (0);
		dup2 (f2[0], 0);
		parseinput (p->_input);
		write (f2[1], p->_input, strlen (p->_input));
	}
#endif
	if (p->_r2preload) {
		if (p->_preload) {
			eprintf ("WARNING: Only one library can be opened at a time\n");
		}
		p->_preload = R2_LIBDIR"/libr2."R_LIB_EXT;
	}
	if (p->_libpath) {
#if __WINDOWS__
		eprintf ("rarun2: libpath unsupported for this platform\n");
#elif __HAIKU__
		r_sys_setenv ("LIBRARY_PATH", p->_libpath);
#elif __APPLE__
		r_sys_setenv ("DYLD_LIBRARY_PATH", p->_libpath);
#else
		r_sys_setenv ("LD_LIBRARY_PATH", p->_libpath);
#endif
	}
	if (p->_preload) {
#if __APPLE__
		// 10.6
		r_sys_setenv ("DYLD_PRELOAD", p->_preload);
		r_sys_setenv ("DYLD_INSERT_LIBRARIES", p->_preload);
		// 10.8
		r_sys_setenv ("DYLD_FORCE_FLAT_NAMESPACE", "1");
#else
		r_sys_setenv ("LD_PRELOAD", p->_preload);
#endif
	}
	if (p->_timeout) {
#if __UNIX__
		int mypid = getpid ();
		if (!fork ()) {
			sleep (p->_timeout);
			if (!kill (mypid, 0))
				eprintf ("\nrarun2: Interrupted by timeout\n");
			kill (mypid, SIGKILL);
			exit (0);
		}
#else
		eprintf ("timeout not supported for this platform\n");
#endif
	}
#if __APPLE__
	posix_spawnattr_init (&attr);
	if (p->_args[0]) {
		char **envp = r_sys_get_environ();
		ut32 spflags = 0; //POSIX_SPAWN_START_SUSPENDED;
		spflags |= POSIX_SPAWN_SETEXEC;
		if (p->_aslr == 0) {
#define _POSIX_SPAWN_DISABLE_ASLR 0x0100
			spflags |= _POSIX_SPAWN_DISABLE_ASLR;
		}
		(void)posix_spawnattr_setflags (&attr, spflags);
		if (p->_bits) {
			size_t copied = 1;
			cpu_type_t cpu;
#if __i386__ || __x86_64__
			cpu = CPU_TYPE_I386;
			if (p->_bits == 64)
				cpu |= CPU_ARCH_ABI64;
#else
			cpu = CPU_TYPE_ANY;
#endif
			posix_spawnattr_setbinpref_np (
					&attr, 1, &cpu, &copied);
		}
		ret = posix_spawnp (&pid, p->_args[0],
			NULL, &attr, p->_args, envp);
		switch (ret) {
		case 0:
			break;
		case 22:
			eprintf ("posix_spawnp: Invalid argument\n");
			break;
		case 86:
			eprintf ("posix_spawnp: Unsupported architecture\n");
			break;
		default:
			eprintf ("posix_spawnp: unknown error %d\n", ret);
			perror ("posix_spawnp");
			break;
		}
		exit (ret);
	}
#endif
	if (p->_system) {
		if (p->_pid) {
			eprintf ("PID: Cannot determine pid with 'system' directive. Use 'program'.\n");
		}
		exit (r_sys_cmd (p->_system));
	}
	if (p->_program) {
		if (!r_file_exists (p->_program)) {
			char *progpath = r_file_path (p->_program);
			if (progpath && *progpath) {
				free (p->_program);
				p->_program = progpath;
			} else {
				free (progpath);
				eprintf ("rarun2: %s: file not found\n", p->_program);
				return 1;
			}
		}
#if __UNIX__
		// XXX HACK close all non-tty fds
		{ int i; for (i=3; i<10; i++) close (i); }
		// TODO: use posix_spawn
		if (p->_setgid) {
			ret = setgid (atoi (p->_setgid));
			if (ret < 0)
				return 1;
		}
		if (p->_pid) {
			eprintf ("PID: %d\n", getpid ());
		}
		if (p->_pidfile) {
			char pidstr[32];
			snprintf (pidstr, sizeof (pidstr), "%d\n", getpid ());
			r_file_dump (p->_pidfile,
				(const ut8*)pidstr,
				strlen (pidstr), 0);
		}
#endif

	if (p->_nice) {
#if __UNIX__
        errno = 0;
        ret = nice(p->_nice);
        if (ret == -1) {
            if (errno != 0) {
                return 1;
            }
        }
#else
	eprintf ("nice not supported for this platform\n");
#endif
    }
		exit (execv (p->_program, (char* const*)p->_args));
	}
	return 0;
}
Example #9
0
/// The ulimit builtin, used for setting resource limits.
int builtin_ulimit(parser_t &parser, io_streams_t &streams, wchar_t **argv) {
    wchar_t *cmd = argv[0];
    int argc = builtin_count_args(argv);
    bool report_all = false;
    bool hard = false;
    bool soft = false;
    int what = RLIMIT_FSIZE;

    const wchar_t *short_options = L":HSacdflmnstuvh";
    const struct woption long_options[] = {{L"all", no_argument, NULL, 'a'},
                                           {L"hard", no_argument, NULL, 'H'},
                                           {L"soft", no_argument, NULL, 'S'},
                                           {L"core-size", no_argument, NULL, 'c'},
                                           {L"data-size", no_argument, NULL, 'd'},
                                           {L"file-size", no_argument, NULL, 'f'},
                                           {L"lock-size", no_argument, NULL, 'l'},
                                           {L"resident-set-size", no_argument, NULL, 'm'},
                                           {L"file-descriptor-count", no_argument, NULL, 'n'},
                                           {L"stack-size", no_argument, NULL, 's'},
                                           {L"cpu-time", no_argument, NULL, 't'},
                                           {L"process-count", no_argument, NULL, 'u'},
                                           {L"virtual-memory-size", no_argument, NULL, 'v'},
                                           {L"help", no_argument, NULL, 'h'},
                                           {NULL, 0, NULL, 0}};

    int opt;
    wgetopter_t w;
    while ((opt = w.wgetopt_long(argc, argv, short_options, long_options, NULL)) != -1) {
        switch (opt) {
            case 'a': {
                report_all = true;
                break;
            }
            case 'H': {
                hard = true;
                break;
            }
            case 'S': {
                soft = true;
                break;
            }
            case 'c': {
                what = RLIMIT_CORE;
                break;
            }
            case 'd': {
                what = RLIMIT_DATA;
                break;
            }
            case 'f': {
                what = RLIMIT_FSIZE;
                break;
            }
#ifdef RLIMIT_MEMLOCK
            case 'l': {
                what = RLIMIT_MEMLOCK;
                break;
            }
#endif
#ifdef RLIMIT_RSS
            case 'm': {
                what = RLIMIT_RSS;
                break;
            }
#endif
            case 'n': {
                what = RLIMIT_NOFILE;
                break;
            }
            case 's': {
                what = RLIMIT_STACK;
                break;
            }
            case 't': {
                what = RLIMIT_CPU;
                break;
            }
#ifdef RLIMIT_NPROC
            case 'u': {
                what = RLIMIT_NPROC;
                break;
            }
#endif
#ifdef RLIMIT_AS
            case 'v': {
                what = RLIMIT_AS;
                break;
            }
#endif
            case 'h': {
                builtin_print_help(parser, streams, cmd, streams.out);
                return 0;
            }
            case ':': {
                streams.err.append_format(BUILTIN_ERR_MISSING, cmd, argv[w.woptind - 1]);
                return STATUS_BUILTIN_ERROR;
            }
            case '?': {
                builtin_unknown_option(parser, streams, cmd, argv[w.woptind - 1]);
                return STATUS_BUILTIN_ERROR;
            }
            default: {
                DIE("unexpected retval from wgetopt_long");
                break;
            }
        }
    }

    if (report_all) {
        print_all(hard, streams);
        return STATUS_BUILTIN_OK;
    }

    int arg_count = argc - w.woptind;
    if (arg_count == 0) {
        // Show current limit value.
        print(what, hard, streams);
        return STATUS_BUILTIN_OK;
    } else if (arg_count != 1) {
        streams.err.append_format(BUILTIN_ERR_TOO_MANY_ARGUMENTS, cmd);
        builtin_print_help(parser, streams, cmd, streams.err);
        return STATUS_BUILTIN_ERROR;
    }

    // Change current limit value.
    if (!hard && !soft) {
        // Set both hard and soft limits if neither was specified.
        hard = soft = true;
    }

    rlim_t new_limit;
    if (*argv[w.woptind] == L'\0') {
        streams.err.append_format(_(L"%ls: New limit cannot be an empty string\n"), cmd);
        builtin_print_help(parser, streams, cmd, streams.err);
        return STATUS_BUILTIN_ERROR;
    } else if (wcscasecmp(argv[w.woptind], L"unlimited") == 0) {
        new_limit = RLIM_INFINITY;
    } else if (wcscasecmp(argv[w.woptind], L"hard") == 0) {
        new_limit = get(what, 1);
    } else if (wcscasecmp(argv[w.woptind], L"soft") == 0) {
        new_limit = get(what, soft);
    } else {
        new_limit = fish_wcstol(argv[w.woptind]);
        if (errno) {
            streams.err.append_format(_(L"%ls: Invalid limit '%ls'\n"), cmd, argv[w.woptind]);
            builtin_print_help(parser, streams, cmd, streams.err);
            return STATUS_BUILTIN_ERROR;
        }
        new_limit *= get_multiplier(what);
    }

    return set_limit(what, hard, soft, new_limit, streams);
}
Example #10
0
bool judge(const char *input_file,
           const char *output_file_std,
           const char *stdout_file_executive,
           const char *stderr_file_executive) {
    rusage rused{};
    pid_t executor = fork();  // create a child process for executor

    if (executor < 0) {
        FM_LOG_FATAL("fork executor failed: %s", strerror(errno));
        exit(EXIT_PRE_JUDGE);
    } else if (executor == 0) {  // child process
        log_add_info("executor");

        off_t fsize = file_size(output_file_std);

        // io redirect, must before set_security_option()
        io_redirect(input_file, stdout_file_executive, stderr_file_executive);

        // chroot & setuid
        set_security_option();

        // set memory, time and file size limit etc.
        set_limit(fsize);  // must after set_security_option()

        FM_LOG_DEBUG("time limit: %d, time limit addtion: %d",
                     oj_solution.time_limit, time_limit_addtion);


        uint64_t real_time_limit = oj_solution.time_limit + time_limit_addtion;  // time fix
        // set real time alarm
        if (EXIT_SUCCESS != malarm(ITIMER_REAL, real_time_limit)) {
            FM_LOG_FATAL("malarm for executor failed: %s", strerror(errno));
            exit(EXIT_PRE_JUDGE);
        }

        FM_LOG_TRACE("begin execute");

        if (ptrace(PTRACE_TRACEME, 0, NULL, NULL) < 0) {
            FM_LOG_FATAL("Trace executor failed: %s", strerror(errno));
            exit(EXIT_PRE_JUDGE_PTRACE);
        }

        // load program
        if (oj_solution.lang == LANG_JAVA) {
            print_executor(EXEC_J);
            execvp(EXEC_J[0], (char *const *) EXEC_J);
        } else if (oj_solution.lang == LANG_KOTLIN) {
            print_executor(EXEC_KT);
            execvp(EXEC_KT[0], (char *const *) EXEC_KT);
        } else if (oj_solution.lang == LANG_PYTHON27) {
            print_executor(EXEC_PY27);
#ifdef FAST_JUDGE
            execvp(EXEC_PY27[0], (char * const *) EXEC_PY27);
#else
            execv(EXEC_PY27[0], (char *const *) EXEC_PY27);
#endif
        } else if (oj_solution.lang == LANG_PYTHON3) {
            print_executor(EXEC_PY3);
#ifdef FAST_JUDGE
            execvp(EXEC_PY3[0], (char * const *) EXEC_PY3);
#else
            execv(EXEC_PY3[0], (char *const *) EXEC_PY3);
#endif
        } else {
            execl("./Main", "./Main", NULL);
        }

        // exec error
        FM_LOG_FATAL("exec error");
        exit(EXIT_PRE_JUDGE_EXECLP);
    } else {
        // Judger
        int status = 0;
        user_regs_struct regs{};
        stderr = freopen("error.txt", "a+", stderr);

        init_syscalls(oj_solution.lang);

        while (true) {
            if (wait4(executor, &status, 0, &rused) < 0) {
                FM_LOG_FATAL("wait4 executor failed: %s", strerror(errno));
                kill(executor, SIGKILL);
                exit(EXIT_JUDGE);
            }

            if (WIFEXITED(status)) {
                if ((oj_solution.lang != LANG_JAVA && oj_solution.lang != LANG_KOTLIN) ||
                    WEXITSTATUS(status) == EXIT_SUCCESS) {
                    // AC PE WA
                    FM_LOG_TRACE("normal quit");
                    int result;
                    if (oj_solution.spj) {
                        // use SPJ
                        result = oj_compare_output_spj(input_file, output_file_std, stdout_file_executive,
                                                       oj_solution.spj_exe_file);
                    } else {
                        // compare file
                        result = oj_compare_output(output_file_std, stdout_file_executive);
                    }
                    // WA
                    if (result == OJ_WA) {
                        oj_solution.result = OJ_WA;
                    } else if (oj_solution.result != OJ_PE) {  // previous case is AC
                        oj_solution.result = result;  // AC or PE
                    } else /* (oj_solution.result == OJ_PE) */ {  // previous case is PE
                        oj_solution.result = OJ_PE;
                    }
                    FM_LOG_NOTICE("case result: %d, problem result: %d", result, oj_solution.result);
                } else {
                    // not return 0
                    oj_solution.result = OJ_RE;
                    FM_LOG_NOTICE("abnormal quit, exit_code: %d", WEXITSTATUS(status));
                }
                break;
            }

            // RE/TLE/OLE
            if (WIFSIGNALED(status) || (WIFSTOPPED(status) && WSTOPSIG(status) != SIGTRAP)) {
                int signo = 0;
                if (WIFSIGNALED(status)) {
                    signo = WTERMSIG(status);
                    FM_LOG_NOTICE("child process killed by signal %d, %s", signo, strsignal(signo));
                } else {
                    signo = WSTOPSIG(status);
                    FM_LOG_NOTICE("child process stopped by signal %d, %s", signo, strsignal(signo));
                }
                switch (signo) {
                    // Ignore
                    case SIGCHLD:
                        oj_solution.result = OJ_AC;
                        break;
                        // TLE
                    case SIGALRM:    // alarm() and setitimer(ITIMER_REAL)
                    case SIGVTALRM:  // setitimer(ITIMER_VIRTUAL)
                    case SIGXCPU:    // exceeds soft processor limit
                        oj_solution.result = OJ_TLE;
                        FM_LOG_TRACE("Time Limit Exceeded: %s", strsignal(signo));
                        break;
                        // OLE
                    case SIGXFSZ:  // exceeds file size limit
                        oj_solution.result = OJ_OLE;
                        FM_LOG_TRACE("Output Limit Exceeded");
                        break;
                        // RE
                    case SIGSEGV:  // segmentation violation
                    case SIGFPE:   // any arithmetic exception
                    case SIGBUS:   // the process incurs a hardware fault
                    case SIGABRT:  // abort() function
                    case SIGKILL:  // exceeds hard processor limit
                    default:
                        oj_solution.result = OJ_RE;
                        FILE *fp = fopen(stderr_file_executive, "a+");
                        if (fp == nullptr) {
                            fprintf(stderr, "%s\n", strsignal(signo));
                            FM_LOG_WARNING("Runtime Error: %s", strsignal(signo));
                        } else {
                            fprintf(fp, "%s\n", strsignal(signo));
                            fclose(fp);
                        }
                        break;
                }  // end of swtich
                kill(executor, SIGKILL);
                break;
            }  // end of  "if (WIFSIGNALED(status) ...)"

            oj_solution.memory_usage = std::max(oj_solution.memory_usage, (unsigned long) rused.ru_maxrss);
            // TODO(power): check why memory exceed too much
            if (oj_solution.memory_usage > oj_solution.memory_limit) {
                oj_solution.result = OJ_MLE;
                kill(executor, SIGKILL);
                break;
            }

            // check syscall
            if (ptrace(PTRACE_GETREGS, executor, NULL, &regs) < 0) {
                FM_LOG_FATAL("ptrace(PTRACE_GETREGS) failed: %s", strerror(errno));
                kill(executor, SIGKILL);
                exit(EXIT_JUDGE);
            }
            int syscall_id = 0;
#ifdef __i386__
            syscall_id = (int)regs.orig_eax;
#else
            syscall_id = (int) regs.orig_rax;
#endif
            if (syscall_id > 0 && !is_valid_syscall(syscall_id)) {
                oj_solution.result = OJ_RF;
                FM_LOG_FATAL("restricted function, syscall_id: %d", syscall_id);
                kill(executor, SIGKILL);
                break;
            }

            if (ptrace(PTRACE_SYSCALL, executor, NULL, NULL) < 0) {
                FM_LOG_FATAL("ptrace(PTRACE_SYSCALL) failed: %s", strerror(errno));
                kill(executor, SIGKILL);
                exit(EXIT_JUDGE);
            }
        }  // end of while
    }  // end of fork for judge process

    oj_solution.memory_usage = std::max(oj_solution.memory_usage, (unsigned long) rused.ru_maxrss);
    if (oj_solution.memory_usage > oj_solution.memory_limit) {
        oj_solution.result = OJ_MLE;
        FM_LOG_NOTICE("memory limit exceeded: %d (fault: %d * %d)",
                      oj_solution.memory_usage, rused.ru_minflt, page_size);
    }

    oj_solution.time_usage = std::max(oj_solution.time_usage,
                                      (unsigned long) rused.ru_utime.tv_sec * 1000 + rused.ru_utime.tv_usec / 1000);

    if (oj_solution.time_usage > oj_solution.time_limit) {
        oj_solution.result = OJ_TLE;
        FM_LOG_TRACE("Time Limit Exceeded");
    }

    if (oj_solution.result != OJ_AC) {
        if (oj_solution.judge_type == ACM) {
            FM_LOG_NOTICE("not AC/PE, no need to continue");
        }
        if (oj_solution.result == OJ_TLE) {
            oj_solution.time_usage = oj_solution.time_limit;
        } else if (oj_solution.result == OJ_WA) {
            if (oj_solution.lang == LANG_JAVA) { // TODO: kotlin
                fix_java_result(stdout_file_executive, stderr_file_executive);
            } else if ((oj_solution.lang == LANG_PYTHON27 || oj_solution.lang == LANG_PYTHON3) &&
                       file_size(stderr_file_executive)) {
                oj_solution.result = OJ_RE;
                FM_LOG_TRACE("Runtime Error");
            }
        }
        return false;
    }
    return true;
}
Example #11
0
File: main.c Project: DAOWAce/pcsxr
int main(int argc, char *argv[])
{
    FILE *in;
    char t[256];
    int len, val = 0;
    char *pB, *p;
    char cfg[255];

#ifdef ENABLE_NLS
    setlocale (LC_ALL, "");
    bindtextdomain (GETTEXT_PACKAGE, LOCALE_DIR);
    bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
    textdomain (GETTEXT_PACKAGE);
#endif

    if (argc < 2) {
    	printf ("Usage: cfgDFSound {about | configure}\n");
		return 0;
	}

    if (strcmp(argv[1], "configure") != 0 && 
		strcmp(argv[1], "about") != 0) {
		printf ("Usage: cfgDFSound {about | configure}\n");
		return 0;
    }

    gtk_init(&argc, &argv);

    if (strcmp(argv[1], "about") == 0) {
		const char *authors[]= {"Pete Bernert and the P.E.Op.S. team", "Ryan Schultz", "Andrew Burton", NULL};
		widget = gtk_about_dialog_new ();
		gtk_about_dialog_set_program_name (GTK_ABOUT_DIALOG (widget), "dfsound PCSXR Sound Plugin");
		gtk_about_dialog_set_version (GTK_ABOUT_DIALOG (widget), "1.6");
		gtk_about_dialog_set_authors (GTK_ABOUT_DIALOG (widget), authors);
		gtk_about_dialog_set_website (GTK_ABOUT_DIALOG (widget), "http://pcsx-df.sourceforge.net/");

		g_signal_connect_data(G_OBJECT(widget), "response",
			G_CALLBACK(on_about_clicked), NULL, NULL, G_CONNECT_AFTER);

		gtk_widget_show (widget);
		gtk_main();

		return 0;
    }
	else if (strcmp(argv[1], "configure") == 0) {
		builder = gtk_builder_new();

		if (!gtk_builder_add_from_file(builder, DATADIR "dfsound.ui", NULL)) {
			g_warning("We could not load the interface!");
			return 0;
		}
		
		MainWindow = gtk_builder_get_object(builder, "CfgWnd");

		strcpy(cfg, CONFIG_FILENAME);

		in = fopen(cfg, READBINARY);
		if (in) {
			pB = (char *)malloc(32767);
			memset(pB, 0, 32767);
			len = fread(pB, 1, 32767, in);
			fclose(in);
		} else {
			pB = 0;
			printf ("Error - no configuration file\n");
			/* TODO Raise error - no configuration file */
		}

		/* ADB TODO Replace a lot of the following with common functions */
		if (pB) {
			strcpy(t, "\nVolume");
			p = strstr(pB, t);
			if (p) {
				p = strstr(p, "=");
				len = 1;
			}
			val = set_limit (p, len, -1, 4) + 1;
		} else val = 2;

		gtk_combo_box_set_active(GTK_COMBO_BOX (gtk_builder_get_object(builder, "cbVolume2")), val);

		if (pB) {
		strcpy(t, "\nUseInterpolation");
		p = strstr(pB, t);
		if (p) {
			p = strstr(p, "=");
			len = 1;
		}
			val = set_limit (p, len, 0, 3);
		} else val = 2;

		gtk_combo_box_set_active(GTK_COMBO_BOX (gtk_builder_get_object(builder, "cbInterpolation2")), val);

		if (pB) {
			strcpy(t, "\nXAPitch");
			p = strstr(pB, t);
			if (p) {
				p = strstr(p, "=");
				len = 1;
			}
			val = set_limit (p, len, 0, 1);
		} else val = 0;

		gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON (gtk_builder_get_object(builder, "chkXASpeed")), val);

		if (pB) {
			strcpy(t, "\nHighCompMode");
			p = strstr(pB, t);
			if (p) {
				p = strstr(p, "=");
				len = 1;
			}
			val = set_limit (p, len, 0, 1);
		} else val = 1;

		gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON (gtk_builder_get_object(builder, "chkHiCompat")), val);

		if (pB) {
			strcpy(t, "\nSPUIRQWait");
			p = strstr(pB, t);
			if (p) {
				p = strstr(p, "=");
				len = 1;
			}

			val = set_limit (p, len, 0, 1);
		} else val = 1;

		gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON (gtk_builder_get_object(builder, "chkIRQWait")), val);

		if (pB) {
			strcpy(t, "\nDisStereo");
			p = strstr(pB, t);
			if (p) {
				p = strstr(p, "=");
				len = 1;
			}

			val = set_limit (p, len, 0, 1);
		} else val = 0;

		gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON (gtk_builder_get_object(builder, "chkDisStereo")), val);

		if (pB) {
			strcpy(t, "\nFreqResponse");
			p = strstr(pB, t);
			if (p) {
				p = strstr(p, "=");
				len = 1;
			}

			val = set_limit (p, len, 0, 1);
		} else val = 0;

		gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON (gtk_builder_get_object(builder, "chkFreqResponse")), val);

		if (pB) {
			strcpy(t, "\nUseReverb");
			p = strstr(pB, t);
			if (p) {
				p = strstr(p, "=");
				len = 1;
			}
			val = set_limit (p, len, 0, 2);
		} else val = 2;

		gtk_combo_box_set_active(GTK_COMBO_BOX(gtk_builder_get_object(builder, "cbReverb2")), val);

		if (pB)
			free(pB);

		widget = gtk_builder_get_object(builder, "CfgWnd");
		g_signal_connect_data(G_OBJECT(widget), "destroy",
			G_CALLBACK(SaveConfig), builder, NULL, 0);

		widget = gtk_builder_get_object(builder, "btn_close");
		g_signal_connect_data(G_OBJECT(widget), "clicked",
			G_CALLBACK(OnConfigClose), builder, NULL, G_CONNECT_AFTER);

		gtk_widget_show(MainWindow);
		gtk_main();
	}
	
    return 0;
}
Example #12
0
/* Set the CPU time limit in seconds. */
void limit_time(unsigned long n)
	{
	set_limit(RLIMIT_CPU,n);
	}
Example #13
0
static int process_line()
{
	const char *config_segment = NULL;
	char *shell = NULL;

	if (current_argument(&config_segment) < 0 || !config_segment) return 0;

	     if (strcmp(config_segment, "execute") == 0)
	{
	if (next_argument(&config_segment) < 0) return -1;
	shell = strdup(config_segment);
	int outcome = add_execute_respawn(shell);
	free(shell);
	if (outcome < 0) return -1;
	}


	else if (strcmp(config_segment, "execute_critical") == 0)
	{
	if (next_argument(&config_segment) < 0) return -1;
	shell = strdup(config_segment);
	int outcome = add_execute_critical_respawn(shell);
	free(shell);
	if (outcome < 0) return -1;
	}


	else if (strcmp(config_segment, "system") == 0)
	{
	if (next_argument(&config_segment) < 0) return -1;
	shell = strdup(config_segment);
	int outcome = add_system_respawn(shell);
	free(shell);
	if (outcome < 0) return -1;
	}


	else if (strcmp(config_segment, "system_critical") == 0)
	{
	if (next_argument(&config_segment) < 0) return -1;
	shell = strdup(config_segment);
	int outcome = add_system_critical_respawn(shell);
	free(shell);
	if (outcome < 0) return -1;
	}


	else if (strcmp(config_segment, "limit") == 0)
	{
	if (remaining_line(&config_segment) < 0 || !config_segment) return -1;
	int new_limit = 0;
	if (!parse_integer10(config_segment, &new_limit) || new_limit < 0) return -1;
	set_limit(new_limit);
	}


	else if (strcmp(config_segment, "security") == 0)
	{
	if (remaining_line(&config_segment) < 0 || !config_segment) return -1;
	permission_mask new_permissions = 0;
	if (!parse_permissions(config_segment, &new_permissions)) return -1;
	set_permissions(new_permissions);
	}


	else if (strcmp(config_segment, "priority") == 0)
	{
	if (remaining_line(&config_segment) < 0 || !config_segment) return -1;
	int new_priority = 0;
	if ( !parse_integer10(config_segment, &new_priority) || new_priority < 0 ||
	     new_priority > 255 )
	return -1;
	set_priority(new_priority);
	}


	else if (strcmp(config_segment, "log_mode") == 0)
	{
	if (remaining_line(&config_segment) < 0 || !config_segment) return -1;
	logging_mode mode_mask = logging_none;
	if (!parse_logging_mode(config_segment, &mode_mask)) return -1;
	set_logging_mode(mode_mask);
	}


	else return -1;

	return 0;
}
Example #14
0
File: run.c Project: f0829/radare2
R_API int r_run_config_env(RRunProfile *p) {
	int ret;

	if (!p->_program && !p->_system && !p->_runlib) {
		printf ("No program, system or runlib rule defined\n");
		return 1;
	}
	// when IO is redirected to a process, handle them together
	if (handle_redirection (p->_stdio, true, true, false) != 0) {
		return 1;
	}
	if (handle_redirection (p->_stdin, true, false, false) != 0) {
		return 1;
	}
	if (handle_redirection (p->_stdout, false, true, false) != 0) {
		return 1;
	}
	if (handle_redirection (p->_stderr, false, false, true) != 0) {
		return 1;
	}
	if (p->_aslr != -1) {
		setASLR (p, p->_aslr);
	}
#if __UNIX__
	set_limit (p->_docore, RLIMIT_CORE, RLIM_INFINITY);
	if (p->_maxfd) {
		set_limit (p->_maxfd, RLIMIT_NOFILE, p->_maxfd);
	}
#ifdef RLIMIT_NPROC
	if (p->_maxproc) {
		set_limit (p->_maxproc, RLIMIT_NPROC, p->_maxproc);
	}
#endif
	if (p->_maxstack) {
		set_limit (p->_maxstack, RLIMIT_STACK, p->_maxstack);
	}
#else
	if (p->_docore || p->_maxfd || p->_maxproc || p->_maxstack)
		eprintf ("Warning: setrlimits not supported for this platform\n");
#endif
	if (p->_connect) {
		char *q = strchr (p->_connect, ':');
		if (q) {
			RSocket *fd = r_socket_new (0);
			*q = 0;
			if (!r_socket_connect_tcp (fd, p->_connect, q+1, 30)) {
				eprintf ("Cannot connect\n");
				return 1;
			}
			if (p->_pty) {
				if (redirect_socket_to_pty (fd) != 0) {
					eprintf ("socket redirection failed\n");
					r_socket_free (fd);
					return 1;
				}
			} else {
				redirect_socket_to_stdio (fd);
			}
		} else {
			eprintf ("Invalid format for connect. missing ':'\n");
			return 1;
		}
	}
	if (p->_listen) {
		RSocket *child, *fd = r_socket_new (0);
		bool is_child = false;
		if (!r_socket_listen (fd, p->_listen, NULL)) {
			eprintf ("rarun2: cannot listen\n");
			r_socket_free (fd);
			return 1;
		}
		while (true) {
			child = r_socket_accept (fd);
			if (child) {
				is_child = true;

				if (p->_dofork && !p->_dodebug) {
#ifdef _MSC_VER
					int child_pid = r_sys_fork ();
#else
					pid_t child_pid = r_sys_fork ();
#endif
					if (child_pid == -1) {
						eprintf("rarun2: cannot fork\n");
						r_socket_free (child);
						r_socket_free (fd);
						return 1;
					} else if (child_pid != 0){
						// parent code
						is_child = false;
					}
				}

				if (is_child) {
					r_socket_close_fd (fd);
					eprintf ("connected\n");
					if (p->_pty) {
						if (redirect_socket_to_pty (child) != 0) {
							eprintf ("socket redirection failed\n");
							r_socket_free (child);
							r_socket_free (fd);
							return 1;
						}
					} else {
						redirect_socket_to_stdio (child);
					}
					break;
				} else {
					r_socket_close_fd (child);
				}
			}
		}
		if (!is_child) {
			r_socket_free (child);
		}
		r_socket_free (fd);
	}
	if (p->_r2sleep != 0) {
		r_sys_sleep (p->_r2sleep);
	}
#if __UNIX__
	if (p->_chroot) {
		if (chdir (p->_chroot) == -1) {
			eprintf ("Cannot chdir to chroot in %s\n", p->_chroot);
			return 1;
		} else {
			if (chroot (".") == -1) {
				eprintf ("Cannot chroot to %s\n", p->_chroot);
				return 1;
			} else {
				// Silenting pedantic meson flags...
				if (chdir ("/") == -1) {
					eprintf ("Cannot chdir to /\n");
					return 1;
				}
				if (p->_chgdir) {
					if (chdir (p->_chgdir) == -1) {
						eprintf ("Cannot chdir after chroot to %s\n", p->_chgdir);
						return 1;
					}
				}
			}
		}
	} else if (p->_chgdir) {
		if (chdir (p->_chgdir) == -1) {
			eprintf ("Cannot chdir after chroot to %s\n", p->_chgdir);
			return 1;
		}
	}
#else
	if (p->_chgdir) {
		ret = chdir (p->_chgdir);
		if (ret < 0) {
			return 1;
		}
	}
	if (p->_chroot) {
		ret = chdir (p->_chroot);
		if (ret < 0) {
			return 1;
		}
	}
#endif
#if __UNIX__
	if (p->_setuid) {
		ret = setgroups (0, NULL);
		if (ret < 0) {
			return 1;
		}
		ret = setuid (atoi (p->_setuid));
		if (ret < 0) {
			return 1;
		}
	}
	if (p->_seteuid) {
		ret = seteuid (atoi (p->_seteuid));
		if (ret < 0) {
			return 1;
		}
	}
	if (p->_setgid) {
		ret = setgid (atoi (p->_setgid));
		if (ret < 0) {
			return 1;
		}
	}
	if (p->_input) {
		char *inp;
		int f2[2];
		if (pipe (f2) != -1) {
			close (0);
			dup2 (f2[0], 0);
		} else {
			eprintf ("[ERROR] rarun2: Cannot create pipe\n");
			return 1;
		}
		inp = getstr (p->_input);
		if (inp) {
			size_t inpl = strlen (inp);
			if  (write (f2[1], inp, inpl) != inpl) {
				eprintf ("[ERROR] rarun2: Cannot write to the pipe\n");
			}
			close (f2[1]);
			free (inp);
		} else {
			eprintf ("Invalid input\n");
		}
	}
#endif
	if (p->_r2preload) {
		if (p->_preload) {
			eprintf ("WARNING: Only one library can be opened at a time\n");
		}
		p->_preload = R2_LIBDIR"/libr2."R_LIB_EXT;
	}
	if (p->_libpath) {
#if __WINDOWS__
		eprintf ("rarun2: libpath unsupported for this platform\n");
#elif __HAIKU__
		r_sys_setenv ("LIBRARY_PATH", p->_libpath);
#elif __APPLE__
		r_sys_setenv ("DYLD_LIBRARY_PATH", p->_libpath);
#else
		r_sys_setenv ("LD_LIBRARY_PATH", p->_libpath);
#endif
	}
	if (p->_preload) {
#if __APPLE__
		// 10.6
#ifndef __MAC_10_7
		r_sys_setenv ("DYLD_PRELOAD", p->_preload);
#endif
		r_sys_setenv ("DYLD_INSERT_LIBRARIES", p->_preload);
		// 10.8
		r_sys_setenv ("DYLD_FORCE_FLAT_NAMESPACE", "1");
#else
		r_sys_setenv ("LD_PRELOAD", p->_preload);
#endif
	}
	if (p->_timeout) {
#if __UNIX__
		int mypid = getpid ();
		if (!r_sys_fork ()) {
			int use_signal = p->_timeout_sig;
			if (use_signal < 1) {
				use_signal = SIGKILL;
			}
			sleep (p->_timeout);
			if (!kill (mypid, 0)) {
				eprintf ("\nrarun2: Interrupted by timeout\n");
			}
			kill (mypid, use_signal);
			exit (0);
		}
#else
		eprintf ("timeout not supported for this platform\n");
#endif
	}
	return 0;
}
Example #15
0
enum result execute(struct request * req, struct run_result * rused)
{
	pid_t pid;
	char outfile[EOJ_PATH_MAX];
	char complete_fname[EOJ_PATH_MAX];
	char fstdout[EOJ_PATH_MAX];
	unsigned int ltime = req->time_limit, lmem = req->mem_limit;
	
	//reset syscall times
	check_syscall(-1, req);
	snprintf(outfile, EOJ_PATH_MAX, "%s%s", req->fname_nosx,
	         req->cpl->execsuffix);
	snprintf(complete_fname, EOJ_PATH_MAX, "%s%s", req->out_dir, outfile);
	snprintf(fstdout, EOJ_PATH_MAX, "%s%s%s", req->out_dir, req->fname_nosx,
	         ".result");
	//add record only at first time
	if (access(fstdout, F_OK))
		add_file_records(&fcreat_record, fstdout);
		
	pid = fork();
	if (pid == 0) {
		if (set_limit(ltime, 1024)) {
			eoj_log("set rlimit error: %s", strerror(errno));
			exit(1);
		}
		if (io_redirect(req->input_file, fstdout)) {
			eoj_log("ioredirect error: %s", strerror(errno));
			exit(1);
		}
		
		ptrace(PTRACE_TRACEME, 0, NULL, NULL );
		if (execl(complete_fname, outfile, NULL ) == -1) {
			eoj_log("exec fail: %s", strerror(errno));
			exit(1);
		}
	}
	enum result result;
	int status;
	struct rusage rusage;
	long orig_ax;
	while (1) {
		if (wait4(pid, &status, 0, &rusage) < 0) {
			eoj_log("wait error: %s", strerror(errno));
			return SYS_ERROR;
		}
		
		result = check_mem_rusage(&rusage, rused, lmem);
		if (result == MEM_LIMIT_EXCEED) {
			kill(pid, SIGKILL);
			//eoj_log("memory limit exceed");
			break;
		}
		
		if (WIFEXITED(status)) {
			result = RNORMAL;
			break;
		} else if (WSTOPSIG(status) != 5) {
			int sig = WSTOPSIG(status);
			switch (sig) {
			case SIGXCPU:
			case SIGKILL:
				//eoj_log("time limt exceed");
				result = TIME_LIMIT_EXCEED;
				break;
			case SIGXFSZ:
				//eoj_log("output limit exceed");
				result = OUTPUT_LIMIT_EXCEED;
				break;
			default:
				eoj_log("unknown error,sig %s", strsignal(sig));
				result = RUN_TIME_ERR;
				break;
			}
			kill(pid, SIGKILL);
			break;
		}
		
		/* it doesn't work.very strange */
//		else if (WIFSIGNALED(status)) {
//			int sig = WTERMSIG(status);
//			switch (sig) {
//			case SIGKILL:
//			case SIGXCPU:
//				eoj_log("%s time limt exceed", req->fname_nosx);
//				result = TIME_LIMIT_EXCEED;
//				break;
//			case SIGXFSZ:
//				result = OUTPUT_LIMIT_EXCEED;
//				eoj_log("%s output limit exceed", req->fname_nosx);
//				break;
//			default:
//				result = RUN_TIME_ERR;
//				break;
//			}
//			break;
//		}
		orig_ax = ptrace(PTRACE_PEEKUSER, pid, WORDLEN * ORIG_AX, NULL );
		if (orig_ax >= 0 && check_syscall(orig_ax, req)) {
			eoj_log("run illegal system call %ld", orig_ax);
			kill(pid, SIGKILL);
			result = RUN_TIME_ERR;
			break;
		}
		if (ptrace(PTRACE_SYSCALL, pid, NULL, NULL ) < 0) {
			eoj_log("ptrace error: %s", strerror(errno));
			kill(pid, SIGKILL);
			result = SYS_ERROR;
			break;
		}
	}
	
	return result;
}
Example #16
0
static int runfile () {
	int ret;
	if (!_program && !_system) {
		printf ("No program or system rule defined\n");
		return 1;
	}
	if (_stdin) {
		int f = open (_stdin, O_RDONLY);
		if (f < 0)
			return 1;
		close (0);
		dup2 (f, 0);
	}
	if (_stdout) {
		int f = open (_stdout, O_WRONLY);
		if (f < 0)
			return 1;
		close (1);
		dup2 (f, 1);
	}
	if (_stderr) {
		int f = open (_stderr, O_WRONLY);
		if (f < 0)
			return 1;
		close (2);
		dup2 (f, 2);
	}
#if __UNIX__
	set_limit (_docore, RLIMIT_CORE, RLIM_INFINITY);
	set_limit (_maxfd, RLIMIT_NOFILE, _maxfd);
	set_limit (_maxproc, RLIMIT_NPROC, _maxproc);
	set_limit (_maxstack, RLIMIT_STACK, _maxstack);
#else
	if (_docore || _maxfd || _maxproc || _maxstack)
		eprintf ("Warning: setrlimits not supported for this platform\n");
#endif

	if (_connect) {
		char *p = strchr (_connect, ':');
		if (p) {
			RSocket *fd = r_socket_new (0);
			*p=0;
			if (!r_socket_connect_tcp (fd, _connect, p+1, 30)) {
				eprintf ("Cannot connect\n");
				return 1;
			}
			eprintf ("connected\n");
			close (0);
			close (1);
			close (2);
			dup2 (fd->fd, 0);
			dup2 (fd->fd, 1);
			dup2 (fd->fd, 2);
		} else {
			eprintf ("Invalid format for connect. missing ':'\n");
			return 1;
		}
	}
	if (_listen) {
		RSocket *child, *fd = r_socket_new (0);
		if (!r_socket_listen (fd, _listen, NULL)) {
			eprintf ("rarun2: cannot listen\n");
			r_socket_free (fd);
			return 1;
		}
		child = r_socket_accept (fd);
		if (child) {
			eprintf ("connected\n");
			close (0);
			close (1);
			close (2);
			dup2 (child->fd, 0);
			dup2 (child->fd, 1);
			dup2 (child->fd, 2);
		}
	}
	if (_r2sleep != 0) {
		r_sys_sleep (_r2sleep);
	}
	if (_chgdir) {
		ret = chdir (_chgdir);
		if (ret < 0)
			return 1;
	}
	if (_chroot) {
		ret = chdir (_chroot);
		if (ret < 0)
			return 1;
	}
#if __UNIX__
	if (_chroot) {
		if (chroot (_chroot)) {
			eprintf ("rarun2: cannot chroot\n");
			return 1;
		}
	}
	if (_setuid) {
		ret = setuid (atoi (_setuid));
		if (ret < 0)
			return 1;
	}
	if (_seteuid) {
		ret = seteuid (atoi (_seteuid));
		if (ret < 0)
			return 1;
	}
	if (_setgid) {
		ret = setgid (atoi (_setgid));
		if (ret < 0)
			return 1;
	}
	if (_input) {
		int f2[2];
		pipe (f2);
		close (0);
		dup2 (f2[0], 0);
		parseinput (_input);
		write (f2[1], _input, strlen (_input));
	}
#endif
	if (_r2preload) {
		if (_preload) {
			eprintf ("WARNING: Only one library can be opened at a time\n");
		}
		_preload = R2_LIBDIR"/libr2."R_LIB_EXT;
	}
	if (_libpath) {
#if __WINDOWS__
		eprintf ("rarun2: libpath unsupported for this platform\n");
#elif __APPLE__
		r_sys_setenv ("DYLD_LIBRARY_PATH", _libpath);
#else
		r_sys_setenv ("LD_LIBRARY_PATH", _libpath);
#endif
	}
	if (_preload) {
#if __APPLE__
		// 10.6
		r_sys_setenv ("DYLD_PRELOAD", _preload);
		r_sys_setenv ("DYLD_INSERT_LIBRARIES", _preload);
		// 10.8
		r_sys_setenv ("DYLD_FORCE_FLAT_NAMESPACE", "1");
#else
		r_sys_setenv ("LD_PRELOAD", _preload);
#endif
	}
	if (_timeout) {
#if __UNIX__
		int mypid = getpid ();
		if (!fork ()) {
			sleep (_timeout);
			if (!kill (mypid, 0))
				eprintf ("\nrarun2: Interrupted by timeout\n");
			kill (mypid, SIGKILL);
			exit (0);
		}
#else
		eprintf ("timeout not supported for this platform\n");
#endif
	}
	if (_system) {
		exit (r_sys_cmd (_system));
	}
	if (!r_file_exists (_program)) {
		eprintf ("rarun2: %s: file not found\n", _program);
		return 1;
	}
	exit (execv (_program, _args));
}
Example #17
0
    // this function must be invoked by forked process
    void execute_command_in_jail(
        fs::path const& host_container_dir,
        container_options_t const& opts,
        linux::user const& user
        )
    {
        // create virtual root for container
        construct_virtual_root(
            host_container_dir,
            opts.mount_points,
            opts.copy_points,
            user
            );

        // into jail
        if ( ::chroot( host_container_dir.c_str() ) == -1 ) {
            std::stringstream ss;
            ss << "Failed to chroot: "
               << " errno=" << errno << " : " << std::strerror( errno );
            throw std::runtime_error( ss.str() );
        }

        // move to home
        fs::current_path( opts.in_container_start_path );

        // set limits
        set_limits( opts.limits );
        set_limit( RLIMIT_STACK, opts.stack_size );

        // overwrite host $PATH environment, to search an executable by execpve
        overwrite_path( opts.envs );
        auto const& path = ::getenv( "PATH" );
        if ( path != nullptr ) {
            std::cout << " = env PATH is " << path << std::endl;
        }

        // log
        std::cout << "[+] chrooted and resource limited!" << std::endl;

        // TODO: set umask

        // std::system("ls -la /proc/self/fd");

        // redirect: pipes[debug]
        for( auto const& pr : opts.pipe_redirects ) {
            std::cout << "==> host fd: " << pr.host_fd
                      << " will recieve data of child fd: " << pr.guest_fd
                      << std::endl;
        }

        // redirect: pipes
        for( auto const& pr : opts.pipe_redirects ) {
            if ( ::dup2( pr.host_fd, pr.guest_fd ) == -1 ) {
                std::stringstream ss;
                ss << "Failed to dup2: "
                   << " errno=" << errno << " : " << std::strerror( errno );
                throw std::runtime_error( ss.str() );
            }

            if ( ::close( pr.host_fd ) == -1 ) {
                std::stringstream ss;
                ss << "Failed to close the host pipe: "
                   << " errno=" << errno << " : " << std::strerror( errno );
                throw std::runtime_error( ss.str() );
            }
        }

        // === discard privilege
        // remove supplementary groups
        const gid_t s_groups[] = {};
        if ( ::setgroups( 0, s_groups ) == -1 ) {
            std::stringstream ss;
            ss << "Failed to setgroups: "
               << " errno=" << errno << " : " << std::strerror( errno );
            throw std::runtime_error( ss.str() );
        }

        // change group
        if ( ::setresgid( user.group_id(), user.group_id(), user.group_id() ) == -1 ) {
            std::stringstream ss;
            ss << "Failed to setresgid: "
               << " errno=" << errno << " : " << std::strerror( errno );
            throw std::runtime_error( ss.str() );
        }

        // change user
        if ( ::setresuid( user.user_id(), user.user_id(), user.user_id() ) == -1 ) {
            std::stringstream ss;
            ss << "Failed to setresuid: "
               << " errno=" << errno << " : " << std::strerror( errno );
            throw std::runtime_error( ss.str() );
        }
        // ===

        // ==
        // now I am in the sandbox!
        // ==
        if ( opts.commands.size() < 1 ) {
            std::stringstream ss;
            ss << "Failed to prepare environment: commands must have >= 1 elements (" << opts.commands.size() << ")";
            throw std::runtime_error( ss.str() );
        }

        auto const& filename = opts.commands[0];

        auto argv_pack = make_buffer_for_execve( opts.commands );
        auto& argv = std::get<0>( argv_pack );

        auto envp_pack = make_buffer_for_execve( opts.envs );
        auto& envp = std::get<0>( envp_pack );

        // replace self process
        if ( ::execvpe( filename.c_str(), argv.data(), envp.data() ) == -1 ) {
            std::stringstream ss;
            ss << "Failed to execvpe: "
               << " errno=" << errno << " : " << std::strerror( errno );
            throw std::runtime_error( ss.str() );
        }
    }
Example #18
0
/*
 * 执行用户提交的程序
 */
static
void judge() {
    struct rusage rused;
    pid_t executive = fork();
    if (executive < 0) {
        exit(JUDGE_CONF::EXIT_PRE_JUDGE);
    } else if (executive == 0) {
        //子进程,用户程序
        FM_LOG_TRACE("Start Judging.");
        io_redirect();

        security_control();

        int real_time_limit = PROBLEM::time_limit;
        if (EXIT_SUCCESS != malarm(ITIMER_REAL, real_time_limit)) {
            exit(JUDGE_CONF::EXIT_PRE_JUDGE);
        }

        set_limit();

        if (ptrace(PTRACE_TRACEME, 0, NULL, NULL) < 0) {
            exit(JUDGE_CONF::EXIT_PRE_JUDGE_PTRACE);
        }

        if (PROBLEM::lang != JUDGE_CONF::LANG_JAVA){
            execl("./a.out", "a.out", NULL);
        } else {
            execlp("java", "java", "Main", NULL);
        }

        //走到这了说明出错了
        exit(JUDGE_CONF::EXIT_PRE_JUDGE_EXECLP);
    } else {
        //父进程
        int status = 0;  //子进程状态
        int syscall_id = 0; //系统调用号
        struct user_regs_struct regs; //寄存器

        init_RF_table(PROBLEM::lang); //初始化系统调用表

        while (true) {//循环监控子进程
            if (wait4(executive, &status, 0, &rused) < 0) {
                FM_LOG_WARNING("wait4 failed.");
                exit(JUDGE_CONF::EXIT_JUDGE);
            }

            //自行退出
            if (WIFEXITED(status)) {
                if (PROBLEM::lang != JUDGE_CONF::LANG_JAVA ||
                    WEXITSTATUS(status) == EXIT_SUCCESS) {
                    FM_LOG_TRACE("OK, normal quit. All is good.");

                    //PROBLEM::result = JUDGE_CONF::PROCEED;
                } else {
                    FM_LOG_WARNING("oh, some error occured.Abnormal quit.");
                    PROBLEM::result = JUDGE_CONF::RE;
                }
                break;
            }

            //被信号终止掉了
            if (WIFSIGNALED(status) ||
                (WIFSTOPPED(status) && WSTOPSIG(status) != SIGTRAP)) { //要过滤掉SIGTRAP信号
                int signo = 0;
                if (WIFSIGNALED(status)) {
                    signo = WTERMSIG(status);
                    FM_LOG_WARNING("child signaled by %d : %s", signo, strsignal(signo));
                } else {
                    signo = WSTOPSIG(status);
                    FM_LOG_WARNING("child stop by %d : %s\n", signo, strsignal(signo));
                }

                switch (signo) {
                    //TLE
                    case SIGALRM:
                    case SIGXCPU:
                    case SIGVTALRM:
                    case SIGKILL:
                        FM_LOG_TRACE("Well, Time Limit Exeeded");
                        PROBLEM::time_usage = 0;
                        PROBLEM::memory_usage = 0;
                        PROBLEM::result = JUDGE_CONF::TLE;
                        break;
                    case SIGXFSZ:
                        FM_LOG_TRACE("File Limit Exceeded");
                        PROBLEM::time_usage = 0;
                        PROBLEM::memory_usage = 0;
                        PROBLEM::result = JUDGE_CONF::OLE;
                        break;
                    case SIGSEGV:
                    case SIGFPE:
                    case SIGBUS:
                    case SIGABRT:
                        //FM_LOG_TRACE("RE了");
                        PROBLEM::time_usage = 0;
                        PROBLEM::memory_usage = 0;
                        PROBLEM::result = JUDGE_CONF::RE;
                        break;
                    default:
                        //FM_LOG_TRACE("不知道哪儿跪了");
                        PROBLEM::time_usage = 0;
                        PROBLEM::memory_usage = 0;
                        PROBLEM::result = JUDGE_CONF::RE;
                        break;
                }

                ptrace(PTRACE_KILL, executive, NULL, NULL);
                break;
            }

            //MLE
            PROBLEM::memory_usage = std::max((long int)PROBLEM::memory_usage,
                    rused.ru_minflt * (getpagesize() / JUDGE_CONF::KILO));

            if (PROBLEM::memory_usage > PROBLEM::memory_limit) {
                PROBLEM::time_usage = 0;
                PROBLEM::memory_usage = 0;
                PROBLEM::result = JUDGE_CONF::MLE;
                FM_LOG_TRACE("Well, Memory Limit Exceeded.");
                ptrace(PTRACE_KILL, executive, NULL, NULL);
                break;
            }

            //获得子进程的寄存器,目的是为了获知其系统调用
            if (ptrace(PTRACE_GETREGS, executive, NULL, &regs) < 0) {
                FM_LOG_WARNING("ptrace PTRACE_GETREGS failed");
                exit(JUDGE_CONF::EXIT_JUDGE);
            }

#ifdef __i386__
            syscall_id = regs.orig_eax;
#else
            syscall_id = regs.orig_rax;
#endif
            //检查系统调用是否合法
            if (syscall_id > 0 &&
                !is_valid_syscall(PROBLEM::lang, syscall_id, executive, regs)) {
                FM_LOG_WARNING("restricted fuction %d\n", syscall_id);
                if (syscall_id == SYS_rt_sigprocmask){
                    FM_LOG_WARNING("The glibc failed.");
                } else {
                    //FM_LOG_WARNING("%d\n", SYS_write);
                    FM_LOG_WARNING("restricted fuction table");
                }
                PROBLEM::result = JUDGE_CONF::RE;
                ptrace(PTRACE_KILL, executive, NULL, NULL);
                break;
            }

            if (ptrace(PTRACE_SYSCALL, executive, NULL, NULL) < 0) {
                FM_LOG_WARNING("ptrace PTRACE_SYSCALL failed.");
                exit(JUDGE_CONF::EXIT_JUDGE);
            }
        }
    }

    //这儿关于time_usage和memory_usage计算的有点混乱
    //主要是为了减轻web的任务
    //只要不是AC,就把time_usage和memory_usage归0
    if (PROBLEM::result == JUDGE_CONF::SE){
        PROBLEM::time_usage += (rused.ru_utime.tv_sec * 1000 +
                                rused.ru_utime.tv_usec / 1000);
        PROBLEM::time_usage += (rused.ru_stime.tv_sec * 1000 +
                                rused.ru_stime.tv_usec / 1000);
    }

}
Example #19
0
/* Set the maximum size of the process' virtual memory (address space) in
bytes. */
void limit_memory(unsigned long n)
	{
	set_limit(RLIMIT_AS,n);
	}
Example #20
0
/* Set the maximum size of the process stack in bytes. */
void limit_stack(unsigned long n)
	{
	set_limit(RLIMIT_STACK,n);
	}