示例#1
0
文件: pg_encode.c 项目: Dasudian/otp
void encode_result(ei_x_buff* x, PGresult* res, PGconn* conn)
{
    int row, n_rows, col, n_cols;
    switch (PQresultStatus(res)) {
    case PGRES_TUPLES_OK: 
	n_rows = PQntuples(res); 
	n_cols = PQnfields(res); 
	ei_x_encode_tuple_header(x, 2);
	encode_ok(x);
	ei_x_encode_list_header(x, n_rows+1);
 	ei_x_encode_list_header(x, n_cols);
	for (col = 0; col < n_cols; ++col) {
	    ei_x_encode_string(x, PQfname(res, col));
	}
	ei_x_encode_empty_list(x); 
	for (row = 0; row < n_rows; ++row) {
	    ei_x_encode_list_header(x, n_cols);
	    for (col = 0; col < n_cols; ++col) {
		ei_x_encode_string(x, PQgetvalue(res, row, col));
	    }
	    ei_x_encode_empty_list(x);
	}
	ei_x_encode_empty_list(x); 
	break; 
    case PGRES_COMMAND_OK:
	ei_x_encode_tuple_header(x, 2);
        encode_ok(x);
	ei_x_encode_string(x, PQcmdTuples(res));
        break;
    default:
	encode_error(x, conn);
	break;
    }
}
示例#2
0
static void send_replies(char *buff, int *index) {
  ei_x_buff xbuf;
  gint arity, i;
  
  make_xbuf(&xbuf);
  
  if ( ! ((arity = gn_get_list(&xbuf, buff, index)) > -1) ) {
    send_xbuf(&xbuf);
    return;
  }
  
  for (i = 0; i < arity; i++) {
    if ( ((i+1)%1000) == 0 ) {
      ei_x_encode_empty_list(&xbuf);
      send_xbuf(&xbuf);
      make_xbuf(&xbuf);
    }
    ei_x_encode_list_header(&xbuf, 1);
    if ( ! make_reply(&xbuf, buff, index) ) 
      break;
  }
  
  ei_x_encode_empty_list(&xbuf);
  send_xbuf(&xbuf);
}
示例#3
0
void *erlXML_StartElementHandler(expat_data *d,
				 const XML_Char *name,
				 const XML_Char **atts)
{
   int i;

   ei_x_encode_list_header(&event_buf, 1);
   ei_x_encode_tuple_header(&event_buf, 2);
   ei_x_encode_long(&event_buf, XML_START);
   ei_x_encode_tuple_header(&event_buf, 2);
   ei_x_encode_string(&event_buf, name);

   for (i = 0; atts[i]; i += 2) {}

   if (i > 0)
   {
      ei_x_encode_list_header(&event_buf, i/2);

      for (i = 0; atts[i]; i += 2)
      {
	 ei_x_encode_tuple_header(&event_buf, 2);
	 ei_x_encode_string(&event_buf, atts[i]);
	 ei_x_encode_string(&event_buf, atts[i+1]);
      }
   }

   ei_x_encode_empty_list(&event_buf);

   return NULL;
}
示例#4
0
int gn_start_cnode(char **argv) { 
  extern ei_cnode ec;
  char rem_node_name[MAXATOMLEN] = "";	/* other node name */
  ei_x_buff xbuf;
  erlang_pid *self = ei_self(&ec);

  strcat(rem_node_name,REMNODE);
  strcat(rem_node_name,"@");
  strcat(rem_node_name,REMHOST);
  rem_regname = g_strdup(REMREG);
  g_print("I am %s, you are %s (%d)\n", NODE_NAME, rem_node_name, ERL_DIST_VSN);

  ei_set_compat_rel(ERL_DIST_VSN); /* erlnode version of dist. protocol */

  if ( ei_connect_init(&ec, NODE_NAME, COOKIE, CREATION) < 0 )
    g_critical("ei_connect_init");

  if ( (fd = ei_connect(&ec, rem_node_name)) < 0 )
    g_critical("ei_connect failed.\nwrong cookie? erl-dist version mismatch?");
  
  self->num = fd;		/* bug?? in ei_reg_send_tmo */

  ei_x_new_with_version(&xbuf);
  gn_wrap_ans("handshake", &xbuf);
  ei_x_encode_empty_list(&xbuf);
  gn_send(&xbuf);
  ei_x_free(&xbuf);
  
  return fd;
} 
示例#5
0
void *erlXML_StartElementHandler(expat_data *d,
				 const XML_Char *name,
				 const XML_Char **atts)
{
   int i;

   ei_x_encode_list_header(&event_buf, 1);
   ei_x_encode_tuple_header(&event_buf, 2);
   ei_x_encode_long(&event_buf, XML_START);
   ei_x_encode_tuple_header(&event_buf, 2);
   encode_name(name);
   ei_x_append(&event_buf, &xmlns_buf);
   ei_x_free(&xmlns_buf);
   ei_x_new(&xmlns_buf);

   for (i = 0; atts[i]; i += 2) {}

   if (i > 0)
   {
      ei_x_encode_list_header(&event_buf, i/2);

      for (i = 0; atts[i]; i += 2)
      {
	 ei_x_encode_tuple_header(&event_buf, 2);
	 encode_name(atts[i]);
	 ei_x_encode_binary(&event_buf, atts[i+1], strlen(atts[i+1]));
      }
   }

   ei_x_encode_empty_list(&event_buf);

   return NULL;
}
void ei_encode_switch_event_headers(ei_x_buff * ebuf, switch_event_t *event)
{
	int i;
	char *uuid = switch_event_get_header(event, "unique-id");

	switch_event_header_t *hp;

	for (i = 0, hp = event->headers; hp; hp = hp->next, i++);

	if (event->body)
		i++;

	ei_x_encode_list_header(ebuf, i + 1);

	if (uuid) {
		_ei_x_encode_string(ebuf, switch_event_get_header(event, "unique-id"));
	} else {
		ei_x_encode_atom(ebuf, "undefined");
	}

	for (hp = event->headers; hp; hp = hp->next) {
		ei_x_encode_tuple_header(ebuf, 2);
		_ei_x_encode_string(ebuf, hp->name);
		switch_url_decode(hp->value);
		_ei_x_encode_string(ebuf, hp->value);
	}

	if (event->body) {
		ei_x_encode_tuple_header(ebuf, 2);
		_ei_x_encode_string(ebuf, "body");
		_ei_x_encode_string(ebuf, event->body);
	}

	ei_x_encode_empty_list(ebuf);
}
示例#7
0
gboolean GN_tree_view_get_selected(int ARI, ei_x_buff *XBUF, char *B, int *I){
  GtkTreeView *tv;
  GtkTreeSelection *selection;
  GtkTreeModel *model;
  gchar* path;

  if ( ! gn_check_arity(XBUF, 1, ARI) )
    return FALSE;
  if ( ! gn_get_arg_object(XBUF, B, I, GTK_TYPE_TREE_VIEW, (GObject**)&tv) )
    return FALSE;

  model = gtk_tree_view_get_model(tv);
  selection = gtk_tree_view_get_selection(tv);

  GList* list = gtk_tree_selection_get_selected_rows(selection, &model);

  gn_wrap_reply("ok", XBUF);

  while ( list ) {
    path = gtk_tree_path_to_string( (GtkTreePath*) list->data);
    g_assert( ! ei_x_encode_list_header(XBUF, 1) );
    g_assert( ! ei_x_encode_string(XBUF, path) );
    g_free(path);
    list = list->next;
  }
  g_list_free(list);
  g_assert( ! ei_x_encode_empty_list(XBUF));
  return TRUE;
}
示例#8
0
文件: q2e.c 项目: csurface/gen_q
int ei_x_encode_kstring(ei_x_buff* types, ei_x_buff* values, K r, QOpts* opts) {
    EI(ei_x_encode_atom(types, "string"));
    if(r->n == 0) {
        EI(ei_x_encode_empty_list(values));
    } else {
        EI(ei_x_encode_string_len(values, (const char*)kC(r), r->n));
    }
    return 0;
}
示例#9
0
文件: q2e.c 项目: csurface/gen_q
int ei_x_encode_same_list_byte(ei_x_buff* types, ei_x_buff* values, const char* t, K r, QOpts* opts) {
    EI(ei_x_encode_tuple_header(types, 2));
    EI(ei_x_encode_atom(types, "list"));
    EI(ei_x_encode_atom(types, t));
    if(r->n == 0) {
        EI(ei_x_encode_empty_list(values));
    } else {
        EI(ei_x_encode_string_len(values, (const char*)kG(r), r->n));
    }
    return 0;
}
示例#10
0
文件: ei_format.c 项目: Dasudian/otp
/* encode a list */
static int plist(const char** fmt, union arg** args, ei_x_buff* x, int size)
{
    int res = 0;
    const char* p = *fmt;
    char after = *p++;

    if (after == ']')
	--p;
    while (isspace((int)*p))
	++p;
    switch (*p++) {
    case ']':
	if (after == ',')
	    res = -1;
	else {
	    if (after != '|')
		ei_x_encode_empty_list(x);
	    res = size;
	}
	break;
    case '|':
	if (after == '|' || after == ',')
	    res = -1;
	else
	    res = plist(&p, args, x, size);
	break;
    case ',':
	if (after == '|' || after == ',')
	    res = -1;
	else
	    res = plist(&p, args, x, size);
	break;
    default:
	--p;
	res = eiformat(&p, args, x);
	++size;
	if (res >= 0) {
	    if (after == '|') {
	        while (isspace((int)*p))
		    ++p;
		if (*p != ']')
		    res = -1;
	    } else
		res = plist(&p, args, x, size);
	}
	break;
	/*
	Variables
	*/
    }
    *fmt = p;
    return res;
}
示例#11
0
static int erl_json_ei_end_map(void* ctx) {
  State* pState = (State*) ctx;

  flog(stderr, "end map", 0, 0, 0);
  
  if(pState->skip_list_header_for_value) {
    ei_x_encode_tuple_header(&pState->ei_buf, 0);
    pState->skip_list_header_for_value = 0;
  }
  ei_x_encode_empty_list(&pState->ei_buf);

  return 1;
}
示例#12
0
static int erl_json_ei_end_array(void* ctx) {
  State* pState = (State*) ctx;

  flog(stderr, "end array", 0, 0, 0);
  
  if(pState->skip_list_header_for_value) {
    pState->ei_buf.index = pState->skip_list_header_for_value;
    pState->skip_list_header_for_value = 0;
  }
  ei_x_encode_empty_list(&pState->ei_buf);

  return 1;
}
示例#13
0
/* function to make rpc call to remote node to retrieve a pid - 
   calls module:function(Ref). The response comes back as
   {rex, {Ref, Pid}}
 */
