Example #1
0
/* Input is available on the given connection.  Add it to the input buffer and
 * see if there are any complete lines in it.
 */
static void add_input(struct file_info *fi){
	fi->input_buffer = realloc(fi->input_buffer, fi->amount_received + 100);
	int n = read(fi->fd, &fi->input_buffer[fi->amount_received], 100);
	if (n < 0) {
		perror("read");
		exit(1);
	}
	if (n > 0) {
		fi->amount_received += n;
		for (;;) {
			char *p = index(fi->input_buffer, '\n');
			if (p == 0) {
				break;
			}
			*p++ = 0;
			handle_line(fi, fi->input_buffer);
			int n = fi->amount_received - (p - fi->input_buffer);
			memmove(fi->input_buffer, p, n);
			fi->amount_received = n;
			if (fi->fd == 0) {
				printf("> ");
				fflush(stdout);
			}
		}
	}
}
Example #2
0
void process_user_input(int fd, struct user_iobuf *userbuf, 
			void (*handle_line)(char *, void *), void *cbdata)
{
  int nread;
  char *ret;

  assert(userbuf != NULL);
  assert(userbuf->buf != NULL);

  /* A real program would propagate this error back to the select loop or
   * implement some other form of error handling */

  if (userbuf->cur >= (USERBUF_SIZE - 1)) {
    fprintf(stderr, "process_user_input error:  buffer full;  line too long!\n");
    exit(-1);
  }

  nread = read(fd, userbuf->buf + userbuf->cur, 
	       (USERBUF_SIZE - userbuf->cur));

  if (nread > 0) {
    userbuf->cur += nread;
  }

 while ((ret = strchr(userbuf->buf, '\n')) != NULL) {
  *ret = '\0';
  handle_line(userbuf->buf, cbdata);
  /* Shift the remaining contents of the buffer forward */
  memmove(userbuf->buf, ret + 1, USERBUF_SIZE - (ret - userbuf->buf));
  userbuf->cur -= (ret - userbuf->buf + 1);
 }

}
Example #3
0
int main(void)
{
    char line_buf[LINE_SIZE];
    int with_title = 1;
    int ret;
    int done = 0;

    af86.init();
    print_greeting(&af86);
    while (1) {
        print_prompt(&af86, with_title, done);
        with_title = 0;
        memset(line_buf, 0, LINE_SIZE);
        if (read_line(line_buf) < 0)
            break;

        ret = handle_line(&af86, line_buf);
        if (ret < 0)
            break;
        else if (ret == 1)
            with_title = 1;
        else if (ret == 2)
            done = 1;
        else if (ret == 3) {
            with_title = 1;
            done = 0;
        }
    }
    return 0;
}
struct osmo_config_list *osmo_config_list_parse(void *ctx, const char *filename)
{
	struct osmo_config_list *entries;
	size_t n;
	char *line;
	FILE *file;

	file = fopen(filename, "r");
	if (!file)
		return NULL;

	entries = alloc_entries(ctx);
	if (!entries) {
		fclose(file);
		return NULL;
	}

	n = 2342;
	line = NULL;
        while (getline(&line, &n, file) != -1) {
		handle_line(entries, line);
		free(line);
		line = NULL;
	}

	fclose(file);
	return entries;
}
Example #5
0
void doit()
{
  char ch;
  int match = 1;
  long linenum = 0;
  stralloc fifoline = { 0 };

  linenum = 0;

  /* try duming data in 23 seconds */
  alarm(dumpfreq);

  buffer_putsflush(buffer_2, ARGV0 "entering main loop\n");

  /* forever read from pipe line by line and handle it */
  while(1)
    {
      while(match) 
	{
	  if(flagdumpasap == 1) 
	    dumpcheck(flagdumpasap, flagchanged, flagchildrunning, flagsighup);

	  ++linenum;
	  if(buffer_get(&wr, &ch, 1) == 1)
	    {
	      if(getln(&wr, &fifoline, &match, '\n') == -1)
		continue;
	      buffer_put(buffer_2, &ch, 1);
	      buffer_putflush(buffer_2, fifoline.s, fifoline.len);
	      handle_line(&fifoline, ch);
	    }
	}
    }
}
Example #6
0
rdConfUnit* rdConfLoader::load_conf(const char* conf_filename) 
{
    std::ifstream conf_file(conf_filename, std::ifstream::in);
    if (conf_file.fail()) {
        return NULL;
    }

    char line[MAX_LINE_LEN];
    rdConfUnit* root = new(std::nothrow) rdConfUnit(rdConfUnit::UT_GROUP);
    if (NULL != root) {
        rdConfUnit* current = root;
        while (conf_file.good()) {
            conf_file.getline(line, MAX_LINE_LEN);

            if (is_white_line(line) || is_comment_line(line)) {
                continue;
            }

            if (0 != handle_line(line, root, current)) {
                delete root;
                root = NULL;
                break;
            }
        }
    }

    conf_file.close();
    return root;
}
Example #7
0
File: cmd.c Project: agadiffe/ft_sh
void			handle_shell_entry(char *line, t_state *state)
{
	char	**cmds;
	char	*new_line;
	char	*tmp;
	int		i;

	i = 0;
	cmds = ft_strsplitwith_quote(line, ";", 0);
	state->cmds_shell_entry_to_free_in_fork = cmds;
	if (cmds)
	{
		while (cmds[i])
		{
			state->env_saved = 0;
			tmp = set_dollar_variable(state->env, cmds[i]);
			ft_strdel(&cmds[i]);
			new_line = set_tilde_variable(state->home, tmp);
			state->new_line_shell_entry_to_free_in_fork = new_line;
			ft_strdel(&tmp);
			handle_line(state, new_line);
			ft_strdel(&new_line);
			i++;
		}
		ft_memdel((void **)&cmds);
	}
}
Example #8
0
int fmt_merge_msg(struct strbuf *in, struct strbuf *out,
		  struct fmt_merge_msg_opts *opts)
{
	int i = 0, pos = 0;
	unsigned char head_sha1[20];
	const char *current_branch;
	void *current_branch_to_free;

	/* get current branch */
	current_branch = current_branch_to_free =
		resolve_refdup("HEAD", head_sha1, 1, NULL);
	if (!current_branch)
		die("No current branch");
	if (!prefixcmp(current_branch, "refs/heads/"))
		current_branch += 11;

	/* get a line */
	while (pos < in->len) {
		int len;
		char *newline, *p = in->buf + pos;

		newline = strchr(p, '\n');
		len = newline ? newline - p : strlen(p);
		pos += len + !!newline;
		i++;
		p[len] = 0;
		if (handle_line(p))
			die ("Error in line %d: %.*s", i, len, p);
	}

	if (opts->add_title && srcs.nr)
		fmt_merge_msg_title(out, current_branch);

	if (origins.nr)
		fmt_merge_msg_sigs(out);

	if (opts->shortlog_len) {
		struct commit *head;
		struct rev_info rev;

		head = lookup_commit_or_die(head_sha1, "HEAD");
		init_revisions(&rev, NULL);
		rev.commit_format = CMIT_FMT_ONELINE;
		rev.ignore_merges = 1;
		rev.limited = 1;

		if (suffixcmp(out->buf, "\n"))
			strbuf_addch(out, '\n');

		for (i = 0; i < origins.nr; i++)
			shortlog(origins.items[i].string,
				 origins.items[i].util,
				 head, &rev, opts->shortlog_len, out);
	}

