Exemplo n.º 1
0
int main(int argc, char **argv)
{
    initialize();
#ifdef __AFL_INIT
    // Enable AFL deferred forkserver mode. Requires compilation using
    // afl-clang-fast++. See fuzzing.md for details.
    __AFL_INIT();
#endif

#ifdef __AFL_LOOP
    // Enable AFL persistent mode. Requires compilation using afl-clang-fast++.
    // See fuzzing.md for details.
    int ret = 0;
    while (__AFL_LOOP(1000)) {
        std::vector<uint8_t> buffer;
        if (!read_stdin(buffer)) {
            continue;
        }
        ret = test_one_input(buffer);
    }
    return ret;
#else
    std::vector<uint8_t> buffer;
    if (!read_stdin(buffer)) {
        return 0;
    }
    return test_one_input(buffer);
#endif
}
Exemplo n.º 2
0
int FAR _export
gsdll_callback(int message, char FAR *str, unsigned long count)
{
char buf[256];
    switch (message) {
	case GSDLL_POLL:
	    // Don't check message queue because we don't
	    // create any windows.
	    // May want to return error code if abort wanted
	    break;
	case GSDLL_STDIN:
	    return read_stdin(str, count);
	case GSDLL_STDOUT:
	    fwrite(str, 1, count, stdout);
	    fflush(stdout);
	    return count;
	case GSDLL_DEVICE:
	    if (count) {
		sprintf(buf, "mswindll device not supported in this version of Ghostscript\n");
		fputs(buf, stdout);
	    }
	    break;
	case GSDLL_SYNC:
	    break;
	case GSDLL_PAGE:
	    break;
	case GSDLL_SIZE:
	    break;
	default:
	    sprintf(buf,"Callback: Unknown message=%d\n",message);
	    fputs(buf, stdout);
	    break;
    }
    return 0;
}
Exemplo n.º 3
0
static void stdin_cmd_poll(rarch_cmd_t *handle)
{
   if (!handle->stdin_enable)
      return;

   size_t ret = read_stdin(handle->stdin_buf + handle->stdin_buf_ptr, STDIN_BUF_SIZE - handle->stdin_buf_ptr - 1);
   if (ret == 0)
      return;

   handle->stdin_buf_ptr += ret;
   handle->stdin_buf[handle->stdin_buf_ptr] = '\0';

   char *last_newline = strrchr(handle->stdin_buf, '\n');
   if (!last_newline)
   {
      // We're receiving bogus data in pipe (no terminating newline),
      // flush out the buffer.
      if (handle->stdin_buf_ptr + 1 >= STDIN_BUF_SIZE)
      {
         handle->stdin_buf_ptr = 0;
         handle->stdin_buf[0] = '\0';
      }

      return;
   }

   *last_newline++ = '\0';
   ptrdiff_t msg_len = last_newline - handle->stdin_buf;

   parse_msg(handle, handle->stdin_buf);

   memmove(handle->stdin_buf, last_newline, handle->stdin_buf_ptr - msg_len);
   handle->stdin_buf_ptr -= msg_len;
}
Exemplo n.º 4
0
static int	talker(int socketDescriptor, t_entry **entry)
{
  char		msg[MAX_MSG];
  int		i;

  get_connection(socketDescriptor);
  while (strcmp(msg, "quit") != 0)
    {
      bzero(msg, sizeof(msg));
      if ((read_stdin(msg)) == EXIT_FAILURE)
	return (EXIT_FAILURE);
      for (i = 0; entry[i]->cmd &&
	     strncmp(entry[i]->cmd, msg, strlen(entry[i]->cmd)) != 0; ++i);
      if (entry[i]->cmd != NULL)
	{
	  if ((entry[i]->fptr(msg, socketDescriptor)) == EXIT_FAILURE)
	    return (EXIT_FAILURE);
	}
      else
	{
	  if ((dprintf(socketDescriptor, "%s", msg)) == -1)
	    return (my_perror("dprintf"));
	}
      get_srv_ret(socketDescriptor);
    }
  return (EXIT_SUCCESS);
}
Exemplo n.º 5
0
int				main(int ac, char **av)
{
	t_env	env;

	if (!(isatty(0)))
		error_quit("Invalid stdin, please run from terminal");
	g_env = &env;
	env.old_width = 0;
	env.old_height = 0;
	env.list_size = ac - 1;
	env.items = NULL;
	get_tty_fd(&env);
	build_list(&env, ac, av);
	env.curr = env.items;
	init_signals();
	tgetent(0, getenv("TERM"));
	if (!(env.caps = malloc(sizeof(*env.caps))))
		error_quit("Failed to malloc env caps");
	init_caps(env.caps);
	key_codes_init(&env);
	terminal_catch();
	env.fd = 2;
	while (1)
	{
		draw_list(&env);
		read_stdin(&env);
	}
}
Exemplo n.º 6
0
Arquivo: main.c Projeto: jb55/chfreq.c
int
main (int argc, char **argv) {
  uint32_t **freq = NULL;
  uint32_t *cur = NULL;
  char *buf = NULL;
  char *format = NULL;
  char *opt = 0;
  int cfirst = 1;

  if (1 == argc && 1 == isatty(0)) { return usage(), 1; }
  else if (ferror(stdin)) { return 1; }

  if (argc > 1) {
    while (*argv++) {
      opt = argv[0];
      switch (opt[0]) {
        case '-':
          switch (opt[1]) {
            case 'h': return usage(), 0;
            case 'V': return printf("%s\n", CHFREQ_VERSION), 0;
            case 'f': opt = *argv++; format = *argv++; break;
          }
          break;
      }
    }
  }

  if (NULL == format) {
    format = "%c | %d";
  }

  // get order of format
  {
    char ch = 0;
    int i = 0;
    while ('\0' != (ch = format[i++])) {
      if ('%' == ch) {
        if ('c' == format[i]) { cfirst = 1; break; }
        else { cfirst = 0; break; }
      }
    }
  }

  if (1 == isatty(0)) { return usage(), 1; }
  else if (ferror(stdin)) { return 1; }
  else {
    do {
      buf = read_stdin();
      if (NULL == buf) { return 1; }
      freq = chfreq(buf);
      for (int i = 0; (cur = freq[i]); ++i) {
        if (1 == cfirst) { printf(format, cur[0], cur[1]); }
        else { printf(format, cur[1], cur[0]); }
        printf("\n");
      }
    } while (NULL != buf);
  }
  return 0;
}
Exemplo n.º 7
0
int main(int argc, const char *const *argv)
{
    struct timeval *tv, tvbuf;
    adns_query qu;
    void *qun_v;
    adns_answer *answer;
    int r, maxfd;
    fd_set readfds, writefds, exceptfds;
    const char *arg;

    ensure_adns_init();

    while ((arg= *++argv)) process_optarg(arg,&argv,0);

    if (!ov_pipe && !ads) usageerr("no domains given, and -f/--pipe not used; try --help");

    for (;;)
    {
        for (;;)
        {
            qu= ov_asynch ? 0 : outstanding.head ? outstanding.head->qu : 0;
            r= adns_check(ads,&qu,&answer,&qun_v);
            if ((r == EAGAIN) || (r == EWOULDBLOCK)) break;
            if (r == ESRCH)
            {
                if (!ov_pipe) goto x_quit;
                else break;
            }
            assert(!r);
            query_done(qun_v,answer);
        }
        maxfd= 0;
        FD_ZERO(&readfds);
        FD_ZERO(&writefds);
        FD_ZERO(&exceptfds);
        if (ov_pipe)
        {
            maxfd= 1;
            FD_SET(0,&readfds);
        }
        tv= 0;
        adns_beforeselect(ads, &maxfd, &readfds,&writefds,&exceptfds, &tv,&tvbuf,0);
        ADNS_CLEAR_ERRNO;
        r= select(maxfd, &readfds,&writefds,&exceptfds, tv);
        ADNS_CAPTURE_ERRNO;
        if (r == -1)
        {
            if (errno == EINTR) continue;
            sysfail("select",errno);
        }
        adns_afterselect(ads, maxfd, &readfds,&writefds,&exceptfds, 0);
        if (ov_pipe && FD_ISSET(0,&readfds)) read_stdin();
    }
x_quit:
    if (fclose(stdout)) outerr();
    quitnow(rcode);
}
Exemplo n.º 8
0
Arquivo: main.c Projeto: eugen0329/tcp
int main(int argc, char *argv[])
{
    int sock;
    struct sockaddr_in addr;
    int port = get_port(argc, argv);
    char server_address_string[16];
    char buf[BUF_SIZE];
    char repeat = 1;
    int id;
    set_address(argc, argv, server_address_string, LENGTH_OF(server_address_string));

    srand(time(NULL));
    id = rand();

    sock = socket(AF_INET, SOCK_STREAM, 0);
    if(WRONG_SOC(sock)) {
        perror("socket");
        exit(1);
    }

    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    /* addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); */
    addr.sin_addr.s_addr = inet_addr(server_address_string);
    if(connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
        perror("connect");
        exit(2);
    }

    printf("%s:%d, ID: %d\n", server_address_string, port, id);

    send(sock, &id, sizeof(id), EMPTY_FLAGS);

    while(repeat) {
        printf("-> ");
        read_stdin(buf, LENGTH_OF(buf));
        if(strlen(buf) == 0) continue;
        if(!strncmp(buf, "close", LENGTH_OF(buf))) repeat = 0;
        send_to(sock, buf);

        // download file if its exists
        if(strstr(buf, "download") && receive_int(sock)) {
            receive_file(sock);

            printf("%s\n", FILE_DOWNLOADED_MSG);
            continue;
        }

        // prints info or error mesages
        receive_and_print_msg(sock);
    }

    close(sock);

    return 0;
}
/* Cat clone */
int main(int argc, char **argv) {
  int i;
  if (argc < 2) {
    read_stdin();
    return 0;
  }
  for (i=1 ; i<argc ; i++) {
    print_file(argv[i]);
  }
  return 0;
}
Exemplo n.º 10
0
int		check_fds(fd_set *fd_read, int *fd,
			  void (*fptr[7])(char buf[515], int *), char *tab[7])
{
  if (FD_ISSET(0, fd_read))
    if (read_stdin(fd, fptr, tab) == -1)
      return (-1);
  if (*fd != -1 && FD_ISSET(*fd, fd_read))
    if (read_socket(fd) == -1)
      return (-1);
  return (0);
}
Exemplo n.º 11
0
static void MojoGui_stdio_msgbox(const char *title, const char *text)
{
    char buf[128];
    char *fmt = xstrdup(_("NOTICE: %0\n[hit enter]"));
    char *msg = format(fmt, text);
    printf("%s\n", msg);
    free(msg);
    free(fmt);
    fflush(stdout);
    read_stdin(buf, sizeof (buf));
} // MojoGui_stdio_msgbox
Exemplo n.º 12
0
int		check_fd(t_env *e)
{
	if (FD_ISSET(e->fd.fd, &e->fd_read))
	{
		return (read_fd(e));
	}
	if (FD_ISSET(0, &e->fd_read))
	{
		read_stdin(e);
	}
	return (1);
}
Exemplo n.º 13
0
int main(int argc, char** argv) {
	char* content;
	if (argc > 1) { content = argv[1]; }
	else { content = read_stdin(); }
	treebank_tokens_t* tokens = treebank_tokenize(content);
	int num_tokens = tokens->length;
	for (int i = 0; i < num_tokens; i++) printf("%s ", 
		tokens->token_array[i]);
	treebank_tokens_free(tokens);
	printf("\n");
	return 0;
}
Exemplo n.º 14
0
int main(int argc, char **argv) {
	entry** table = mk_table();
	if (argc > 1 ) {
		for (int i=1; i < argc; i++) {
			read_file(argv[i], table);
		}
	} else {
		read_stdin(table);
	}
	print_table(table);
	del_table(table);
	return 0;
} 
Exemplo n.º 15
0
static MojoGuiYNAN MojoGui_stdio_promptynan(const char *title, const char *txt,
                                            boolean defval)
{
    MojoGuiYNAN retval = MOJOGUI_NO;
    if (!feof(stdin))
    {
        char *fmt = xstrdup(_("%0\n[y/n/Always/Never]: "));
        char *msg = format(fmt, txt);
        char *localized_no = xstrdup(_("N"));
        char *localized_yes = xstrdup(_("Y"));
        char *localized_always = xstrdup(_("Always"));
        char *localized_never = xstrdup(_("Never"));
        boolean getout = false;
        char buf[128];

        while (!getout)
        {
            int rc = 0;

            getout = true;  // we may reset this later.
            printf("%s\n", msg);
            fflush(stdout);
            rc = read_stdin(buf, sizeof (buf));

            if (rc < 0)
                retval = MOJOGUI_NO;
            else if (rc == 0)
                retval = (defval) ? MOJOGUI_YES : MOJOGUI_NO;
            else if (strcasecmp(buf, localized_no) == 0)
                retval = MOJOGUI_NO;
            else if (strcasecmp(buf, localized_yes) == 0)
                retval = MOJOGUI_YES;
            else if (strcasecmp(buf, localized_always) == 0)
                retval = MOJOGUI_ALWAYS;
            else if (strcasecmp(buf, localized_never) == 0)
                retval = MOJOGUI_NEVER;
            else
                getout = false;  // try again.
        } // while

        free(localized_never);
        free(localized_always);
        free(localized_yes);
        free(localized_no);
        free(msg);
        free(fmt);
    } // if

    return retval;
} // MojoGui_stdio_promptynan
Exemplo n.º 16
0
int
main(int argc , char * argv[])
{
	int ch;
	const char * proto = NULL;
	const char * message = NULL;
	const char * datafile = NULL;
	int mode = 0;
	while ((ch = getopt(argc, argv, "hDp:m:d:")) != -1) {
		switch(ch) {
		case 'h':
			usage(argv[0]);
			return 0;
		case 'p':
			proto = optarg;
			break;
		case 'm':
			message = optarg;
			break;
		case 'd':
			datafile = optarg;
			break;
		case 'D':
			mode = 10;
			break;
		default:
			usage(argv[0]);
			return 1;
		}
	}

	if (proto == NULL || message == NULL) {
		usage(argv[0]);
		return 1;
	}

	struct pbc_slice data;

	if (datafile == NULL) {
		read_stdin(mode, &data);
	} else {
		read_file(datafile , &data);
	}

	dump(proto , message , &data);

	return 0;
}
Exemplo n.º 17
0
int main(int argc, char **argv)
{
	int n;
	char **in;
	char *path;

	option_parse(argc, argv);
	agurim_init();

	argc -= optind;
	argv += optind;

	if (argc == 0){
		/* stdin supports re-aggregation format only. */
		if (query.outfmt != REAGGREGATION) 
			usage();
		else
			read_stdin();
	}

again:
	n = argc;
	in = argv;

	while (n > 0) {
		path = *in;
		if (is_dir(path))
			read_dir(path);
		else
			read_file(path);
		++in;
		--n;
	}
	if (inparam.mode == HHH_MAIN_MODE){
		hhh_run();
		if (query.outfmt != REAGGREGATION) {
			/* reset internal parameters for text processing */
			param_set_nextmode();
			/* goto the second pass */
			goto again;
		}
	} else {
		plot_run();
	}
	agurim_finish();

	return (0);
}
Exemplo n.º 18
0
Arquivo: burp.c Projeto: sxdtxl/burp
static char *ask_password(void) {
  char *passwd, *r;

  passwd = malloc(128 + 1);
  if (passwd == NULL)
    return NULL;

  printf("[%s] Enter password: ", arg_username);

  r = read_stdin(passwd, 128, false);
  if (r == NULL) {
    free(passwd);
    return NULL;
  }

  return passwd;
}
Exemplo n.º 19
0
Arquivo: burp.c Projeto: sxdtxl/burp
static char *ask_username(void) {
  char *username, *r;

  username = malloc(128 + 1);
  if (username == NULL)
    return NULL;

  printf("Enter username: ");

  r = read_stdin(username, 128, true);
  if (r == NULL) {
    free(username);
    return NULL;
  }

  return username;
}
Exemplo n.º 20
0
void mgrep(const regex_t* preg, flags_t flags) {
    if (flags.mmap) {
	struct stat sb;
	if (fstat(0, &sb) == -1) {
	    perror ("fstat");
	    exit(1);
	}
	char *p =mmap(0, sb.st_size, PROT_READ, MAP_PRIVATE, 0, 0);
	if (p == MAP_FAILED) {
	    perror("mmap");
	    exit(1);
	}
	readlines(preg, p, sb.st_size);
	munmap(p,sb.st_size);
    } else {
	read_stdin(preg);
    }
}
Exemplo n.º 21
0
Arquivo: main.c Projeto: pamolloy/dzen
static void
event_loop(void) {
	int xfd, nbits, dr=0;
	fd_set rmask;

	// Assign connection number for the specified display
	xfd = ConnectionNumber(dzen.dpy);
	while(dzen.running) {
		FD_ZERO(&rmask);	// Clear newly declared set
		FD_SET(xfd, &rmask);	// Assign the fd to a set
		if(dr != -2)	//TODO (PM) Won't this statement always return true?
			FD_SET(STDIN_FILENO, &rmask);
			//TODO (PM) This would make a second call to the same function.
			// Can more than one fd be assigned to a set?

		while(XPending(dzen.dpy))
			handle_xev();

		nbits = select(xfd+1, &rmask, NULL, NULL, NULL);
		if (nbits != -1) {
			//TODO (PM) Again, dr has only been assigned the value, zero
			if (dr != -2 && FD_ISSET(STDIN_FILENO, &rmask)) {
				if ((dr = read_stdin()) == -1)
					return;
				handle_newl();
			}
			if (dr == -2 && dzen.timeout > 0) {
				/* set an alarm to kill us after the timeout */
				struct itimerval t;
				memset(&t, 0, sizeof t);
				t.it_value.tv_sec = dzen.timeout;
				t.it_value.tv_usec = 0;
				setitimer(ITIMER_REAL, &t, NULL);
			}
			if (FD_ISSET(xfd, &rmask))
				handle_xev();
		}
		else {
			perror("select");	//TODO (PM) Consolidate error handling
			exit(EXIT_FAILURE);
		}
	}
	return;
}
Exemplo n.º 22
0
static boolean MojoGui_stdio_promptyn(const char *title, const char *text,
                                      boolean defval)
{
    boolean retval = false;
    if (!feof(stdin))
    {
        const char *_fmt = ((defval) ? _("%0 [Y/n]: ") : _("%0 [y/N]: "));
        char *fmt = xstrdup(_fmt);
        char *msg = format(fmt, text);
        char *localized_no = xstrdup(_("N"));
        char *localized_yes = xstrdup(_("Y"));
        boolean getout = false;
        char buf[128];

        while (!getout)
        {
            int rc = 0;

            getout = true;  // we may reset this later.
            printf("%s", msg);
            fflush(stdout);
            rc = read_stdin(buf, sizeof (buf));

            if (rc < 0)
                retval = false;
            else if (rc == 0)
                retval = defval;
            else if (strcasecmp(buf, localized_no) == 0)
                retval = false;
            else if (strcasecmp(buf, localized_yes) == 0)
                retval = true;
            else
                getout = false;  // try again.
        } // while

        free(localized_yes);
        free(localized_no);
        free(msg);
        free(fmt);
    } // if

    return retval;
} // MojoGui_stdio_promptyn
Exemplo n.º 23
0
static int readstr(const char *prompt, char *buf, int len,
                   boolean back, boolean fwd)
{
    // !!! FIXME: if read_stdin() returns -1, we return 0, which makes it
    // !!! FIXME:  indistinguishable from "user hit enter" ... maybe we should
    // !!! FIXME:  abort in read_stdin() if i/o fails?

    int retval = 0;
    char *backstr = (back) ? xstrdup(_("back")) : NULL;

    if (prompt != NULL)
        printf("%s\n", prompt);

    if (back)
    {
        char *fmt = xstrdup(_("Type '%0' to go back."));
        char *msg = format(fmt, backstr);
        printf("%s\n", msg);
        free(msg);
        free(fmt);
    } // if

    if (fwd)
    {
        printf("%s", _("Press enter to continue."));
        printf("\n");
    } // if

    printf("%s",_("> "));
    fflush(stdout);

    if ((retval = read_stdin(buf, len)) >= 0)
    {
        if ((back) && (strcmp(buf, backstr) == 0))  // !!! FIXME: utf8casecmp?
            retval = -1;
    } // if

    free(backstr);
    return retval;
} // readstr
Exemplo n.º 24
0
int		main(int ac, char **av)
{
	int		fd[ac];
	int		return_val[ac];
	char	*line;
	int		i;

	line = NULL;
	if (ac == 1)
	{
		read_stdin(line);
		return (0);
	}
	i = 0;
	while (++i < ac)
	{
		fd[i - 1] = open(av[i], O_RDONLY);
		if (fd[i - 1] == -1)
		{
			ft_putendl("erreur lors de l'ouverture du fichier");
			return (-1);
		}
		return_val[i - 1] = 1;
	}
	i = 0;
	while (!is_finished(return_val, ac))
	{
		return_val[i] = get_next_line(fd[i], &line);
		if (return_val[i] == 1)
			ft_putendl(line);
		i++;
		if (i == ac - 1)
			i = 0;
		free(line);
	}
}
Exemplo n.º 25
0
Arquivo: lvmtsd.c Projeto: Auboo/lvmts
int main(int argc, char **argv)
{
    struct extent_info_t *extent_info;

    if(argc==1) {
        fprintf(stderr, "Usage: %s <dev name> [<number of extents to print>]\n", argv[0]);
        exit(1);
    }

    parse_lv_name(argv[1]);

    if(argc>2)
        ext_to_print = atoi(argv[2]);

    extent_info = calloc(sizeof(struct extent_info_t), EXTENTS);
    if (!extent_info) {
        fprintf(stderr, "can't allocate memory!\n");
        exit(1);
    }

    uint64_t now = time(NULL);

    extent_info = read_stdin(now, extent_info);

    printf("individual extent score:\n");
    for(size_t i=0; i<EXTENTS; i++)
        if(extent_info[i].reads[0] || extent_info[i].writes[0]) {
            printf("%lu: r: %u, w:%u\n", i, get_read_score(&extent_info[i]), get_write_score(&extent_info[i]));
//          print_io(&extent_info[i]);
        }

    print_extents(extent_info);

    free(extent_info);
    return 0;
}
Exemplo n.º 26
0
static void
event_loop(void) {
	int xfd, ret, dr=0;
	fd_set rmask;

	xfd = ConnectionNumber(dzen.dpy);
	while(dzen.running) {
		FD_ZERO(&rmask);
		FD_SET(xfd, &rmask);
		if(dr != -2)
			FD_SET(STDIN_FILENO, &rmask);

		while(XPending(dzen.dpy))
			handle_xev();

		ret = select(xfd+1, &rmask, NULL, NULL, NULL);
		if(ret) {
			if(dr != -2 && FD_ISSET(STDIN_FILENO, &rmask)) {
				if((dr = read_stdin()) == -1)
					return;
				handle_newl();
			}
			if(dr == -2 && dzen.timeout > 0) {
				/* set an alarm to kill us after the timeout */
				struct itimerval t;
				memset(&t, 0, sizeof t);
				t.it_value.tv_sec = dzen.timeout;
				t.it_value.tv_usec = 0;
				setitimer(ITIMER_REAL, &t, NULL);
			}
			if(FD_ISSET(xfd, &rmask))
				handle_xev();
		}
	}
	return;
}
Exemplo n.º 27
0
int
main (int argc, char **argv)
{
  struct jpeg_decompress_struct cinfo;
  struct jpeg_error_mgr jerr;
#ifdef PROGRESS_REPORT
  struct cdjpeg_progress_mgr progress;
#endif
  int file_index;
  djpeg_dest_ptr dest_mgr = NULL;
  FILE * input_file;
  FILE * output_file;
  JDIMENSION num_scanlines;

  /* On Mac, fetch a command line. */
#ifdef USE_CCOMMAND
  argc = ccommand(&argv);
#endif

  progname = argv[0];
  if (progname == NULL || progname[0] == 0)
    progname = "djpeg";		/* in case C library doesn't provide it */

  /* Initialize the JPEG decompression object with default error handling. */
  cinfo.err = jpeg_std_error(&jerr);
  jpeg_create_decompress(&cinfo);
  /* Add some application-specific error messages (from cderror.h) */
  jerr.addon_message_table = cdjpeg_message_table;
  jerr.first_addon_message = JMSG_FIRSTADDONCODE;
  jerr.last_addon_message = JMSG_LASTADDONCODE;

  /* Insert custom marker processor for COM and APP12.
   * APP12 is used by some digital camera makers for textual info,
   * so we provide the ability to display it as text.
   * If you like, additional APPn marker types can be selected for display,
   * but don't try to override APP0 or APP14 this way (see libjpeg.doc).
   */
  jpeg_set_marker_processor(&cinfo, JPEG_COM, print_text_marker);
  jpeg_set_marker_processor(&cinfo, JPEG_APP0+12, print_text_marker);

  /* Now safe to enable signal catcher. */
#ifdef NEED_SIGNAL_CATCHER
  enable_signal_catcher((j_common_ptr) &cinfo);
#endif

  /* Scan command line to find file names. */
  /* It is convenient to use just one switch-parsing routine, but the switch
   * values read here are ignored; we will rescan the switches after opening
   * the input file.
   * (Exception: tracing level set here controls verbosity for COM markers
   * found during jpeg_read_header...)
   */

  file_index = parse_switches(&cinfo, argc, argv, 0, FALSE);

#ifdef TWO_FILE_COMMANDLINE
  /* Must have either -outfile switch or explicit output file name */
  if (outfilename == NULL) {
    if (file_index != argc-2) {
      fprintf(stderr, "%s: must name one input and one output file\n",
	      progname);
      usage();
    }
    outfilename = argv[file_index+1];
  } else {
    if (file_index != argc-1) {
      fprintf(stderr, "%s: must name one input and one output file\n",
	      progname);
      usage();
    }
  }
#else
  /* Unix style: expect zero or one file name */
  if (file_index < argc-1) {
    fprintf(stderr, "%s: only one input file\n", progname);
    usage();
  }
#endif /* TWO_FILE_COMMANDLINE */

  /* Open the input file. */
  if (file_index < argc) {
    if ((input_file = fopen(argv[file_index], READ_BINARY)) == NULL) {
      fprintf(stderr, "%s: can't open %s\n", progname, argv[file_index]);
      exit(EXIT_FAILURE);
    }
  } else {
    /* default input file is stdin */
    input_file = read_stdin();
  }

  /* Open the output file. */
  if (outfilename != NULL) {
    if ((output_file = fopen(outfilename, WRITE_BINARY)) == NULL) {
      fprintf(stderr, "%s: can't open %s\n", progname, outfilename);
      exit(EXIT_FAILURE);
    }
  } else {
    /* default output file is stdout */
    output_file = write_stdout();
  }

#ifdef PROGRESS_REPORT
  start_progress_monitor((j_common_ptr) &cinfo, &progress);
#endif

  /* Specify data source for decompression */
  jpeg_stdio_src(&cinfo, input_file);

  /* Read file header, set default decompression parameters */
  (void) jpeg_read_header(&cinfo, TRUE);

  /* Adjust default decompression parameters by re-parsing the options */
  file_index = parse_switches(&cinfo, argc, argv, 0, TRUE);

  /* Initialize the output module now to let it override any crucial
   * option settings (for instance, GIF wants to force color quantization).
   */
  switch (requested_fmt) {
#ifdef BMP_SUPPORTED
  case FMT_BMP:
    dest_mgr = jinit_write_bmp(&cinfo, FALSE);
    break;
  case FMT_OS2:
    dest_mgr = jinit_write_bmp(&cinfo, TRUE);
    break;
#endif
#ifdef GIF_SUPPORTED
  case FMT_GIF:
    dest_mgr = jinit_write_gif(&cinfo);
    break;
#endif
#ifdef PPM_SUPPORTED
  case FMT_PPM:
    dest_mgr = jinit_write_ppm(&cinfo);
    break;
#endif
#ifdef RLE_SUPPORTED
  case FMT_RLE:
    dest_mgr = jinit_write_rle(&cinfo);
    break;
#endif
#ifdef TARGA_SUPPORTED
  case FMT_TARGA:
    dest_mgr = jinit_write_targa(&cinfo);
    break;
#endif
  default:
    ERREXIT(&cinfo, JERR_UNSUPPORTED_FORMAT);
    break;
  }
  dest_mgr->output_file = output_file;

  /* Start decompressor */
  (void) jpeg_start_decompress(&cinfo);

  /* Write output file header */
  (*dest_mgr->start_output) (&cinfo, dest_mgr);

  /* Process data */
  while (cinfo.output_scanline < cinfo.output_height) {
    num_scanlines = jpeg_read_scanlines(&cinfo, dest_mgr->buffer,
					dest_mgr->buffer_height);
    (*dest_mgr->put_pixel_rows) (&cinfo, dest_mgr, num_scanlines);
  }

#ifdef PROGRESS_REPORT
  /* Hack: count final pass as done in case finish_output does an extra pass.
   * The library won't have updated completed_passes.
   */
  progress.pub.completed_passes = progress.pub.total_passes;
#endif

  /* Finish decompression and release memory.
   * I must do it in this order because output module has allocated memory
   * of lifespan JPOOL_IMAGE; it needs to finish before releasing memory.
   */
  (*dest_mgr->finish_output) (&cinfo, dest_mgr);
  (void) jpeg_finish_decompress(&cinfo);
  jpeg_destroy_decompress(&cinfo);

  /* Close files, if we opened them */
  if (input_file != stdin)
    fclose(input_file);
  if (output_file != stdout)
    fclose(output_file);

#ifdef PROGRESS_REPORT
  end_progress_monitor((j_common_ptr) &cinfo);
#endif

  /* All done. */
  exit(jerr.num_warnings ? EXIT_WARNING : EXIT_SUCCESS);
  return 0;			/* suppress no-return-value warnings */
}
Exemplo n.º 28
0
/*
  sockfdp is a pointer to an established stream or CURL_SOCKET_BAD

  if sockfd is CURL_SOCKET_BAD, listendfd is a listening socket we must
  accept()
*/
static bool juggle(curl_socket_t *sockfdp,
                   curl_socket_t listenfd,
                   enum sockmode *mode)
{
  struct timeval timeout;
  fd_set fds_read;
  fd_set fds_write;
  fd_set fds_err;
  curl_socket_t sockfd = CURL_SOCKET_BAD;
  int maxfd = -99;
  ssize_t rc;
  ssize_t nread_socket;
  ssize_t bytes_written;
  ssize_t buffer_len;
  int error = 0;

