Ejemplo n.º 1
0
int find_nacl(int conn)
{
    char argbuf[70], outbuf[256];
    char* cut;
    int idx = 0, c;

    if ((c = read(conn, argbuf, sizeof(argbuf)-1)) < 0) {
       syserror("Failed to read arguments");
       return -1;
    }
    argbuf[c] = 0;

    cut = strchr(argbuf, ' ');
    if (!cut) {
        error("No ' ' in findnacl arguments: %s.", argbuf);
        return -1;
    }
    *cut = 0;

    char *cmd = "croutonfindnacl";
    char* args[] = {cmd, argbuf, cut + 1, NULL};

    c = popen2(cmd, args, NULL, 0, outbuf, sizeof(outbuf)-1);
    if (c <= 0) {
        error("Error running helper");
        return -1;
    }
    outbuf[c] = 0;

    /* Parse PID:file output */
    cut = strchr(outbuf, ':');
    if (!cut) {
        error("No ':' in helper reply: %s.", outbuf);
        return -1;
    }
    *cut = 0;

    char* endptr;
    long pid = strtol(outbuf, &endptr, 10);
    if(outbuf == endptr || *endptr != '\0') {
        error("Invalid pid: %s", outbuf);
        return -1;
    }

    char* file = cut+1;
    int ret = 0;
    int fd = -1;
    if (pid > 0) {
        if ((fd = open(file, O_RDWR)) < 0)
            syserror("Cannot open file %s", file);
    }

    if (send_pid_fd(conn, pid, fd) < 0) {
        syserror("FD-passing failed.");
        ret = -1;
    }

    close(fd);
    return ret;
}
Ejemplo n.º 2
0
Archivo: r.c Proyecto: wpwrak/subosm
static void triangulate(void)
{
	FILE *files[2];
	unsigned i, faces;
	unsigned a, b, c;
	int n;

	/* start qdelaunay */

	if (popen2("qdelaunay Qt i", files) < 0) {
		perror("popen2");
		exit(1);
	}

	/* send list of points */

	if (fprintf(files[1], "2\n%u\n", n_nodes) < 0) {
		perror("fprintf");
		exit(1);
	}
	for (i = 0; i != n_nodes; i++) {
		if (fprintf(files[1], "%d %d\n", node[i].x, node[i].y) < 0) {
			perror("fprintf");
			exit(1);
		}
	}
	if (fclose(files[1]) < 0) {
		perror("fclose");
		exit(1);
	}

	/* read list of faces (triangles) */

	n = fscanf(files[0], "%u", &faces);
	if (n < 0) {
		perror("fscanf");
		exit(1);
	}
	if (n != 1) {
		fprintf(stderr, "bad result (length)\n");
		exit(1);
	}
	for (i = 0; i != faces; i++) {
		n = fscanf(files[0], "%u %u %u", &a, &b, &c);
		if (n < 0) {
			perror("fscanf");
			exit(1);
		}
		if (n != 3) {
			fprintf(stderr, "bad result (face)\n");
			exit(1);
		}
		add_face(a, b, c);
	}
	fclose(files[0]);
}
int main(){

	FILE *fp;
	char buf[BUFSIZ];

	fp=popen2("ls","r");
	while(fgets(buf,BUFSIZ,fp)!=NULL)
		fputs(buf,stdout);


}
int main()
{
    FILE *fp;
    FILE *popen2(const char *command, const char *mode);
    char buf[BUFSIZ];

    fp = popen2("ls", "r");

    while(fgets(buf, BUFSIZ, fp) != NULL)
        fputs(buf, stdout);

    return 0;
}
Ejemplo n.º 5
0
int main(void) {
    char buf[1000];
    struct popen2 kid;
    popen2("tr a-z A-Z", &kid);
    write(kid.to_child, "testing\n", 8);
    close(kid.to_child);
    memset(buf, 0, 1000);
    read(kid.from_child, buf, 1000);
    printf("kill(%d, 0) -> %d\n", kid.child_pid, kill(kid.child_pid, 0)); 
    printf("from child: %s", buf); 
    printf("waitpid() -> %d\n", waitpid(kid.child_pid, NULL, 0));
    printf("kill(%d, 0) -> %d\n", kid.child_pid, kill(kid.child_pid, 0)); 
    return 0;
}
Ejemplo n.º 6
0
/*
** SSH initialization of the transport layer
*/
int transport_ssh_open(UrlData *pUrlData){
  /* For SSH we need to create and run SSH fossil http 
  ** to talk to the remote machine.
  */
  const char *zSsh;  /* The base SSH command */
  Blob zCmd;         /* The SSH command */
  char *zHost;       /* The host name to contact */
  int n;             /* Size of prefix string */

  socket_ssh_resolve_addr(pUrlData);
  zSsh = db_get("ssh-command", zDefaultSshCmd);
  blob_init(&zCmd, zSsh, -1);
  if( pUrlData->port!=pUrlData->dfltPort && pUrlData->port ){
#ifdef __MINGW32__
    blob_appendf(&zCmd, " -P %d", pUrlData->port);
#else
    blob_appendf(&zCmd, " -p %d", pUrlData->port);
#endif
  }
  if( g.fSshTrace ){
    fossil_force_newline();
    fossil_print("%s", blob_str(&zCmd));  /* Show the base of the SSH command */
  }
  if( pUrlData->user && pUrlData->user[0] ){
    zHost = mprintf("%s@%s", pUrlData->user, pUrlData->name);
  }else{
    zHost = mprintf("%s", pUrlData->name);
  }
  n = blob_size(&zCmd);
  blob_append(&zCmd, " ", 1);
  shell_escape(&zCmd, zHost);
  blob_append(&zCmd, " ", 1);
  shell_escape(&zCmd, mprintf("%s", pUrlData->fossil));
  blob_append(&zCmd, " test-http", 10);
  if( pUrlData->path && pUrlData->path[0] ){
    blob_append(&zCmd, " ", 1);
    shell_escape(&zCmd, mprintf("%s", pUrlData->path));
  }
  if( g.fSshTrace ){
    fossil_print("%s\n", blob_str(&zCmd)+n);  /* Show tail of SSH command */
  }
  free(zHost);
  popen2(blob_str(&zCmd), &sshIn, &sshOut, &sshPid);
  if( sshPid==0 ){
    socket_set_errmsg("cannot start ssh tunnel using [%b]", &zCmd);
  }
  blob_reset(&zCmd);
  return sshPid==0;
}
Ejemplo n.º 7
0
void gPhotoCam::start(){
	startThread(true, false);   // blocking, verbose
	if (popen2("/opt/local/bin/gphoto2 --shell", &infp, &outfp) <= 0)
	{
		printf("Unable to exec gphoto2\n");
		exit(1);
	}
	memset (buf, 0x0, 10000);	
	write(infp, ("lcd " + ofToDataPath("images/scaler") + "\n").c_str(), ("lcd " + ofToDataPath("images") + "\n").length());
	write(infp, ("capture-image\n"), 14);
	ofSleepMillis(30*100);
	read(outfp, buf, 10000);
	cout<<buf<<endl;
	state = READY;

}
Ejemplo n.º 8
0
void RemoteConsole::reset()
{
	// TODO: check for errors!
	int infp, outfp;
	std::string command_line(_command);
	command_line += " --ccons-use-std-io --ccons-serialized-output";
	if (_DebugMode)
		command_line += " --ccons-debug";
	popen2(command_line.c_str(), &infp, &outfp);
	_ostream = fdopen(infp, "w");
	setlinebuf(_ostream);
	_istream = fdopen(outfp, "r");
	setlinebuf(_istream);
	_prompt = ">>> ";
	_input = "";
}
Ejemplo n.º 9
0
std::string execute_cmd_with_abort(ParallelController* controller, int step,
		std::string command) {
	int status;
	int fd;
	pollfd pollfd[1];
	pid_t pid = popen2(command.c_str(), NULL, &fd);

	int flags;
	flags = fcntl(fd, F_GETFL, 0);
	flags |= O_NONBLOCK | FASYNC;
	fcntl(fd, F_SETFL, flags);

	pollfd[0].fd = fd;
	pollfd[0].events = POLL_IN;

	char buffer[128];
	std::string result = "";
	while (1) {

		poll(pollfd, 1, 1000);

		if (pollfd[0].revents & POLLHUP) //EOF
			break;
		else if (pollfd[0].revents & POLLIN) { //read
			while (read(fd, buffer, 128) > 0)
				result += buffer;
		}

		if (!controller->isStepNeeded(step)) {
			std::cout << ("Abort Step: " + std::to_string(step)) << std::endl;

			kill(-pid, SIGKILL);

			while ((waitpid(-1, &status, WNOHANG)) > 0)
				sleep(1);

			break;
		}
	}

	close(fd);

	return result;
}
Ejemplo n.º 10
0
int main(void)
{
  FILE *fp[2];
  char buf[1024], *ret;

  popen2("sort", fp);
  fprintf(fp[1], "orange\n");
  fprintf(fp[1], "apple\n");
  fprintf(fp[1], "banana\n");
  fclose(fp[1]);

  while (1) {
    ret = fgets(buf, sizeof(buf), fp[0]);
    if (ret == NULL) break;
    printf("%s", buf);
  }

  return 0;
}
Ejemplo n.º 11
0
/* FIXME: Maybe errors here should not be fatal... */
void change_resolution(const struct resolution* rin) {
    /* Setup parameters and run command */
    char arg1[32], arg2[32];
    int c;
    c = snprintf(arg1, sizeof(arg1), "%d", rin->width);
    trueorabort(c > 0, "snprintf");
    c = snprintf(arg2, sizeof(arg2), "%d", rin->height);
    trueorabort(c > 0, "snprintf");

    char* cmd = "setres";
    char* args[] = {cmd, arg1, arg2, NULL};
    char buffer[256];
    log(2, "Running %s %s %s", cmd, arg1, arg2);
    c = popen2(cmd, args, NULL, 0, buffer, sizeof(buffer));
    trueorabort(c > 0, "popen2");

    /* Parse output */
    buffer[c < sizeof(buffer) ? c : (sizeof(buffer)-1)] = 0;
    log(2, "Result: %s", buffer);
    char* cut = strchr(buffer, '_');
    if (cut) *cut = 0;
    cut = strchr(buffer, 'x');
    trueorabort(cut, "Invalid answer: %s", buffer);
    *cut = 0;

    char* endptr;
    long nwidth = strtol(buffer, &endptr, 10);
    trueorabort(buffer != endptr && *endptr == '\0',
                "Invalid width: '%s'", buffer);
    long nheight = strtol(cut+1, &endptr, 10);
    trueorabort(cut+1 != endptr && (*endptr == '\0' || *endptr == '\n'),
                "Invalid height: '%s'", cut+1);
    log(1, "New resolution %ld x %ld", nwidth, nheight);

    char reply_raw[FRAMEMAXHEADERSIZE + sizeof(struct resolution)];
    struct resolution* r = (struct resolution*)(reply_raw + FRAMEMAXHEADERSIZE);
    r->type = 'R';
    r->width = nwidth;
    r->height = nheight;
    socket_client_write_frame(reply_raw, sizeof(*r), WS_OPCODE_BINARY, 1);
}
Ejemplo n.º 12
0
int run_mapping(char *physical, char *logical, int len, mapping_defn *map) {
	FILE *in, *out;
	int i, status;
	pid_t pid;

	
#line 2898 "ifupdown.nw"
pid = popen2(&in, &out, map->script, physical, NULL);
if (pid == 0) {
	return 0;
}
#line 2845 "ifupdown.nw"
	
#line 2857 "ifupdown.nw"
for (i = 0; i < map->n_mappings; i++) {
	fprintf(in, "%s\n", map->mapping[i]);
}
fclose(in);
#line 2846 "ifupdown.nw"
	
#line 2864 "ifupdown.nw"
waitpid(pid, &status, 0);
#line 2847 "ifupdown.nw"
	
#line 2868 "ifupdown.nw"
if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
	if (fgets(logical, len, out)) {
		char *pch = logical + strlen(logical) - 1;
		while (pch >= logical && isspace(*pch)) 
			*(pch--) = '\0';
	}
}
fclose(out);	