	strbuf_complete_line(out);
	free(current_branch_to_free);
	return 0;
}
Example #9
0
void Preprocessor::preprocess(string raw_code) {
    vector<string> code_vector;
    code_vector = read_line(raw_code, code_vector);

    for (int i = 0; i < code_vector.size(); i++) {
        string line = code_vector[i];
        handle_line(line);
    }
}
Example #10
0
int read_config (char *filename, struct parsedfile *config) {
	FILE *conf;
	char line[MAXLINE];
	int rc = 0;
	int lineno = 1;
	struct serverent *server;

   /* Clear out the structure */
   memset(config, 0x0, sizeof(*config));

	/* Initialization */
   currentcontext = &(config->defaultserver);

	/* If a filename wasn't provided, use the default */
	if (filename == NULL) {
		strncpy(line, CONF_FILE, sizeof(line) - 1);
		/* Insure null termination */
		line[sizeof(line) - 1] = (char) 0;
		filename = line;
	}

	/* Read the configuration file */
	if ((conf = fopen(filename, "r")) == NULL) {
		show_msg(MSGERR, "Could not open socks configuration file "
			   "(%s), assuming all networks local\n", filename);
      handle_local(config, 0, "0.0.0.0/0.0.0.0");
		rc = 1; /* Severe errors reading configuration */
	}	
	else {
      memset(&(config->defaultserver), 0x0, sizeof(config->defaultserver));

		while (NULL != fgets(line, MAXLINE, conf)) {
			/* This line _SHOULD_ end in \n so we  */
			/* just chop off the \n and hand it on */
			if (strlen(line) > 0)
				line[strlen(line) - 1] = '\0';
			handle_line(config, line, lineno);
			lineno++;
		} 
		fclose(conf);

		/* Always add the 127.0.0.1/255.0.0.0 subnet to local */
		handle_local(config, 0, "127.0.0.0/255.0.0.0");

		/* Check default server */
		check_server(&(config->defaultserver));
		server = (config->paths);
		while (server != NULL) {
			check_server(server);
			server = server->next;
		}

	}

	return(rc);
}
Example #11
0
void Netlist::process_file() {
  std::ifstream data(file_name.c_str());
  if (!data) throw FileNotFound("Cannot open file \"" + file_name + "\"");
  std::string line;
  std::getline(data, title);
  number_of_nodes = atoi(title.c_str());
  while (std::getline(data, line)) {
    handle_line(line);
  }
}
Example #12
0
SR_PRIV int fluke_receive_data(int fd, int revents, void *cb_data)
{
	struct sr_dev_inst *sdi;
	struct dev_context *devc;
	struct sr_serial_dev_inst *serial;
	int len;
	int64_t now, elapsed;

	(void)fd;

	if (!(sdi = cb_data))
		return TRUE;

	if (!(devc = sdi->priv))
		return TRUE;

	serial = sdi->conn;
	if (revents == G_IO_IN) {
		/* Serial data arrived. */
		while (FLUKEDMM_BUFSIZE - devc->buflen - 1 > 0) {
			len = serial_read_nonblocking(serial, devc->buf + devc->buflen, 1);
			if (len < 1)
				break;
			devc->buflen++;
			*(devc->buf + devc->buflen) = '\0';
			if (*(devc->buf + devc->buflen - 1) == '\r') {
				*(devc->buf + --devc->buflen) = '\0';
				handle_line(sdi);
				break;
			}
		}
	}

	if (sr_sw_limits_check(&devc->limits)) {
		sdi->driver->dev_acquisition_stop(sdi);
		return TRUE;
	}

	now = g_get_monotonic_time() / 1000;
	elapsed = now - devc->cmd_sent_at;
	/* Send query command at poll_period interval, or after 1 second
	 * has elapsed. This will make it easier to recover from any
	 * out-of-sync or temporary disconnect issues. */
	if ((devc->expect_response == FALSE && elapsed > devc->profile->poll_period)
			|| elapsed > devc->profile->timeout) {
		if (serial_write_blocking(serial, "QM\r", 3, SERIAL_WRITE_TIMEOUT_MS) < 0)
			sr_err("Unable to send QM.");
		devc->cmd_sent_at = now;
		devc->expect_response = TRUE;
	}

	return TRUE;
}
Example #13
0
SR_PRIV int fluke_receive_data(int fd, int revents, void *cb_data)
{
	struct sr_dev_inst *sdi;
	struct dev_context *devc;
	int len;
	int64_t now, elapsed;

	(void)fd;

	if (!(sdi = cb_data))
		return TRUE;

	if (!(devc = sdi->priv))
		return TRUE;

	if (revents == G_IO_IN) {
		/* Serial data arrived. */
		while(FLUKEDMM_BUFSIZE - devc->buflen - 1 > 0) {
			len = serial_read(devc->serial, devc->buf + devc->buflen, 1);
			if (len < 1)
				break;
			devc->buflen++;
			*(devc->buf + devc->buflen) = '\0';
			if (*(devc->buf + devc->buflen - 1) == '\r') {
				*(devc->buf + --devc->buflen) = '\0';
				handle_line(sdi);
				break;
			}
		}
	}

	if (devc->num_samples >= devc->limit_samples) {
		sdi->driver->dev_acquisition_stop(sdi, cb_data);
		return TRUE;
	}

	now = g_get_monotonic_time() / 1000;
	elapsed = now - devc->cmd_sent_at;
	/* Send query command at poll_period interval, or after 1 second
	 * has elapsed. This will make it recover from any out-of-sync
	 * or temporary disconnect issues. */
	if ((devc->expect_response == FALSE && elapsed > devc->profile->poll_period)
			|| elapsed > 1000) {
		sr_spew("Sending QM.");
		if (serial_write(devc->serial, "QM\r", 3) == -1)
			sr_err("Unable to send QM: %s.", strerror(errno));
		devc->cmd_sent_at = now;
		devc->expect_response = TRUE;
	}

	return TRUE;
}
void SocketConnection::on_read_ready()
{
	std::vector<char> buffer(4096);
	const ssize_t received = ::recv(socket_, buffer.data(), buffer.size(), MSG_DONTWAIT);

	if (received < 0)
	{
		if (errno == EAGAIN || errno == EWOULDBLOCK)
			return;

		if (errno == EPIPE || errno == ETIMEDOUT || errno == ECONNRESET)
		{
			DH_LOG(Warning) << "recv error, connection closed: " << ::strerror(errno);
			handle_error();
			return;
		}

		DH_LOG(Error) << "recv error: " << ::strerror(errno);
		throw std::runtime_error( std::string("recv error: ") + ::strerror(errno) );
	}
	else if (received == 0)
		return;

	read_buffer_.append(buffer.data(), received);
	std::vector<char>().swap(buffer);

	size_t start = 0, end = 0;
	while (true)
	{
		end = read_buffer_.find_first_of("\r\n", start);
		if (end == std::string::npos)
		{
			read_buffer_.replace(0, start, std::string());
			break;
		}

		const std::string line = read_buffer_.substr(start, end - start);
		if (line.find_first_not_of(" \t") != std::string::npos)
			handle_line( line );

		start = read_buffer_.find_first_not_of("\r\n", end);
		if (start == std::string::npos)
		{
			read_buffer_.clear();
			break;
		}
	}
}
static void handle_input(Client *c) {
    assert(c);

    for (;;) {
        char *e;
        size_t k;

        if (!(e = memchr(c->inbuf, '\n', c->inbuf_length)))
            break;

        k = e - (char*) c->inbuf;
        *e = 0;

        handle_line(c, c->inbuf);
        c->inbuf_length -= k + 1;
        memmove(c->inbuf, e+1, c->inbuf_length);
    }
}
Example #16
0
File: imap.c Project: SirCmpwn/aerc
static void test_handle_line_known_handler(void **state) {
	int _;
	struct imap_connection *imap = malloc(sizeof(struct imap_connection));
	imap_init(imap);

	imap_arg_t *arg = malloc(sizeof(imap_arg_t));
	imap_parse_args("a001 FOOBAR", arg, &_);

	expect_string(__wrap_hashtable_get, key, "FOOBAR");
	will_return(__wrap_hashtable_get, test_handler);

	handle_line(imap, arg);

	assert_int_equal(handler_called, 1);

	free(arg);
	imap_close(imap);
}
Example #17
0
/* filedandler for fill_db() */
int readfileintodb(char *file, time_t ctime)
{
  uint32 uid   =  0;
  uint32 t;
  int fd;
  int match = 1;
  int linenum;
  
  fd = open_read(file);
  if(fd == -1) 
    {
      strerr_warn3("unable to open file: ", file, " ", &strerr_sys);
      return -1;
    }
  
  buffer_init(&rb, read, fd, rbspace, sizeof rbspace);
  
  /* The file might contain references to more than one user id,
     therefore we work through all lines */
  
  linenum = 0;
  while(match) 
    {
      ++linenum;
      if(getln(&rb, &line, &match, '\n') == -1)
	{
	  strerr_warn3("unable to read line: ", file, " ", &strerr_sys);
	  return -1;
	}
      
      /* skip empty lines and comments */
      if(!line.len) continue;
      if(line.s[0] == '#') continue;
      
      handle_line(&line, 's');
    }
  
  close(fd);
  
  return 0;
}
void process_user_input(int fd, struct user_iobuf *userbuf, 
			void (*handle_line)(char *, void *, bt_config_t *config, int sock), void *cbdata, 
                        bt_config_t *config, int sock)
{
  int nread;
  char *ret;
  printf("Reached here.. in process user input\n");
  assert(userbuf != NULL);
  assert(userbuf->buf != NULL);
  /* A real program would propagate this error back to the select loop or
   * implement some other form of error handling */

  if (userbuf->cur >= (USERBUF_SIZE - 1)) {
    fprintf(stderr, "process_user_input error:  buffer full;  line too long!\n");
    printf("process_user_input error:  buffer full;  line too long!\n");
    exit(-1);
  }
  printf("Reached here.. before read syscall in process user input\n");
  nread = read(fd, userbuf->buf + userbuf->cur, 
	       (USERBUF_SIZE - userbuf->cur));

  printf("Reached here.. after read syscall in process user input userbuf->buf is %s\n", userbuf->buf);
  printf("(Outside if) No. of bytes read are %d\n", nread);

  if (nread > 0) {
    printf("No. of bytes read are %d\n", nread);
    userbuf->cur += nread;
  }

 while ((ret = strchr(userbuf->buf, '\n')) != NULL) {
  printf("Entered while..\n");
  *ret = '\0';
  printf("Calling handle_line\n");
  handle_line(userbuf->buf, cbdata, config, sock);
  /* Shift the remaining contents of the buffer forward */
  memmove(userbuf->buf, ret + 1, USERBUF_SIZE - (ret - userbuf->buf));
  userbuf->cur -= (ret - userbuf->buf + 1);
 }

}
Example #19
0
File: pf.c Project: aosm/X11apps
void process_line (char *buffer)
{
    int len;
    int i;
    char *cp;

    /* copy buffer since it may point to unwritable date */
    len = strlen(buffer);
    cp = chk_malloc(len + 1);
    strcpy(cp, buffer);
    buffer = cp;
    
    for (i = 0; i < len; i++) {		/* look for blank lines */
	register char c = buffer[i];
	if (!(isspace(c) || c == '\n')) break;
    }
    if (i == len) return;

    cp = &buffer[i];

    if (*cp == '!') return;		/* look for comments */
    len -= (cp - buffer);		/* adjust len by how much we skipped */

					/* pipe through cpp */

					/* strip trailing space */
    for (i = len-1; i >= 0; i--) {
	register char c = cp[i];
	if (!(isspace(c) || c == '\n')) break;
    }
    if (i >= 0) cp[len = (i+1)] = '\0';  /* nul terminate */

    if (verbose) {
	printf ("! %d:  %s\n", lineno+1, cp);
    }

    /* handle input */
    handle_line (cp, len);
}
Example #20
0
int cmd_main(int argc, const char **argv)
{
	struct line_buffer stdin_buf = LINE_BUFFER_INIT;
	struct line_buffer file_buf = LINE_BUFFER_INIT;
	struct line_buffer *input = &stdin_buf;
	const char *filename;
	char *s;

	if (argc == 1)
		filename = NULL;
	else if (argc == 2)
		filename = argv[1];
	else
		usage("test-line-buffer [file | &fd] < script");

	if (buffer_init(&stdin_buf, NULL))
		die_errno("open error");
	if (filename) {
		if (*filename == '&') {
			if (buffer_fdinit(&file_buf, strtouint32(filename + 1)))
				die_errno("error opening fd %s", filename + 1);
		} else {
			if (buffer_init(&file_buf, filename))
				die_errno("error opening %s", filename);
		}
		input = &file_buf;
	}

	while ((s = buffer_read_line(&stdin_buf)))
		handle_line(s, input);

	if (filename && buffer_deinit(&file_buf))
		die("error reading from %s", filename);
	if (buffer_deinit(&stdin_buf))
		die("input error");
	if (ferror(stdout))
		die("output error");
	return 0;
}
Example #21
0
void read_loop(void)
{
	overclock = 1.0;
	left_a = 1.0;
	right_a = 1.0;
	tune = 1.0;
	if (!track_file)
	{
		fprintf(stderr,"Error: File is not open, nothing to read!\n");
		return;
	}
	print_head();
	char *line_buffer = (char *)malloc(sizeof(char) * LINE_BUFFER_SIZE + 1);
	memset(line_buffer,0,sizeof(char) * LINE_BUFFER_SIZE + 1);
	while (fgets(line_buffer, LINE_BUFFER_SIZE, track_file))
	{
		handle_line(line_buffer);
	}
	fclose(track_file);
	free (line_buffer);

}
Example #22
0
/* this function is repeated called in daemon normal work.
   it's job is to help the host do the send & recv work of at cmd. 
   there should be 5 status, any of the status can only be changed 
   by 'host' OR 'daemon', never both. */