 /* 'buffer' is this excessively large only to be able to support things like
    test 1003 which tests exceedingly large server response lines */
  unsigned char buffer[17010];
  char data[16];

  if(got_exit_signal) {
    logmsg("signalled to die, exiting...");
    return FALSE;
  }

#ifdef HAVE_GETPPID
  /* As a last resort, quit if sockfilt process becomes orphan. Just in case
     parent ftpserver process has died without killing its sockfilt children */
  if(getppid() <= 1) {
    logmsg("process becomes orphan, exiting");
    return FALSE;
  }
#endif

  timeout.tv_sec = 120;
  timeout.tv_usec = 0;

  FD_ZERO(&fds_read);
  FD_ZERO(&fds_write);
  FD_ZERO(&fds_err);

  FD_SET((curl_socket_t)fileno(stdin), &fds_read);

  switch(*mode) {

  case PASSIVE_LISTEN:

    /* server mode */
    sockfd = listenfd;
    /* there's always a socket to wait for */
    FD_SET(sockfd, &fds_read);
    maxfd = (int)sockfd;
    break;

  case PASSIVE_CONNECT:

    sockfd = *sockfdp;
    if(CURL_SOCKET_BAD == sockfd) {
      /* eeek, we are supposedly connected and then this cannot be -1 ! */
      logmsg("socket is -1! on %s:%d", __FILE__, __LINE__);
      maxfd = 0; /* stdin */
    }
    else {
      /* there's always a socket to wait for */
      FD_SET(sockfd, &fds_read);
#ifdef USE_WINSOCK
      FD_SET(sockfd, &fds_err);
#endif
      maxfd = (int)sockfd;
    }
    break;

  case ACTIVE:

    sockfd = *sockfdp;
    /* sockfd turns CURL_SOCKET_BAD when our connection has been closed */
    if(CURL_SOCKET_BAD != sockfd) {
      FD_SET(sockfd, &fds_read);
#ifdef USE_WINSOCK
      FD_SET(sockfd, &fds_err);
#endif
      maxfd = (int)sockfd;
    }
    else {
      logmsg("No socket to read on");
      maxfd = 0;
    }
    break;

  case ACTIVE_DISCONNECT:

    logmsg("disconnected, no socket to read on");
    maxfd = 0;
    sockfd = CURL_SOCKET_BAD;
    break;

  } /* switch(*mode) */