#line 2849 "ifupdown.nw"
	return 1;
}
Ejemplo n.º 13
0
int main(int argc, char **argv)
{
	FILE *pin, *pout;
	char buf[256];
	char *args[] = { "bc", NULL };
	int pid, status;

	if((pid = popen2(args, &pin, &pout)) == -1)
		return(1);

	fprintf(pin, "2+2\n");
	fclose(pin);

	while(!feof(pout))
	{
		fgets(buf, 255, pout);
		printf("%s", buf);
		buf[0] = '\0';
	}
	fclose(pout);
	waitpid(pid, &status, 0);

	return(0);
}
Ejemplo n.º 14
0
int main(int argc, char* argv[]) {
	int nbytes;
	int status;
	unsigned int previous, ch;
	unsigned int temp_extruder = 0, temp_bed = 0;
	// rename TODO
	unsigned int key_mask=0;

	unsigned int jog_distance = DEFAULT_JOG_DISTANCE;
	unsigned int jog_speed = DEFAULT_JOG_SPEED;
	unsigned int temp_target = DEFAULT_TEMP_TARGET;
	unsigned int feedrate = DEFAULT_FEEDRATE;
	// Explain?
	float delta_e = 0.001666669999999968 * (float)feedrate;;

	// TODO heater on/off keys

	// TODO consider a struct to hold state, then we can declare it once
	// and pass a single pointer around to various functions!!!

	// TODO float? need to?
	int posX=0, posY=0, posZ=0;
	float posE=0.0;
	int extruding=0;

	time_t last_temp = time(NULL);
	time_t last_extrude = time(NULL);

	int pipe_gcode = 0, pipe_feedback = 0;
	//stream_gcode = fdopen(pipe_gcode[1], "w");

	FILE *stream_gcode = NULL, *stream_feedback = NULL;

	// User options
	char *serial_port = NULL;

	char *cmd = NULL;	// Command string to execute austerus-core

	//size_t line_feedback_len = PIPE_LINE_BUFFER_LEN;
	//char *line_feedback = NULL;
	char line_feedback[LINE_FEEDBACK_LEN];

	// Allocate inital size of input line buffer
	//pipe_buffer = (char *) malloc (pipe_buffer_len + 1);

	// Read command line options
	int option_index = 0, opt=0;
	static struct option loptions[] = {
		{"help", no_argument, 0, 'h'},
		{"port", required_argument, 0, 'p'},
		{"baud", required_argument, 0, 'b'},
		{"verbose", no_argument, 0, 'v'}
	};

	// Generate the command line for austerus-core
	asprintf(&cmd, "/usr/bin/env AG_ACKCOUNT=1 PATH=$PWD:$PATH");

	while(opt >= 0) {
		opt = getopt_long(argc, argv, "hp:b:v", loptions,
			&option_index);

		switch (opt) {
			case 'h':
				usage();
				return EXIT_SUCCESS;
			case 'p':
				serial_port = optarg;
				asprintf(&cmd, "%s AG_SERIALPORT=%s", cmd,
					optarg);
				break;
			case 'b':
				asprintf(&cmd, "%s AG_BAUDRATE=%ld", cmd,
					strtol(optarg, NULL, 10));
				break;
			case 'v':
				asprintf(&cmd, "%s AG_VERBOSE=1", cmd);
				break;
		}
	}

	if (!serial_port & !getenv("AG_SERIALPORT")) {
		fprintf(stderr, "A serial port must be specified\n");
		return EXIT_FAILURE;
	}

	asprintf(&cmd, "%s austerus-core", cmd);

	// Open the gcode output stream to austerus-core
	popen2(cmd, &pipe_gcode, &pipe_feedback);
	free(cmd);

	// Make feedback pipe non-blocking
	fcntl(pipe_feedback, F_SETFL, O_NONBLOCK);

	stream_gcode = fdopen(pipe_gcode, "w");
	stream_feedback = fdopen(pipe_feedback, "r");

	if (!stream_gcode) {
		fprintf(stderr, "unable to open output stream\n");
		return EXIT_FAILURE;
	}

	if (!stream_feedback) {
		fprintf(stderr, "unable to open feedback stream\n");
		return EXIT_FAILURE;
	}

	// Start curses mode
	initscr();
	// Line buffering disabled
	raw();
	//  We get F1, F2 etc
	keypad(stdscr, TRUE);
	// Don't echo() while we do getch
	noecho();
	// Hide cursor
	curs_set(0);

	// Timeout so we can run extruder and check for feedback
	timeout(CURSES_TIMEOUT);

	// draw initial screen
	mvprintw(0, 0, "austerusG %s", VERSION);
	mvprintw(0, 30, "- +");

	print_fkeys(PANEL_POS_NUMBERS_X, PANEL_POS_NUMBERS_Y);
	print_extruder_keys(key_mask);
	print_keys(PANEL_POS_KEYS_X, PANEL_POS_KEYS_Y, key_mask);

	print_temperature(temp_extruder, temp_target);
	print_feedrate(feedrate);
	print_jog_distance(jog_distance);
	print_jog_speed(jog_speed);
	print_fan(0);

	mvprintw(LINES - 1, 0, "Status: Idle");

	refresh();

	// start of print reset
	fprintf(stream_gcode, "M110\n");
	// set absolute positioning
	fprintf(stream_gcode, "G90\n");
	// set to mm
	fprintf(stream_gcode, "G21\n");
	// reset coordinates to zero
	fprintf(stream_gcode, "G92 X0 Y0 Z0 E0\n");
	fflush(stream_gcode);

	while (1) {
		// Wait for user input
		ch = getch();

		// Handle any two key sequences
		switch (previous) {
			case KEY_HOME:
				if (home_axis(stream_gcode, ch)) {
					key_mask = key_mask & !BIT_H;
					print_keys(PANEL_POS_KEYS_X, PANEL_POS_KEYS_Y, key_mask);
				}
				break;
			case KEY_END:
				if (end_axis(stream_gcode, ch)) {
					key_mask = key_mask & !BIT_END;
					print_keys(PANEL_POS_KEYS_X, PANEL_POS_KEYS_Y, key_mask);
				}
				break;
		}

		// Handle single key press
		switch (ch) {
			case '1':
				// Decrease target temperature
				if (temp_target > 0) {
					temp_target = temp_target - 1;

					fprintf(stream_gcode, "M104 S%d\n", temp_target);
					fflush(stream_gcode);

					print_temperature(temp_extruder, temp_target);
				}
				break;

			case '2':
				// Increase target temperature
				temp_target = temp_target + 1;

				fprintf(stream_gcode, "M104 S%d\n", temp_target);
				fflush(stream_gcode);

				print_temperature(temp_extruder, temp_target);
				break;

			case '3':
				// Decrease feedrate
				if (feedrate >= 1) {
					feedrate -= 1;
					delta_e = 0.001666669999999968 * (float)feedrate;
					print_feedrate(feedrate);
				}
				break;

			case '4':
				// Increase feedrate
				feedrate += 1;
				delta_e = 0.001666669999999968 * (float)feedrate;
				print_feedrate(feedrate);
				break;

			case '5':
				// Decrease jog distance
				if (jog_distance > 10) {
					fprintf(stream_gcode, "M104 %d\n", temp_target);
					fflush(stream_gcode);
					jog_distance = jog_distance - 10;
					print_jog_distance(jog_distance);
				}
				break;

			case '6':
				// Increase jog distance
				jog_distance = jog_distance + 10;
				print_jog_distance(jog_distance);
				break;

			case '7':
				// Decrease jog speed
				if (jog_speed > 10) {
					jog_speed = jog_speed - 100;
					print_jog_speed(jog_speed);
				}
				break;

			case '8':
				// Increase jog speed
				jog_speed = jog_speed + 100;
				print_jog_speed(jog_speed);
				break;

			case 'e':
				extruding = 1;
				key_mask = (key_mask | BIT_E) & ~(BIT_D | BIT_R);
				print_extruder_keys(key_mask);
				break;

			case 'd':
				extruding = 0;
				key_mask = (key_mask | BIT_D) & ~(BIT_E | BIT_R);
				print_extruder_keys(key_mask);
				break;

			case 'r':
				extruding = -1;
				key_mask = (key_mask | BIT_R) & ~(BIT_D | BIT_E);
				print_extruder_keys(key_mask);
				break;

			case KEY_LEFT:
				// Jog X axis minus
				// TODO merits of G0 or G1 moves?
				posX -= jog_distance;
				fprintf(
					stream_gcode, "G1 X%d Y%d Z%d F%d\n",
					posX, posY, posZ, jog_speed
				);
				fflush(stream_gcode);
				key_mask = key_mask | BIT_MX;
				print_keys(PANEL_POS_KEYS_X, PANEL_POS_KEYS_Y, key_mask);
				break;

			case KEY_RIGHT:
				// Jog X axis plus
				posX += jog_distance;
				fprintf(
					stream_gcode, "G1 X%d Y%d Z%d F%d\n",
					posX, posY, posZ, jog_speed
				);
				fflush(stream_gcode);
				key_mask = key_mask | BIT_PX;
				print_keys(PANEL_POS_KEYS_X, PANEL_POS_KEYS_Y, key_mask);
				break;

			case KEY_UP:
				// Jog Y axis plus
				posY += jog_distance;
				fprintf(
					stream_gcode, "G1 X%d Y%d Z%d F%d\n",
					posX, posY, posZ, jog_speed
				);
				fflush(stream_gcode);
				key_mask = key_mask | BIT_PY;
				print_keys(PANEL_POS_KEYS_X, PANEL_POS_KEYS_Y, key_mask);
				break;

			case KEY_DOWN:
				// Jog Y axis minus
				posY -= jog_distance;
				fprintf(
					stream_gcode, "G1 X%d Y%d Z%d F%d\n",
					posX, posY, posZ, jog_speed
				);
				fflush(stream_gcode);
				key_mask = key_mask | BIT_MY;
				print_keys(PANEL_POS_KEYS_X, PANEL_POS_KEYS_Y, key_mask);
				break;

			case KEY_PPAGE:
				// Jog Z axis up
				posZ += jog_distance;
				fprintf(
					stream_gcode, "G1 X%d Y%d Z%d F%d\n",
					posX, posY, posZ, jog_speed
				);
				fflush(stream_gcode);
				key_mask = key_mask | BIT_PZ;
				print_keys(PANEL_POS_KEYS_X, PANEL_POS_KEYS_Y, key_mask);
				break;

			case KEY_NPAGE:
				// Jog Z axis down
				posZ -= jog_distance;
				fprintf(
					stream_gcode, "G1 X%d Y%d Z%d F%d\n",
					posX, posY, posZ, jog_speed
				);
				fflush(stream_gcode);
				key_mask = key_mask | BIT_MZ;
				print_keys(PANEL_POS_KEYS_X, PANEL_POS_KEYS_Y, key_mask);
				break;

			case KEY_HOME:
				// Start of two key move to home command
				key_mask = key_mask | BIT_H;
				print_keys(PANEL_POS_KEYS_X, PANEL_POS_KEYS_Y, key_mask);
				previous = ch;
				break;

			case KEY_END:
				// Start of two key move to end command
				key_mask = key_mask | BIT_END;
				print_keys(PANEL_POS_KEYS_X, PANEL_POS_KEYS_Y, key_mask);
				previous = ch;
				break;

			case 'f':
			case 'F':
				// Fan on
				fprintf(stream_gcode, "M106\n");
				fflush(stream_gcode);
				print_fan(1);

				break;

			case 'g':
			case 'G':
				// Fan off
				fprintf(stream_gcode, "M107\n");
				fflush(stream_gcode);
				print_fan(0);

				break;

			case 'q':
			case KEY_ESC:
				// Shutdown printer
				fprintf(stream_gcode, "M112\n");
				// Exit core
				fprintf(stream_gcode, "#ag:exit\n\n");
				fflush(stream_gcode);

				endwin();

				pclose(stream_gcode);
				pclose(stream_feedback);

				close(pipe_gcode);
				close(pipe_feedback);

				//if (line_feedback)
				//	free(line_feedback);

				wait(&status);
				printf("core exit = %d\n", status);

				return EXIT_SUCCESS;
		}

		// TODO check core alive?

		if (time(NULL) - last_temp > TEMP_PERIOD)
		{
			do {
				nbytes = nonblock_getline(line_feedback, stream_feedback);
				
				//nbytes = getline(&line_feedback, &line_feedback_len, stream_feedback);

				//fprintf(stream_gcode, "NB %d %s\n", nbytes);
				//fflush(stream_gcode);

				if (nbytes > 0) {

					mvprintw(LINES - 3, 0, "nb %d", nbytes);
					sscanf(line_feedback, "ok T:%d B:%d", &temp_extruder, &temp_bed);

					//
					if (nbytes > 66) {
						line_feedback[63] = '.';
						line_feedback[64] = '.';
						line_feedback[65] = '.';
						line_feedback[66] = '\0';
					}

					mvprintw(LINES - 2, 0, "Response: %s", line_feedback);
					print_temperature(temp_extruder, temp_target);
				}

			} while (nbytes != -1);


			last_temp = time(NULL);

			fprintf(stream_gcode, "M105\n");
			fflush(stream_gcode);

			// tODO this needs it's own clock too!
			// tODO arrow keys etc
			if (key_mask |  BIT_D) {
				key_mask = key_mask & ~BIT_D;
				print_extruder_keys(key_mask);
			}

			// We can make one mask #def? from all keys we want cleared
			// and use it for check andf clear!


		}


		if (time(NULL) - last_extrude > EXTRUDE_PERIOD)
		{
			last_extrude = time(NULL);

			// This needs to be on an indepentent time check so it can be controlled!! TODO
			if (extruding > 0) {
				posE += delta_e;
				fprintf(stream_gcode, "G1 E%.2f F%d\n", posE, feedrate);
				fflush(stream_gcode);
			} else if (extruding < 0) {
				posE -= delta_e;
				fprintf(stream_gcode, "G1 E%.2f F%d\n", posE, feedrate);
				fflush(stream_gcode);
			}

			// tODO arrow keys etc
			if (key_mask |  BIT_D) {
				key_mask = key_mask & ~BIT_D;
				print_extruder_keys(key_mask);
			}

			// We can make one mask #def? from all keys we want cleared
			// and use it for check andf clear!
		}
		refresh();


		// TODO check core is still alive

	}
}
Ejemplo n.º 15
0
/* Finds NaCl/Chromium shm memory using external handler.
 * Reply must be in the form PID:file */
