Exemple #1
0
static void print_ns(buf_t *buf, hubbub_ns ns)
{
    if (ns_names[ns] != NULL) {
        buf_add(buf, ns_names[ns]);
        buf_add(buf, " ");
    }
}
Exemple #2
0
void
vt_scroll(int lines, int scroll_up)
{
        /* We move vt_top and redraw the entire buffer */
        if (scroll_up) {
                /* Check against the head of the buffer */
                if (circ_dist(vt_curterm->vt_top,
                              vt_curterm->vt_head) <
                    lines * DISPLAY_WIDTH) {
                        vt_curterm->vt_top = vt_curterm->vt_head;
                } else {
                        buf_add(vt_curterm->vt_top,
                                -lines * DISPLAY_WIDTH);
                }
        } else {
                /* Check against tail of buffer */
                /* Note we add one as tail points AFTER the last
                 * line */
                if (circ_dist(vt_curterm->vt_tail,
                              vt_curterm->vt_top) <
                    (lines + 1) * DISPLAY_WIDTH) {
                        vt_curterm->vt_top = vt_curterm->vt_tail;
                        buf_add(vt_curterm->vt_top, -DISPLAY_WIDTH);
                } else {
                        buf_add(vt_curterm->vt_top, lines * DISPLAY_WIDTH);
                }
        }
        vt_redraw();
}
Exemple #3
0
static void
test_proto_control0(void *arg)
{
  (void)arg;
  buf_t *buf = buf_new();

  /* The only remaining function for the v0 control protocol is the function
     that detects whether the user has stumbled across an old controller
     that's using it.  The format was:
        u16 length;
        u16 command;
        u8 body[length];
  */

  /* Empty buffer -- nothing to do. */
  tt_int_op(0, OP_EQ, peek_buf_has_control0_command(buf));
  /* 3 chars in buf -- can't tell */
  buf_add(buf, "AUT", 3);
  tt_int_op(0, OP_EQ, peek_buf_has_control0_command(buf));
  /* command in buf -- easy to tell */
  buf_add(buf, "HENTICATE ", 10);
  tt_int_op(0, OP_EQ, peek_buf_has_control0_command(buf));

  /* Control0 command header in buf: make sure we detect it. */
  buf_clear(buf);
  buf_add(buf, "\x09\x05" "\x00\x05" "blah", 8);
  tt_int_op(1, OP_EQ, peek_buf_has_control0_command(buf));

 done:
  buf_free(buf);
}
Exemple #4
0
/*
 * Send header information which includes current working direcotry,
 * command line arguments, and CLASSPATH environment variable
 * to the server.
 */