  do {

    /* select() blocking behavior call on blocking descriptors please */

    rc = select(maxfd + 1, &fds_read, &fds_write, &fds_err, &timeout);

    if(got_exit_signal) {
      logmsg("signalled to die, exiting...");
      return FALSE;
    }

  } while((rc == -1) && ((error = errno) == EINTR));

  if(rc < 0) {
    logmsg("select() failed with error: (%d) %s",
           error, strerror(error));
    return FALSE;
  }

  if(rc == 0)
    /* timeout */
    return TRUE;


  if(FD_ISSET(fileno(stdin), &fds_read)) {
    /* read from stdin, commands/data to be dealt with and possibly passed on
       to the socket

       protocol:

       4 letter command + LF [mandatory]

       4-digit hexadecimal data length + LF [if the command takes data]
       data                       [the data being as long as set above]

       Commands:

       DATA - plain pass-thru data
    */

    if(!read_stdin(buffer, 5))
      return FALSE;

    logmsg("Received %c%c%c%c (on stdin)",
           buffer[0], buffer[1], buffer[2], buffer[3] );

    if(!memcmp("PING", buffer, 4)) {
      /* send reply on stdout, just proving we are alive */
      if(!write_stdout("PONG\n", 5))
        return FALSE;
    }

    else if(!memcmp("PORT", buffer, 4)) {
      /* Question asking us what PORT number we are listening to.
         Replies to PORT with "IPv[num]/[port]" */
      sprintf((char *)buffer, "%s/%hu\n", ipv_inuse, port);
      buffer_len = (ssize_t)strlen((char *)buffer);
      snprintf(data, sizeof(data), "PORT\n%04zx\n", buffer_len);
      if(!write_stdout(data, 10))
        return FALSE;
      if(!write_stdout(buffer, buffer_len))
        return FALSE;
    }
    else if(!memcmp("QUIT", buffer, 4)) {
      /* just die */
      logmsg("quits");
      return FALSE;
    }
    else if(!memcmp("DATA", buffer, 4)) {
      /* data IN => data OUT */

      if(!read_stdin(buffer, 5))
        return FALSE;

      buffer[5] = '\0';

      buffer_len = (ssize_t)strtol((char *)buffer, NULL, 16);
      if (buffer_len > (ssize_t)sizeof(buffer)) {
        logmsg("ERROR: Buffer size (%zu bytes) too small for data size "
               "(%zd bytes)", sizeof(buffer), buffer_len);
        return FALSE;
      }
      logmsg("> %zd bytes data, server => client", buffer_len);

      if(!read_stdin(buffer, buffer_len))
        return FALSE;

      lograw(buffer, buffer_len);

      if(*mode == PASSIVE_LISTEN) {
        logmsg("*** We are disconnected!");
        if(!write_stdout("DISC\n", 5))
          return FALSE;
      }
      else {
        /* send away on the socket */
        bytes_written = swrite(sockfd, buffer, buffer_len);
        if(bytes_written != buffer_len) {
          logmsg("Not all data was sent. Bytes to send: %zd sent: %zd",
                 buffer_len, bytes_written);
        }
      }
    }
    else if(!memcmp("DISC", buffer, 4)) {
      /* disconnect! */
      if(!write_stdout("DISC\n", 5))
        return FALSE;
      if(sockfd != CURL_SOCKET_BAD) {
        logmsg("====> Client forcibly disconnected");
        sclose(sockfd);
        *sockfdp = CURL_SOCKET_BAD;
        if(*mode == PASSIVE_CONNECT)
          *mode = PASSIVE_LISTEN;
        else
          *mode = ACTIVE_DISCONNECT;
      }
      else
        logmsg("attempt to close already dead connection");
      return TRUE;
    }
  }