struct cache_entry* find_shm(uint64_t paddr, uint64_t sig, size_t length) {
    struct cache_entry* entry = NULL;

    /* Find entry in cache */
    if (cache[0].paddr == paddr) {
        entry = &cache[0];
    } else if (cache[1].paddr == paddr) {
        entry = &cache[1];
    } else {
        /* Not found: erase an existing entry. */
        entry = &cache[next_entry];
        next_entry = (next_entry + 1) % 2;
        close_mmap(entry);
    }

    int try;
    for (try = 0; try < 2; try++) {
        /* Check signature */
        if (entry->map) {
            if (*((uint64_t*)entry->map) == sig)
                return entry;

            log(1, "Invalid signature, fetching new shm!");
            close_mmap(entry);
        }

        /* Setup parameters and run command */
        char arg1[32], arg2[32];
        int c;

        c = snprintf(arg1, sizeof(arg1), "%08lx", (long)paddr & 0xffffffff);
        trueorabort(c > 0, "snprintf");
        int i, p = 0;
        for (i = 0; i < 8; i++) {
            c = snprintf(arg2 + p, sizeof(arg2) - p, "%02x",
                         ((uint8_t*)&sig)[i]);
            trueorabort(c > 0, "snprintf");
            p += c;
        }

        char* cmd = "croutonfindnacl";
        char* args[] = {cmd, arg1, arg2, NULL};
        char buffer[256];
        log(2, "Running %s %s %s", cmd, arg1, arg2);
        c = popen2(cmd, args, NULL, 0, buffer, sizeof(buffer));
        if (c <= 0) {
            error("Error running helper.");
            return NULL;
        }
        buffer[c < sizeof(buffer) ? c : (sizeof(buffer)-1)] = 0;
        log(2, "Result: %s", buffer);

        /* Parse PID:file output */
        char* cut = strchr(buffer, ':');
        if (!cut) {
            error("No ':' in helper reply: %s.", cut);
            return NULL;
        }
        *cut = 0;

        char* endptr;
        long pid = strtol(buffer, &endptr, 10);
        if(buffer == endptr || *endptr != '\0') {
            error("Invalid pid: %s", buffer);
            return NULL;
        }
        char* file = cut+1;
        log(2, "PID:%ld, FILE:%s", pid, file);

        entry->paddr = paddr;
        entry->fd = open(file, O_RDWR);
        if (entry->fd < 0) {
            error("Cannot open file %s\n", file);
            return NULL;
        }

        entry->length = length;
        entry->map = mmap(NULL, length, PROT_READ|PROT_WRITE, MAP_SHARED,
                          entry->fd, 0);
        if (!entry->map) {
            error("Cannot mmap %s\n", file);
            close(entry->fd);
            return NULL;
        }

        log(2, "mmap ok %p %zu %d", entry->map, entry->length, entry->fd);
    }