void do_send_and_recv(MODAT * p)
{
	MODAT_AT_BUF *at = &p->at;
	RBUF *r = p->r;

	/* do the responses */
	switch (at->status) {
	case AT_READY:
		break;
	case AT_REQUEST:
		{
			/* host has announced a query cmd */
			int datalen, sent;
			datalen = strlen(at->send_buf);
			dbg(1, "send : %s", at->send_buf);
			sent = write(p->portfd, at->send_buf, datalen);
			if (sent != datalen) {
				dbg(1,
				    "ERROR WRITE PORT, sent is %d, datalen %d.",
				    sent, datalen);
				at->ret = AT_NOT_RET;
				at->status = AT_RECVED;
				break;
			}
			/* clear recv buffer */
			bzero(at->recv_buf, sizeof(at->recv_buf));
			at->start_copy = 0;	/* initially not copy recved data into recv_buf */
			at->status = AT_SENT;
			/* remember sent timestamp */
			at->sent_time = time(NULL);
			sleep(1);
			break;
		}
	case AT_SENT:
		{
			time_t time_gone = time(NULL) - at->sent_time;
			if (time_gone >= AT_TIMEOUT_SEC) {
				/* wowow, it's totally timeout! */
				dbg(1,
				    "TIMEOUT AT cmd for %d time, force return.",
				    ++at->time_out_count);
				at->ret = AT_NOT_RET;
				at->status = AT_RECVED;
				if (at->time_out_count >= AT_TIMEOUT_COUNT_MAX) {
					dbg(1,
					    "this device has %d time(s) of at cmd timeout now, reseting.",
					    at->time_out_count);
					modat_set_status(p, NOT_RESPONDING);
					return;
				}
			}
		}
		break;
	case AT_RECVED:
		break;
	}

	/* do the daily recv */
	{
		unsigned int len, done;
		char buf[DAEMON_RECV_BUFFER_SIZE];
		char *pch, *pch2;

		/* added for Q2687, if portfd==0, do not read */
		/* TOFIX */
		if (p->portfd == 0) {
			/* do nothing */
			len = 0;
		} else {
			len =
			    read(p->portfd, buf, DAEMON_RECV_BUFFER_SIZE - 10);
		}

		if (len == DAEMON_RECV_BUFFER_SIZE - 10)
			dbg(1, "WARNING: RECV BUFFER MAY OVERFLOWED.");

		if (len > 0) {
			/* do some special treatment to string "\n>" when using SMS 
			   at cmd. solution is : add another "\n" after '\n>' */
			buf[len] = 0x00;
			//dbg(1, "recv : %s", buf);
			if (!strncmp(buf, "> ", 2))
				pch = buf;	/* "> " is found at the beginning (normally) */
			else
				pch = strstr(buf, "\n> ");	/* found in the middle */
			if (pch) {	/* no matter where, we found "> " */
				pch += 2;
				for (pch2 = buf + len - 1; pch2 > pch; pch2--)
					*(pch2 + 1) = *pch2;
				*(pch2 + 1) = '\n';
				len++;
				buf[len] = 0x00;
			}
			/* after this, "\n>" are converted to "\n>\n", 
			   now we can recog it.  so tricky ... */

			done = r->write(r, buf, len);
			if (done != len) {
				dbg(1,
				    "RBUF wrote length %d, while %d needed to write, "
				    "possibly the buffer is not big enough.",
				    done, len);
			}
		} else if (len < 0) {
			dbg(1, "error in read(): %s", strerror(errno));
			modat_set_status(p, DEAD);
			return;
		}
	}

	/* handle related infomation */
	{
		char *line;

		while ((line = r->readline(r))) {
//                      dbg(1, "recv : %s", line);
			/* recved a whole line */
			if (at->status == AT_SENT) {

				/* record required response */
//                              if (at->mode & AT_MODE_LINE) {
//                                      if (strcasestr(line, at->keyword))
//                                              /* always the newest! */
//                                              strncpy(at->recv_buf, line, MODAT_RECV_BUFLEN);
//                              } else { /* mode BLOCK */
//                                      /* xzpeter fixed 2010.6.9, mem overflow! when using strcat */
//                                      strncat(at->recv_buf, line, MODAT_RECV_BUFLEN - strlen(at->recv_buf));
//                              }

				if (at->start_copy) {
					if (at->mode == AT_MODE_BLOCK)
						strncat(at->recv_buf, line,
							MODAT_RECV_BUFLEN -
							strlen(at->recv_buf));
				} else {
					/* not start copy yet */
					if (at->keyword[0]
					    && strcasestr(line, at->keyword)) {
						/* if there is a keyword and matched */
						at->start_copy = 1;	/* trigger copy */
						strncpy(at->recv_buf, line,
							MODAT_RECV_BUFLEN);
					}
				}

				/* host is waiting for "OK" and "keyword" */
				if (strstr(line, "OK")) {
					at->ret = AT_OK;
					at->status = AT_RECVED;
					if (!at->start_copy)
						strcpy(at->recv_buf, line);
				} else if (strstr(line, "CME ERROR")) {
					at->ret = AT_CME_ERROR;
					at->status = AT_RECVED;
					if (!at->start_copy)
						strcpy(at->recv_buf, line);
				} else if (strstr(line, "CMS ERROR")) {
					at->ret = AT_CMS_ERROR;
					at->status = AT_RECVED;
					if (!at->start_copy)
						strcpy(at->recv_buf, line);
				} else if (strstr(line, "ERROR")) {
					at->ret = AT_ERROR;
					at->status = AT_RECVED;
					if (!at->start_copy)
						strcpy(at->recv_buf, line);
				} else if (!strncmp(line, "> ", 2)) {
					at->ret = AT_RAWDATA;
					at->status = AT_RECVED;
				} else if (strstr(line, "NO CARRIER")) {
					at->ret = AT_NO_CARRIER;
					at->status = AT_RECVED;
					if (!at->start_copy)
						strcpy(at->recv_buf, line);
				}
			}
			handle_line(p, line);
		}
	}
}
Example #23
0
int main(int argc, char *argv[]) {
    int opt, sortarcs = 1;
    char *infilename;
    struct fsm *net;

    setvbuf(stdout, buffer, _IOFBF, sizeof(buffer));

    while ((opt = getopt(argc, argv, "abhHiI:qs:uw:vx")) != -1) {
        switch(opt) {
        case 'a':
	    apply_alternates = 1;
	    break;
        case 'b':
	    buffered_output = 0;
	    break;
        case 'h':
	    printf("%s%s\n", usagestring,helpstring);
            exit(0);
        case 'i':
	    direction = DIR_DOWN;
	    applyer = &apply_down;
	    break;
        case 'q':
	    sortarcs = 0;
	    break;
	case 'I':
	    if (strcmp(optarg, "f") == 0) {
		index_flag_states = 1;
		index_arcs = 1;
	    } else if (strstr(optarg, "k") != NULL && strstr(optarg,"K") != NULL) {
		/* k limit */
		index_mem_limit = 1024*atoi(optarg);
		index_arcs = 1;
	    } else if (strstr(optarg, "m") != NULL && strstr(optarg,"M") != NULL) {
		/* m limit */
		index_mem_limit = 1024*1024*atoi(optarg);
		index_arcs = 1;
	    } else if (isdigit(*optarg)) {
		index_arcs = 1;
		index_cutoff = atoi(optarg);
	    }
	    break;
	case 's':
	    separator = strdup(optarg);
	    break;
	case 'u':
	    mark_uppercase = 1;
	    if (!setlocale(LC_CTYPE, "")) {
		fprintf(stderr, "Check uppercase flag is on, but can't set locale!\n");
	    }
	    break;
	case 'w':
	    wordseparator = strdup(optarg);
	    break;
        case 'v':
	    printf("cgflookup 1.03 (foma library version %s)\n", fsm_get_library_version_string());
	    exit(0);
	default:
            fprintf(stderr, "%s", usagestring);
            exit(EXIT_FAILURE);
	}
    }
    if (optind == argc) {
	fprintf(stderr, "%s", usagestring);
	exit(EXIT_FAILURE);
    }

    infilename = argv[optind];

    if ((fsrh = fsm_read_binary_file_multiple_init(infilename)) == NULL) {
        perror("File error");
	exit(EXIT_FAILURE);
    }
    chain_head = chain_tail = NULL;

    while ((net = fsm_read_binary_file_multiple(fsrh)) != NULL) {
	numnets++;
	chain_new = xxmalloc(sizeof(struct lookup_chain));	
	if (direction == DIR_DOWN && net->arcs_sorted_in != 1 && sortarcs) {
	    fsm_sort_arcs(net, 1);
	}
	if (direction == DIR_UP && net->arcs_sorted_out != 1 && sortarcs) {
	    fsm_sort_arcs(net, 2);
	}
	chain_new->net = net;
	chain_new->ah = apply_init(net);
	if (direction == DIR_DOWN && index_arcs) {
	    apply_index(chain_new->ah, APPLY_INDEX_INPUT, index_cutoff, index_mem_limit, index_flag_states);
	}
	if (direction == DIR_UP && index_arcs) {
	    apply_index(chain_new->ah, APPLY_INDEX_OUTPUT, index_cutoff, index_mem_limit, index_flag_states);
	}

	chain_new->next = NULL;
	chain_new->prev = NULL;
	if (chain_tail == NULL) {
	    chain_tail = chain_head = chain_new;
	} else if (direction == DIR_DOWN || apply_alternates == 1) {
	    chain_tail->next = chain_new;
	    chain_new->prev = chain_tail;
	    chain_tail = chain_new;
	} else {
	    chain_new->next = chain_head;
	    chain_head->prev = chain_new;
	    chain_head = chain_new;
	}
    }

    if (numnets < 1) {
	fprintf(stderr, "%s: %s\n", "File error", infilename);
	exit(EXIT_FAILURE);
    }

    /* Standard read from stdin */
    line = xxcalloc(LINE_LIMIT, sizeof(char));
    INFILE = stdin;
    while (get_next_line() != NULL) {
	results = 0;
	handle_line(line);
	if (results == 0) {
	    app_print(NULL);
	}
	fprintf(stdout, "%s", wordseparator);
	if (!buffered_output) {
	    fflush(stdout);
	}
    }
    /* Cleanup */
    for (chain_pos = chain_head; chain_pos != NULL; chain_pos = chain_head) {
	chain_head = chain_pos->next;
	if (chain_pos->ah != NULL) {
	    apply_clear(chain_pos->ah);
	}
	if (chain_pos->net != NULL) {
	    fsm_destroy(chain_pos->net);
	}
	xxfree(chain_pos);
    }
    if (line != NULL)
    	xxfree(line);
    exit(0);
}
Example #24
0
int fmt_merge_msg(struct strbuf *in, struct strbuf *out,
		  struct fmt_merge_msg_opts *opts)
{
	int i = 0, pos = 0;
	unsigned char head_sha1[20];
	const char *current_branch;
	void *current_branch_to_free;
	struct merge_parents merge_parents;