  if((sockfd != CURL_SOCKET_BAD) && (FD_ISSET(sockfd, &fds_read)) ) {

    curl_socket_t newfd = CURL_SOCKET_BAD; /* newly accepted socket */

    if(*mode == PASSIVE_LISTEN) {
      /* there's no stream set up yet, this is an indication that there's a
         client connecting. */
      newfd = accept(sockfd, NULL, NULL);
      if(CURL_SOCKET_BAD == newfd) {
        error = SOCKERRNO;
        logmsg("accept(%d, NULL, NULL) failed with error: (%d) %s",
               sockfd, error, strerror(error));
      }
      else {
        logmsg("====> Client connect");
        if(!write_stdout("CNCT\n", 5))
          return FALSE;
        *sockfdp = newfd; /* store the new socket */
        *mode = PASSIVE_CONNECT; /* we have connected */
      }
      return TRUE;
    }

    /* read from socket, pass on data to stdout */
    nread_socket = sread(sockfd, buffer, sizeof(buffer));

    if(nread_socket > 0) {
      snprintf(data, sizeof(data), "DATA\n%04zx\n", nread_socket);
      if(!write_stdout(data, 10))
        return FALSE;
      if(!write_stdout(buffer, nread_socket))
        return FALSE;

      logmsg("< %zd bytes data, client => server", nread_socket);
      lograw(buffer, nread_socket);
    }

    if(nread_socket <= 0
#ifdef USE_WINSOCK
       || FD_ISSET(sockfd, &fds_err)
#endif
       ) {
      logmsg("====> Client disconnect");
      if(!write_stdout("DISC\n", 5))
        return FALSE;
      sclose(sockfd);
      *sockfdp = CURL_SOCKET_BAD;
      if(*mode == PASSIVE_CONNECT)
        *mode = PASSIVE_LISTEN;
      else
        *mode = ACTIVE_DISCONNECT;
      return TRUE;
    }
  }