    error("Cannot find shm.");
    return NULL;
}

/* WebSocket functions */

XImage* img = NULL;
XShmSegmentInfo shminfo;

/* Writes framebuffer image to websocket/shm */
int write_image(const struct screen* screen) {
    char reply_raw[FRAMEMAXHEADERSIZE + sizeof(struct screen_reply)];
    struct screen_reply* reply =
        (struct screen_reply*)(reply_raw + FRAMEMAXHEADERSIZE);
    int refresh = 0;

    memset(reply_raw, 0, sizeof(reply_raw));

    reply->type = 'S';
    reply->width = screen->width;
    reply->height = screen->height;

    /* Allocate XShmImage */
    if (!img || img->width != screen->width || img->height != screen->height) {
        if (img) {
            XDestroyImage(img);
            shmdt(shminfo.shmaddr);
            shmctl(shminfo.shmid, IPC_RMID, 0);
        }

        /* FIXME: Some error checking should happen here... */
        img = XShmCreateImage(dpy, DefaultVisual(dpy, 0), 24,
                              ZPixmap, NULL, &shminfo,
                              screen->width, screen->height);
        trueorabort(img, "XShmCreateImage");
        shminfo.shmid = shmget(IPC_PRIVATE, img->bytes_per_line*img->height,
                               IPC_CREAT|0777);
        trueorabort(shminfo.shmid != -1, "shmget");
        shminfo.shmaddr = img->data = shmat(shminfo.shmid, 0, 0);
        trueorabort(shminfo.shmaddr != (void*)-1, "shmat");
        shminfo.readOnly = False;
        int ret = XShmAttach(dpy, &shminfo);
        trueorabort(ret, "XShmAttach");
        /* Force refresh */
        refresh = 1;
    }

    if (screen->refresh) {
        log(1, "Force refresh from client.");
        /* refresh forced by the client */
        refresh = 1;
    }

    XEvent ev;
    /* Register damage on new windows */
    while (XCheckTypedEvent(dpy, MapNotify, &ev)) {
        register_damage(dpy, ev.xcreatewindow.window);
        refresh = 1;
    }

    /* Check for damage */
    while (XCheckTypedEvent(dpy, damageEvent + XDamageNotify, &ev)) {
        refresh = 1;
    }

    /* Check for cursor events */
    reply->cursor_updated = 0;
    while (XCheckTypedEvent(dpy, fixesEvent + XFixesCursorNotify, &ev)) {
        XFixesCursorNotifyEvent* curev = (XFixesCursorNotifyEvent*)&ev;
        if (verbose >= 2) {
            char* name = XGetAtomName(dpy, curev->cursor_name);
            log(2, "cursor! %ld %s", curev->cursor_serial, name);
            XFree(name);
        }
        reply->cursor_updated = 1;
        reply->cursor_serial = curev->cursor_serial;
    }

    /* No update */
    if (!refresh) {
        reply->shm = 0;
        reply->updated = 0;
        socket_client_write_frame(reply_raw, sizeof(*reply),
                                  WS_OPCODE_BINARY, 1);
        return 0;
    }

    /* Get new image from framebuffer */
    XShmGetImage(dpy, DefaultRootWindow(dpy), img, 0, 0, AllPlanes);

    int size = img->bytes_per_line * img->height;

    trueorabort(size == screen->width*screen->height*4,
                "Invalid screen byte count");

    trueorabort(screen->shm, "Non-SHM rendering is not supported");

    struct cache_entry* entry = find_shm(screen->paddr, screen->sig, size);

    reply->shm = 1;
    reply->updated = 1;
    reply->shmfailed = 0;

    if (entry && entry->map) {
        if (size == entry->length) {
            memcpy(entry->map, img->data, size);
            msync(entry->map, size, MS_SYNC);
        } else {
            /* This should never happen (it means the client passed an
             * outdated buffer to us). */
            error("Invalid shm entry length (client bug!).");
            reply->shmfailed = 1;
        }
    } else {
        /* Keep the flow going, even if we cannot find the shm. Next time
         * the NaCl client reallocates the buffer, we are likely to be able
         * to find it. */
        error("Cannot find shm, moving on...");
        reply->shmfailed = 1;
    }

    /* Confirm write is done */
    socket_client_write_frame(reply_raw, sizeof(*reply),
                              WS_OPCODE_BINARY, 1);

    return 0;
}

/* Writes cursor image to websocket */
int write_cursor() {
    XFixesCursorImage *img = XFixesGetCursorImage(dpy);
    if (!img) {
        error("XFixesGetCursorImage returned NULL");
        return -1;
    }
    int size = img->width*img->height;
    const int replylength = sizeof(struct cursor_reply) + size*sizeof(uint32_t);
    char reply_raw[FRAMEMAXHEADERSIZE + replylength];
    struct cursor_reply* reply =
        (struct cursor_reply*)(reply_raw + FRAMEMAXHEADERSIZE);

    memset(reply_raw, 0, sizeof(*reply_raw));

    reply->type = 'P';
    reply->width = img->width;
    reply->height = img->height;
    reply->xhot = img->xhot;
    reply->yhot = img->yhot;
    reply->cursor_serial = img->cursor_serial;
    /* This casts long[] to uint32_t[] */
    int i;
    for (i = 0; i < size; i++)
        reply->pixels[i] = img->pixels[i];

    socket_client_write_frame(reply_raw, replylength, WS_OPCODE_BINARY, 1);
    XFree(img);

    return 0;
}
Ejemplo n.º 16
0
/*
 * basil_request - issue BASIL request and parse response
 * @bp:	method-dependent parse data to guide the parsing process
 *
 * Returns 0 if ok, a negative %basil_error otherwise.
 */