	memset(&merge_parents, 0, sizeof(merge_parents));

	/* get current branch */
	current_branch = current_branch_to_free =
		resolve_refdup("HEAD", RESOLVE_REF_READING, head_sha1, NULL);
	if (!current_branch)
		die("No current branch");
	if (starts_with(current_branch, "refs/heads/"))
		current_branch += 11;

	find_merge_parents(&merge_parents, in, head_sha1);

	/* get a line */
	while (pos < in->len) {
		int len;
		char *newline, *p = in->buf + pos;

		newline = strchr(p, '\n');
		len = newline ? newline - p : strlen(p);
		pos += len + !!newline;
		i++;
		p[len] = 0;
		if (handle_line(p, &merge_parents))
			die ("Error in line %d: %.*s", i, len, p);
	}

	if (opts->add_title && srcs.nr)
		fmt_merge_msg_title(out, current_branch);

	if (origins.nr)
		fmt_merge_msg_sigs(out);

	if (opts->shortlog_len) {
		struct commit *head;
		struct rev_info rev;

		head = lookup_commit_or_die(head_sha1, "HEAD");
		init_revisions(&rev, NULL);
		rev.commit_format = CMIT_FMT_ONELINE;
		rev.merge_diff_mode = MERGE_DIFF_IGNORE;
		rev.limited = 1;

		strbuf_complete_line(out);

		for (i = 0; i < origins.nr; i++)
			shortlog(origins.items[i].string,
				 origins.items[i].util,
				 head, &rev, opts, out);
	}