  return TRUE;
}
Exemplo n.º 29
0
int
main (int argc, char **argv)
{

  int i;
  int lo_fd;
  fd_set rfds;
  struct timeval tv;
  int retval;
  int done = 0;
  int loadOK = 0;

  funcion = 0;
  gui.Pexit = 0 ;
  gui.Pexitprogram = 0;
  gui.ready = 0;
  gui.D_Vol_c = 0;
  gui.D_Tune_c = 0;
  gui.D_Portamento_c = 0;
  gui.D_LFO_Volume_c = 0;
  gui.D_LFO_Frequency_c = 0;
  gui.D_LFO_Delay_c = 0;
  gui.D_LFO_Wave_c = 0;
  gui.cop = 0;
  for (i = 0; i < 6; i++)
    {
      gui.D_Wave_c[i] = 0;
      gui.D_H_c[i] = 0;
      gui.D_HF_c[i] = 0;
      gui.D_OVol_c[i] = 0;
      gui.D_pLFO_c[i] = 0;
      gui.D_Attack_c[i] = 0;
      gui.D_Decay_c[i] = 0;
      gui.D_Sustain_c[i] = 0;
      gui.D_Release_c[i] = 0;
    }

  gui.D_Ftype_c = 0;
  gui.D_Fgain_c = 0;
  gui.D_Fcutoff_c = 0;
  gui.D_Fq_c = 0;
  gui.D_FLFO_c = 0;
  gui.D_FADSR_c = 0;
  gui.D_Fstages_c = 0;
  gui.D_Fvelocity_c = 0;
  gui.D_Algo_c = 0;


  New ();
  New_Bank ();
  char *url = argv[1];
  char *host = lo_url_get_hostname (url);
  char *port = lo_url_get_port (url);
  char *path = lo_url_get_path (url);
  char *label = argv[3];
  char *temp;


  pthread_create (&thr1, NULL, thread1, NULL);
  gui.ui_win->copy_label (argv[3]);
  gui.ui_win->show ();

  sprintf (gui.uBankFilename, "%s/Default.goomf", DATADIR);
  loadOK = loadbank (gui.uBankFilename);




  osc_server = 0;
  m_host = lo_address_new (host, port);

  osc_configure_path = osc_build_path (path, "/configure");
  osc_control_path = osc_build_path (path, "/control");
  osc_exiting_path = osc_build_path (path, "/exiting");
  osc_hide_path = osc_build_path (path, "/hide");
  osc_midi_path = osc_build_path (path, "/midi");
  osc_program_path = osc_build_path (path, "/program");
  osc_quit_path = osc_build_path (path, "/quit");
  osc_show_path = osc_build_path (path, "/show");
  osc_update_path = osc_build_path (path, "/update");

  osc_server = lo_server_new (NULL, osc_error);

  lo_server_add_method (osc_server, osc_configure_path, "ss",
			configure_handler, NULL);
  lo_server_add_method (osc_server, osc_control_path, "if", control_handler,
			NULL);
  lo_server_add_method (osc_server, osc_hide_path, "", hide_handler, NULL);
  lo_server_add_method (osc_server, osc_program_path, "ii", program_handler,
			NULL);
  lo_server_add_method (osc_server, osc_quit_path, "", quit_handler, NULL);
  lo_server_add_method (osc_server, osc_exiting_path, "", exiting_handler,
			NULL);
  lo_server_add_method (osc_server, osc_show_path, "", show_handler, NULL);
  lo_server_add_method (osc_server, NULL, NULL, debug_handler, NULL);

  temp = lo_server_get_url (osc_server);
  myurl = osc_build_path (temp, (strlen (path) > 1 ? path + 1 : path));
  lo_send (m_host, osc_update_path, "s", myurl);
  sleep (2);
  gui.d_osc_label->copy_label (myurl);
  gui.d_osc_label->redraw ();
  if (!loadOK)
    Send_laristra ();


  lo_fd = lo_server_get_socket_fd (osc_server);

  if (lo_fd > 0)
    {

      do
	{
	  FD_ZERO (&rfds);
	  FD_SET (lo_fd, &rfds);

	  retval = select (lo_fd + 1, &rfds, NULL, NULL, NULL);

	  if (retval == -1)
	    {
	      printf ("select() error\n");
	      exit (1);

	    }
	  else if (retval > 0)

	    {

	      if (FD_ISSET (0, &rfds))
		{
		  read_stdin ();
		}
	      if (FD_ISSET (lo_fd, &rfds))
		{
		  lo_server_recv_noblock (osc_server, 0);
		}
	    }


	}
      while (!done);

    }
  else
    {

      do
	{
	  FD_ZERO (&rfds);
	  FD_SET (0, &rfds);
	  tv.tv_sec = 0;
	  tv.tv_usec = 10000;

	  retval = select (1, &rfds, NULL, NULL, &tv);

	  if (retval == -1)
	    {

	      printf ("select() error\n");
	      exit (1);

	    }
	  else if (retval > 0 && FD_ISSET (0, &rfds))
	    {

	      read_stdin ();

	    }

	  lo_server_recv_noblock (osc_server, 0);



	}
      while (!done);

    }





  free (host);
  free (port);
  free (path);
  free (osc_configure_path);
  free (osc_control_path);
  free (osc_exiting_path);
  free (osc_hide_path);
  free (osc_midi_path);
  free (osc_program_path);
  free (osc_quit_path);
  free (osc_show_path);
  free (osc_update_path);
  free (myurl);


  return (0);





}
Exemplo n.º 30
0
int
main (int argc, char **argv)
{
  struct jpeg_compress_struct cinfo;
  struct jpeg_error_mgr jerr;
#ifdef PROGRESS_REPORT
  struct cdjpeg_progress_mgr progress;
#endif
  int file_index;
  cjpeg_source_ptr src_mgr;
  FILE * input_file;
  FILE * output_file;
  JDIMENSION num_scanlines;

  /* On Mac, fetch a command line. */
#ifdef USE_CCOMMAND
  argc = ccommand(&argv);
#endif

  progname = argv[0];
  if (progname == NULL || progname[0] == 0)
    progname = "cjpeg";		/* in case C library doesn't provide it */

  /* Initialize the JPEG compression object with default error handling. */
  cinfo.err = jpeg_std_error(&jerr);
  jpeg_create_compress(&cinfo);
  /* Add some application-specific error messages (from cderror.h) */
  jerr.addon_message_table = cdjpeg_message_table;
  jerr.first_addon_message = JMSG_FIRSTADDONCODE;
  jerr.last_addon_message = JMSG_LASTADDONCODE;

  /* Now safe to enable signal catcher. */
#ifdef NEED_SIGNAL_CATCHER
  enable_signal_catcher((j_common_ptr) &cinfo);
#endif

  /* Initialize JPEG parameters.
   * Much of this may be overridden later.
   * In particular, we don't yet know the input file's color space,
   * but we need to provide some value for jpeg_set_defaults() to work.
   */

  cinfo.in_color_space = JCS_RGB; /* arbitrary guess */
  jpeg_set_defaults(&cinfo);

  /* Scan command line to find file names.
   * It is convenient to use just one switch-parsing routine, but the switch
   * values read here are ignored; we will rescan the switches after opening
   * the input file.
   */

  file_index = parse_switches(&cinfo, argc, argv, 0, FALSE);

#ifdef TWO_FILE_COMMANDLINE
  /* Must have either -outfile switch or explicit output file name */
  if (outfilename == NULL) {
    if (file_index != argc-2) {
      fprintf(stderr, "%s: must name one input and one output file\n",
	      progname);
      usage();
    }
    outfilename = argv[file_index+1];
  } else {
    if (file_index != argc-1) {
      fprintf(stderr, "%s: must name one input and one output file\n",
	      progname);
      usage();
    }
  }
#else
  /* Unix style: expect zero or one file name */
  if (file_index < argc-1) {
    fprintf(stderr, "%s: only one input file\n", progname);
    usage();
  }
#endif /* TWO_FILE_COMMANDLINE */

  /* Open the input file. */
  if (file_index < argc) {
    if ((input_file = fopen(argv[file_index], READ_BINARY)) == NULL) {
      fprintf(stderr, "%s: can't open %s\n", progname, argv[file_index]);
      exit(EXIT_FAILURE);
    }
  } else {
    /* default input file is stdin */
    input_file = read_stdin();
  }

  /* Open the output file. */
  if (outfilename != NULL) {
    if ((output_file = fopen(outfilename, WRITE_BINARY)) == NULL) {
      fprintf(stderr, "%s: can't open %s\n", progname, outfilename);
      exit(EXIT_FAILURE);
    }
  } else {
    /* default output file is stdout */
    output_file = write_stdout();
  }

#ifdef PROGRESS_REPORT
  start_progress_monitor((j_common_ptr) &cinfo, &progress);
#endif

  /* Figure out the input file format, and set up to read it. */
  src_mgr = select_file_type(&cinfo, input_file);
  src_mgr->input_file = input_file;

  /* Read the input file header to obtain file size & colorspace. */
  (*src_mgr->start_input) (&cinfo, src_mgr);

  /* Now that we know input colorspace, fix colorspace-dependent defaults */
  jpeg_default_colorspace(&cinfo);

  /* Adjust default compression parameters by re-parsing the options */
  file_index = parse_switches(&cinfo, argc, argv, 0, TRUE);

  /* Specify data destination for compression */
  jpeg_stdio_dest(&cinfo, output_file);

  /* Start compressor */
  jpeg_start_compress(&cinfo, TRUE);

  /* Process data */
  while (cinfo.next_scanline < cinfo.image_height) {
    num_scanlines = (*src_mgr->get_pixel_rows) (&cinfo, src_mgr);
    (void) jpeg_write_scanlines(&cinfo, src_mgr->buffer, num_scanlines);
  }

  /* Finish compression and release memory */
  (*src_mgr->finish_input) (&cinfo, src_mgr);
  jpeg_finish_compress(&cinfo);
  jpeg_destroy_compress(&cinfo);

  /* Close files, if we opened them */
  if (input_file != stdin)
    fclose(input_file);
  if (output_file != stdout)
    fclose(output_file);

#ifdef PROGRESS_REPORT
  end_progress_monitor((j_common_ptr) &cinfo);
#endif

  /* All done. */
  exit(jerr.num_warnings ? EXIT_WARNING : EXIT_SUCCESS);
  return 0;			/* suppress no-return-value warnings */
}