int basil_request(struct basil_parse_data *bp)
{
	int to_child, from_child;
	int ec, rc = -BE_UNKNOWN;
	FILE *apbasil;
	pid_t pid;

	if (log_sel == -1)
		_init_log_config();

	if (!cray_conf->apbasil) {
		error("No alps client defined");
		return 0;
	}
	assert(bp->version < BV_MAX);
	assert(bp->method > BM_none && bp->method < BM_MAX);

	pid = popen2(cray_conf->apbasil, &to_child, &from_child, true);
	if (pid < 0)
		fatal("popen2(\"%s\", ...)", cray_conf->apbasil);

	/* write out request */
	apbasil = fdopen(to_child, "w");
	if (apbasil == NULL)
		fatal("fdopen(): %s", strerror(errno));
	setlinebuf(apbasil);

	_write_xml(apbasil, "<?xml version=\"1.0\"?>\n"
		   "<BasilRequest protocol=\"%s\" method=\"%s\" ",
		   bv_names[bp->version], bm_names[bp->method]);

	switch (bp->method) {
	case BM_engine:
		_write_xml(apbasil, "type=\"ENGINE\"/>");
		break;
	case BM_inventory:
		_write_xml(apbasil, "type=\"INVENTORY\"/>");
		break;
	case BM_reserve:
		_write_xml(apbasil, ">\n");
		_rsvn_write_reserve_xml(apbasil, bp->mdata.res);
		break;
	case BM_confirm:
		if (bp->version == BV_1_0 && *bp->mdata.res->batch_id != '\0')
			_write_xml(apbasil, "job_name=\"%s\" ",
				   bp->mdata.res->batch_id);
		_write_xml(apbasil, "reservation_id=\"%u\" %s=\"%llu\"/>\n",
			   bp->mdata.res->rsvn_id,
			   bp->version >= BV_3_1 ? "pagg_id" : "admin_cookie",
			   (unsigned long long)bp->mdata.res->pagg_id);
		break;
	case BM_release:
		_write_xml(apbasil, "reservation_id=\"%u\"/>\n",
			   bp->mdata.res->rsvn_id);
		break;
	case BM_switch:
	{
		char *suspend = bp->mdata.res->suspended ? "OUT" : "IN";
		_write_xml(apbasil, ">\n");
		_write_xml(apbasil, " <ReservationArray>\n");
		_write_xml(apbasil, "  <Reservation reservation_id=\"%u\" "
			   "action=\"%s\"/>\n",
			   bp->mdata.res->rsvn_id, suspend);
		_write_xml(apbasil, " </ReservationArray>\n");
		_write_xml(apbasil, "</BasilRequest>\n");
	}
		break;
	default: /* ignore BM_none, BM_MAX, and BM_UNKNOWN covered above */
		break;
	}

	if (fclose(apbasil) < 0)	/* also closes to_child */
		error("fclose(apbasil): %s", strerror(errno));

	rc = parse_basil(bp, from_child);
	ec = wait_for_child(pid);
	if (ec) {
		error("%s child process for BASIL %s method exited with %d",
		      cray_conf->apbasil, bm_names[bp->method], ec);
	}

	return rc;
}
Ejemplo n.º 17
0
bool Activator::doScript(const string &strServerId,
                         const string &strScript,
                         string &strResult,
                         map <string,string> &mResult,
                         const string &sEndMark)
{
    LOG->info()<<"doScript "<<strScript<<" begin----"<<endl;

    if(!TC_File::isFileExistEx(strScript))
    {
        strResult = "The script file: " + strScript+" is not exist";
        return false;
    }
    string sRealEndMark = sEndMark;
    if(sRealEndMark == "")
    {
        sRealEndMark = "end-"+TC_File::extractFileName(strScript);
    }
    LOG->info()<<"doScript "<<strScript<<" endMark----"<<sRealEndMark<<endl;

    if(!TC_File::canExecutable(strScript))
    {
        TC_File::setExecutable(strScript,true);
    }
	string sRedirect ="";
	if(_sRedirectPath != "")
	{
		sRedirect =  " 2>&1 >>" +_sRedirectPath;
	}

    string sCmd = strScript + sRedirect + " " + strServerId + " &";
    FILE  *fp =  popen2(sCmd.c_str(),"r");
    if(fp == NULL)
    {
        strResult = "popen script file: "+ strScript +" error ";
        return false;
    }

    int flags;
    if((flags=fcntl(fileno(fp), F_GETFL, 0)) < 0)
    {
        strResult = "fcntl get error.script file: "+ strScript;
		fflush(fp);
		pclose2(fp);
        return false;
    }
    flags |= O_NONBLOCK;
    if( fcntl(fileno(fp), F_SETFL, flags) < 0 )
    {
        strResult = "fcntl set error.script file: "+ strScript;
		fflush(fp);
		pclose2(fp);

        return false;
    }
    //strResult = "";

    char c;
    time_t tNow = TC_TimeProvider::getInstance()->getNow();
    while(TC_TimeProvider::getInstance()->getNow()- 2 < tNow)
    {
        usleep(200000);
        while((c=fgetc(fp))!=EOF )
        {
            strResult += c;
        }
        if(sRealEndMark == "" || strResult.find(sRealEndMark) != string::npos)
        {
            LOG->info()<<"doScript "<<sCmd<<"|sEndMark "<<sRealEndMark <<" finded|"<<strResult<<endl;
            break;
        }
    }
    strResult = TC_Common::replace(strResult,"\n","\r\n");
    LOG->info()<<"doScript "<<sCmd<<" result:"<<strResult<<endl;
    fflush(fp);
    pclose2(fp);
    mResult = parseScriptResult(strServerId,strResult);
    return true;
}
Ejemplo n.º 18
0
/* Handle unrequested packet from extension.
 * Returns 0 on success. On error, returns -1 and closes websocket connection.
 */
static int socket_client_handle_unrequested(const char* buffer,
                                            const int length) {
    /* Process the client request. */
    switch (buffer[0]) {
        case 'C': {  /* Send a command to croutoncycle */
            char reply[BUFFERSIZE];
            int replylength = 1;
            reply[FRAMEMAXHEADERSIZE] = 'C';

            char* cmd = "croutoncycle";
            char param[length];
            memcpy(param, buffer+1, length-1);
            param[length-1] = '\0';
            char* args[] = { cmd, param, NULL };

            log(2, "Received croutoncycle command (%s)", param);

            /* We are only interested in the output for list commands */
            if (param[0] == 'l') {
                int n = popen2(cmd, args, NULL, 0,
                               &reply[FRAMEMAXHEADERSIZE+1],
                               BUFFERSIZE-FRAMEMAXHEADERSIZE-1);
                if (n < 0) {
                    error("Call to croutoncycle failed.");
                    socket_client_close(0);
                    return -1;
                }
                replylength += n;
            } else if (param[0] == 'O') {
                /* Extra OK response from a C back-and-forth. Disregard. */
                break;
            } else {
                /* Launch command in background (this is necessary as
                   croutoncycle may send a websocket command, leaving us
                   deadlocked...) */
                pid_t pid = fork();
                if (pid < 0) {
                    syserror("Fork error.");
                    exit(1);
                } else if (pid == 0) {
                    /* Double-fork to avoid zombies */
                    pid_t pid2 = fork();
                    if (pid2 < 0) {
                        syserror("Fork error.");
                        exit(1);
                    } else if (pid2 == 0) {
                        execvp(cmd, args);
                        error("Error running '%s'.", cmd);
                        exit(127);
                    }
                    exit(0);
                }
                /* Wait for first fork to complete. */
                waitpid(pid, NULL, 0);
            }
            if (socket_client_write_frame(reply, replylength,
                                          WS_OPCODE_TEXT, 1) < 0) {
                error("Write error.");
                socket_client_close(0);
                return -1;
            }
            break;
        }
        default: {
            int len = length > 64 ? 64 : length;
            char dump[len+1];
            memcpy(dump, buffer, len);
            dump[len] = '\0';
            error("Received an unexpected packet from client (%s).", dump);
            socket_client_close(0);
            return -1;
        }
    }

    return 0;
}
Ejemplo n.º 19
0
/**
 * Взаимодействие с пользователем.
 *
 * @param[in] connection описание соединения.
 * @return статус завершения.
 */