	strbuf_complete_line(out);
	free(current_branch_to_free);
	free(merge_parents.item);
	return 0;
}
Example #25
0
int main( int argc, char *argv[] )
{
  /* for parsing args */
  extern char *optarg;
  extern int optind;
  int ch;

  /* vars */
  int i,j;
  int listenfd;

  /* select vars */
  fd_set read_set;
  int fdmax;

  /* client arr */
  Arraylist clientList;
  /* channel arr */
  Arraylist channelList;

  /* servername */
  char servername[MAX_SERVERNAME+1];

  while ((ch = getopt(argc, argv, "hD:")) != -1)
  switch (ch) {
  case 'D':
    if (set_debug(optarg)) {
      exit(0);
    }
    break;
  case 'h':
  default: /* FALLTHROUGH */
    usage();
  }
  argc -= optind;
  argv += optind;

  if (argc < 2) {
    usage();
  }
  signal(SIGPIPE, SIG_IGN);
  init_node(argv[0], argv[1]);

  printf( "I am node %lu and I listen on port %d for new users\n", curr_nodeID, curr_node_config_entry->irc_port );

  /* Start your engines here! */
  if (gethostname(servername,MAX_SERVERNAME) < 0){
    perror("gethostname");
    return EXIT_FAILURE;
  }
  servername[MAX_SERVERNAME] = '\0';

  /* delegate all function calling to setupListenSocket.
        It should print out relevant err messages. */
  listenfd = setupListenSocket(curr_node_config_entry->irc_port);
  if (listenfd < 0){
    return EXIT_FAILURE;
  }

  /* initialize client array */
  clientList = arraylist_create();

  /* initialize channel array */
  channelList = arraylist_create();

  /* prepare for select */
  fdmax = listenfd;
  FD_ZERO(&master_set);
  FD_ZERO(&write_set);
  FD_SET(listenfd,&master_set);

  /* FD_ZERO(&write_set);  initially no data to write */

  /* main loop!! */
  for (;;){
    int retval;
    read_set = master_set;

    /* wait until any sockets become available */
    retval = select(fdmax+1,&read_set,&write_set,NULL,NULL);

    if (retval <= 0){
      if (retval < 0)
      DEBUG_PERROR("select");
      continue; /* handle errors gracefully and wait again if timed out (it shouldn't)*/
    }
    /* at least one socket ready*/
    for (i = 0; i <= fdmax; i++){
      if (FD_ISSET(i, &write_set)) {
        int listIndex = findClientIndexBySockFD(clientList,i);
        client_t *thisClient = (client_t *) CLIENT_GET(clientList,listIndex);
        /*client data ready to be written */
        int nbytes;
        /* iterate through item to be sent, until it will block */
        Arraylist outbuf = thisClient->outbuf;

        while (!arraylist_is_empty(outbuf))
        {
          /* write */
          char *dataToSend = (char *) (arraylist_get(outbuf,0)) + thisClient->outbuf_offset;
          size_t sizeToSend = strlen(dataToSend);
          nbytes = send(thisClient->sock, dataToSend, sizeToSend, 0);
          if (nbytes <0){
            /* error */
            if (errno == EPIPE || errno == ECONNRESET){
              /* connection lost or closed by the peer */

              DPRINTF(DEBUG_SOCKETS,"send: client %d hungup\n",i);
              remove_client(clientList,listIndex);
              continue;
            }
          }
          else if (nbytes == sizeToSend){
            /* current line completely sent */
            char *toRemove = (char *) (arraylist_get(outbuf,0));
            arraylist_removeIndex(outbuf,0);
            free(toRemove);
          }
          else{
            /* partial send */
            thisClient->outbuf_offset += nbytes;
            break;
          }
        }
        if (arraylist_is_empty(outbuf))
          FD_CLR(i, &write_set);
      }
      if (FD_ISSET(i, &read_set)) {
        if (i == listenfd){
          /* incoming connection */
          int newindex = handle_incoming_conn(clientList,servername,listenfd);
          if (newindex < 0){
            continue;
          }
          client_t *newClient = CLIENT_GET(clientList,newindex);
          int newfd = newClient->sock;
          FD_SET(newfd,&master_set);
          if (newfd > fdmax){
            fdmax = newfd;
          }
        }
        else{
          /* client data ready */
          char *tempPtr;
          int listIndex = findClientIndexBySockFD(clientList,i);

          /* for split function */
          char** tokenArr;
          int numToken;
          int lastTokenTerminated;

          if (listIndex < 0){
            close(i);
            FD_CLR(i,&master_set);
            continue;
          }

          int nbytes = recv(i, CLIENT_GET(clientList,listIndex)->inbuf + CLIENT_GET(clientList,listIndex)->inbuf_size,
          MAX_MSG_LEN - CLIENT_GET(clientList,listIndex)->inbuf_size, 0);

          /* recv failed. Either client left or error */
          if (nbytes <= 0){
            if (nbytes == 0){
              DPRINTF(DEBUG_SOCKETS,"recv: client %d hungup\n",i);
              remove_client(clientList, listIndex);

            }
            else if (errno == ECONNRESET || errno == EPIPE){
              DPRINTF(DEBUG_SOCKETS,"recv: client %d connection reset \n",i);
              remove_client(clientList, listIndex);

            }
            else{
              perror("recv");
            }
            continue;
          }

          /* NULL terminate to use strpbrk */
          CLIENT_GET(clientList,listIndex)->inbuf_size += nbytes;
          CLIENT_GET(clientList,listIndex)->inbuf[CLIENT_GET(clientList,listIndex)->inbuf_size] = '\0';
          tempPtr = strpbrk(CLIENT_GET(clientList,listIndex)->inbuf,"\r\n");
          if (!tempPtr){
            if (CLIENT_GET(clientList,listIndex)->inbuf_size == MAX_MSG_LEN){
              /* Message too long. Dump the content */
              DPRINTF(DEBUG_INPUT,"recv: message longer than MAX_MESSAGE detected. The message will be discarded\n");
              CLIENT_GET(clientList,listIndex)->inbuf_size = 0;
            }
            continue;
          }

          tokenArr = splitByDelimStr(CLIENT_GET(clientList,listIndex)->inbuf,"\r\n",&numToken,&lastTokenTerminated);
          /* since we have checked if there's delimeter beforehand, there should be at least one terminated token available*/
          if (!tokenArr){
            DPRINTF(DEBUG_INPUT,"splitByDelimStr: failed to split inputToken\n");
            CLIENT_GET(clientList,listIndex)->inbuf_size = 0;
            continue;
          }
          if (!lastTokenTerminated){
            CLIENT_GET(clientList,listIndex)->inbuf_size = strlen(tokenArr[numToken-1]);
            memcpy(CLIENT_GET(clientList,listIndex)->inbuf,tokenArr[numToken-1],CLIENT_GET(clientList,listIndex)->inbuf_size);
            numToken--;
          }

          for (j=0;j<numToken;j++){
            handle_line(clientList,listIndex,channelList,servername,tokenArr[j]);
          }

          for (j = 0; j < arraylist_size(clientList); j++){
            client_t *client = CLIENT_GET(clientList,j);
            if (arraylist_size(client->outbuf)){
                FD_SET(client->sock,&write_set);
            }
          }
          freeTokens(&tokenArr,numToken);
        }
      }
    }
  }

  return 0;
}
Example #26
0
/** The MAIN loop. */
int main(void) {
  // Turn off the CPU prescale.
  CLKPR = 0x80;
  CLKPR = 0x00;

  // PORTA are general purpose inputs.
  DDRA = 0x00;
  PORTA = 0xff; // pull-ups all enabled

  PORTD = 0xff;
  DDRD = 0x00; // pull-ups all enabled

  DDRF = 0x00; // These are ADC lines.
  PORTF = 0x00;

  usb_init();

  // Set up Timer 0 to match compare every 1ms.
  OCR0A = 250;
  TCCR0A = 0x02; // CTC
  TCCR0B = 0x03; // CK/64 (64 * 250 == 16000)

  sei();
  char line_buf[128] = {};
  uint8_t line_len = 0;
  uint8_t usb_ready = 0;
  while (1) {
    wdt_reset();
    g_main_loop_count++;

    if (usb_configured() && (usb_serial_get_control() & USB_SERIAL_DTR)) {
      if (!usb_ready) {
        usb_ready = 1;
        strcpy_P(line_buf, PSTR("!GNR WELCOME " DEV_VERSION EOL));
        usb_serial_write((uint8_t*)line_buf, strlen(line_buf));
        line_len = 0;
      }
    } else {
      stream_stop_all();
      usb_serial_flush_input();
      usb_ready = 0;
      line_len = 0;
      g_arm_code = 0;
    }

    if (usb_serial_available()) {
      int16_t c = usb_serial_getchar();
      if (c == '\r' || c == '\n') {
        line_buf[line_len] = 0;
        handle_line(line_buf);
        if (g_arm_code) { g_arm_timer = ARM_TIMEOUT_MS; }
        line_len = 0;
      } else {
        line_buf[line_len++] = c & 0xff;

        if ((line_len + 1) >= sizeof(line_buf)) {
          /* Clobber the first byte so that this line will be reported
             as an error. */
          line_buf[0] = MAGIC_OVERRUN_CODE;
          line_len--;
        }
      }
    }

    if (TIFR0 & (1 << OCF0A)) {
      TIFR0 |= (1 << OCF0A);
      g_timer++;
      stream_timer_update();
      hit_timer_update();

      g_main_loop_count = (uint16_t) (((uint32_t) g_main_loop_count) * 7 / 8);
    }

    stream_poll();
    usb_poll();
    hit_poll();
  }
}
Example #27
0
int cmd_fmt_merge_msg(int argc, const char **argv, const char *prefix)
{
	int limit = 20, i = 0;
	char line[1024];
	FILE *in = stdin;
	const char *sep = "";
	unsigned char head_sha1[20];
	const char *current_branch;

	git_config(fmt_merge_msg_config);

	while (argc > 1) {
		if (!strcmp(argv[1], "--log") || !strcmp(argv[1], "--summary"))
			merge_summary = 1;
		else if (!strcmp(argv[1], "--no-log")
				|| !strcmp(argv[1], "--no-summary"))
			merge_summary = 0;
		else if (!strcmp(argv[1], "-F") || !strcmp(argv[1], "--file")) {
			if (argc < 3)
				die ("Which file?");
			if (!strcmp(argv[2], "-"))
				in = stdin;
			else {
				fclose(in);
				in = fopen(argv[2], "r");
				if (!in)
					die("cannot open %s", argv[2]);
			}
			argc--; argv++;
		} else
			break;
		argc--; argv++;
	}

	if (argc > 1)
		usage(fmt_merge_msg_usage);

	/* get current branch */
	current_branch = resolve_ref("HEAD", head_sha1, 1, NULL);
	if (!current_branch)
		die("No current branch");
	if (!prefixcmp(current_branch, "refs/heads/"))
		current_branch += 11;

	while (fgets(line, sizeof(line), in)) {
		i++;
		if (line[0] == 0)
			continue;
		if (handle_line(line))
			die ("Error in line %d: %s", i, line);
	}

	printf("Merge ");
	for (i = 0; i < srcs.nr; i++) {
		struct src_data *src_data = srcs.payload[i];
		const char *subsep = "";

		printf(sep);
		sep = "; ";

		if (src_data->head_status == 1) {
			printf(srcs.list[i]);
			continue;
		}
		if (src_data->head_status == 3) {
			subsep = ", ";
			printf("HEAD");
		}
		if (src_data->branch.nr) {
			printf(subsep);
			subsep = ", ";
			print_joined("branch ", "branches ", &src_data->branch);
		}
		if (src_data->r_branch.nr) {
			printf(subsep);
			subsep = ", ";
			print_joined("remote branch ", "remote branches ",
					&src_data->r_branch);
		}
		if (src_data->tag.nr) {
			printf(subsep);
			subsep = ", ";
			print_joined("tag ", "tags ", &src_data->tag);
		}
		if (src_data->generic.nr) {
			printf(subsep);
			print_joined("commit ", "commits ", &src_data->generic);
		}
		if (strcmp(".", srcs.list[i]))
			printf(" of %s", srcs.list[i]);
	}

	if (!strcmp("master", current_branch))
		putchar('\n');
	else
		printf(" into %s\n", current_branch);

	if (merge_summary) {
		struct commit *head;
		struct rev_info rev;

		head = lookup_commit(head_sha1);
		init_revisions(&rev, prefix);
		rev.commit_format = CMIT_FMT_ONELINE;
		rev.ignore_merges = 1;
		rev.limited = 1;

		for (i = 0; i < origins.nr; i++)
			shortlog(origins.list[i], origins.payload[i],
					head, &rev, limit);
	}

	/* No cleanup yet; is standalone anyway */

	return 0;
}
Example #28
0
int read_config (char *filename, struct parsedfile *config) {
    FILE *conf;
    char line[MAXLINE];
    int rc = 0;
    int lineno = 1;
    struct serverent *server;

   /* Clear out the structure */
   memset(config, 0x0, sizeof(*config));

   /* Initialization */
   currentcontext = &(config->defaultserver);

   /* Tordns defaults */
   config->tordns_cache_size = 256;
   config->tordns_enabled = 1;


    /* If a filename wasn't provided, use the default */
    if (filename == NULL) {
        strncpy(line, CONF_FILE, sizeof(line) - 1);
        /* Insure null termination */
        line[sizeof(line) - 1] = (char) 0;
        filename = line;
        show_msg(MSGWARN, "Configuration file not provided by TORSOCKS_CONF_FILE "
                "environment variable, attempting to use defaults in %s.\n", filename);
    }

    /* If there is no configuration file use reasonable defaults for Tor */
    if ((conf = fopen(filename, "r")) == NULL) {
        show_msg(MSGERR, "Could not open socks configuration file "
                "(%s) errno (%d), assuming sensible defaults for Tor.\n", filename, errno);
        memset(&(config->defaultserver), 0x0, sizeof(config->defaultserver));
        check_server(&(config->defaultserver));
        handle_local(config, 0, "127.0.0.0/255.0.0.0");
        handle_local(config, 0, "10.0.0.0/255.0.0.0");
        handle_local(config, 0, "192.168.0.0/255.255.0.0");
        handle_local(config, 0, "172.16.0.0/255.240.0.0");
        handle_local(config, 0, "169.254.0.0/255.255.0.0");
        rc = 1; /* Severe errors reading configuration */
    } else {
        memset(&(config->defaultserver), 0x0, sizeof(config->defaultserver));

        while (NULL != fgets(line, MAXLINE, conf)) {
            /* This line _SHOULD_ end in \n so we  */
            /* just chop off the \n and hand it on */
            if (strlen(line) > 0)
                line[strlen(line) - 1] = '\0';
            handle_line(config, line, lineno);
            lineno++;
        }
        fclose(conf);

        /* Always add the 127.0.0.1/255.0.0.0 subnet to local */
        handle_local(config, 0, "127.0.0.0/255.0.0.0");
        /* We always consider this local, because many users' dsl
          routers act as their DNS. */
        handle_local(config, 0, "10.0.0.0/255.0.0.0");
        handle_local(config, 0, "192.168.0.0/255.255.0.0");
        handle_local(config, 0, "172.16.0.0/255.240.0.0");
        handle_local(config, 0, "169.254.0.0/255.255.0.0");
        handle_local(config, 0, "192.168.0.0/255.255.0.0");

        /* Check default server */
        check_server(&(config->defaultserver));
        server = (config->paths);
        while (server != NULL) {
            check_server(server);
            server = server->next;
        }
    }

    /* Initialize tordns deadpool_range if not supplied */
    if(config->tordns_deadpool_range == NULL) {
        handle_tordns_deadpool_range(config, 0, "127.0.69.0/255.255.255.0");
    }

    return(rc);
}
Example #29
0
int main(int argc, char *argv[]) {
    int opt, sortarcs = 1;
    char *infilename;
    struct fsm *net;

    setvbuf(stdout, buffer, _IOFBF, sizeof(buffer));

    while ((opt = getopt(argc, argv, "abhHiI:qs:SA:P:w:vx")) != -1) {
        switch(opt) {
        case 'a':
	    apply_alternates = 1;
	    break;
        case 'b':
	    buffered_output = 0;
	    break;
        case 'h':
	    printf("%s%s\n", usagestring,helpstring);
            exit(0);
        case 'i':
	    direction = DIR_DOWN;
	    applyer = &apply_down;
	    break;
        case 'q':
	    sortarcs = 0;
	    break;
	case 'I':
	    if (strcmp(optarg, "f") == 0) {
		index_flag_states = 1;
		index_arcs = 1;
	    } else if (strcasestr(optarg, "k") != NULL) {
		/* k limit */
		index_mem_limit = 1024*atoi(optarg);
		index_arcs = 1;
	    } else if (strcasestr(optarg, "m") != NULL) {
		/* m limit */
		index_mem_limit = 1024*1024*atoi(optarg);
		index_arcs = 1;
	    } else if (isdigit(*optarg)) {
		index_arcs = 1;
		index_cutoff = atoi(optarg);
	    }
	    break;
	case 's':
	    separator = strdup(optarg);
	    break;
	case 'S':
	    mode_server = 1;
	    break;
	case 'A':
	    server_address = strdup(optarg);
	    break;
	case 'P':
	    port_number = atoi(optarg);
	    break;
	case 'w':
	    wordseparator = strdup(optarg);
	    break;
        case 'v':
	    printf("flookup 1.02 (foma library version %s)\n", fsm_get_library_version_string());
	    exit(0);
        case 'x':
	    echo = 0;
	    break;
	default:
            fprintf(stderr, "%s", usagestring);
            exit(EXIT_FAILURE);
	}
    }
    if (optind == argc) {
	fprintf(stderr, "%s", usagestring);
	exit(EXIT_FAILURE);
    }

    infilename = argv[optind];

    if ((fsrh = fsm_read_binary_file_multiple_init(infilename)) == NULL) {
        perror("File error");
	exit(EXIT_FAILURE);
    }
    chain_head = chain_tail = NULL;

    while ((net = fsm_read_binary_file_multiple(fsrh)) != NULL) {
	numnets++;
	chain_new = xxmalloc(sizeof(struct lookup_chain));	
	if (direction == DIR_DOWN && net->arcs_sorted_in != 1 && sortarcs) {
	    fsm_sort_arcs(net, 1);
	}
	if (direction == DIR_UP && net->arcs_sorted_out != 1 && sortarcs) {
	    fsm_sort_arcs(net, 2);
	}
	chain_new->net = net;
	chain_new->ah = apply_init(net);
	if (direction == DIR_DOWN && index_arcs) {
	    apply_index(chain_new->ah, APPLY_INDEX_INPUT, index_cutoff, index_mem_limit, index_flag_states);
	}
	if (direction == DIR_UP && index_arcs) {
	    apply_index(chain_new->ah, APPLY_INDEX_OUTPUT, index_cutoff, index_mem_limit, index_flag_states);
	}

	chain_new->next = NULL;
	chain_new->prev = NULL;
	if (chain_tail == NULL) {
	    chain_tail = chain_head = chain_new;
	} else if (direction == DIR_DOWN || apply_alternates == 1) {
	    chain_tail->next = chain_new;
	    chain_new->prev = chain_tail;
	    chain_tail = chain_new;
	} else {
	    chain_new->next = chain_head;
	    chain_head->prev = chain_new;
	    chain_head = chain_new;
	}
    }

    if (numnets < 1) {
	fprintf(stderr, "%s: %s\n", "File error", infilename);
	exit(EXIT_FAILURE);
    }

    if (mode_server) {
	server_init();
	serverstring = xxcalloc(UDP_MAX+1, sizeof(char));
	line = xxcalloc(UDP_MAX+1, sizeof(char));
	addrlen = sizeof(clientaddr);
	for (;;) {
	    numbytes = recvfrom(listen_sd, line, UDP_MAX, 0,(struct sockaddr *)&clientaddr, &addrlen);
	    if (numbytes == -1) {
		perror("recvfrom() failed, aborting");
		break;
	    }
	    line[numbytes] = '\0';
	    line[strcspn(line, "\n\r")] = '\0';
	    fflush(stdout);
	    results = 0;
	    udpsize = 0;
	    serverstring[0] = '\0';
	    handle_line(line);
	    if (results == 0) {
		app_print(NULL);
	    }
	    if (serverstring[0] != '\0') {
		numbytes = sendto(listen_sd, serverstring, strlen(serverstring), 0, (struct sockaddr *)&clientaddr, addrlen);
		if (numbytes < 0) {
		    perror("sendto() failed"); fflush(stdout);
		}
	    }
	}
    } else {
	/* Standard read from stdin */
	line = xxcalloc(LINE_LIMIT, sizeof(char));
	INFILE = stdin;
	while (get_next_line() != NULL) {
	    results = 0;
	    handle_line(line);
	    if (results == 0) {
		app_print(NULL);
	    }
	    fprintf(stdout, "%s", wordseparator);
	    if (!buffered_output) {
		fflush(stdout);
	    }
	}
    }
   /* Cleanup */
    for (chain_pos = chain_head; chain_pos != NULL; chain_pos = chain_head) {
	chain_head = chain_pos->next;
	if (chain_pos->ah != NULL) {
	    apply_clear(chain_pos->ah);
	}
	if (chain_pos->net != NULL) {
	    fsm_destroy(chain_pos->net);
	}
	xxfree(chain_pos);
    }
    if (serverstring != NULL)
	xxfree(serverstring);
    if (line != NULL)
    	xxfree(line);
    exit(0);
}
Example #30
0
/* parse HTTP request and prepare header */
static int http_parse_request(HTTPContext *c)
{
    char *q, msg[1024];
    const char *mime_type, *p;
	HTTPContext *ctx;
	int ret = 0, is_first = 0;
	const char *first_tag = "First-Request=0";
	RequestData rd = {{0}};

    p = c->buffer;
	while(get_line(msg, sizeof(msg), &p) > 0){
		ret = handle_line(c, msg, sizeof(msg), &rd);
		if(ret < 0)return ret;
	}
	is_first = !av_stristr(rd.cookie, first_tag);
	
	if(c->post && c->content_length 
		&& !av_match_ext(c->url, "m3u8")
		&& !av_match_ext(c->url, "ts")
		&& !av_match_ext(c->url, "flv")){
		c->post = 0;
		c->content_length = read_request_content(c, rd.content, sizeof(rd.content));
	}
	#if defined(PLUGIN_DVB)
	if(!c->post && !strcmp(c->url, "digitalDvb/allServiceType/getClientInfo")){
		uint32_t *ptr = (uint32_t*)rd.content, *ptr_end = (uint32_t*)(rd.content+sizeof(rd.content)-8);
		for(ctx = first_http_ctx; ctx; ctx = ctx->next) 
			if(!ctx->post && av_match_ext(ctx->url, "flv") )
			{/*todo: record hls*/
				if(ptr < ptr_end){
					int chid = -1;
					sscanf(ctx->url, "%d", &chid);
		
					*ptr++ = inet_addr(inet_ntoa(ctx->from_addr.sin_addr));
					*ptr++ = chid;

					printf("ip %s id %u %s\t", inet_ntoa(ctx->from_addr.sin_addr), chid, ctx->url);
				}
			}
	}
	#endif

    //http_log("New conn: %s:%u %d %s cookie:%s\n", inet_ntoa(c->from_addr.sin_addr), ntohs(c->from_addr.sin_port), c->post, c->url, rd.cookie);

	/*handle m3u8/ts request solely*/
	if(av_match_ext(c->url, "m3u8") 
			|| av_match_ext(c->url, "ts")){
		c->keep_alive = 0; 
		ret = hls_parse_request(c, c->url, is_first);
		if(ret < 0)goto send_error;
		else if(ret == 1){
			long chid = atoi(c->url);
			if(!(0 <= chid && chid <= 10000)){
				sprintf(msg, "bad request: %s-->%ld", c->url, chid);
				http_log("%s\n", msg);
				goto send_error;
			}
			#if defined(PLUGIN_DVB)
			ff_ctl_send_string(1, c->url, rd.content);
			#endif
			http_log("wait get %s\n", c->url);
		}
		if(c->state == HTTPSTATE_SEND_HEADER)
			goto send_header;
		return 0; /*end here*/
	}

	#if defined(PLUGIN_DVB)
	ret = plugin_dvb(c, &rd);
	if(ret < 0){
		goto send_error;
	}else if(ret > 0){
		return 0;
	}
	#endif

    /*handle feed request*/
    if (c->post) {
		ctx = find_feed(c->url);
		if(ctx && ctx != c){
			sprintf(msg, "file %s has been feeded", c->url);
			http_log("%s\n", msg);
			goto send_error;
		}
        c->http_error = 0;
        c->state = HTTPSTATE_RECEIVE_DATA;
        return 0; /*end here*/
	}else{
		if(prepare_local_file(c) > 0){
			c->http_error = 200;
			c->state = HTTPSTATE_SEND_HEADER;
			return 0; /*no need feed, send local files directly.*/
		}
		
		ctx = find_feed(c->url);
		if(!ctx){
			c->keep_alive = 0; 
			sprintf(msg, "wait to get %s", c->url);
			http_log("%s\n", msg);
			#if defined(PLUGIN_DVB)
			ff_ctl_send(2, c->url, strlen(c->url)+1, rd.content, sizeof(rd.content)); 
			#endif
		}else{
			ctx->sff_ref_cnt++;
		}
		c->feed_ctx = ctx; 
	}

send_header:
    /* prepare HTTP header */
    c->buffer[0] = 0;
    av_strlcatf(c->buffer, c->buffer_size, "HTTP/1.1 200 OK\r\n");
	mime_type =  get_mine_type(c->url);
    av_strlcatf(c->buffer, c->buffer_size, "Pragma: no-cache\r\n");
    av_strlcatf(c->buffer, c->buffer_size, "Content-Type: %s\r\n", mime_type);
	av_strlcatf(c->buffer, c->buffer_size, "Connection: %s\r\n", (c->keep_alive ? "keep-alive" : "close"));
	av_strlcatf(c->buffer, c->buffer_size, "Set-Cookie: %s; Path=/; Domain=%s\r\n", first_tag, rd.domain);
    av_strlcatf(c->buffer, c->buffer_size, "\r\n");

    q = c->buffer + strlen(c->buffer);

    /* prepare output buffer */
    c->http_error = 0;
    c->buffer_ptr = c->buffer;
    c->buffer_end = q;
    c->state = HTTPSTATE_SEND_HEADER;

	#if 0
	if(S == c->hls_idx){
		HLS *s = &s_hls[c->hls_idx];
		char *ext = strrchr(c->url, '.');
		if(!(2 == s->flag && s->data && s->csize > 0)){/*not exist yet, fake one*/
			c->http_error = 200;
			c->buffer_end += sprintf(c->buffer_end, 
				"#EXTM3U\n"
				"#EXT-X-VERSION:3\n"
				"#EXT-X-TARGETDURATION:2\n"
				"#EXT-X-MEDIA-SEQUENCE:0\n"
				"#EXTINF:1.283989,\n"
				"%.*s0.ts\n", ext - c->url, c->url);
		}
	}
	#endif
    return 0;
 send_error:
	c->keep_alive = 0;
    c->http_error = 404;
    q = c->buffer;
    htmlstrip(msg);
    snprintf(q, c->buffer_size,
                  "HTTP/1.1 404 Not Found\r\n"
                  "Content-type: text/html\r\n"
                  "\r\n"
                  "<html>\n"
                  "<head><title>404 Not Found</title></head>\n"
                  "<body>%s</body>\n"
                  "</html>\n", msg);
    q += strlen(q);
    /* prepare output buffer */
    c->buffer_ptr = c->buffer;
    c->buffer_end = q;
    c->state = HTTPSTATE_SEND_HEADER;
    return 0;
}