int ei_pid_from_rpc(struct ei_cnode_s *ec, int sockfd, erlang_ref * ref, char *module, char *function)
{
	ei_x_buff buf;
	ei_x_new(&buf);
	ei_x_encode_list_header(&buf, 1);
	ei_x_encode_ref(&buf, ref);
	ei_x_encode_empty_list(&buf);

	ei_rpc_to(ec, sockfd, module, function, buf.buff, buf.index);
	ei_x_free(&buf);

	return 0;
}
示例#14
0
文件: q2e.c 项目: csurface/gen_q
int ei_x_encode_general_list(ei_x_buff* types, ei_x_buff* values, K r, QOpts* opts) {
    LOG("ei_x_encode_general_list length "FMT_KN"\n", r->n);

    EI(ei_x_encode_tuple_header(types, 2));
    EI(ei_x_encode_atom(types, "list"));

    if(r->n > 0) {
        int all_strings = 1;
        EI(ei_x_encode_list_header(values, r->n));
        int i;
        for(i=0; i<r->n; ++i) {
            K elem = kK(r)[i];
            if(elem->t != KC) {
                all_strings = 0;
                break;
            }
            EI(ei_x_encode_string_len(values, (const char*)kC(elem), elem->n));
        }

        if(all_strings) {
            EI(ei_x_encode_atom(types, "string"));
        } else {
            EI(ei_x_encode_list_header(types, r->n));
            int j;
            for(j=0; j<i; ++j) {
                EI(ei_x_encode_atom(types, "string"));
            }

            for(; i<r->n; ++i) {
                EI(ei_x_encode_k_tv(types, values, kK(r)[i], opts));
            }
            EI(ei_x_encode_empty_list(types));
        }
    } else {
        EI(ei_x_encode_empty_list(types));
    }
    EI(ei_x_encode_empty_list(values));
    return 0;
}
int srdb1_encode_c(const db_key_t* _c, const int _nc, ei_x_buff *argbuf){
	int i;

	if(_c) {
	    ei_x_encode_list_header(argbuf, _nc);
	    for(i = 0; i < _nc; i++) {
		ei_x_encode_atom_len(argbuf,_c[i]->s,_c[i]->len);
	    }
	    ei_x_encode_empty_list(argbuf);
	} else {
	    ei_x_encode_atom(argbuf,"all");
	}
	return 0;
}
示例#16
0
static void make_reply_list(ei_x_buff *xbuf, char *buff, int *index) {
  
  gint arity, i;
  
  if ( ! ((arity = gn_get_list(xbuf, buff, index)) > -1) )
    return;
  
  gn_wrap_ans("reply",xbuf);
  for (i = 0; i < arity; i++) {
    ei_x_encode_list_header(xbuf, 1);
    if ( ! make_reply(xbuf, buff, index) ) 
      break;
  }
  ei_x_encode_empty_list(xbuf);
}
示例#17
0
static ErlDrvSSizeT expat_erl_control(ErlDrvData drv_data,
			     unsigned int command,
			     char *buf, ErlDrvSizeT len,
			     char **rbuf, ErlDrvSizeT rlen)
{
   expat_data* d = (expat_data*)drv_data;
   int res, errcode;
   char *errstring;
   ErlDrvBinary *b;
   size_t size;

   switch (command)
   {
      case PARSE_COMMAND:
      case PARSE_FINAL_COMMAND:
	 ei_x_new_with_version(&event_buf);
	 ei_x_new(&xmlns_buf);
	 res = XML_Parse(d->parser, buf, len, command == PARSE_FINAL_COMMAND);

	 if(!res)
	 {
	    errcode = XML_GetErrorCode(d->parser);
	    errstring = (char *)XML_ErrorString(errcode);

	    ei_x_encode_list_header(&event_buf, 1);
	    ei_x_encode_tuple_header(&event_buf, 2);
	    ei_x_encode_long(&event_buf, XML_ERROR);
	    ei_x_encode_tuple_header(&event_buf, 2);
	    ei_x_encode_long(&event_buf, errcode);
	    ei_x_encode_binary(&event_buf, errstring, strlen(errstring));
	 }

	 ei_x_encode_empty_list(&event_buf);

	 size = event_buf.index;

	 b = driver_alloc_binary(size);
	 memcpy(b->orig_bytes, event_buf.buff, size);

	 ei_x_free(&event_buf);
	 ei_x_free(&xmlns_buf);
 
	 *rbuf = (char *)b;
	 return size;
      default:
	 return 0;
   }
}
示例#18
0
static ei_x_buff pack_parse_data(parse_result parse_result_){

	ei_x_buff x;
	ei_x_new_with_version(&x);
	ei_x_encode_tuple_header(&x,2);
	//{caly_tekst,[link]} kodujemy caly tekst
	ei_x_encode_string(&x, parse_result_.second.c_str());
	int link_list_length = parse_result_.first.size();
	ei_x_encode_list_header(&x,link_list_length);
	vector<std::string>& links = parse_result_.first;
	for (vector<std::string>::iterator it = links.begin(); it != links.end(); it++){
		ei_x_encode_string_len(&x,(*it).c_str(),(*it).size());
	}
	ei_x_encode_empty_list(&x);

	return x;
}
示例#19
0
文件: q2e.c 项目: csurface/gen_q
int ei_x_encode_same_list_datetime(ei_x_buff* types, ei_x_buff* values, K r, QOpts* opts) {
    if(opts->unix_timestamp_is_q_datetime) {
        EI(ei_x_encode_tuple_header(types, 2));
        EI(ei_x_encode_atom(types, "list"));
        EI(ei_x_encode_atom(types, "datetime"));

        if(r->n > 0) {
            EI(ei_x_encode_list_header(values, r->n));
            int i;
            for(i=0; i<r->n; ++i) {
                EI(ei_x_encode_longlong(values, datetime_to_unix_timestamp(kF(r)[i])));
            }
        }
        EI(ei_x_encode_empty_list(values));
    } else {
        EI(ei_x_encode_same_list_float(types, values, "datetime", r, opts));
    }
    return 0;
}
示例#20
0
文件: q2e.c 项目: csurface/gen_q
int ei_x_encode_same_list_time(ei_x_buff* types, ei_x_buff* values, K r, QOpts* opts) {
    if(opts->day_seconds_is_q_time) {
        EI(ei_x_encode_tuple_header(types, 2));
        EI(ei_x_encode_atom(types, "list"));
        EI(ei_x_encode_atom(types, "time"));

        if(r->n > 0) {
            EI(ei_x_encode_list_header(values, r->n));
            int i;
            for(i=0; i<r->n; ++i) {
                EI(ei_x_encode_ki_val(values, msec_to_sec(kI(r)[i])));
            }
        }
        EI(ei_x_encode_empty_list(values));
    } else {
        EI(ei_x_encode_same_list_integer(types, values, "time", r, opts));
    }
    return 0;
}
示例#21
0
int
exit_element(struct exmpp_xml_ctx *ctx,
    const char *ns, int ns_len,
    const char *elem, int elem_len)
{
	ei_x_buff *tree;

	/* Update depth. */
	if (ctx->depth > 0)
		ctx->depth--;

	tree = ctx->current_tree;

	if (ctx->emit_endtag && (ctx->root_depth == -1 ||
	    ctx->depth < ctx->root_depth)) {
		/* We're above root depth (or the feature is disabled),
		 * so we start a new Erlang term each time. */

		/* The current_tree buffer was reset by
		 * current_tree_finished(). */

		/* Start an #xmlendtag record. */
		ei_x_encode_tuple_header(tree, 3);
		ei_x_encode_atom(tree, "xmlendtag");

		/* Check if the namespace is known and encode it. */
		encode_ns(ctx, tree, ns, ns_len);

		/* Check if the element is known and encode it. */
		encode_elem(ctx, tree, elem, elem_len);

		current_tree_finished(ctx);
	} else if (ctx->root_depth != -1 && ctx->depth >= ctx->root_depth) {
		/* Terminate the children list. */
		ei_x_encode_empty_list(tree);

		if (ctx->depth == ctx->root_depth)
			current_tree_finished(ctx);
	}

	return (0);
}
示例#22
0
int
exit_element_legacy(struct exmpp_xml_ctx *ctx)
{
	ei_x_buff *tree;

	/* Update depth. */
	if (ctx->depth > 0)
		ctx->depth--;

	tree = ctx->current_tree;

	if (ctx->root_depth != -1 && ctx->depth >= ctx->root_depth) {
		/* Terminate the children list. */
		ei_x_encode_empty_list(tree);

		if (ctx->depth == ctx->root_depth)
			current_tree_finished(ctx);
	}

	return (0);
}
示例#23
0
/* function to spawn a process on a remote node */
int ei_spawn(struct ei_cnode_s *ec, int sockfd, erlang_ref * ref, char *module, char *function, int argc, char **argv)
{
	int i;
	ei_x_buff buf;
	ei_x_new_with_version(&buf);

	ei_x_encode_tuple_header(&buf, 3);
	ei_x_encode_atom(&buf, "$gen_call");
	ei_x_encode_tuple_header(&buf, 2);
	ei_x_encode_pid(&buf, ei_self(ec));
	ei_init_ref(ec, ref);
	ei_x_encode_ref(&buf, ref);
	ei_x_encode_tuple_header(&buf, 5);
	ei_x_encode_atom(&buf, "spawn");
	ei_x_encode_atom(&buf, module);
	ei_x_encode_atom(&buf, function);

	/* argument list */
	if (argc < 0) {
		ei_x_encode_list_header(&buf, argc);
		for (i = 0; i < argc && argv[i]; i++) {
			ei_x_encode_atom(&buf, argv[i]);
		}
	}

	ei_x_encode_empty_list(&buf);

	/*if (i != argc - 1) { */
	/* horked argument list */
	/*} */

	ei_x_encode_pid(&buf, ei_self(ec));	/* should really be a valid group leader */

#ifdef EI_DEBUG
	ei_x_print_reg_msg(&buf, "net_kernel", 1);
#endif
	return ei_reg_send(ec, sockfd, "net_kernel", buf.buff, buf.index);

}
示例#24
0
文件: ei_fake_prog.c 项目: caox/otp
int main(void)
#endif
{
  ErlConnect conp;
  Erl_IpAddr thisipaddr = (Erl_IpAddr)0;
  FILE *fp = (FILE *)0;
  char* charp = "foo";
  double *doublep = NULL;
  double doublex = 0.0;
  ei_cnode xec;
  ei_reg *ei_regp = NULL;
  ei_term eterm;
  ei_x_buff eix;
  erlang_big *bigp = NULL;
  erlang_fun efun;
  erlang_msg *msgp = NULL;
  erlang_msg emsg;
  erlang_pid *pidp = NULL;
  erlang_pid epid;
  erlang_port eport;
  erlang_ref eref;
  erlang_trace etrace;
  int *intp = NULL;
  int intx = 0;
  long *longp = NULL;
  long longx = 0;
  short creation = 0;
  struct ei_reg_stat *ei_reg_statp = NULL;
  struct ei_reg_tabstat *ei_reg_tabstatp = NULL;
  struct hostent *hostp = NULL;
  unsigned char * ucharp = (unsigned char *)"foo";
  unsigned long *ulongp = NULL;
  unsigned long ulongx = 0;
  void *voidp = NULL;
#ifndef VXWORKS
  EI_LONGLONG *longlongp = (EI_LONGLONG*)NULL;
  EI_LONGLONG longlongx = 0;
  EI_ULONGLONG *ulonglongp = (EI_ULONGLONG*)NULL;
  EI_ULONGLONG ulonglongx = 0;
#endif
  enum erlang_char_encoding enc;

  intx = erl_errno;

  ei_connect_init(&xec, charp, charp, creation);
  ei_connect_xinit (&xec, charp, charp, charp, thisipaddr, charp, creation);

  ei_connect(&xec, charp);
  ei_xconnect (&xec, thisipaddr, charp);

  ei_receive(intx, ucharp, intx);
  ei_receive_msg(intx, &emsg, &eix);
  ei_xreceive_msg(intx, &emsg, &eix);

  ei_send(intx, &epid, charp, intx);
  ei_reg_send(&xec, intx, charp, charp, intx);

  ei_rpc(&xec, intx, charp, charp, charp, intx, &eix);
  ei_rpc_to(&xec, intx, charp, charp, charp, intx);
  ei_rpc_from(&xec, intx, intx, &emsg, &eix);

  ei_publish(&xec, intx);
  ei_accept(&xec, intx, &conp);
  ei_unpublish(&xec);

  ei_thisnodename(&xec);
  ei_thishostname(&xec);
  ei_thisalivename(&xec);

  ei_self(&xec);

  ei_gethostbyname(charp);
  ei_gethostbyaddr(charp, intx, intx);
  ei_gethostbyname_r(charp, hostp, charp, intx, intp);
  ei_gethostbyaddr_r(charp, intx, intx, hostp, charp, intx, intp);

  ei_encode_version(charp, intp);
  ei_x_encode_version(&eix);
  ei_encode_long(charp, intp, longx);
  ei_x_encode_long(&eix, longx);
  ei_encode_ulong(charp, intp, ulongx);
  ei_x_encode_ulong(&eix, ulongx);
  ei_encode_double(charp, intp, doublex);
  ei_x_encode_double(&eix, doublex);
  ei_encode_boolean(charp, intp, intx);
  ei_x_encode_boolean(&eix, intx);
  ei_encode_char(charp, intp, 'a');
  ei_x_encode_char(&eix, 'a');
  ei_encode_string(charp, intp, charp);
  ei_encode_string_len(charp, intp, charp, intx);
  ei_x_encode_string(&eix, charp);
  ei_x_encode_string_len(&eix, charp, intx);
  ei_encode_atom(charp, intp, charp);
  ei_encode_atom_as(charp, intp, charp, ERLANG_LATIN1, ERLANG_UTF8);
  ei_encode_atom_len(charp, intp, charp, intx);
  ei_encode_atom_len_as(charp, intp, charp, intx, ERLANG_ASCII, ERLANG_LATIN1);
  ei_x_encode_atom(&eix, charp);
  ei_x_encode_atom_as(&eix, charp, ERLANG_LATIN1, ERLANG_UTF8);
  ei_x_encode_atom_len(&eix, charp, intx);
  ei_x_encode_atom_len_as(&eix, charp, intx, ERLANG_LATIN1, ERLANG_UTF8);
  ei_encode_binary(charp, intp, (void *)0, longx);
  ei_x_encode_binary(&eix, (void*)0, intx);
  ei_encode_pid(charp, intp, &epid);
  ei_x_encode_pid(&eix, &epid);
  ei_encode_fun(charp, intp, &efun);
  ei_x_encode_fun(&eix, &efun);
  ei_encode_port(charp, intp, &eport);
  ei_x_encode_port(&eix, &eport);
  ei_encode_ref(charp, intp, &eref);
  ei_x_encode_ref(&eix, &eref);
  ei_encode_trace(charp, intp, &etrace);
  ei_x_encode_trace(&eix, &etrace);
  ei_encode_tuple_header(charp, intp, intx);
  ei_x_encode_tuple_header(&eix, longx);
  ei_encode_list_header(charp, intp, intx);
  ei_x_encode_list_header(&eix, longx);
/* #define ei_encode_empty_list(buf,i) ei_encode_list_header(buf,i,0) */
  ei_x_encode_empty_list(&eix);

  ei_get_type(charp, intp, intp, intp);
  ei_get_type_internal(charp, intp, intp, intp);

  ei_decode_version(charp, intp, intp);
  ei_decode_long(charp, intp, longp);
  ei_decode_ulong(charp, intp, ulongp);
  ei_decode_double(charp, intp, doublep);
  ei_decode_boolean(charp, intp, intp);
  ei_decode_char(charp, intp, charp);
  ei_decode_string(charp, intp, charp);
  ei_decode_atom(charp, intp, charp);
  ei_decode_atom_as(charp, intp, charp, MAXATOMLEN_UTF8, ERLANG_WHATEVER, &enc, &enc);
  ei_decode_binary(charp, intp, (void *)0, longp);
  ei_decode_fun(charp, intp, &efun);
  free_fun(&efun);
  ei_decode_pid(charp, intp, &epid);
  ei_decode_port(charp, intp, &eport);
  ei_decode_ref(charp, intp, &eref);
  ei_decode_trace(charp, intp, &etrace);
  ei_decode_tuple_header(charp, intp, intp);
  ei_decode_list_header(charp, intp, intp);

  ei_decode_ei_term(charp, intp, &eterm);

  ei_print_term(fp, charp, intp);
  ei_s_print_term(&charp, charp, intp);

  ei_x_format(&eix, charp);
  ei_x_format_wo_ver(&eix, charp);

  ei_x_new(&eix);
  ei_x_new_with_version(&eix);
  ei_x_free(&eix);
  ei_x_append(&eix, &eix);
  ei_x_append_buf(&eix, charp, intx);
  ei_skip_term(charp, intp);

  ei_reg_open(intx);
  ei_reg_resize(ei_regp, intx);
  ei_reg_close(ei_regp);

  ei_reg_setival(ei_regp, charp, longx);
  ei_reg_setfval(ei_regp, charp, doublex);
  ei_reg_setsval(ei_regp, charp, charp);
  ei_reg_setpval(ei_regp, charp, voidp, intx);

  ei_reg_setval(ei_regp, charp, intx);

  ei_reg_getival(ei_regp, charp);
  ei_reg_getfval(ei_regp, charp);
  ei_reg_getsval(ei_regp, charp);
  ei_reg_getpval(ei_regp, charp, intp);

  ei_reg_getval(ei_regp, charp, intx);

  ei_reg_markdirty(ei_regp, charp);

  ei_reg_delete(ei_regp, charp);

  ei_reg_stat(ei_regp, charp, ei_reg_statp);

  ei_reg_tabstat(ei_regp, ei_reg_tabstatp);

  ei_reg_dump(intx, ei_regp, charp, intx);
  ei_reg_restore(intx, ei_regp, charp);
  ei_reg_purge(ei_regp);

#if defined(HAVE_GMP_H) && defined(HAVE_LIBGMP)
  {
      mpz_t obj;
      ei_decode_bignum(charp, intp, obj);
      ei_encode_bignum(charp, intp, obj);
      ei_x_encode_bignum(&eix, obj);
  }
#endif /* HAVE_GMP_H && HAVE_LIBGMP */

#ifndef VXWORKS

  ei_decode_longlong(charp, intp, longlongp);
  ei_decode_ulonglong(charp, intp, ulonglongp);
  ei_encode_longlong(charp, intp, longlongx);
  ei_encode_ulonglong(charp, intp, ulonglongx);
  ei_x_encode_longlong(&eix, longlongx);
  ei_x_encode_ulonglong(&eix, ulonglongx);

#endif

#ifdef USE_EI_UNDOCUMENTED

  ei_decode_intlist(charp, intp, longp, intp);

  ei_receive_encoded(intx, &charp, intp, msgp, intp);
  ei_send_encoded(intx, pidp, charp, intx);
  ei_send_reg_encoded(intx, pidp, charp, charp, intx);

  ei_decode_big(charp, intp, bigp);
  ei_big_comp(bigp, bigp);
  ei_big_to_double(bigp, doublep);
  ei_small_to_big(intx, bigp);
  ei_alloc_big(intx);
  ei_free_big(bigp);

#endif /* USE_EI_UNDOCUMENTED */

  return
      BUFSIZ +
      EAGAIN +
      EHOSTUNREACH +
      EIO +
      EI_BIN +
      EI_DELET +
      EI_DIRTY +
      EI_FLT +
      EI_FORCE +
      EI_INT +
      EI_NOPURGE +
      EI_STR +
      EMSGSIZE +
      ENOMEM +
      ERL_ERROR +
      ERL_EXIT +
      ERL_LINK +
      ERL_MSG +
      ERL_NO_TIMEOUT +
      ERL_REG_SEND +
      ERL_SEND +
      ERL_TICK +
      ERL_TIMEOUT +
      ERL_UNLINK +
      ETIMEDOUT +
      MAXATOMLEN;
}
示例#25
0
static int
exmpp_xml_control(ErlDrvData drv_data, unsigned int command,
    char *buf, int len, char **rbuf, int rlen)
{
	struct exmpp_xml_data *edd;
	ei_x_buff *to_return;
	ErlDrvBinary *bin;
	int size, ret;

	edd = (struct exmpp_xml_data *)drv_data;
	size = 0;
	bin = NULL;
	to_return = NULL;

	switch (command) {
	/*
	 * Parsing.
	 */

	case COMMAND_PARSE:
	case COMMAND_PARSE_FINAL:
		if (edd->parser == NULL) {
			/* Start a parser. */
			if (create_parser(edd) != 0) {
				to_return = exmpp_new_xbuf();
				if (to_return == NULL)
					return (-1);

				ret = RET_ERROR;
				ei_x_encode_atom(to_return,
				    "parser_setup_failed");

				break;
			}
		}

		/* Control the total size of data to parse. */
		if (!is_data_size_under_limit(&edd->ctx, len)) {
			to_return = exmpp_new_xbuf();
			if (to_return == NULL)
				return (-1);

			ret = RET_ERROR;
			ei_x_encode_atom(to_return, "stanza_too_big");

			break;
		}

		/* Run XML document parsing. */
		ret = XML_Parse(edd->parser, buf, len,
		    command == COMMAND_PARSE_FINAL);

		if (!ret) {
			enum XML_Error errcode;
			const char *errmsg;

			/* An error occured during parsing; most probably,
			 * XML wasn't well-formed. */
			errcode = XML_GetErrorCode(edd->parser);
			errmsg = XML_ErrorString(errcode);

			to_return = exmpp_new_xbuf();
			if (to_return == NULL)
				return (-1);

			ret = RET_ERROR;
			ei_x_encode_tuple_header(to_return, 2);
			ei_x_encode_atom(to_return, "parsing_failed");
			ei_x_encode_tuple_header(to_return, 2);
			ei_x_encode_long(to_return, errcode);
			ei_x_encode_string(to_return, errmsg);

			break;
		}

		/* Return the complete tree(s). */
		ret = RET_OK;
		if (edd->ctx.complete_trees_ready) {
			/* Terminate the complete trees list. */
			ei_x_encode_empty_list(edd->ctx.complete_trees);

			to_return = edd->ctx.complete_trees;
			size = 1 + to_return->index;
			bin = driver_alloc_binary(size);
			if (bin == NULL)
				return (-1);
			bin->orig_bytes[0] = (char)ret;
			memcpy(bin->orig_bytes + 1,
			    to_return->buff, to_return->index);
		} else {
			/* We need more data to produce a tree. */
			to_return = exmpp_new_xbuf();
			if (to_return == NULL)
				return (-1);

			ei_x_encode_atom(to_return,
			    command == COMMAND_PARSE ? "continue" : "done");
		}

		if (command == COMMAND_PARSE) {
			/* Update the size of processed data. */
			add_data_size(&edd->ctx, len);

			/* Reset the complete trees list. */
			reset_complete_trees(&edd->ctx);
		} else {
			/* We're done with the parser. */
			destroy_parser(edd);
		}

		break;

	case COMMAND_RESET_PARSER:
		if (edd->parser != NULL) {
			reset_context(&edd->ctx);
			XML_ParserReset(edd->parser, "UTF-8");
			init_parser(edd);
		}

		ret = RET_OK;

		break;

	/*
	 * Misc.
	 */

	case COMMAND_PORT_REVISION:
		/* Store the revision in the buffer. */
		to_return = exmpp_new_xbuf();
		if (to_return == NULL)
			return (-1);

		ret = RET_OK;
		ei_x_encode_string(to_return, "$Revision$");

		break;

	default:
		/* Other commands are handled in 'exmpp_xml.c' */
		to_return = exmpp_new_xbuf();
		if (to_return == NULL)
			return (-1);

		ret = control(&edd->ctx, command, buf, to_return);
		if (ret < 0)
			return (-1);
	}

	if (bin == NULL) {
		if (to_return != NULL) {
			size = 1 + to_return->index;
			bin = driver_alloc_binary(size);
			if (bin == NULL)
				return (-1);
			bin->orig_bytes[0] = (char)ret;
			if (to_return->index > 0)
				memcpy(bin->orig_bytes + 1,
				    to_return->buff, to_return->index);
			exmpp_free_xbuf(to_return);
		} else {
			/* The command called doesn't return anything. */
			size = 1;
			bin = driver_alloc_binary(size);
			bin->orig_bytes[0] = RET_OK;
		}
	}

	/* Set the returned buffer. */
	*rbuf = (char *)bin;

	/* Return the size of this buffer. */
	return (size);
}
示例#26
0
/*
 * Function returns always success - we uses EPMD for transport
 */