int user_interaction(IN struct connection_vars_t* conn)
{
	TRACE;

	int infp, outfp;
	int pid = popen2(user_command, &infp, &outfp);

	CHECK_ERRNO(pid, "Execute application");

	char* buf = calloc(1, sizeof(char));

	struct pollfd* fds = calloc(sizeof(struct pollfd), 2);
	fds[0].fd = outfp;
	fds[1].fd = conn->sockfd;
	fds[0].events = fds[1].events = POLLIN;

	while (true) {
		int status = poll(fds, 2, TIMEOUT_MS);

		CHECK_ERRNO(status, "Polling");

		DBG_printf("Revents: %d %d\n", fds[0].revents, fds[1].revents);

		if ((fds[0].revents | fds[1].revents) & POLLNVAL) {
			/* Один из дескрипторов закрылся */
			DBG_printf("One of fd has been closed\n");
			break;
		}

		if (0 == status) {
			/* Время ожидания истекло */
			send(conn->sockfd, CONN_TIMEOUT_MSG,
			     sizeof(CONN_TIMEOUT_MSG), 0);
			break;
		}

		int count = 0;	/* Количество данных в fd */

		status = ioctl(conn->sockfd, FIONREAD, &count);

		CHECK_ERRNO(status, "Get available data in sockfd");

		DBG_printf("%d bytes to read from socket\n", count);

		if ((0 == count) && (fds[1].revents & POLLIN)) {
			/*
			 * Если poll возвращает, что данные есть,
			 * но эти данные нельзя прочитать, то
			 * скорее всего сокет закрылся, а эти данные
			 * это что-то для сетевого стека, а не для нас.
			 */
			DBG_printf("Socket most likely closed\n");
			break;
		}

		if (count > MAX_DATA_COUNT) {
			/* TODO: Возможно, стоит генерировать сообщение. */
			break;
		}

		if (count > 0) {
			TRACE;

			buf = realloc(buf, count);

			int ret = recv(conn->sockfd, buf, count, 0);

			DBG_printf("%d bytes ret from socket\n", ret);

			if (ret < 0) {
				break;
			}

			ret = write(infp, buf, ret);

			if (ret < 0) {
				break;
			}
		}

		status = ioctl(outfp, FIONREAD, &count);

		CHECK_ERRNO(status, "Get available data in outfp");

		DBG_printf("%d bytes to read from outfp\n", count);

		if (count > MAX_DATA_COUNT) {
			/* TODO: Возможно, стоит генерировать сообщение. */
			break;
		}

		if (count > 0) {
			TRACE;

			buf = realloc(buf, count);

			int ret = read(outfp, buf, sizeof(buf));

			DBG_printf("%d bytes ret from outfp\n", ret);

			if (ret < 0) {
				break;
			}

			ret = send(conn->sockfd, buf, ret, 0);

			if (ret < 0) {
				break;
			}
		}
	}

	close(infp);
	close(outfp);

	free(buf);
	free(fds);

	kill(pid, SIGTERM);

	TRACE;

	return 0;
}
Ejemplo n.º 20
0
/*
** Global initialization of the transport layer
*/
void transport_global_startup(void){
  if( g.urlIsSsh ){
    /* Only SSH requires a global initialization.  For SSH we need to create
    ** and run an SSH command to talk to the remote machine.
    */
    const char *zSsh;  /* The base SSH command */
    Blob zCmd;         /* The SSH command */
    char *zHost;       /* The host name to contact */
    char zIn[200];     /* An input line received back from remote */

    zSsh = db_get("ssh-command", zDefaultSshCmd);
    blob_init(&zCmd, zSsh, -1);
    if( g.urlPort!=g.urlDfltPort ){
#ifdef __MINGW32__
      blob_appendf(&zCmd, " -P %d", g.urlPort);
#else
      blob_appendf(&zCmd, " -p %d", g.urlPort);
#endif
    }
    if( g.urlUser && g.urlUser[0] ){
      zHost = mprintf("%s@%s", g.urlUser, g.urlName);
#ifdef __MINGW32__
      /* Only win32 (and specifically PLINK.EXE support the -pw option */
      if( g.urlPasswd && g.urlPasswd[0] ){
        Blob pw;
        blob_zero(&pw);
        if( g.urlPasswd[0]=='*' ){
          char *zPrompt;
          zPrompt = mprintf("Password for [%s]: ", zHost);
          prompt_for_password(zPrompt, &pw, 0);
          free(zPrompt);
        }else{
          blob_init(&pw, g.urlPasswd, -1);
        }
        blob_append(&zCmd, " -pw ", -1);
        shell_escape(&zCmd, blob_str(&pw));
        blob_reset(&pw);
      }
#endif
    }else{
      zHost = mprintf("%s", g.urlName);
    }
    blob_append(&zCmd, " ", 1);
    shell_escape(&zCmd, zHost);
    free(zHost);
    /* printf("%s\n", blob_str(&zCmd)); */
    popen2(blob_str(&zCmd), &sshIn, &sshOut, &sshPid);
    if( sshPid==0 ){
      fossil_fatal("cannot start ssh tunnel using [%b]", &zCmd);
    }
    blob_reset(&zCmd);

    /* Send an "echo" command to the other side to make sure that the
    ** connection is up and working.
    */
    fprintf(sshOut, "echo test\n");
    fflush(sshOut);
    sshin_read(zIn, sizeof(zIn));
    if( memcmp(zIn, "test", 4)!=0 ){
      pclose2(sshIn, sshOut, sshPid);
      fossil_fatal("ssh connection failed: [%s]", zIn);
    }
  }
}
Ejemplo n.º 21
0
int main(int argc, char* argv[])
{
    int fifo_fp = -1;
    int udp_sock = -1;
    int tcp_sock = -1;
    int tcp_client_sock = -1;
    int max_sock = -1;
    struct sockaddr_in my_addr;
    struct sockaddr_in peer_addr;
    struct sockaddr_in receiver_addr;
    int addr_len;
    char resp_msg_buf[512];
    char data_msg_buf[1024];
    int len;
    fd_set fd_r;
    int gst_in_fp = -1;
    int gst_out_fp = -1;
    pid_t gst_pid = -1;
    int just_connect = 0;
    char *gst_sink;
    int no_data_count = 0;

    if (argc != 2 || strlen(argv[1]) <= 0) {
        perror("Missing sink setting");
        return -1;
    }

    gst_sink = argv[1];
    printf("Using sink: %s\n", gst_sink);

#if USE_FIFO
    unlink(FIFO_PATH);
    if (mkfifo(FIFO_PATH, 0666) < 0) {
        perror("Error when creating fifo");
        return 0;
    }
#endif

#ifdef CLIENT_MODE
    if ((tcp_client_sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        perror("Error when creating tcp socket");
        return 0;
    }

    memset((char *)&peer_addr, 0, sizeof(peer_addr));
    peer_addr.sin_family = AF_INET;
    peer_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    peer_addr.sin_port = htons(LOCAL_SERVER_PORT);

    if (connect(tcp_client_sock, (const struct sockaddr *)&peer_addr, sizeof(peer_addr)) < 0) {
        perror("Error when connecting to remote");
        return 0;
    }
    if (send(tcp_client_sock, "mirror\n", 7, 0) < 0) {
        perror("Error when sending mirror command");
        return 0;
    }
    just_connect = 1;

#else
    udp_sock = setup_udp_socket();
    if ((tcp_sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        perror("Error when creating tcp socket");
        return 0;
    }

    memset((char *)&my_addr, 0, sizeof(my_addr));
    my_addr.sin_family = AF_INET;
    my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    my_addr.sin_port = htons(DISCOVER_PORT);

    if (bind(tcp_sock, (struct sockaddr *)&my_addr, sizeof(my_addr)) < 0) {
        perror("Error when binding tcp socket");
        return 0;
    }

    if (listen(tcp_sock, 3) < 0) {
        perror("Error when listening tcp socket");
        return 0;
    }
#endif

    for (;;) {
        int timeout = 0;
        struct timeval tv;
        // set connect timeout
        tv.tv_sec = 3;
        tv.tv_usec = 0;
        FD_ZERO(&fd_r);
        FD_SET(udp_sock, &fd_r);
        FD_SET(tcp_sock, &fd_r);
        if (tcp_sock > udp_sock) {
            max_sock = tcp_sock;
        } else {
            max_sock = udp_sock;
        }
        if (tcp_client_sock > 0) {
            FD_SET(tcp_client_sock, &fd_r);
            if (tcp_client_sock > max_sock) {
                max_sock = tcp_client_sock;
            }
        }
        switch (select(max_sock + 1, &fd_r, NULL, NULL, &tv)) {
            case -1:
                printf("error occur, %s\n", strerror(errno));
                break;
            case 0:
                timeout = 1;
            default: {
                if (FD_ISSET(udp_sock, &fd_r)) {
                    size_t aux[128 / sizeof(size_t)];
                    char broadcast_msg_buf[128];
                    struct iovec io;
                    struct msghdr msg;
                    struct cmsghdr *cmsg;
                    io.iov_base = broadcast_msg_buf;
                    io.iov_len = sizeof(broadcast_msg_buf);
                    memset(&msg, 0, sizeof(msg));
                    msg.msg_iov = &io;
                    msg.msg_iovlen = 1;
                    msg.msg_control = aux;
                    msg.msg_controllen = sizeof(aux);
                    msg.msg_flags = 0;
                    msg.msg_name = &peer_addr;
                    msg.msg_namelen = sizeof(peer_addr);
                    len = recvmsg(udp_sock, &msg, 0);
                    if (len < 0) {
                        printf("Error when receiving data from discover socket, errno: %s\n", strerror(errno));
                        close(udp_sock);
                        udp_sock = setup_udp_socket();
                        break;
                    }
                    printf("Receive broadcast msg: %s from: %s:%d\n", broadcast_msg_buf, inet_ntoa(peer_addr.sin_addr), ntohs(peer_addr.sin_port));
                    if (!strncmp(broadcast_msg_buf, DISCOVER_MSG, 5)) {
                        printf("Receive discover msg: %s, from: %s\n", broadcast_msg_buf, inet_ntoa(peer_addr.sin_addr));
                        for (cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
                            if (cmsg->cmsg_level == IPPROTO_IP) {
                                struct in_pktinfo *i = (struct in_pktinfo*) CMSG_DATA(cmsg);
                                printf("Response discover msg with local ip: %s\n", inet_ntoa(i->ipi_spec_dst));
                                memset(resp_msg_buf, 0, sizeof(resp_msg_buf));
                                snprintf(resp_msg_buf, sizeof(resp_msg_buf), DISCOVER_MSG_TEMPLATE, DISCOVER_PORT, inet_ntoa(i->ipi_spec_dst), inet_ntoa(i->ipi_spec_dst));
                                if (sendto(udp_sock, resp_msg_buf, strlen(resp_msg_buf), 0, (struct sockaddr *)&peer_addr, sizeof(peer_addr)) < 0) {
                                    printf("Error when send discover response to peer\n");
                                }
                            }
                        }
                    }
                } else if (FD_ISSET(tcp_sock, &fd_r)) {
                    if (tcp_client_sock < 0) {
                        addr_len = sizeof(peer_addr);
                        tcp_client_sock = accept(tcp_sock, (struct sockaddr *)&peer_addr, &addr_len);
                        if (tcp_client_sock < 0) {
                            printf("Error when accepting client\n");
                        } else {
                            just_connect = 1;
                            printf("Accept peer addr: %s:%d\n", inet_ntoa(peer_addr.sin_addr), ntohs(peer_addr.sin_port));
                            if (!strncmp(gst_sink, "ffplay", 6)) {
#if USE_FIFO
                                const char *command[] = {"ffplay", "-framerate", "50", "-infbuf", "-framedrop", "-analyzeduration", "1", FIFO_PATH, NULL};
#else
                                const char *command[] = {"ffplay", "-framerate", "50", "-infbuf", "-framedrop", "-analyzeduration", "1", "-", NULL};
#endif
                                gst_pid = popen2(command, &gst_in_fp, &gst_out_fp);
                            } else {
#if USE_FIFO
                                char location_buf[32] = {0};
                                strcat(location_buf, "location=");
                                strcat(location_buf, FIFO_PATH);
#ifdef VPUDEC
                                const char *command[] = {"gst-launch-0.10", "filesrc", location_buf, "!", "video\/x-h264,width=800,height=480,framerate=30\/1", "!", "vpudec", "framedrop=true", "frame-plus=1", "low-latency=true", "!", gst_sink, NULL};
#else
                                const char *command[] = {"gst-launch-1.0", "filesrc", location_buf, "!", "h264parse", "!", "decodebin", "!", gst_sink, NULL};
#endif
#else
#ifdef VPUDEC
                                const char *command[] = {"gst-launch-0.10", "fdsrc", "!", "video\/x-h264,width=800,height=480,framerate=30\/1", "!", "vpudec", "framedrop=true", "frame-plus=1", "low-latency=true", "!", gst_sink, NULL};
#else
                                const char *command[] = {"gst-launch-1.0", "fdsrc", "!", "h264parse", "!", "decodebin", "!", gst_sink, NULL};
                                //const char *command[] = {"gst-launch-1.0", "fdsrc", "!", "video\/x-h264,width=800,height=480,framerate=0\/1,stream-format=avc", "!", "avdec_h264", "!", gst_sink, NULL};
#endif
#endif
                                gst_pid = popen2(command, &gst_in_fp, &gst_out_fp);
                            }
                            printf("gst pid: %d\n", gst_pid);
#if USE_FIFO
                            fifo_fp = open(FIFO_PATH, O_WRONLY);
                            printf("fifo_fp: %d\n", fifo_fp);
#endif
                        }
                    } else {
                        printf("Could not accept client, another connection still exist\n");
                    }
                } else if (tcp_client_sock > 0 && FD_ISSET(tcp_client_sock, &fd_r)) {
                    memset(data_msg_buf, 0, sizeof(data_msg_buf));
                    len = read(tcp_client_sock, data_msg_buf, sizeof(data_msg_buf));
                    //printf("Receive data len: %d\n", len);
                    if (len < 0 || no_data_count > 2) {
                        printf("Failed to receive from tcp client socket, close the socket\n");
                        close(tcp_client_sock);
                        tcp_client_sock = -1;
                        if (gst_pid > 0) {
                            kill(gst_pid, SIGKILL);
                            waitpid(gst_pid, NULL, 0);
                            gst_pid = -1;
                            gst_in_fp = -1;
                            gst_out_fp = -1;
                        }
                        if (fifo_fp > 0) {
                            close(fifo_fp);
                            fifo_fp = -1;
                        }
#ifdef CLIENT_MODE
                        return 0;
#endif
                    } else {
                        if (len > 0) {
                            no_data_count = 0;
                        } else {
			    no_data_count++;
                        }
                        if (just_connect && strstr(data_msg_buf, "\r\n")) {
                            int width = 800;
                            int height = 480;
                            printf("Receive control data(%u): %s\n", len, data_msg_buf);
                            char *control_end = strstr(data_msg_buf, "\r\n\r\n");
                            int bdata_len = 0;
                            if (control_end + 4 - data_msg_buf > 0) {
                                bdata_len = len - (control_end + 4 - data_msg_buf);
                                control_end = control_end + 4;
                            }
                            char *info = strtok(data_msg_buf, "\r\n");
                            while (info) {
                                //printf("info: %s\n", info);
                                if (strstr(info, "X-WIDTH:")) {
                                    width = atoi(strstr(info, " "));
                                    printf("width: %d\n", width);
                                }
                                if (strstr(info, "X-HEIGHT:")) {
                                    height = atoi(strstr(info, " "));
                                    printf("height: %d\n", height);
                                }
                                info = strtok(NULL, "\r\n");
                            }

                            if (!strncmp(gst_sink, "ffplay", 6)) {
#if USE_FIFO
                                const char *command[] = {"ffplay", "-framerate", "50", "-infbuf", "-framedrop", "-analyzeduration", "1", FIFO_PATH, NULL};
#else
                                const char *command[] = {"ffplay", "-framerate", "50", "-infbuf", "-framedrop", "-analyzeduration", "1", "-", NULL};
#endif
                                gst_pid = popen2(command, &gst_in_fp, &gst_out_fp);
                            } else {
#if USE_FIFO
                                char location_buf[32] = {0};
                                strcat(location_buf, "location=");
                                strcat(location_buf, FIFO_PATH);
#ifdef VPUDEC
                                char mime_buf[70] = {0};
                                snprintf(mime_buf, 70, "video\/x-h264,width=%d,height=%d,framerate=30\/1", width, height);
                                //snprintf(mime_buf, 70, "video\/x-h264,width=%d,height=%d,framerate=30\/1,stream-format=avc", width, height);
                                printf("Using cap: %s\n", mime_buf);
                                const char *command[] = {"gst-launch-0.10", "filesrc", location_buf, "!", mime_buf, "!", "vpudec", "framedrop=true", "frame-plus=1", "low-latency=true", "!", gst_sink, NULL};
#else
                                const char *command[] = {"gst-launch-1.0", "filesrc", location_buf, "!", "h264parse", "!", "decodebin", "!", gst_sink, NULL};
#endif
#else
#ifdef VPUDEC
                                char mime_buf[70] = {0};
                                snprintf(mime_buf, 70, "video\/x-h264,width=%d,height=%d,framerate=30\/1", width, height);
                                //snprintf(mime_buf, 70, "video\/x-h264,width=%d,height=%d,framerate=30\/1,stream-format=avc", width, height);
                                printf("Using cap: %s\n", mime_buf);
                                const char *command[] = {"gst-launch-0.10", "fdsrc", "do-timestamp=true", "!", mime_buf, "!", "vpudec", "framedrop=false", "frame-plus=1", "low-latency=true", "!", gst_sink, NULL};
#else
                                const char *command[] = {"gst-launch-1.0", "fdsrc", "!", "h264parse", "!", "decodebin", "!", gst_sink, NULL};
#endif
#endif

                                gst_pid = popen2(command, &gst_in_fp, &gst_out_fp);
                            }
                            printf("gst pid: %d\n", gst_pid);
                            printf("gst in fp: %d\n", gst_in_fp);
#if USE_FIFO
                            fifo_fp = open(FIFO_PATH, O_WRONLY);
                            printf("fifo_fp: %d\n", fifo_fp);
#endif

                            just_connect = 0;
                            if (bdata_len > 0) {
#if USE_FIFO
                                if (fifo_fp > 0) {
                                    len = write(fifo_fp, control_end, bdata_len);
                                    printf("Write non control data len: %d\n", len);
                                }
#else
                                if (gst_in_fp > 0) {
                                    len = write(gst_in_fp, control_end, bdata_len);
                                    printf("Write non control data len: %d\n", len);
                                }
#endif
                            }
                        } else {
#if USE_FIFO
                            if (fifo_fp > 0) {
Ejemplo n.º 22
0
int get_result(size_t size,size_t points_size,point_t *points,int ***result)
{
	size_t iter = 0,iter_,result_size;
	int hs_size = size,***hs_points = malloc(sizeof(int **)*(points_size+1))
		,***hs_result,errcode;
	FILE *pin,*pout;
	if(!hs_points)return 0;
	while(iter != points_size){
		hs_points[iter] = malloc(sizeof(int *)*2);
		if(!hs_points[iter]){
			free_iituplelist(hs_points);
			return 0;
		}
		hs_points[iter][0] = malloc(sizeof(int));
		hs_points[iter][1] = malloc(sizeof(int));
		if(!hs_points[iter][0] || !hs_points[iter][1]){
			free(hs_points[iter][0]);
			free(hs_points[iter][1]);
			free(hs_points[iter]);
			hs_points[iter] = NULL;
			free_iituplelist(hs_points);
			return 0;
		}
		*hs_points[iter][0] = points[iter].x;
		*hs_points[iter][1] = points[iter].y;
		iter++;
	}
	hs_points[points_size] = NULL;
	errcode = popen2("runyadorigi ./nqueens.hs",&pout,&pin);
	if(errcode < 0){
		free_iituplelist(hs_points);
		return 0;
	}
	output_int(pin,&hs_size);
	fputc('\n',pin);
	output_iituplelist(pin,hs_points);
	fputc('\n',pin);
	fclose(pin);
	hs_result = parse_intlistlist(pout);
	fclose(pout);
	if(!hs_result)return 0;
	result_size = parray_length((void **)hs_result);
	*result = malloc(sizeof(int *)*(result_size+1));
	if(!*result){
		free_intlistlist(hs_result);
		return 0;
	}
	iter = 0;
	while(iter != result_size){
		(*result)[iter] = malloc(sizeof(int)*size);
		if(!(*result)[iter]){
			while(iter--)free((*result)[iter]);
			free(*result);
			return 0;
		}
		iter_ = 0;
		while(iter_ != size){
			(*result)[iter][iter_] = *hs_result[iter][iter_];
			iter_++;
		}
		iter++;
	}
	(*result)[result_size] = NULL;
	return 1;
}
Ejemplo n.º 23
0
Archivo: util.c Proyecto: clarive/clax
int execute(char *command, char *request, char *obuf, size_t olen)
{
    int ret;
    popen2_t ctx;
    char *r = request;

    ret = popen2(command, environ, &ctx);
    if (ret < 0) {
        fprintf(stderr, "Command '%s' failed=%d", command, ret);
        return -1;
    }

    int offset = 0;
    size_t request_len = strlen(request);
    int wcount = 0;

#ifdef MVS
    r = clax_etoa_alloc(request, request_len);
#endif

    while (1) {
        ret = write(ctx.in, r + offset, request_len - offset);
        wcount += ret;

        if (wcount == request_len)
            break;

        if (ret < 0 && errno == EAGAIN) {
            continue;
        }

        offset += ret;
    }

#ifdef MVS
    free(r);
#endif

    offset = 0;
    while (1) {
        ret = read(ctx.out, obuf + offset, olen - offset);

        if (ret == 0)
            break;

        if (ret < 0 && errno == EAGAIN) {
            continue;
        }

        offset += ret;
    }
    obuf[offset] = 0;

#ifdef MVS
    clax_atoe(obuf, offset);
#endif

    int exit_code = pclose2(&ctx);
    if (exit_code != 0) {
        fprintf(stderr, "Exit code=%d\n", exit_code);
        return -1;
    }

    return offset;
}
Ejemplo n.º 24
0
// Print gcode from stream_input to austerus-core on stream_gcode
int print_file(FILE *stream_input, size_t lines, const char *cmd,
	unsigned int filament, unsigned int *table, int mode, int verbose) {

	int pipe_gcode = 0;
	int pipe_feedback = 0;

	FILE *stream_gcode = NULL;
	FILE *stream_feedback = NULL;

	int status;
	time_t start;

	int i;

	char *line = NULL;
	size_t line_len = 0;
	ssize_t nbytes;
	ssize_t fbytes;
	size_t tally = 0;
	char line_feedback[1024];

	int pcta = -1, pctb = 0;

	pid_t pid;

	start = time(NULL);

	// Open the input and output streams to austerus-core
	pid = popen2(cmd, &pipe_gcode, &pipe_feedback);

	// Make feedback pipe non-blocking
	fcntl(pipe_feedback, F_SETFL, O_NONBLOCK);

	stream_gcode = fdopen(pipe_gcode, "w");
	stream_feedback = fdopen(pipe_feedback, "r");

	if (!stream_gcode) {
		fprintf(stderr, "unable to open output stream\n");
		abort();
	}

	if (!stream_feedback) {
		fprintf(stderr, "unable to open feedback stream\n");
		abort();
	}

	if (mode == NORMAL) {
		for(i=0; i<BAR_WIDTH; i++)
			printf(" ");
	}

	while (nbytes != -1) {
		// Read the next line from file
		nbytes = getline(&line, &line_len, stream_input);
		if (nbytes < 0) {
			break;
		}

		// Strip out any comments
		nbytes = filter_comments(line);

		if (nbytes == 0) {
			continue;
		}

		if (nbytes == 1 && line[0] == '\n') {
			continue;
		}

		if (nbytes == 2 && line[0] == '\t' && line[1] == '\n') {
			continue;
		}

		// Write the file to the core
		fprintf(stream_gcode, "%s", line);
		fflush(stream_gcode);

		if (verbose) {
			printf("SEND: %s", line);
		}
		
		// Read any available feedback lines
		do {
			fbytes = nonblock_getline(line_feedback, stream_feedback);
			if (fbytes > 0) {
				if (strncmp(line_feedback, MSG_ACK,
						MSG_ACK_LEN) == 0 ||
					strncmp(line_feedback, MSG_DUD,
						MSG_DUD_LEN) == 0) {
					tally++;
				}
				if (verbose) {
					printf("FEEDBACK: %s\n", line_feedback);
				}
			}
		} while (fbytes != -1);

		if (tally > lines) {
			fprintf(stderr, "Expected %lu valid lines, got more\n",
				(long unsigned int) lines);
			return 0;
		}

		if (filament == 0) {
			pctb = 0;
		} else {
			pctb = 100 * table[tally] / filament;
		}

		if (pcta != pctb) {
			pcta = pctb;

			if (mode == NORMAL) {
				printf("\r");
				print_status(pcta, 0, 0);
			} else {
				print_status_stream(pcta, start);
			}

			fflush(stdout);
		}
	}

	if (mode == NORMAL) {
		printf("\n");
	}

	/*
	 * Now we have written and flushed all outgoing gcode we can close the
	 * pipe leaving the core to finish reading the data.
	 */

	// Block until stream is closed
	if (pclose(stream_gcode) != 0) {
		perror("error closing output stream");
	}
	close(pipe_gcode);

	if (wait(&status) != pid) {
		perror("error waiting for core");
	}
	status = WEXITSTATUS(status);

	/*
	 * Read any remaining data from the feedback pipe until the core has
	 * exited.
	 */

	while (1) {
		fbytes = nonblock_getline(line_feedback, stream_feedback);
		if (fbytes == -1) {
			if (kill(pid, 0) == 0)
				usleep(100);
			else
				break;
		}

		if (fbytes > 0) {
			if (strncmp(line_feedback, MSG_ACK,
					MSG_ACK_LEN) == 0 ||
				strncmp(line_feedback, MSG_DUD,
					MSG_DUD_LEN) == 0) {
				tally++;
			}
			if (verbose) {
				printf("FEEDBACK (post): %s\n", line_feedback);
			}
			/*
			 * TODO We should still be updating progress here */
		}
	}

	if (tally != lines) {
		fprintf(stderr, "Expected %lu valid lines, got more %lu\n",
			(long unsigned int) lines, (long unsigned int) tally);
	}

	if (pclose(stream_feedback) != 0) {
		perror("error closing feedback stream");
	}
	
	if (line) {
		free(line);
	}
	close(pipe_feedback);

	return status;
}
Ejemplo n.º 25
0
/*
 * basil_request - issue BASIL request and parse response
 * @bp:	method-dependent parse data to guide the parsing process
 *
 * Returns 0 if ok, a negative %basil_error otherwise.
 */
int basil_request(struct basil_parse_data *bp)
{
	int to_child, from_child;
	int ec, i, rc = -BE_UNKNOWN;
	FILE *apbasil;
	pid_t pid = -1;
	pthread_t thread;
	pthread_attr_t attr;
	int time_it_out = 1;
	DEF_TIMERS;

	if (log_sel == -1)
		_init_log_config();

	if (!cray_conf->apbasil) {
		error("No alps client defined");
		return 0;
	}

	if ((cray_conf->apbasil_timeout == 0) ||
	    (cray_conf->apbasil_timeout == (uint16_t) NO_VAL)) {
		debug2("No ApbasilTimeout configured (%u)",
		       cray_conf->apbasil_timeout);
		time_it_out = 0;
	} else {
		slurm_attr_init(&attr);
		pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
	}

	assert(bp->version < BV_MAX);
	assert(bp->method > BM_none && bp->method < BM_MAX);

	START_TIMER;
	for (i = 0; ((i < 10) && (pid < 0)); i++) {
		if (i)
			usleep(100000);
		pid = popen2(cray_conf->apbasil, &to_child, &from_child, true);
	}
	if (pid < 0)
		fatal("popen2(\"%s\", ...)", cray_conf->apbasil);

	if (time_it_out) {
		pthread_create(&thread, &attr, _timer_func, (void*)&pid);
	}

	/* write out request */
	apbasil = fdopen(to_child, "w");
	if (apbasil == NULL)
		fatal("fdopen(): %s", strerror(errno));
	setlinebuf(apbasil);

	_write_xml(apbasil, "<?xml version=\"1.0\"?>\n"
		   "<BasilRequest protocol=\"%s\" method=\"%s\" ",
		   bv_names[bp->version], bm_names[bp->method]);

	switch (bp->method) {
	case BM_engine:
		_write_xml(apbasil, "type=\"ENGINE\"/>");
		break;
	case BM_inventory:
		_write_xml(apbasil, "type=\"INVENTORY\"/>");
		break;
	case BM_reserve:
		_write_xml(apbasil, ">\n");
		_rsvn_write_reserve_xml(apbasil, bp->mdata.res, bp->version);
		break;
	case BM_confirm:
		if (bp->version == BV_1_0 && *bp->mdata.res->batch_id != '\0')
			_write_xml(apbasil, "job_name=\"%s\" ",
				   bp->mdata.res->batch_id);
		_write_xml(apbasil, "reservation_id=\"%u\" %s=\"%llu\"/>\n",
			   bp->mdata.res->rsvn_id,
			   bp->version >= BV_3_1 ? "pagg_id" : "admin_cookie",
			   (unsigned long long)bp->mdata.res->pagg_id);
		break;
	case BM_release:
		_write_xml(apbasil, "reservation_id=\"%u\"/>\n",
			   bp->mdata.res->rsvn_id);
		break;
	case BM_switch:
	{
		char *suspend = bp->mdata.res->suspended ? "OUT" : "IN";
		_write_xml(apbasil, ">\n");
		_write_xml(apbasil, " <ReservationArray>\n");
		_write_xml(apbasil, "  <Reservation reservation_id=\"%u\" "
			   "action=\"%s\"/>\n",
			   bp->mdata.res->rsvn_id, suspend);
		_write_xml(apbasil, " </ReservationArray>\n");
		_write_xml(apbasil, "</BasilRequest>\n");
	}
		break;
	default: /* ignore BM_none, BM_MAX, and BM_UNKNOWN covered above */
		break;
	}

	if (fclose(apbasil) < 0)	/* also closes to_child */
		error("fclose(apbasil): %s", strerror(errno));

	rc = parse_basil(bp, from_child);
	ec = wait_for_child(pid);

	if (time_it_out) {
		slurm_attr_destroy(&attr);
		debug2("Killing the timer thread.");
		pthread_mutex_lock(&timer_lock);
		pthread_cond_broadcast(&timer_cond);
		pthread_mutex_unlock(&timer_lock);
	}

	END_TIMER;
	if (ec) {
		error("%s child process for BASIL %s method exited with %d",
		      cray_conf->apbasil, bm_names[bp->method], ec);
	} else if (DELTA_TIMER > 5000000) {	/* 5 seconds limit */
		info("%s child process for BASIL %s method time %s",
		     cray_conf->apbasil, bm_names[bp->method], TIME_STR);
	}

	return rc;
}