void send_header(int fd, int argc, char** argv, char* authtoken)
{
    char path_buffer[MAXPATHLEN];
    buf read_buf = buf_new(BUFFER_SIZE, NULL);
    int i;

    // send current working directory.
    buf_printf(&read_buf, "%s: ", HEADER_KEY_CURRENT_WORKING_DIR);
    char* cwd = getcwd(path_buffer, MAXPATHLEN);
    if (cwd == NULL) {
        perror("ERROR: getcwd");
        exit(1);
    }

    buf_add(&read_buf, cwd);
    buf_add(&read_buf, "\n");

    buf_printf(&read_buf, "%s: %s\n", HEADER_KEY_AUTHTOKEN, authtoken);

    // send command line arguments.
    char *encoded_ptr, *encoded_work;
    for (i = 1; i < argc; i++) {
        if (argv[i] != NULL) {
            // base64 encoded data is less "(original size) * 1.5 + 5" as much as raw data
            // "+5" is a extra space for '=' padding and NULL as the end of string
            encoded_ptr = malloc(sizeof(char) * strlen(argv[i]) * 1.5 + 5);
            if (encoded_ptr == NULL) {
                perror("ERROR: failed to malloc");
                exit(1);
            }
            encoded_work = encoded_ptr; // copy for free
            base64_encode(encoded_work, (unsigned char*) argv[i]);
            buf_printf(&read_buf, "%s: %s\n", HEADER_KEY_ARG, encoded_work);
            free(encoded_ptr);
        }
    }

    // send envvars.
    if (client_option.env_include_mask != NULL) {
        make_env_headers(&read_buf,
                         environ,
                         client_option.env_include_mask,
                         client_option.env_exclude_mask);
    }

    char* cp = getenv("CLASSPATH");
    if (cp != NULL) {
        buf_printf(&read_buf, "%s: %s\n", HEADER_KEY_CP, cp);
    }

    buf_printf(&read_buf, "\n");
    read_buf.size--; /* remove trailing '\0' */

#ifdef WINDOWS
    send(fd, read_buf.buffer, read_buf.size, 0);
#else
    write(fd, read_buf.buffer, read_buf.size);
#endif
    buf_delete(&read_buf);
}
Exemple #5
0
static void indent(buf_t *buf, unsigned depth)
{
    unsigned int i;

    buf_add(buf, "| ");

    for (i = 0; i < depth; i++) {
        buf_add(buf, "  ");
    }
}
void test_add() {
  buf b = buf_new(0, NULL);
  buf_add(&b, "abcde");
  assert(memcmp(b.buffer, "abcde\0", 6) == 0);
  buf_add(&b, "fghij");
  assert(memcmp(b.buffer, "abcdefghij\0", 11) == 0);
  assert(b.buffer_size == DEFAULT_BUFFER_SIZE);
  assert(b.size == 11);
  buf_delete(&b);
}
void test_add_extend() {
  buf b = buf_new(2, NULL);
  buf_add(&b, "abcde");
  assert(memcmp(b.buffer, "abcde\0", 6) == 0);
  buf_add(&b, "fghij");
  assert(memcmp(b.buffer, "abcdefghij\0", 11) == 0);
  assert(b.buffer_size == 16);
  assert(b.size == 11);
  buf_delete(&b);
}
Exemple #8
0
int
imsg_add(struct buf *msg, void *data, u_int16_t datalen)
{
	if (datalen)
		if (buf_add(msg, data, datalen) == -1) {
			buf_free(msg);
			return (-1);
		}
	return (datalen);
}
Exemple #9
0
int
imsg_add(struct buf *msg, void *data, u_int16_t datalen)
{
	if (datalen)
		if (buf_add(msg, data, datalen) == -1) {
			log_warnx("imsg_add: buf_add error");
			buf_free(msg);
			return (-1);
		}
	return (datalen);
}
Exemple #10
0
static void test_buffer()
{
  size_t i;
  SizeBuffer abuf;
  buf_alloc(&abuf, 8);

  for(i = 0; i < 100; i++) assert(i == buf_add(&abuf, i));
  for(i = 0; i < 100; i++) assert(abuf.b[i] == i);

  buf_dealloc(&abuf);
}
Exemple #11
0
void buf_add_xml (struct buf *buf, char c)
{
    if (c == '<') {
        buf_add_str(buf, "&lt;");
    } else if (c == '>') {
        buf_add_str(buf, "&gt;");
    } else if (c == '\"') {
        buf_add_str(buf, "&quot;");
    } else if (c == '\'') {
        buf_add_str(buf, "&apos;");
    } else if (c == '&') {
        buf_add_str(buf, "&amp;");
    } else {
        buf_add(buf, c);
    }
}
Exemple #12
0
static void
test_proto_line(void *arg)
{
  (void)arg;
  char tmp[60];
  buf_t *buf = buf_new();
#define S(str) str, sizeof(str)-1
  const struct {
    const char *input;
    size_t input_len;
    size_t line_len;
    const char *output;
    int returnval;
  } cases[] = {
    { S("Hello world"), 0, NULL, 0 },
    { S("Hello world\n"), 12, "Hello world\n", 1 },
    { S("Hello world\nMore"), 12, "Hello world\n", 1 },
    { S("\n oh hello world\nMore"), 1, "\n", 1 },
    { S("Hello worpd\n\nMore"), 12, "Hello worpd\n", 1 },
    { S("------------------------------------------------------------\n"), 0,
      NULL, -1 },
  };
  unsigned i;
  for (i = 0; i < ARRAY_LENGTH(cases); ++i) {
    buf_add(buf, cases[i].input, cases[i].input_len);
    memset(tmp, 0xfe, sizeof(tmp));
    size_t sz = sizeof(tmp);
    int rv = buf_get_line(buf, tmp, &sz);
    tt_int_op(rv, OP_EQ, cases[i].returnval);
    if (rv == 1) {
      tt_int_op(sz, OP_LT, sizeof(tmp));
      tt_mem_op(cases[i].output, OP_EQ, tmp, sz+1);
      tt_int_op(buf_datalen(buf), OP_EQ, cases[i].input_len - strlen(tmp));
      tt_int_op(sz, OP_EQ, cases[i].line_len);
    } else {
      tt_int_op(buf_datalen(buf), OP_EQ, cases[i].input_len);
      // tt_int_op(sz, OP_EQ, sizeof(tmp));
    }
    buf_clear(buf);
  }

 done:
  buf_free(buf);
}
Exemple #13
0
void
vt_provide_char(tty_driver_t *ttyd, char c)
{
        KASSERT(NULL != ttyd);

        virtterm_t *vt = driver_to_vt(ttyd);

        /* Store for optimizing */
        int old_cursor = vt->vt_cursor;
        int old_top = vt->vt_top;
        int can_write_char;

        /* If cursor is not on the screen, we move top */
        if (circ_dist(vt->vt_cursor, vt->vt_top) >= DISPLAY_SIZE) {
                /* Cursor should be on the last row in this case */

                vt->vt_top = next_row(vt->vt_cursor);
                buf_add(vt->vt_top, -DISPLAY_SIZE);
        }

        can_write_char = vt_handle_char(vt, c);

        /* Redraw if it's the current terminal */
        if (vt_curterm == vt) {
                /*
                 * Check if we can optimize (just put 1 char instead
                 * of redrawing screen)
                 */
                if (old_top == vt->vt_top) {
                        if (can_write_char) {
                                int rel_cursor = circ_dist(old_cursor, vt->vt_top);
                                screen_putchar(c, rel_cursor %
                                               DISPLAY_WIDTH,
                                               rel_cursor / DISPLAY_WIDTH);
                        }
                        vt_cursor_redraw();
                } else {
                        vt_redraw();
                }
        }
}
Exemple #14
0
int main() {
  MYSQL_ROW row;
  MYSQL_RES *result;
  int i;
  char query[1024];

  int hdr;
#define HDR ((struct header *)(buf+hdr))

  if (!(conn = mysql_init(NULL))) return -1;
  mysql_options(conn, MYSQL_SET_CHARSET_NAME, "utf8");
  if (!mysql_real_connect(conn, "localhost", DBUSER, DBPASS, "pismo", 0, MYSQL_SOCKET, 0)) {
    fprintf(stderr, "Failed to connect to database: Error: %s\n", mysql_error(conn));
    return -2;
  }

  buf_init();
  hdr = buf_alloc(sizeof(struct header));
  HDR->signature = SIGNATURE;

  mysql_query(conn, "select o.id, o.spis, coalesce(o.alias,''), max(coalesce(t._1,0)), min(coalesce(t.id,1000000))-1, max(coalesce(t.id,-1))-1 "
      "from doc__biblia_obsah o left outer join doc__biblia_text t on o.id=t._0 "
      "group by o.id, o.spis, coalesce(o.alias,'') "
      "order by o.id asc");
  result = mysql_store_result(conn);
  HDR->n_knihy = mysql_num_rows(result);
  ASGN(HDR->knihy, buf_alloc(HDR->n_knihy * sizeof(struct kniha)));
#define KNH ((struct kniha *)(buf+HDR->knihy))
  i=0;
  while ((row = mysql_fetch_row(result))) {
    int j;

    sscanf(row[0], "%d", &j);
    if (i!=j-1) { fprintf(stderr, "nesuvisle id\n"); exit(1); }

    ASGN(KNH[i].meno, buf_add(row[1], strlen(row[1])+1));
    ASGN(KNH[i].alias, buf_add(row[2], strlen(row[2])+1));
    sscanf(row[3], "%d", &KNH[i].n_hlav);
    sscanf(row[4], "%d", &KNH[i].min);
    sscanf(row[5], "%d", &KNH[i].max);
    ASGN(KNH[i].hlava, buf_alloc(sizeof(struct hlava)*KNH[i].n_hlav));

    for (j=0; j<KNH[i].n_hlav; j++) {
      MYSQL_ROW row2;
      MYSQL_RES *result2;
      int k;
#define HLV ((struct hlava *)(buf+KNH[i].hlava))

      sprintf(query, "select min(coalesce(t.id,1000000))-1, max(coalesce(t.id,-1))-1 "
          "from doc__biblia_text t "
          "where t._0=%d and t._1=%d", i+1, j+1);
      mysql_query(conn, query);
      result2 = mysql_store_result(conn);
      row2 = mysql_fetch_row(result2);
      sscanf(row2[0], "%d", &HLV[j].min);
      sscanf(row2[1], "%d", &HLV[j].max);
      // printf("kniha %d, hlava %d, min %d, max %d\n", i, j, HLV[j].min, HLV[j].max);
      mysql_free_result(result2);

      sprintf(query, "select t._2, min(t.id)-1, max(t.id)-1 "
          "from doc__biblia_text t "
          "where t._0=%d and t._1=%d and t._2 is not null group by t._2", i+1, j+1);
      mysql_query(conn, query);
      result2 = mysql_store_result(conn);
      HLV[j].n_versov = mysql_num_rows(result2);
      // if (!HLV[j].n_versov) printf("kniha = %s; hlava = %d; versov=%d\n", row[1], j, HLV[j].n_versov);
      ASGN(HLV[j].vers, buf_alloc(sizeof(struct vers)*HLV[j].n_versov));

      for (k=0; k < HLV[j].n_versov; k++) {
        int l;
#define VRS ((struct vers *)(buf+HLV[j].vers))
        row2 = mysql_fetch_row(result2);
        sscanf(row2[0], "%d", &l);
        if (l-1 != k) { fprintf(stderr, "nesuvisle id versa k=%d h=%d v=%d!=%d\n", i+1, j+1, l, k+1); exit(1); }
        sscanf(row2[1], "%d", &VRS[k].min);
        sscanf(row2[2], "%d", &VRS[k].max);
        // printf("k=%d min=%d=%s max=%d=%s\n", k, VRS[k].min, row2[1], VRS[k].max, row2[2]);
      }

      mysql_free_result(result2);
    }

    i++;
  }
  mysql_free_result(result);

  mysql_query(conn, "select max(coalesce(id,0)) from doc__biblia_text where _0 is not null order by id asc");
  result = mysql_store_result(conn);
  row = mysql_fetch_row(result);
  sscanf(row[0], "%d", &HDR->n_text);
  mysql_free_result(result);

  mysql_query(conn, "select id, _0-1, coalesce(_1, 0)-1, coalesce(_2, 0)-1, coalesce(html,'') from doc__biblia_text where _0 is not null order by id asc");
  result = mysql_store_result(conn);
  i=0;
  ASGN(HDR->text, buf_alloc(sizeof(struct text)*HDR->n_text));
#define TXT ((struct text *)(buf+HDR->text))
  while ((row = mysql_fetch_row(result))) {
    int j;

    sscanf(row[0], "%d", &j);
    while (i<j-1) {
      TXT[i].k = TXT[i].h = TXT[i].v = -1;
      ASGN(TXT[i].t, buf_add("", 1));
      i++;
    }
    sscanf(row[1], "%d", &TXT[i].k);
    sscanf(row[2], "%d", &TXT[i].h);
    sscanf(row[3], "%d", &TXT[i].v);
    ASGN(TXT[i].t, buf_add(row[4], strlen(row[4])+1));
    // printf("txt %d = %s\n", i, row[4]);
    i++;
  }
  mysql_free_result(result);

  mysql_query(conn, "select max(coalesce(id,0)) from doc__biblia_ppc order by id asc");
  result = mysql_store_result(conn);
  row = mysql_fetch_row(result);
  sscanf(row[0], "%d", &HDR->n_ppc);
  mysql_free_result(result);

  mysql_query(conn, "select id, coalesce(html,'') from doc__biblia_ppc order by id asc");
  result = mysql_store_result(conn);
  i=0;
  ASGN(HDR->ppc, buf_alloc(sizeof(int32_t)*HDR->n_ppc));
#define PPC ((int32_t *)(buf+HDR->ppc))
  while ((row = mysql_fetch_row(result))) {
    int j;

    sscanf(row[0], "%d", &j);
    while (i<j-1) {
      ASGN(PPC[i], buf_add("", 1));
      i++;
    }
    ASGN(PPC[i], buf_add(row[1], strlen(row[1])+1));
    i++;
  }
  mysql_free_result(result);

  /*
  mysql_query(conn, "select datum, zalm, citania from liturgicke_citania order by datum asc");
  result = mysql_store_result(conn);
  HDR->n_kalendar = mysql_num_rows(result);
  ASGN(HDR->kalendar, buf_alloc(sizeof(struct kalendar)*HDR->n_kalendar));
#define KAL ((struct kalendar *)(buf+HDR->kalendar))
  i = 0;
  while ((row = mysql_fetch_row(result))) {
    sscanf(row[0], "%d-%d-%d", &KAL[i].y, &KAL[i].m, &KAL[i].d);
    ASGN(KAL[i].zalm, buf_add(row[1], strlen(row[1])+1));
    ASGN(KAL[i].text, buf_add(row[2], strlen(row[2])+1));
    i++;
  }
  mysql_free_result(result);
  */

  for (i=0; i<TABLES; i++) {
    int j;
    int min = (1<<i);
    int max = (i==TABLES-1) ? (1<<30) : (1<<(i+1))-1;
    sprintf(query, "(select 0, id-1, start-1 as start, end-1 from doc__biblia_text "
        "where end-start+1>=%d and end-start+1<=%d) union "
        "(select 1, id-1, start-1, end-1 from doc__biblia_ppc "
        "where end-start+1>=%d and end-start+1<=%d) order by start asc", min, max, min, max);
    mysql_query(conn, query);
    result = mysql_store_result(conn);

    HDR->n_item[i] = mysql_num_rows(result);
    ASGN(HDR->item[i], buf_alloc(sizeof(struct item)*HDR->n_item[i]));
#define ITM ((struct item *)(buf+HDR->item[i]))

    j = 0;
    while ((row = mysql_fetch_row(result))) {
      sscanf(row[0], "%d", &ITM[j].comment);
      sscanf(row[1], "%d", &ITM[j].id);
      sscanf(row[2], "%d", &ITM[j].b);
      sscanf(row[3], "%d", &ITM[j].e);
      j++;
    }
    mysql_free_result(result);
  }

  mysql_query(conn, "select o.id, o.popis, o.text "
      "from doc__biblia_uvod o "
      "order by o.id asc");
  result = mysql_store_result(conn);
  HDR->n_uvod = mysql_num_rows(result);
  ASGN(HDR->uvod, buf_alloc(HDR->n_uvod * sizeof(struct uvod)));
#define UVD ((struct uvod *)(buf+HDR->uvod))
  i=0;
  while ((row = mysql_fetch_row(result))) {
    ASGN(UVD[i].kniha, buf_add(row[1], strlen(row[1])+1));
    ASGN(UVD[i].text, buf_add(row[2], strlen(row[2])+1));
    i++;
  }
  mysql_free_result(result);

  dump("pismo.bin");
  mysql_close(conn);
  return 0;
}
Exemple #15
0
static void
test_proto_ext_or_cmd(void *arg)
{
  ext_or_cmd_t *cmd = NULL;
  buf_t *buf = buf_new();
  char *tmp = NULL;
  (void) arg;

  /* Empty -- should give "not there. */
  tt_int_op(0, OP_EQ, fetch_ext_or_command_from_buf(buf, &cmd));
  tt_ptr_op(NULL, OP_EQ, cmd);

  /* Three bytes: shouldn't work. */
  buf_add(buf, "\x00\x20\x00", 3);
  tt_int_op(0, OP_EQ, fetch_ext_or_command_from_buf(buf, &cmd));
  tt_ptr_op(NULL, OP_EQ, cmd);
  tt_int_op(3, OP_EQ, buf_datalen(buf));

  /* 0020 0000: That's a nil command. It should work. */
  buf_add(buf, "\x00", 1);
  tt_int_op(1, OP_EQ, fetch_ext_or_command_from_buf(buf, &cmd));
  tt_ptr_op(NULL, OP_NE, cmd);
  tt_int_op(0x20, OP_EQ, cmd->cmd);
  tt_int_op(0, OP_EQ, cmd->len);
  tt_int_op(0, OP_EQ, buf_datalen(buf));
  ext_or_cmd_free(cmd);
  cmd = NULL;

  /* Now try a length-6 command with one byte missing. */
  buf_add(buf, "\x10\x21\x00\x06""abcde", 9);
  tt_int_op(0, OP_EQ, fetch_ext_or_command_from_buf(buf, &cmd));
  tt_ptr_op(NULL, OP_EQ, cmd);
  buf_add(buf, "f", 1);
  tt_int_op(1, OP_EQ, fetch_ext_or_command_from_buf(buf, &cmd));
  tt_ptr_op(NULL, OP_NE, cmd);
  tt_int_op(0x1021, OP_EQ, cmd->cmd);
  tt_int_op(6, OP_EQ, cmd->len);
  tt_mem_op("abcdef", OP_EQ, cmd->body, 6);
  tt_int_op(0, OP_EQ, buf_datalen(buf));
  ext_or_cmd_free(cmd);
  cmd = NULL;

  /* Now try a length-10 command with 4 extra bytes. */
  buf_add(buf, "\xff\xff\x00\x0aloremipsum\x10\x00\xff\xff", 18);
  tt_int_op(1, OP_EQ, fetch_ext_or_command_from_buf(buf, &cmd));
  tt_ptr_op(NULL, OP_NE, cmd);
  tt_int_op(0xffff, OP_EQ, cmd->cmd);
  tt_int_op(10, OP_EQ, cmd->len);
  tt_mem_op("loremipsum", OP_EQ, cmd->body, 10);
  tt_int_op(4, OP_EQ, buf_datalen(buf));
  ext_or_cmd_free(cmd);
  cmd = NULL;

  /* Finally, let's try a maximum-length command. We already have the header
   * waiting. */
  tt_int_op(0, OP_EQ, fetch_ext_or_command_from_buf(buf, &cmd));
  tmp = tor_malloc_zero(65535);
  buf_add(buf, tmp, 65535);
  tt_int_op(1, OP_EQ, fetch_ext_or_command_from_buf(buf, &cmd));
  tt_ptr_op(NULL, OP_NE, cmd);
  tt_int_op(0x1000, OP_EQ, cmd->cmd);
  tt_int_op(0xffff, OP_EQ, cmd->len);
  tt_mem_op(tmp, OP_EQ, cmd->body, 65535);
  tt_int_op(0, OP_EQ, buf_datalen(buf));
  ext_or_cmd_free(cmd);
  cmd = NULL;

 done:
  ext_or_cmd_free(cmd);
  buf_free(buf);
  tor_free(tmp);
}
Exemple #16
0
void
dispatch_imsg(struct interface_info *ifi, int fd)
{
	struct imsg_hdr		 hdr;
	char			*medium, *reason, *filename,
				*servername, *prefix;
	size_t			 medium_len, reason_len, filename_len,
				 servername_len, prefix_len, totlen;
	struct client_lease	 lease;
	int			 ret, i, optlen;
	struct buf		*buf;

	buf_read(fd, &hdr, sizeof(hdr));

	switch (hdr.code) {
	case IMSG_SCRIPT_INIT:
		if (hdr.len < sizeof(hdr) + sizeof(size_t))
			error("corrupted message received");
		buf_read(fd, &medium_len, sizeof(medium_len));
		if (hdr.len < medium_len + sizeof(size_t) + sizeof(hdr)
		    + sizeof(size_t) || medium_len == SIZE_T_MAX)
			error("corrupted message received");
		if (medium_len > 0) {
			if ((medium = calloc(1, medium_len + 1)) == NULL)
				error("%m");
			buf_read(fd, medium, medium_len);
		} else
			medium = NULL;

		buf_read(fd, &reason_len, sizeof(reason_len));
		if (hdr.len < medium_len + reason_len + sizeof(hdr) ||
		    reason_len == SIZE_T_MAX)
			error("corrupted message received");
		if (reason_len > 0) {
			if ((reason = calloc(1, reason_len + 1)) == NULL)
				error("%m");
			buf_read(fd, reason, reason_len);
		} else
			reason = NULL;

		priv_script_init(reason, medium);
		free(reason);
		free(medium);
		break;
	case IMSG_SCRIPT_WRITE_PARAMS:
		bzero(&lease, sizeof lease);
		totlen = sizeof(hdr) + sizeof(lease) + sizeof(size_t);
		if (hdr.len < totlen)
			error("corrupted message received");
		buf_read(fd, &lease, sizeof(lease));

		buf_read(fd, &filename_len, sizeof(filename_len));
		totlen += filename_len + sizeof(size_t);
		if (hdr.len < totlen || filename_len == SIZE_T_MAX)
			error("corrupted message received");
		if (filename_len > 0) {
			if ((filename = calloc(1, filename_len + 1)) == NULL)
				error("%m");
			buf_read(fd, filename, filename_len);
		} else
			filename = NULL;

		buf_read(fd, &servername_len, sizeof(servername_len));
		totlen += servername_len + sizeof(size_t);
		if (hdr.len < totlen || servername_len == SIZE_T_MAX)
			error("corrupted message received");
		if (servername_len > 0) {
			if ((servername =
			    calloc(1, servername_len + 1)) == NULL)
				error("%m");
			buf_read(fd, servername, servername_len);
		} else
			servername = NULL;

		buf_read(fd, &prefix_len, sizeof(prefix_len));
		totlen += prefix_len;
		if (hdr.len < totlen || prefix_len == SIZE_T_MAX)
			error("corrupted message received");
		if (prefix_len > 0) {
			if ((prefix = calloc(1, prefix_len + 1)) == NULL)
				error("%m");
			buf_read(fd, prefix, prefix_len);
		} else
			prefix = NULL;

		for (i = 0; i < 256; i++) {
			totlen += sizeof(optlen);
			if (hdr.len < totlen)
				error("corrupted message received");
			buf_read(fd, &optlen, sizeof(optlen));
			lease.options[i].data = NULL;
			lease.options[i].len = optlen;
			if (optlen > 0) {
				totlen += optlen;
				if (hdr.len < totlen || optlen == SIZE_T_MAX)
					error("corrupted message received");
				lease.options[i].data =
				    calloc(1, optlen + 1);
				if (lease.options[i].data == NULL)
				    error("%m");
				buf_read(fd, lease.options[i].data, optlen);
			}
		}
		lease.server_name = servername;
		lease.filename = filename;

		priv_script_write_params(prefix, &lease);

		free(servername);
		free(filename);
		free(prefix);
		for (i = 0; i < 256; i++)
			if (lease.options[i].len > 0)
				free(lease.options[i].data);
		break;
	case IMSG_SCRIPT_GO:
		if (hdr.len != sizeof(hdr))
			error("corrupted message received");

		ret = priv_script_go();

		hdr.code = IMSG_SCRIPT_GO_RET;
		hdr.len = sizeof(struct imsg_hdr) + sizeof(int);
		if ((buf = buf_open(hdr.len)) == NULL)
			error("buf_open: %m");
		if (buf_add(buf, &hdr, sizeof(hdr)))
			error("buf_add: %m");
		if (buf_add(buf, &ret, sizeof(ret)))
			error("buf_add: %m");
		if (buf_close(fd, buf) == -1)
			error("buf_close: %m");
		break;
	case IMSG_SEND_PACKET:
		send_packet_priv(ifi, &hdr, fd);
		break;
	default:
		error("received unknown message, code %d", hdr.code);
	}
}
Exemple #17
0
/*-----------------------------------------------------------------------------
*
* ID: m_func 02.11.06 0.0.A.
*
* Summary: The func, method, operator, property, text processing
*
-----------------------------------------------------------------------------*/
plexem STDCALL m_func( plexem curlex, uint flgextern )
{
#ifdef DOUT
   uint     i;
#endif 


   uint     funckey;  //Вид функции
   uint     flgfunc;  //Флаги функции   

   pflabel  curlabel; // Текущий элемент в таблице меток
   pflabel  endlabel; // Конец таблицы меток
   uint     isreturn; //Есть return

   uint     thistype; //Тип переменной this для методов+
   pubyte   name;     //Имя функции
   plexem   lexname;  //Лексема с именем функции
   plexem   lexprev;

   s_desctype desctype;//Описание типа
   s_descid   descvar; //Описание переменной

   uint off_parcount; //Смещение в заголовке функции на кол. параметров
   uint off_blccount; //Смещение в заголовке функции на кол. блоков

   bcflag     bcf;    //Переменная для получение флагов функции
   pbuf       b;
   pfwith     pwith; 
   pvmobj     funcobj;   
   uint       thisid; //Номер переменной для this в текст функции

D( "Func start\n" );

// Инициализация
   desctype.idtype = 0;
   descvar.idtype = 0;
   descvar.flgdesc = 0;
   mem_zero( &fd, sizeof( fd ) );
   thistype = 0;
   funckey = curlex->key;
   hash_init( &fd.nvars, sizeof( uint ) );
   hash_init( &fd.nlabels, sizeof( uint ) );
   for ( b = &fd.bhead; b <= &fd.bvarsas; b++ )
   {
      buf_init( b );
      buf_reserve( b, 0x200 );
      b->step = 0x200;
   }
   fd.bvars.use = sizeof( fvar );
   fd.blabels.use = sizeof( flabel );
//   _compile->pout = &fd.bhead;   
//   fd.blcount = 0;
//   fd.varcount = 0;
//   fd.curcount = 0;
//   fd.lastcurcount = 0;
//   fd.bllevel = 0;
//   fd.blcycle = 0;
   fd.offlcbreak = -1;
   fd.offlccontinue = -1;   
//   fd.functype = 0;

   switch ( funckey )
   {
      case KEY_METHOD:
         flgfunc = GHBC_METHOD;
         break;
      case KEY_OPERATOR:
         flgfunc = GHBC_OPERATOR;
         break;
      case KEY_PROPERTY:
         flgfunc = GHBC_PROPERTY;
         break;
      case KEY_TEXT:
         flgfunc = GHBC_TEXT;
         break;
      default:
         flgfunc = 0;
   }
   curlex = lexem_next( curlex, LEXNEXT_IGNLINE );

// Получаем тип возвращаемого значения функции/метода если он есть
   if ( curlex->type == LEXEM_NAME )
      curlex = desc_idtype( curlex, &desctype );

   if ( desctype.idtype )
   {
      if ( ( funckey == KEY_METHOD || funckey == KEY_PROPERTY ) &&
           curlex->type == LEXEM_OPER &&
           curlex->oper.operid == OpWith )
      {
         //Возврат на лексему влево текущая лексема тип объекта
         desctype.idtype = 0;
         curlex--;
      }
      else
      {
         fd.functype = desctype.idtype;
         fd.funcoftype = desctype.oftype;
      }
   }
   lexprev = curlex;
   curlex = lexem_next( curlex, LEXNEXT_SKIPLINE );
// Получаем тип объекта для метода
   if ( funckey == KEY_METHOD || funckey == KEY_PROPERTY )
   {
      //Получаем тип объекта
	  if ( curlex->type > 32 )
		 msg( MExptype | MSG_LEXERR, lexprev );
	  if ( thistype = bc_type( curlex ) )
      {
         curlex = lexem_next( curlex, 0 );
         if ( curlex->type == LEXEM_OPER &&
              curlex->oper.operid == OpWith )
         {
            curlex = lexem_next( curlex, 0 );
         }
         else
            msg( MExppoint | MSG_LEXERR, curlex );
      }
      else
         msg( MExptype | MSG_LEXERR, curlex );
   }
// Получение имени функции, метода ...   
   if ( funckey == KEY_OPERATOR )
   {
      if ( curlex->type != LEXEM_OPER )
         msg( MExpoper | MSG_LEXERR, curlex );
      name = ( pubyte )&curlex->oper.name;
   }
   else
   {
      if ( curlex->type != LEXEM_NAME )
         msg( MExpname | MSG_LEXERR, curlex );
      name = lexem_getname( curlex );      
   }
   lexname = curlex;
   _vm.pos = curlex->pos;
   
// Получение списка директив
   curlex = lexem_next( curlex, flgextern ? 0 : LEXNEXT_IGNLINE );   
   curlex = bc_flag( curlex, BFLAG_FUNC, &bcf );   
   flgfunc |= GHCOM_NAME | bcf.value;
   _compile->pout = &fd.bhead;   
   out_head( OVM_BYTECODE, flgfunc, name );

   create_varmode( &fd.bhead, &desctype, 0 );//Возвращаемое значение

   off_parcount = fd.bhead.use;
   out_adduint( 0 );//Количество параметров

   if ( funckey == KEY_METHOD || funckey == KEY_PROPERTY )
   {   //Создание параметра this
      mem_zero( &descvar, sizeof( descvar ));
      descvar.idtype = thistype;
      descvar.name = "this";
      descvar.lex = curlex;
      descvar.flgdesc = DESCID_PARFUNC;

      pwith = ( pfwith )buf_appendtype( &fd.bwith, sizeof( fwith )) ;
      pwith->num = var_checkadd( &descvar );
      pwith->oftype = 0;
      pwith->type = thistype;
   }

//Получение списка параметров
   if ( curlex->type == LEXEM_OPER &&
        curlex->oper.operid == OpLbrack )//Открывающая скобка
   {
      curlex = lexem_next( curlex, LEXNEXT_IGNLINE );
      curlex = var_def( curlex, DESCID_PARFUNC );
      if ( curlex->type != LEXEM_OPER ||//Системная лексема
           curlex->oper.operid != OpRbrack )//Закрывающая скобка
         msg( MExpclosebr | MSG_LEXERR, curlex );

      curlex = lexem_next( curlex, flgextern ? 0 : LEXNEXT_IGNLINE );
   }
   else
   {
      if ( funckey == KEY_OPERATOR )
         msg( MExpopenbr | MSG_LEXERR, curlex );
   }

   fd.flgfunc = flgfunc;
   if ( flgfunc & GHBC_RESULT )
   {   //Создание параметра result
      if ( !fd.functype || fd.functype <= TUlong )
         msg( MResulttype | MSG_LEXERR, curlex );
      mem_zero( &descvar, sizeof( descvar ));
      descvar.idtype = desctype.idtype;
      descvar.oftype = desctype.oftype;
      descvar.flgdesc = DESCID_PARFUNC;
      descvar.name = "result";
      descvar.lex = curlex;
      fd.idresult = var_checkadd( &descvar );
      fd.functype = 0;
   }
   if ( fd.varcount )
   {
      *( puint )( fd.bhead.data + off_parcount ) = fd.varcount;//Кол-во параметров
      if ( flgfunc & ( GHBC_ENTRY | GHBC_MAIN ) )
         msg( MMainpar | MSG_LEXERR, curlex );
      fd.curcount = 0;
   }
   off_blccount = fd.bhead.use;
   out_adduint( 0 );//Количество блоков

   if ( funckey == KEY_PROPERTY )
   {      
      if ( ( fd.functype && fd.varcount > 1 ) ||
           (!fd.functype && fd.varcount != 2 ))
      {
         msg( MProppar | MSG_LEXERR, curlex );//Неверное количество параметров в описании свойства
      }
      if ( type_fieldname( thistype, name ) )
      {
         msg( MPropfield | MSG_LEXERR, curlex );//Свойство совпадает с именем поля
      }
   }
   
   funcobj = load_bytecode( &fd.bhead.data, flgextern ? VMLOAD_EXTERN : VMLOAD_FIRST );   
   if ( bcf.value & GHRT_ALIAS )
   {  
      alias_setid( bcf.alias, funcobj->id );     
   }
   if ( !( flgextern ) )
   {      
      if ( _compile->flag & CMPL_DEBUG )
      {  
         _compile->pout = fd.bout = &fd.bsubout;
         out_adduints( 3,  CDatasize, 
                           str_len( _compile->cur->filename ) + 5,
                           str_pos2line( _compile->cur->src, lexname->pos, 0 ) + 1 );
         out_addptr( str_ptr( _compile->cur->filename ), str_len( _compile->cur->filename ) + 1 );                     
         out_adduint( CDbgFunc );
         _compile->pout = fd.bout = &fd.bfuncout; 
      }
      _compile->pout = fd.bout = &fd.bfuncout;
      if ( funckey == KEY_TEXT )
      {   //Создание параметра this для Text функции
         mem_zero( &descvar, sizeof( descvar ));
         descvar.idtype = TUint;
         descvar.name = "this";
         descvar.lex = curlex;
         descvar.flgdesc = DESCID_VAR;///DESCID_PARFUNC;
         thisid = var_checkadd( &descvar );
         
         /*pwith = ( pfwith )buf_appendtype( &fd.bwith, sizeof( fwith )) ;
         pwith->num = var_checkadd( &descvar );
         //print( "ssssssssss %x %x %x %x", fd.bvars.data, fd.bvars.use, pwith->num, sizeof( fvar ) );
         pwith->oftype = 0;
         pwith->type = TStr;*/
         ((pfvar)(fd.bvars.data + fd.bvars.use - sizeof( fvar )))->type = TStr;
         out_adduints( 4, CVarptrload, thisid, CGetText, CSetI );
         /*buf_appenduint( &fd.bblinit, CVarptrload );
         buf_appenduint( &fd.bblinit, thisid );
         buf_appenduint( &fd.bblinit, CGetText );
         buf_appenduint( &fd.bblinit, CSetI );*/
      }
      curlex = f_body( curlex );
      
      *((puint)(fd.bhead.data+off_blccount)) = fd.blcount;

      curlabel = ( pflabel )( fd.blabels.data ) + 1;
      endlabel = ( pflabel )( fd.blabels.data + fd.blabels.use );
      //Контроль неразрешённых меток и проверка выходов из функции
      isreturn = 0;
      while( curlabel < endlabel )
      {
         if ( curlabel->type & LABT_GT )
         {
            if ( ( curlabel->type & LABT_GTUNDEF ) == LABT_GTUNDEF )
               msg( MUnklabel | MSG_LEXNAMEERR, curlabel->lex );
            *( puint )(fd.bfuncout.data + curlabel->offbout ) = 
                     ((( pflabel )(fd.blabels.data + curlabel->link ))->offbout + 
                      fd.bsubout.use )/sizeof(uint);
            if ( !isreturn )//Помечаем метку как отработавшую (на неё был переход)
               (( pflabel )(fd.blabels.data + curlabel->link ))->type |= LABT_LABELWORK;            
         }
         else
         if ( curlabel->type & LABT_RETURN )
         {
            isreturn = 1;//Устанавливаем флаг
         }
         else
         if ( curlabel->type & LABT_LABELWORK )
            isreturn = 0;//Если была отработавшая метка, то сбрасываем флаг
         curlabel++;
      }
      if ( fd.functype )
      {
         if ( !isreturn )
            msg( MMustret | MSG_LEXNAMEERR, lexname );
      }
      else
         if ( !isreturn )
         {
            if ( fd.flgfunc & GHBC_RESULT )
            {
               out_add2uint( CVarload, fd.idresult );
            }
            out_adduint( CReturn );
         }      
      buf_add( &fd.bhead, &fd.bvardef );
      
      if ( fd.bsubout.use )
      {
         if ( fd.offsubgoto )
         {
            //*((( puint)fd.bsubout.data ) + 1) = fd.bsubout.use/sizeof( uint );
            *( puint )( fd.bsubout.data + fd.offsubgoto ) = fd.bsubout.use / sizeof( uint );
         }
         buf_add( &fd.bhead, &fd.bsubout );
      }
      buf_add( &fd.bhead, &fd.bfuncout );
      _compile->pout = &fd.bhead;
      out_finish();
#ifdef DOUT
   //Тестируемый вывод 
   //if ( name[0] == 'c' && name[1] == 'r' ) getch();
   print( "FUNC OUT %x %s:\n", funcobj->id, name );
   for (i = 0; i < fd.bhead.use ; i++ )
   {
      print( "  %x", fd.bhead.data[i] );
   } 
   print( "\n" );
#endif            
      load_bytecode( &fd.bhead.data, VMLOAD_OK );
    //  print( "funcobjid2 =%x\n", funcobj->id );
   }
   //Очистка памяти
   for ( b = &fd.bhead;/*&fd.bblinit;*/ b <= &fd.bvarsas; b++ )
   {
      buf_delete( b );
   }
   hash_delete( &fd.nvars );
   hash_delete( &fd.nlabels );

D( "Func Stop\n" );
   return curlex;
}
Exemple #18
0
static void node_print(buf_t *buf, node_t *node, unsigned depth)
{
    size_t i;

    if (!node) return;

    indent(buf, depth);

    switch (node->type)
    {
    case DOCTYPE:
        buf_add(buf, "<!DOCTYPE ");
        buf_add(buf, node->data.doctype.name);

        if (node->data.doctype.public_id ||
                node->data.doctype.system_id) {
            if (node->data.doctype.public_id) {
                buf_add(buf, " \"");
                buf_add(buf, node->data.doctype.public_id);
                buf_add(buf, "\" ");
            } else {
                buf_add(buf, "\"\" ");
            }

            if (node->data.doctype.system_id) {
                buf_add(buf, " \"");
                buf_add(buf, node->data.doctype.system_id);
                buf_add(buf, "\"");
            } else {
                buf_add(buf, "\"\"");
            }
        }

        buf_add(buf, ">\n");
        break;
    case ELEMENT:
        buf_add(buf, "<");
        print_ns(buf, node->data.element.ns);
        buf_add(buf, node->data.element.name);
        buf_add(buf, ">\n");

        qsort(node->data.element.attrs, node->data.element.n_attrs,
              sizeof *node->data.element.attrs,
              compare_attrs);

        for (i = 0; i < node->data.element.n_attrs; i++) {
            indent(buf, depth + 1);
            print_ns(buf, node->data.element.attrs[i].ns);
            buf_add(buf, node->data.element.attrs[i].name);
            buf_add(buf, "=");
            buf_add(buf, "\"");
            buf_add(buf, node->data.element.attrs[i].value);
            buf_add(buf, "\"\n");
        }

        break;
    case CHARACTER:
        buf_add(buf, "\"");
        buf_add(buf, node->data.content);
        buf_add(buf, "\"\n");
        break;
    case COMMENT:
        buf_add(buf, "<!-- ");
        buf_add(buf, node->data.content);
        buf_add(buf, " -->\n");
        break;
    default:
        printf("Unexpected node type %d\n", node->type);
        assert(0);
    }

    if (node->child) {
        node_print(buf, node->child, depth + 1);
    }

    if (node->next) {
        node_print(buf, node->next, depth);
    }
}
Exemple #19
0
static void
test_proto_var_cell(void *arg)
{
  (void)arg;
  char *mem_op_hex_tmp = NULL;
  char tmp[1024];
  buf_t *buf = NULL;
  var_cell_t *cell = NULL;

  buf = buf_new();
  memset(tmp, 0xf0, sizeof(tmp));

  /* Short little commands will make us say "no cell yet." */
  tt_int_op(0, OP_EQ, fetch_var_cell_from_buf(buf, &cell, 4));
  tt_ptr_op(cell, OP_EQ, NULL);
  buf_add(buf, "\x01\x02\x02\0x2", 4);
  tt_int_op(0, OP_EQ, fetch_var_cell_from_buf(buf, &cell, 4));
  /* An incomplete fixed-length cell makes us say "no cell yet". */
  buf_add(buf, "\x03", 1);
  tt_int_op(0, OP_EQ, fetch_var_cell_from_buf(buf, &cell, 4));
  /* A complete fixed length-cell makes us say "not a variable-length cell" */
  buf_add(buf, tmp, 509);
  tt_int_op(0, OP_EQ, fetch_var_cell_from_buf(buf, &cell, 4));
  buf_clear(buf);

  /* An incomplete versions cell is a variable-length cell that isn't ready
   * yet. */
  buf_add(buf,
          "\x01\x02\x03\x04" /* circid */
          "\x07" /* VERSIONS */
          "\x00\x04" /* 4 bytes long */
          "\x00" /* incomplete */, 8);
  tt_int_op(1, OP_EQ, fetch_var_cell_from_buf(buf, &cell, 4));
  tt_ptr_op(cell, OP_EQ, NULL);
  /* Complete it, and it's a variable-length cell. Leave a byte on the end for
   * fun. */
  buf_add(buf, "\x09\x00\x25\ff", 4);
  tt_int_op(1, OP_EQ, fetch_var_cell_from_buf(buf, &cell, 4));
  tt_ptr_op(cell, OP_NE, NULL);
  tt_int_op(cell->command, OP_EQ, CELL_VERSIONS);
  tt_uint_op(cell->circ_id, OP_EQ, 0x01020304);
  tt_int_op(cell->payload_len, OP_EQ, 4);
  test_mem_op_hex(cell->payload, OP_EQ, "00090025");
  var_cell_free(cell);
  cell = NULL;
  tt_int_op(buf_datalen(buf), OP_EQ, 1);
  buf_clear(buf);

  /* In link protocol 3 and earlier, circid fields were two bytes long. Let's
   * ensure that gets handled correctly. */
  buf_add(buf,
          "\x23\x45\x81\x00\x06" /* command 81; 6 bytes long */
          "coraje", 11);
  tt_int_op(1, OP_EQ, fetch_var_cell_from_buf(buf, &cell, 3));
  tt_ptr_op(cell, OP_NE, NULL);
  tt_int_op(cell->command, OP_EQ, 129);
  tt_uint_op(cell->circ_id, OP_EQ, 0x2345);
  tt_int_op(cell->payload_len, OP_EQ, 6);
  tt_mem_op(cell->payload, OP_EQ, "coraje", 6);
  var_cell_free(cell);
  cell = NULL;
  tt_int_op(buf_datalen(buf), OP_EQ, 0);

  /* In link protocol 2, only VERSIONS cells counted as variable-length */
  buf_add(buf,
          "\x23\x45\x81\x00\x06"
          "coraje", 11); /* As above */
  tt_int_op(0, OP_EQ, fetch_var_cell_from_buf(buf, &cell, 2));
  buf_clear(buf);
  buf_add(buf,
          "\x23\x45\x07\x00\x06"
          "futuro", 11);
  tt_int_op(1, OP_EQ, fetch_var_cell_from_buf(buf, &cell, 2));
  tt_ptr_op(cell, OP_NE, NULL);
  tt_int_op(cell->command, OP_EQ, 7);
  tt_uint_op(cell->circ_id, OP_EQ, 0x2345);
  tt_int_op(cell->payload_len, OP_EQ, 6);
  tt_mem_op(cell->payload, OP_EQ, "futuro", 6);
  var_cell_free(cell);
  cell = NULL;

 done:
  buf_free(buf);
  var_cell_free(cell);
  tor_free(mem_op_hex_tmp);
}
Exemple #20
0
int main(int argc, char **argv)
{
	FILE *fp;
	char line[2048];

	bool reprocess = false;
	bool passed = true;

	hubbub_parser *parser = NULL;
	enum reading_state state = EXPECT_DATA;

	buf_t expected = { NULL, 0, 0 };
	buf_t got = { NULL, 0, 0 };


	if (argc != 2) {
		printf("Usage: %s <filename>\n", argv[0]);
		return 1;
	}

	fp = fopen(argv[1], "rb");
	if (fp == NULL) {
		printf("Failed opening %s\n", argv[1]);
		return 1;
	}

	/* We rely on lines not being anywhere near 2048 characters... */
	while (reprocess || (passed && fgets(line, sizeof line, fp) == line)) {
		reprocess = false;

		switch (state)
		{
		case ERASE_DATA:
			buf_clear(&got);
			buf_clear(&expected);

			hubbub_parser_destroy(parser);
			while (Document) {
				node_t *victim = Document;
				Document = victim->next;
				delete_node(victim);
			}
			Document = NULL;

			state = EXPECT_DATA;

 		case EXPECT_DATA:
			if (strcmp(line, "#data\n") == 0) {
				parser = setup_parser();
				state = READING_DATA;
			}
			break;

		case READING_DATA:
		case READING_DATA_AFTER_FIRST:
			if (strcmp(line, "#errors\n") == 0) {
				assert(hubbub_parser_completed(parser) == HUBBUB_OK);
				state = READING_ERRORS;
			} else {
				size_t len = strlen(line);

				if (state == READING_DATA_AFTER_FIRST) {
					assert(hubbub_parser_parse_chunk(parser,
						(uint8_t *)"\n",
						1) == HUBBUB_OK);
				} else {
					state = READING_DATA_AFTER_FIRST;
				}

				printf(": %s", line);
				assert(hubbub_parser_parse_chunk(parser, (uint8_t *)line,
						len - 1) == HUBBUB_OK);
			}
			break;


		case READING_ERRORS:
			if (strcmp(line, "#document-fragment\n") == 0) {
				state = ERASE_DATA;
				reprocess = true;
			}

			if (strcmp(line, "#document\n") == 0)
				state = READING_TREE;
			else {
			}
			break;

		case READING_TREE:
			if (strcmp(line, "#data\n") == 0) {
				node_print(&got, Document, 0);

				/* Trim off the last newline */
				expected.buf[strlen(expected.buf) - 1] = '\0';

				passed = !strcmp(got.buf, expected.buf);
				if (!passed) {
					printf("expected:\n");
					printf("%s", expected.buf);
					printf("got:\n");
					printf("%s", got.buf);
				}

				state = ERASE_DATA;
				reprocess = true;
			} else {
				buf_add(&expected, line);
			}
			break;
		}
	}

	if (Document != NULL) {
		node_print(&got, Document, 0);

		passed = !strcmp(got.buf, expected.buf);
		if (!passed) {
			printf("expected:\n");
			printf("%s", expected.buf);
			printf("got:\n");
			printf("%s", got.buf);
		}

		hubbub_parser_destroy(parser);
		while (Document) {
			node_t *victim = Document;
			Document = victim->next;
			delete_node(victim);
		}
	}

	printf("%s\n", passed ? "PASS" : "FAIL");

	fclose(fp);

	free(got.buf);
	free(expected.buf);

	return 0;
}
Exemple #21
0
void buf_add_str (struct buf *buf, char *str)
{
    char c;
    int i = 0;
    while ((c = str[i++]) != '\0') buf_add(buf, c);
}
Exemple #22
0
int main (int argc, char *argv[])
{
    FILE *fpi = stdin, *fpo = stdout, *fpmap;
    struct mapper mapper;
    struct record record;
    struct map *map;
    struct field *field;
    struct buf *val_buf = buf_new(1024), *xml_buf = NULL;
    char *xml_key, *key_buf, prev_seq[9], seq[9], tag[4], ind1, ind2;
    int file_args = 0, array = 1, xml = 0, mapfile = 0, count = 0,
        first = 0, first_sub = 0, first_char, skip_sub = 0, c, i, j;

    tag[3] = '\0';

    for (i = 1; i < argc; i++) {
        if (!strcmp(argv[i], "--usage") || !strcmp(argv[i], "--help") || !strcmp(argv[i], "-?")) {
            usage(argv[0], 0);
        } else if (!strcmp(argv[i], "--newline")) {
            array = 0;
        } else if (!strcmp(argv[i], "--xml")) {
            xml = 1;
        } else if (!strcmp(argv[i], "--json")) {
            xml = 0;
        } else if (!strcmp(argv[i], "--xmlkey")) {
            if (++i == argc) usage(argv[0], 1);
            xml_key = argv[i];
            xml_buf = buf_new(2048);
        } else if (!strcmp(argv[i], "--mapfile")) {
            if (++i == argc) usage(argv[0], 1);

            key_buf = malloc(256);

            if ((fpmap = fopen(argv[i], "r")) == NULL) {
                fprintf(stderr, "Can't open %s for reading\n", argv[i]);
                return 1;
            }

            if (!mapfile) {
                mapfile = 1;

                mapper.size = mapper.grow = 100;
                mapper.used = 0;
                mapper.maps = malloc(sizeof(struct map) * mapper.size);

                record.size = record.grow = 100;
                record.used = 0;
                record.fields = malloc(sizeof(struct field) * record.size);
                for (j = 0; j < record.size; j++) {
                    record.fields[j].val = buf_new(1024);
                }
            }

            while ((c = getc(fpmap)) != EOF) {
                if (isspace(c)) continue;
                if (c == '#') {
                    while (more(c = getc(fpmap)));
                    continue;
                }
                map = mapper.maps + mapper.used;
                map->key = NULL;
                map->tag[0] = c;
                map->tag[1] = getc(fpmap);
                map->tag[2] = getc(fpmap);
                if (isspace(c = getc(fpmap))) {
                    map->op = '\0';
                } else {
                    map->op = c;
                    fscanf(fpmap, "%s", map->subfields);
                }
                fscanf(fpmap, "%s", key_buf);
                for (j = 0; j < mapper.used; j++) {
                    if (!strcmp(mapper.maps[j].key, key_buf)) {
                        map->key = mapper.maps[j].key;
                        break;
                    }
                }
                if (!map->key) {
                    map->key = malloc(strlen(key_buf) + 1);
                    strcpy(map->key, key_buf);
                }

                mapper.used++;
                if (mapper.used == mapper.size) {
                    mapper.size += mapper.grow;
                    mapper.maps = realloc(mapper.maps, sizeof(struct map) * mapper.size);
                }
            }

            free(key_buf);
            fclose(fpmap);
        } else {
            switch (++file_args) {
            case 1:
                if ((fpi = fopen(argv[i], "r")) == NULL) {
                    fprintf(stderr, "Can't open %s for reading\n", argv[i]);
                    return 1;
                }
                break;
            case 2:
                if ((fpo = fopen(argv[i], "w")) == NULL) {
                    fprintf(stderr, "Can't open %s for writing\n", argv[i]);
                    return 1;
                }
                break;
            }
        }
    }

    if (xml) {
        fputs("<?xml version=\"1.0\" encoding=\"UTF-8\"?><collection xmlns=\"http://www.loc.gov/MARC21/slim\">", fpo);
    } else if (array) {
        fputs("[", fpo);
    }

    while ((c = getc(fpi)) != EOF) {
        if (isspace(c)) continue;
        seq[0] = c;
        for (i = 1; i < 9; ++i) seq[i] = getc(fpi);
        getc(fpi);
        for (i = 0; i < 3; ++i) tag[i] = getc(fpi);
        ind1 = getc(fpi);
        ind2 = getc(fpi);
        for (i = 0; i < 3; ++i) getc(fpi);
        val_buf->used = 0;
        while (more(c = getc(fpi))) buf_add(val_buf, c);
        buf_add(val_buf, '\0');

        if (!count || strncmp(seq, prev_seq, 9)) {
            if (count++) {
                if (xml_buf) {
                    buf_add_str(xml_buf, "</record>");
                    buf_add(xml_buf, '\0');
                }
                if (mapfile) {
                    fputs("{", fpo);
                    for (i = 0; i < record.used; i++) {
                        field = record.fields + i;
                        if (i) putc(',', fpo);
                        buf_add(field->val, '\0');
                        fprintf(fpo, "\"%s\":[%s]", field->key, field->val->str);
                    }
                    if (xml_buf) {
                        if (i) putc(',', fpo);
                        fprintf(fpo, "\"%s\":\"", xml_key);
                        put_json_str(xml_buf->str, fpo);
                        putc('\"', fpo);
                    }
                    fputs(array ? "},\n" : "}\n", fpo);
                    record.used = 0;
                } else if (xml) {
                    fputs("</record>\n", fpo);
                } else {
                    fputs(array ? "]},\n" : "]}\n", fpo);
                }
                if (xml_buf) {
                    xml_buf->used = 0;
                }
            }
        }

        for (i = 0; i < 9; ++i) prev_seq[i] = seq[i];

        if (mapfile) {
            for (i = 0; i < mapper.used; i++) {
                map = mapper.maps + i;
                if ((map->tag[0] == '*' || map->tag[0] == tag[0]) &&
                    (map->tag[1] == '*' || map->tag[1] == tag[1]) &&
                    (map->tag[2] == '*' || map->tag[2] == tag[2])) {
                    field = NULL;
                    for (j = 0; j < record.used; j++) {
                        field = record.fields + j;
                        if (field->key == map->key) {
                            break;
                        }
                        field = NULL;
                    }
                    if (!field) {
                        field = record.fields + record.used;
                        field->key = map->key;
                        field->val->used = 0;
                        record.used++;
                    }
                    skip_sub = 0;
                    first_char = 1;
                    for (j = 0; j < val_buf->used-1; j++) {
                        if (val_buf->str[j] == '$' && val_buf->str[j+1] == '$') {
                            j+= 2;
                            if ( (map->op == '+' && strchr(map->subfields, val_buf->str[j]) == NULL) ||
                                 (map->op == '-' && strchr(map->subfields, val_buf->str[j]) != NULL) ) {
                                skip_sub = 1;
                                continue;
                            }
                            skip_sub = 0;
                            j++;
                            if (j == val_buf->used-1) break;
                        }

                        if (!skip_sub) {
                            if (first_char) {
                                if (field->val->used) buf_add(field->val, ',');
                                buf_add(field->val, '"');
                                first_char = 0;
                            }
                            if (val_buf->str[j] == '"') buf_add(field->val, '\\');
                            if (val_buf->str[j] == '\\') buf_add(field->val, '\\');
                            buf_add(field->val, val_buf->str[j]);
                        }
                    }
                    if (!first_char) buf_add(field->val, '"');
                }
            }
        }

        if (!strncmp(tag, "FMT", 3)) continue;

        if (!strncmp(tag, "LDR", 3)) {
            if (xml_buf) {
                buf_add_str(xml_buf, "<record><leader>");
                buf_add_str(xml_buf, val_buf->str);
                buf_add_str(xml_buf, "</leader>");
            } else if (xml) {
                fprintf(fpo, "<record><leader>%s</leader>", val_buf->str);
            } else if (!mapfile) {
                fprintf(fpo, "{\"leader\":\"%s\",\"fields\":[", val_buf->str);
            }
            first = 1;
            continue;
        }

        if (first) {
            first = 0;
        } else if (!xml_buf && !xml && !mapfile) {
            putc(',', fpo);
        }

        if (tag[0] == '0' && tag[1] == '0') {
            if (xml_buf) {
                buf_add_str(xml_buf, "<controlfield tag=\"");
                for (i = 0; i < 3; i++) buf_add(xml_buf, tag[i]);
                buf_add_str(xml_buf, "\">");
                buf_add_xml_str(xml_buf, val_buf->str);
                buf_add_str(xml_buf, "</controlfield>");
            } else if (xml) {
                fprintf(fpo, "<controlfield tag=\"%3s\">", tag);
                for (i = 0; i < val_buf->used-1; i++) put_xml(val_buf->str[i], fpo);
                fputs("</controlfield>", fpo);
            } else if (!mapfile) {
                fprintf(fpo, "{\"%3s\":\"", tag);
                for (i = 0; i < val_buf->used-1; i++) put_json(val_buf->str[i], fpo);
                fputs("\"}", fpo);
            }
        } else {
            if (xml_buf) {
                buf_add_str(xml_buf, "<datafield tag=\"");
                for (i = 0; i < 3; i++) buf_add(xml_buf, tag[i]);
                buf_add_str(xml_buf, "\" ind1=\"");
                buf_add(xml_buf, ind1);
                buf_add_str(xml_buf, "\" ind2=\"");
                buf_add(xml_buf, ind2);
                buf_add_str(xml_buf, "\">");
            } else if (xml) {
                fprintf(fpo, "<datafield tag=\"%3s\" ind1=\"%c\" ind2=\"%c\">", tag, ind1, ind2);
            } else if (!mapfile) {
                fprintf(fpo, "{\"%3s\":{\"ind1\":\"%c\",\"ind2\":\"%c\",\"subfields\":[", tag, ind1, ind2);
            }
            first_sub = 1;
            for (i = 0; i < val_buf->used-1; i++) {
                if (val_buf->str[i] == '$' && val_buf->str[i+1] == '$') {
                    i+= 2;
                    if (first_sub) {
                        first_sub = 0;
                    } else {
                        if (xml_buf) {
                            buf_add_str(xml_buf, "</subfield>");
                        } else if (xml) {
                            fputs("</subfield>", fpo);
                        } else if (!mapfile) {
                            fputs("\"},", fpo);
                        }
                    }
                    if (xml_buf) {
                        buf_add_str(xml_buf, "<subfield code=\"");
                        buf_add(xml_buf, val_buf->str[i]);
                        buf_add_str(xml_buf, "\">");
                    } else if (xml) {
                        fprintf(fpo, "<subfield code=\"%c\">", val_buf->str[i]);
                    } else if (!mapfile) {
                        fprintf(fpo, "{\"%c\":\"", val_buf->str[i]);
                    }
                    continue;
                }
                if (xml_buf) {
                    buf_add_xml(xml_buf, val_buf->str[i]);
                } else if (xml) {
                    put_xml(val_buf->str[i], fpo);
                } else if (!mapfile) {
                    put_json(val_buf->str[i], fpo);
                }
            }
            if (!first_sub) {
                if (xml_buf) {
                    buf_add_str(xml_buf, "</subfield>");
                } else if (xml) {
                    fputs("</subfield>", fpo);
                } else if (!mapfile) {
                    fputs("\"}", fpo);
                }
            }
            if (xml_buf) {
                buf_add_str(xml_buf, "</datafield>");
            } else if (xml) {
                fputs("</datafield>", fpo);
            } else if (!mapfile) {
                fputs("]", fpo);
            }
        }
    }

    if (count && mapfile) {
        fputs("{", fpo);
        for (i = 0; i < record.used; i++) {
            field = record.fields + i;
            if (i) putc(',', fpo);
            buf_add(field->val, '\0');
            fprintf(fpo, "\"%s\":[%s]", field->key, field->val->str);
        }
        if (xml_buf) {
            if (i) putc(',', fpo);
            fprintf(fpo, "\"%s\":\"", xml_key);
            put_json_str(xml_buf->str, fpo);
            putc('\"', fpo);
        }
    }

    if (xml) {
        if (count) fputs("</record>", fpo);
        fputs("</collection>", fpo);
    } else {
        if (count) fputs("}", fpo);
        if (array) fputs("]", fpo);
    }

    fclose(fpi);
    fclose(fpo);

    return 0;
}
Exemple #23
0
void modbus_rec(uint8_t val)
{
    uint16_t add = 0, num = 0;
    uint8_t i;
    uint16_t *pt = mod_buf;
    
    rec_buf[rec_num] = val;
    clear_flag = 1;
    clear_num = 0;
    
    if (mb_step== 0)
    {
        if (rec_num == 0)
        {
            //判断地址是否一致,不是则放弃
            if (rec_buf[rec_num] == dev_addr)
            {
                //地址一致,则继续
                rec_num ++;
            }
            else
            {
                //地址不一致,则放弃
                rec_buf[0] = 0;
            }
        }
        else if (rec_num == 1)
        {
            //功能码判断
            if (rec_buf[1] == 0x03)
            {
                //读参数
                mb_step = 1;
                rec_num ++;
            }
            else if (rec_buf[1] == 0x06)
            {
                //写数据
                mb_step = 2;
                rec_num ++;
            }
            else
            {
                //不支持的命令,则清零
                rec_num = 0;
                rec_buf[0] = 0;
                rec_buf[1] = 0;
            }
        }       
    }
    else if(mb_step == 1)
    {
        rec_num ++;
        
        if (rec_num == 8)
        {
            //得到8个数据后处理
            add = (rec_buf[2] << 8) + rec_buf[3];
            num = (rec_buf[4] << 8) + rec_buf[5];
            
            if ((add >= 0x10) && (add < (0x10 + MODBUS_SIZE)) && (num < (MODBUS_SIZE + 1)) && (num >= 1))
            {
                //减去偏移量
                add -= 0x10;
                
                if (num > ((MODBUS_SIZE + 1) - add))
                {
                    //保证不读取多余的无效位
                    num = (MODBUS_SIZE + 1) - add;
                }
                
                //移动起始位置
                pt += add;
                
                buf_add(dev_addr);
                buf_add(0x03);
                buf_add(2 * num);
                
                for (i = 0; i < num; i ++)
                {
                    //读取num * 2个数据加入发送缓存
                    buf_add((uint8_t)(*(pt + i) >> 8));     //高字节在前
                    buf_add((uint8_t)(*(pt + i) & 0xff));   //低字节在后
                }
                
                send_flag = 1;
            }
Exemple #24
0
void wiki_out(Database* db, char* page_name)
{
    Wiki* wiki_a = wiki_new();
    char* line_a;
    char* c;
    char* p;
    LineMode mode = LINE_MODE_NORMAL;

    wiki_a = db_get_newest_wiki(db, page_name, wiki_a);
    p = wiki_a->content;
    /* FIXME 非効率だけど、安全のために、1行分のバッファに全文の長さを確保する。 */
    line_a = xalloc(sizeof(char) * strlen(wiki_a->content));
    buf_clear();
    while ((strlen(p) != 0)) {
        if ((c = strchr(p, '\n')) != NULL) {
            int len = c - p;
            strncpy(line_a, p, len);
            line_a[len] = '\0';
            p += len + 1;
        } else {
            strcpy(line_a, p);
            p += strlen(p);
        }
        if (mode == LINE_MODE_PRE && strncmp(line_a, "|<", strlen("|<")) != 0) {
            /* LINE_MODE_PRE中は、成形済ブロック */
            buf_add(TYPE_PRE, line_a);
        } else if (mode == LINE_MODE_NORMAL && strncmp(line_a, ">|", strlen(">|")) == 0) {
            /* 成形済ブロック終了 */
            buf_flush();
            mode = LINE_MODE_PRE;
        } else if (mode == LINE_MODE_PRE && strncmp(line_a, "|<", strlen("|<")) == 0) {
            /* 成形済ブロック開始 */
            buf_flush();
            mode = LINE_MODE_NORMAL;
        } else if (strncmp(line_a, "****", strlen("****")) == 0) {
            buf_flush();
            element_out("h6", line_a + strlen("****"));
        } else if (strncmp(line_a, "***", strlen("***")) == 0) {
            buf_flush();
            element_out("h5", line_a + strlen("***"));
        } else if (strncmp(line_a, "**", strlen("**")) == 0) {
            buf_flush();
            element_out("h4", line_a + strlen("**"));
        } else if (strncmp(line_a, "*", strlen("*")) == 0) {
            buf_flush();
            element_out("h3", line_a + strlen("*"));
        } else if (strncmp(line_a, "----", strlen("----")) == 0) {
            buf_flush();
            element_out_without_content("hr");
        } else if (strncmp(line_a, "-", strlen("-")) == 0) {
            buf_add(TYPE_LI, line_a + strlen("-"));
        } else if (strncmp(line_a, "\n", strlen("\n")) == 0) {
            buf_flush();
        } else {
            buf_add(TYPE_TEXT, line_a);
        }
    }
    buf_flush();
    xfree(line_a);
    wiki_free(wiki_a);
}
Exemple #25
0
pstr  STDCALL str_add( pstr dest, pstr src )
{
   dest->use--;
   return buf_add( dest, src );
}