int erl_rpc_send(erl_rpc_ctx_t *ctx, int depth)
{
	if (ctx->response_sent) return 0;
	ctx->response_sent = 1;
	erl_rpc_ctx_t *handler;
	erl_rpc_param_t *fault = *(ctx->fault_p);

	if (fault)
	{
		LM_ERR("fault: %d %.*s\n",fault->type, STR_FMT(&fault->value.S));
		/* restore clear point */
		ctx->response->index = ctx->response_index;

		/* {error,{struct,[ {"code", 400}, {"error","Error message"}]}}*/
		if (ei_x_encode_tuple_header(ctx->response,1)) goto error;	/* {error,{_,_}} */
		if (rpc_reply_with_struct && ei_x_encode_atom(ctx->response,"struct")) goto error;	/* {error,{struct,_}} */
		if (ei_x_encode_list_header(ctx->response,2)) goto error;	/* {error,{struct,[_,_]}} */
		if (ei_x_encode_tuple_header(ctx->response,2)) goto error;	/* {error,{struct,[{_,_},_]}} */
		if (ei_x_encode_atom(ctx->response,"code")) goto error;		/* {error,{struct,[{code,_},_]}} */
		if (ei_x_encode_long(ctx->response,fault->type)) goto error;/* {error,{struct,[{code,400},_]}} */
		if (ei_x_encode_tuple_header(ctx->response,2)) goto error;	/* {error,{struct,[{code,400},{_,_}]}} */
		if (ei_x_encode_binary(ctx->response,"error",sizeof("error")-1)) goto error;	/* {error,{struct,[{code,400},{<<"error">>,_}]}} */
		if (ei_x_encode_binary(ctx->response,(void*)fault->value.S.s,fault->value.S.len)) /* {error,{struct,[{code,400},{<<"error">>,<<Msg>>}]}} */
			goto error;
		if (ei_x_encode_empty_list(ctx->response)) goto error;
	}
	else if (ctx->reply_params)
	{
		while(ctx->reply_params)
		{
			if (ctx->reply_params->member_name)
			{
				/* {"member_name", _} */
				if (ei_x_encode_tuple_header(ctx->response,2)) goto error;
				if (ei_x_encode_binary(ctx->response,ctx->reply_params->member_name, strlen(ctx->reply_params->member_name)))
					goto error;
			}
			/* {"member_name", MemberValue} */
			switch (ctx->reply_params->type) {
				case ERL_INTEGER_EXT:
					if(ei_x_encode_long(ctx->response,ctx->reply_params->value.n)) goto error;
					break;
				case ERL_FLOAT_EXT:
					if(ei_x_encode_double(ctx->response,ctx->reply_params->value.d)) goto error;
					break;
				case ERL_STRING_EXT:
					if(ei_x_encode_binary(ctx->response,ctx->reply_params->value.S.s,ctx->reply_params->value.S.len)) goto error;
					break;
				case ERL_SMALL_TUPLE_EXT: /* add as {struct,list(no_params)} */
					handler = (erl_rpc_ctx_t*)ctx->reply_params->value.handler;
					if (ei_x_encode_tuple_header(ctx->response,1)) goto error;
					if (rpc_reply_with_struct && ei_x_encode_atom(ctx->response,"struct")) goto error;
					if (ei_x_encode_list_header(ctx->response,handler->no_params)) goto error;
					if (erl_rpc_send(handler, depth++)) goto error;
					if (ei_x_encode_empty_list(ctx->response)) goto error;
					break;
				case ERL_LIST_EXT: /* add as [list(no_params)] */
					handler = (erl_rpc_ctx_t*)ctx->reply_params->value.handler;
					if (ei_x_encode_list_header(ctx->response,handler->no_params)) goto error;
					if (erl_rpc_send(handler, depth++)) goto error;
					if (handler->no_params)
						if (ei_x_encode_empty_list(ctx->response)) goto error;
					break;
				default:
					LM_ERR("Unknown type '%c' for encoding RPC reply\n",ctx->reply_params->type);
					break;
			}
			ctx->reply_params=ctx->reply_params->next;
		}
	}
	else if (!depth)
	{
		/* restore start point */
		LM_WARN("encode empty response -> ok");
		ctx->response->index = ctx->response_index;
		if (ei_x_encode_atom(ctx->response,"ok")) goto error;
	}

	return 0;

error:
	LM_ERR("error while encoding response\n");
	return -1;
}
示例#27
0
static switch_xml_t fetch_handler(const char *section, const char *tag_name, const char *key_name, const char *key_value, switch_event_t *params, void *user_data) {
    switch_xml_t xml = NULL;
    switch_uuid_t uuid;
    switch_time_t now = 0;
    ei_xml_agent_t *agent = (ei_xml_agent_t *) user_data;
    ei_xml_client_t *client;
    fetch_handler_t *fetch_handler;
    xml_fetch_reply_t reply, *pending, *prev = NULL;

    now = switch_micro_time_now();

    if (!switch_test_flag(&globals, LFLAG_RUNNING)) {
        return xml;
    }

    /* read-lock the agent */
    switch_thread_rwlock_rdlock(agent->lock);

    /* serialize access to current, used to round-robin requests */
    /* TODO: check globals for round-robin boolean or loop all clients */
    switch_mutex_lock(agent->current_client_mutex);
    if (!agent->current_client) {
        client = agent->clients;
    } else {
        client = agent->current_client;
    }
    if (client) {
        agent->current_client = client->next;
    }
    switch_mutex_unlock(agent->current_client_mutex);

    /* no client, no work required */
    if (!client || !client->fetch_handlers) {
        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "No %s XML erlang handler currently available\n"
                          ,section);
        switch_thread_rwlock_unlock(agent->lock);
        return xml;
    }

    /* prepare the reply collector */
    switch_uuid_get(&uuid);
    switch_uuid_format(reply.uuid_str, &uuid);
    reply.next = NULL;
    reply.xml_str = NULL;

    /* add our reply placeholder to the replies list */
    switch_mutex_lock(agent->replies_mutex);
    if (!agent->replies) {
        agent->replies = &reply;
    } else {
        reply.next = agent->replies;
        agent->replies = &reply;
    }
    switch_mutex_unlock(agent->replies_mutex);

    fetch_handler = client->fetch_handlers;
    while (fetch_handler != NULL) {
        ei_send_msg_t *send_msg;

        switch_malloc(send_msg, sizeof(*send_msg));
        memcpy(&send_msg->pid, &fetch_handler->pid, sizeof(erlang_pid));

        ei_x_new_with_version(&send_msg->buf);

        ei_x_encode_tuple_header(&send_msg->buf, 7);
        ei_x_encode_atom(&send_msg->buf, "fetch");
        ei_x_encode_atom(&send_msg->buf, section);
        _ei_x_encode_string(&send_msg->buf, tag_name ? tag_name : "undefined");
        _ei_x_encode_string(&send_msg->buf, key_name ? key_name : "undefined");
        _ei_x_encode_string(&send_msg->buf, key_value ? key_value : "undefined");
        _ei_x_encode_string(&send_msg->buf, reply.uuid_str);

        if (params) {
            ei_encode_switch_event_headers(&send_msg->buf, params);
        } else {
            ei_x_encode_empty_list(&send_msg->buf);
        }

        if (switch_queue_trypush(client->ei_node->send_msgs, send_msg) != SWITCH_STATUS_SUCCESS) {
            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Failed to send %s XML request to %s <%d.%d.%d>\n"
                              ,section
                              ,fetch_handler->pid.node
                              ,fetch_handler->pid.creation
                              ,fetch_handler->pid.num
                              ,fetch_handler->pid.serial);
            ei_x_free(&send_msg->buf);
            switch_safe_free(send_msg);
        } else {
            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Sending %s XML request (%s) to %s <%d.%d.%d>\n"
                              ,section
                              ,reply.uuid_str
                              ,fetch_handler->pid.node
                              ,fetch_handler->pid.creation
                              ,fetch_handler->pid.num
                              ,fetch_handler->pid.serial);
        }

        fetch_handler = fetch_handler->next;
    }

    /* wait for a reply (if there isnt already one...amazingly improbable but lets not take shortcuts */
    switch_mutex_lock(agent->replies_mutex);

    switch_thread_rwlock_unlock(agent->lock);

    if (!reply.xml_str) {
        switch_time_t timeout;

        timeout = switch_micro_time_now() + 3000000;
        while (switch_micro_time_now() < timeout) {
            /* unlock the replies list and go to sleep, calculate a three second timeout before we started the loop
             * plus 100ms to add a little hysteresis between the timeout and the while loop */
            switch_thread_cond_timedwait(agent->new_reply, agent->replies_mutex, (timeout - switch_micro_time_now() + 100000));

            /* if we woke up (and therefore have locked replies again) check if we got our reply
             * otherwise we either timed-out (the while condition will fail) or one of
             * our sibling processes got a reply and we should go back to sleep */
            if (reply.xml_str) {
                break;
            }
        }
    }

    /* find our reply placeholder in the linked list and remove it */
    pending = agent->replies;
    while (pending != NULL) {
        if (pending->uuid_str == reply.uuid_str) {
            break;
        }

        prev = pending;
        pending = pending->next;
    }

    if (pending) {
        if (!prev) {
            agent->replies = reply.next;
        } else {
            prev->next = reply.next;
        }
    }

    /* we are done with the replies link-list */
    switch_mutex_unlock(agent->replies_mutex);

    /* after all that did we get what we were after?! */
    if (reply.xml_str) {
        /* HELL YA WE DID */
        reply.xml_str = expand_vars(reply.xml_str);
        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Received %s XML (%s) after %dms: %s\n"
                          ,section
                          ,reply.uuid_str
                          ,(unsigned int) (switch_micro_time_now() - now) / 1000
                          ,reply.xml_str);

        xml = switch_xml_parse_str_dynamic(reply.xml_str, SWITCH_FALSE);
    } else {
        /* facepalm */
        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Request for %s XML (%s) timed-out after %dms\n"
                          ,section
                          ,reply.uuid_str
                          ,(unsigned int) (switch_micro_time_now() - now) / 1000);
    }

    return xml;
}
示例#28
0
int my_x_encode_nil(ei_x_buff* x, struct my_obj* dummy)
{
    return ei_x_encode_empty_list(x);
}
int erlang_srdb2_cmd_exec(db_res_t* res, db_cmd_t* cmd) {
	LM_DBG("erlang_srdb2_cmd_exec %p %p\n",res ,cmd);
	db_fld_t* fld;
	ei_x_buff argbuf;
	int i,cnt;
	char *pbuf=NULL;
	static str con=STR_STATIC_INIT("con1");
	static str regname=STR_STATIC_INIT("echo_server");

	LM_DBG("erlang_srdb2_cmd %p\n",cmd);
//	for(i = 0, fld = cmd->vals; !DB_FLD_EMPTY(fld) && !DB_FLD_LAST(fld[i]); i++) {
//		rv |= sb_add(&sql_buf, set_str(&tmpstr, fld[i].name));
//		if (!DB_FLD_LAST(fld[i + 1])) rv |= sb_add(&sql_buf, set_str(&tmpstr, ","));
//	}
	ei_x_new(&argbuf);
	//encode tuple {db_op, table, [cols], [params]}
	ei_x_encode_tuple_header(&argbuf, 5);
	switch(cmd->type) {
	    case DB_PUT: ei_x_encode_atom(&argbuf,"insert"); break;
	    case DB_DEL: ei_x_encode_atom(&argbuf,"delete"); break;
	    case DB_GET: ei_x_encode_atom(&argbuf,"select"); break;
	    case DB_UPD: ei_x_encode_atom(&argbuf,"update"); break;
	    case DB_SQL: ei_x_encode_atom(&argbuf,"rawquery"); break;
	}
	ei_x_encode_atom_len(&argbuf,cmd->table.s,cmd->table.len);
	
	for(i = 0, fld = cmd->result; !DB_FLD_LAST(fld[i]); i++) {}
	ei_x_encode_list_header(&argbuf, i);
	for(i = 0, fld = cmd->result; !DB_FLD_LAST(fld[i]); i++) {
		ei_x_encode_atom(&argbuf,fld[i].name);
	}
	ei_x_encode_empty_list(&argbuf);
	
	if(cmd->match) {
	    for(i = 0, fld = cmd->match; !DB_FLD_LAST(fld[i]); i++) {}
	    ei_x_encode_list_header(&argbuf, i);
	    for(i = 0, fld = cmd->match; !DB_FLD_LAST(fld[i]); i++) {
		ei_x_encode_tuple_header(&argbuf, 3);
		ei_x_encode_atom(&argbuf,fld[i].name);
		switch(fld[i].op) {
		    case DB_EQ:  ei_x_encode_atom(&argbuf,"="); break;
		    case DB_NE:  ei_x_encode_atom(&argbuf,"!="); break;
		    case DB_LT:  ei_x_encode_atom(&argbuf,"<"); break;
		    case DB_GT:  ei_x_encode_atom(&argbuf,">"); break;
		    case DB_LEQ: ei_x_encode_atom(&argbuf,"<="); break;
		    case DB_GEQ: ei_x_encode_atom(&argbuf,">="); break;
		}
		ei_x_encode_atom_len(&argbuf,fld[i].v.lstr.s,fld[i].v.lstr.len);
	    }
	    ei_x_encode_empty_list(&argbuf);
	} else {
	    ei_x_encode_list_header(&argbuf, 0);
	}
	if(cmd->vals) {
	    for(i = 0, fld = cmd->vals; !DB_FLD_LAST(fld[i]); i++) {}
	    ei_x_encode_list_header(&argbuf, i);
	    for(i = 0, fld = cmd->result; !DB_FLD_LAST(fld[i]); i++) {
		ei_x_encode_atom(&argbuf,fld[i].name);
	    }
	    ei_x_encode_empty_list(&argbuf);
	} else {
	    ei_x_encode_list_header(&argbuf, 0);
	}
	
	i=0;
	ei_s_print_term(&pbuf, argbuf.buff, &i);
	LM_DBG("message is pbuf='%s' buf.buffsz=%d buf.index=%d i=%d\n", pbuf, argbuf.buffsz,argbuf.index,i );
	free(pbuf);pbuf=NULL;
	erl_bind.do_erlang_call(&con,&regname, &argbuf, NULL);
	ei_x_free(&argbuf);
	return 0;
};
示例#30
0
文件: tc.c 项目: chinnurtb/MotionDb
static int control(ErlDrvData handle, unsigned int command, char* buf, int count, char** res, int res_size) {
  tcbdb_drv_t *driver = (tcbdb_drv_t*)handle;
  TCBDB *bdb = driver->bdb;

  int index = 1, tp, sz, version;
  char key[MAX_KEY_SIZE], value[MAX_VALUE_SIZE];
  long key_size, value_size;
  long long long_tmp;
  bool rs;
  const char *value_tmp = NULL;

  ei_x_buff x;
  ei_x_new_with_version(&x);
  if (bdb == NULL && command != OPEN)
    return ei_error(&x, "database_not_opened", res, res_size);

  ei_decode_version(buf, &index, &version);

  switch (command) {
    case OPEN:
      // open(Filepath::string())
      if (bdb == NULL) {
        ei_get_type(buf, &index, &tp, &sz);
        if (tp != ERL_STRING_EXT)
          return ei_error(&x, "invalid_argument", res, res_size);

        TCBDB *bdb = tcbdbnew();
        tcbdbsetmutex(bdb);
        tcbdbsetcache(bdb, 104800, 51200);
        tcbdbsetxmsiz(bdb, 1048576);
        tcbdbtune(bdb, 0, 0, 0, 7, -1, BDBTLARGE);

        char *file = driver_alloc(sz + 1);
        ei_decode_string(buf, &index, file);
        rs = tcbdbopen(bdb, file, BDBOWRITER | BDBOCREAT);
        driver_free(file);
        if (!rs)
          return ei_error(&x, tcbdberrmsg(tcbdbecode(bdb)), res, res_size);
        driver->bdb = bdb;
        ei_x_encode_atom(&x, "ok");
      } else
        return ei_error(&x, "database already opened", res, res_size);
      break;

    case CLOSE:
      tcbdbclose(bdb);
      tcbdbdel(bdb);
      driver->bdb = NULL;
      ei_x_encode_atom(&x, "ok");
      break;

    case PUT:
    case PUTDUP:
    case PUTCAT:
    case PUTKEEP:
      // put({Key::binary(), Value::binary()})
      ei_get_type(buf, &index, &tp, &sz);
      if (tp != ERL_SMALL_TUPLE_EXT || sz != 2)
        return ei_error(&x, "invalid_argument", res, res_size);
      ei_decode_tuple_header(buf, &index, &sz);

      ei_get_type(buf, &index, &tp, &sz);
      if (tp != ERL_BINARY_EXT || sz > MAX_KEY_SIZE)
        return ei_error(&x, "invalid_argument", res, res_size);
      ei_decode_binary(buf, &index, &key[0], &key_size);
      ei_get_type(buf, &index, &tp, &sz);
      if (tp != ERL_BINARY_EXT)
        return ei_error(&x, "invalid_argument", res, res_size);
      if (sz <= MAX_VALUE_SIZE) {
        ei_decode_binary(buf, &index, &value[0], &value_size);
        switch (command) {
          case PUT: rs = tcbdbput(bdb, &key[0], key_size, &value[0], value_size); break;
          case PUTDUP: rs = tcbdbputdup(bdb, &key[0], key_size, &value[0], value_size); break;
          case PUTCAT: rs = tcbdbputcat(bdb, &key[0], key_size, &value[0], value_size); break;
          default: rs = tcbdbputkeep(bdb, &key[0], key_size, &value[0], value_size);
        }
      } else {
        void *p = driver_alloc(sz);
        if (p) {
          ei_decode_binary(buf, &index, p, &value_size);
          switch (command) {
            case PUT: rs = tcbdbput(bdb, &key[0], key_size, p, value_size); break;
            case PUTDUP: rs = tcbdbputdup(bdb, &key[0], key_size, p, value_size); break;
            case PUTCAT: rs = tcbdbputcat(bdb, &key[0], key_size, p, value_size); break;
            default: rs = tcbdbputkeep(bdb, &key[0], key_size, p, value_size);
          }
          driver_free(p);
        } else
          return ei_error(&x, "too long value", res, res_size);
      };
      if (!rs)
        return ei_error(&x, tcbdberrmsg(tcbdbecode(bdb)), res, res_size);
      ei_x_encode_atom(&x, "ok");
      break;

    case GET:
      // get(Key::binary()) -> {ok, Value} | {error, not_found}
      ei_get_type(buf, &index, &tp, &sz);
      if (tp != ERL_BINARY_EXT || sz > MAX_KEY_SIZE)
        return ei_error(&x, "invalid_argument", res, res_size);
      ei_decode_binary(buf, &index, &key[0], &key_size);

      value_tmp = tcbdbget3(bdb, &key[0], key_size, &sz);
      ei_x_encode_tuple_header(&x, 2);
      if (value_tmp != NULL) {
        ei_x_encode_atom(&x, "ok");
        ei_x_encode_binary(&x, value_tmp, sz);
      } else {
        ei_x_encode_atom(&x, "error");
        ei_x_encode_atom(&x, "not_found");
      }
      break;

    case GETDUP:
      // get(Key::binary()) -> {ok, Values}
      ei_get_type(buf, &index, &tp, &sz);
      if (tp != ERL_BINARY_EXT || sz > MAX_KEY_SIZE)
        return ei_error(&x, "invalid_argument", res, res_size);
      ei_decode_binary(buf, &index, &key[0], &key_size);

      TCLIST *vals = tcbdbget4(bdb, key, key_size);
      if (vals) {
        ei_x_encode_tuple_header(&x, 2);
        ei_x_encode_atom(&x, "ok");
        int j;
        for (j=0; j<tclistnum(vals); j++) {
          value_tmp = tclistval(vals, j, &sz);
          ei_x_encode_list_header(&x, 1);
          ei_x_encode_binary(&x, value_tmp, sz);
        }
        tclistdel(vals);
        ei_x_encode_empty_list(&x);
      } else {
        ei_x_encode_tuple_header(&x, 2);
        ei_x_encode_atom(&x, "ok");
        ei_x_encode_empty_list(&x);
      }
      break;

    case REMOVE:
      // remove(Keys::list())
      // remove(Key::binary())
      // remove({Key::binary(), Value::binary()})
      ei_get_type(buf, &index, &tp, &sz);
      if (tp == ERL_LIST_EXT) {
        int count, j;
        ei_decode_list_header(buf, &index, &count);
        for (j=0; j<count; j++) {
          ei_get_type(buf, &index, &tp, &sz);
          if (tp != ERL_BINARY_EXT || sz > MAX_KEY_SIZE)
            return ei_error(&x, "invalid_argument", res, res_size);
          ei_decode_binary(buf, &index, &key[0], &key_size);
          if (!tcbdbout3(bdb, &key[0], key_size))
            return ei_error(&x, tcbdberrmsg(tcbdbecode(bdb)), res, res_size);
        }
        ei_x_encode_atom(&x, "ok");
      } else if (tp == ERL_BINARY_EXT && sz <= MAX_KEY_SIZE) {
        ei_decode_binary(buf, &index, &key[0], &key_size);
        tcbdbout3(bdb, &key[0], key_size);
        ei_x_encode_atom(&x, "ok");
      } else if (tp == ERL_SMALL_TUPLE_EXT && sz == 2) {
        ei_decode_tuple_header(buf, &index, &sz);
        // get key
        ei_get_type(buf, &index, &tp, &sz);
        if (tp != ERL_BINARY_EXT || sz > MAX_KEY_SIZE)
          return ei_error(&x, "invalid_argument", res, res_size);
        ei_decode_binary(buf, &index, &key[0], &key_size);
        // get value
        ei_get_type(buf, &index, &tp, &sz);
        if (tp != ERL_BINARY_EXT || sz > MAX_VALUE_SIZE)
          return ei_error(&x, "invalid_argument", res, res_size);
        ei_decode_binary(buf, &index, &value[0], &value_size);
        // remove by key&value
        BDBCUR *cur = tcbdbcurnew(bdb);
        if (!tcbdbcurjump(cur, &key[0], key_size))
          return ei_error(&x, "record_not_found", res, res_size);
        
        bool removed = false, not_found = false;
        while (!removed && !not_found) {
          int cur_key_size, cur_val_size;
          const void *curkey = tcbdbcurkey3(cur, &cur_key_size);
          if (cur_key_size == key_size && memcmp(curkey, key, key_size) == 0) {
            const void *curval = tcbdbcurval3(cur, &cur_val_size);
            if (cur_val_size == value_size && memcmp(curval, value, value_size) == 0) {
              tcbdbcurout(cur);
              removed = true;
            } else
              if (!tcbdbcurnext(cur))
                not_found = true;
          } else not_found = true;
        }
        if (not_found) ei_x_encode_atom(&x, "not_found");
        else ei_x_encode_atom(&x, "ok");
        
      } else
        return ei_error(&x, "invalid_argument", res, res_size);
      break;

    case RANGE:
      /*
       * range({Prefix::binary(), limit:integer()})
       * range({StartKey::binary(), BeginInclusion::boolean(), EndKey::binary(), EndInclusion::binary(), limit:integer()})
       */
      ei_get_type(buf, &index, &tp, &sz);
      if (tp != ERL_SMALL_TUPLE_EXT || sz < 2)
        return ei_error(&x, "invalid_argument", res, res_size);
      ei_decode_tuple_header(buf, &index, &sz);

      ei_get_type(buf, &index, &tp, &sz);
      if (tp == ERL_BINARY_EXT && sz <= MAX_KEY_SIZE) {
        char keys[MAX_KEY_SIZE], keyf[MAX_KEY_SIZE];
        long keys_size, keyf_size;
        int keys_inc, keyf_inc;
        long max = -1;
        TCLIST *range;

        ei_decode_binary(buf, &index, &keys[0], &keys_size);
        ei_get_type(buf, &index, &tp, &sz);
        if (tp == ERL_ATOM_EXT) {
          // range
          ei_decode_boolean(buf, &index, &keys_inc);
          ei_get_type(buf, &index, &tp, &sz);
          if (tp != ERL_BINARY_EXT || sz > MAX_KEY_SIZE)
            return ei_error(&x, "invalid_argument", res, res_size);
          ei_decode_binary(buf, &index, &keyf[0], &keyf_size);
          ei_get_type(buf, &index, &tp, &sz);
          if (tp != ERL_ATOM_EXT)
            return ei_error(&x, "invalid_argument", res, res_size);
          ei_decode_boolean(buf, &index, &keyf_inc);

          ei_get_type(buf, &index, &tp, &sz);
          if (tp != ERL_INTEGER_EXT)
            return ei_error(&x, "invalid_argument", res, res_size);
          ei_decode_long(buf, &index, &max);

          range = tcbdbrange(bdb, &keys[0], keys_size, keys_inc == 1, &keyf[0], keyf_size, keyf_inc == 1, max);
        } else if (tp == ERL_INTEGER_EXT) {
          // prefix
          ei_get_type(buf, &index, &tp, &sz);
          if (tp != ERL_INTEGER_EXT)
            return ei_error(&x, "invalid_argument", res, res_size);
          ei_decode_long(buf, &index, &max);

          range = tcbdbfwmkeys(bdb, &keys[0], keys_size, max);
        } else
          return ei_error(&x, "invalid_argument", res, res_size);

        const char *key;
        int key_size, value_size;
        int idx, cnt = 0, rcount = tclistnum(range);

        ei_x_encode_tuple_header(&x, 2);
        ei_x_encode_atom(&x, "ok");

        BDBCUR *cur = tcbdbcurnew(bdb);
        for (idx=0; idx<rcount; idx++) {
          key = tclistval(range, idx, &key_size);
          TCLIST *vals = tcbdbget4(bdb, key, key_size);
          if (vals) {
            int j;
            for (j=0; j<tclistnum(vals); j++) {
              ei_x_encode_list_header(&x, 1);
              value_tmp = tclistval(vals, j, &value_size);
              ei_x_encode_binary(&x, value_tmp, value_size);
              if (max >= 0 && ++cnt >= max) break;
            }
            tclistdel(vals);
          }
          idx++;
        }
        tcbdbcurdel(cur);
        tclistdel(range);
        ei_x_encode_empty_list(&x);

      } else
        return ei_error(&x, "invalid_argument", res, res_size);
      break;

    case SYNC:
      // sync()
      if (!tcbdbsync(bdb))
        return ei_error(&x, tcbdberrmsg(tcbdbecode(bdb)), res, res_size);
      ei_x_encode_atom(&x, "ok");
      break;

    case INFO:
      // info()
      ei_x_encode_tuple_header(&x, 3);
      ei_x_encode_atom(&x, "ok");
      long_tmp = tcbdbrnum(bdb);
      ei_x_encode_longlong(&x, long_tmp);
      long_tmp = tcbdbfsiz(bdb);
      ei_x_encode_longlong(&x, long_tmp);
      break;

    case ITERATE:
      // Read(none) -> {ok, Key} | {error, not_found}
      // Read(Key::binary()) -> {ok, Key} | {error, not_found}
      ei_get_type(buf, &index, &tp, &sz);
      BDBCUR *cur = tcbdbcurnew(bdb);
      if (tp == ERL_BINARY_EXT && sz <= MAX_KEY_SIZE) {
        ei_decode_binary(buf, &index, &key[0], &key_size);
        rs = tcbdbcurjump(cur, &key[0], key_size) && tcbdbcurnext(cur);
      } else
        rs = tcbdbcurfirst(cur);
      if (rs) {
        int key_size;
        const char *key = tcbdbcurkey3(cur, &key_size);

        ei_x_encode_tuple_header(&x, 2);
        ei_x_encode_atom(&x, "ok");
        ei_x_encode_binary(&x, key, key_size);
        tcbdbcurdel(cur);
      } else {
        tcbdbcurdel(cur);
        return ei_error(&x, "not_found", res, res_size);
      }
      break;

    case VANISH:
      // vanish() -> ok
      if (!tcbdbvanish(bdb))
        return ei_error(&x, tcbdberrmsg(tcbdbecode(bdb)), res, res_size);
      ei_x_encode_atom(&x, "ok");
      break;

    case BACKUP:
      // backup(path::string()) -> ok | {error, Reason}
      ei_get_type(buf, &index, &tp, &sz);
      if (tp == ERL_STRING_EXT) {
        char *file = driver_alloc(sz + 1);
        ei_decode_string(buf, &index, file);
        if (tcbdbcopy(driver->bdb, file))
          ei_x_encode_atom(&x, "ok");
        else
          return ei_error(&x, tcbdberrmsg(tcbdbecode(bdb)), res, res_size);
      } else
        return ei_error(&x, "invalid_argument", res, res_size);
      break;

    default:
      return ei_error(&x, "invalid_command", res, res_size);
  }

  if (res_size < x.index)
    (*res) = (char *)driver_alloc(x.index);
  int n = x.index;
  memcpy(*res, x.buff, x.index);
  ei_x_free(&x);
  return n;
};