Exemplo n.º 1
0
static VALUE font_open(VALUE klass, VALUE filename)
{
  SWFFont font = newSWFFont_fromFile(StringValuePtr(filename));
  if(font == NULL) rb_raise(rb_eRuntimeError, "could not read file");
  return Data_Wrap_Struct(klass, NULL, deallocate, font);
}
Exemplo n.º 2
0
VALUE ARGSS::ABitmap::rtext_size(VALUE self, VALUE str) {
	ARGSS::ABitmap::CheckDisposed(self);
	return Bitmap::Get(self)->GetTextSize(StringValuePtr(str)).GetARGSS();
}
Exemplo n.º 3
0
VALUE am_sqlite3_database_open(int argc, VALUE *argv, VALUE class)
{
    VALUE  self = am_sqlite3_database_alloc(class);
    VALUE  rFlags;
    VALUE  rFilename;
    int     flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
    char*   filename;
    int     rc;
    am_sqlite3* am_db;

    /* at least a filename argument is required */
    rb_scan_args( argc, argv, "11", &rFilename, &rFlags );

    /* convert flags to the sqlite version */
    flags  = ( Qnil == rFlags ) ? flags : FIX2INT(rFlags);
    filename = StringValuePtr(rFilename);

    /* extract the sqlite3 wrapper struct */
    Data_Get_Struct(self, am_sqlite3, am_db);

    /* open the sqlite3 database */
    rc = sqlite3_open_v2( filename, &(am_db->db), flags, 0);
    if ( SQLITE_OK != rc ) {
        rb_raise(eAS_Error, "Failure to open database %s : [SQLITE_ERROR %d] : %s\n",
                filename, rc, sqlite3_errmsg(am_db->db));
    }

    /* by default turn on the extended result codes */
    rc = sqlite3_extended_result_codes( am_db->db, 1);
    if ( SQLITE_OK != rc ) {
        rb_raise(eAS_Error, "Failure to set extended result codes %s : [SQLITE_ERROR %d] : %s\n",
Exemplo n.º 4
0
static VALUE
oletypelib_search_registry2(VALUE self, VALUE args)
{
    HKEY htypelib, hguid, hversion;
    double fver;
    DWORD j;
    LONG err;
    VALUE found = Qfalse;
    VALUE tlib;
    VALUE ver;
    VALUE version_str;
    VALUE version = Qnil;
    VALUE typelib = Qnil;
    HRESULT hr;
    ITypeLib *pTypeLib;

    VALUE guid = rb_ary_entry(args, 0);
    version_str = make_version_str(rb_ary_entry(args, 1), rb_ary_entry(args, 2));

    err = reg_open_key(HKEY_CLASSES_ROOT, "TypeLib", &htypelib);
    if(err != ERROR_SUCCESS) {
        return Qfalse;
    }
    err = reg_open_vkey(htypelib, guid, &hguid);
    if (err != ERROR_SUCCESS) {
        RegCloseKey(htypelib);
        return Qfalse;
    }
    if (version_str != Qnil) {
        err = reg_open_vkey(hguid, version_str, &hversion);
        if (err == ERROR_SUCCESS) {
            tlib = reg_get_val(hversion, NULL);
            if (tlib != Qnil) {
                typelib = tlib;
                version = version_str;
            }
        }
        RegCloseKey(hversion);
    } else {
        fver = 0.0;
        for(j = 0; ;j++) {
            ver = reg_enum_key(hguid, j);
            if (ver == Qnil)
                break;
            err = reg_open_vkey(hguid, ver, &hversion);
            if (err != ERROR_SUCCESS)
                continue;
            tlib = reg_get_val(hversion, NULL);
            if (tlib == Qnil) {
                RegCloseKey(hversion);
                continue;
            }
            if (fver < atof(StringValuePtr(ver))) {
                fver = atof(StringValuePtr(ver));
                version = ver;
                typelib = tlib;
            }
            RegCloseKey(hversion);
        }
    }
    RegCloseKey(hguid);
    RegCloseKey(htypelib);
    if (typelib != Qnil) {
        hr = oletypelib_from_guid(guid, version, &pTypeLib);
        if (SUCCEEDED(hr)) {
            found = Qtrue;
            oletypelib_set_member(self, pTypeLib);
        }
    }
    return found;
}
Exemplo n.º 5
0
static void full_connect(VALUE self, PGconn *db) {

  PGresult *result = NULL;
  VALUE r_host, r_user, r_password, r_path, r_port, r_query, r_options;
  char *host = NULL, *user = NULL, *password = NULL, *path = NULL, *database = NULL;
  const char *port = "5432";
  VALUE encoding = Qnil;
  const char *search_path = NULL;
  char *search_path_query = NULL;
  const char *backslash_off = "SET backslash_quote = off";
  const char *standard_strings_on = "SET standard_conforming_strings = on";
  const char *warning_messages = "SET client_min_messages = warning";

  if((r_host = rb_iv_get(self, "@host")) != Qnil) {
    host     = StringValuePtr(r_host);
  }

  if((r_user = rb_iv_get(self, "@user")) != Qnil) {
    user     = StringValuePtr(r_user);
  }

  if((r_password = rb_iv_get(self, "@password")) != Qnil) {
    password = StringValuePtr(r_password);
  }

  if((r_port = rb_iv_get(self, "@port")) != Qnil) {
    port = StringValuePtr(r_port);
  }

  if((r_path = rb_iv_get(self, "@path")) != Qnil) {
    path = StringValuePtr(r_path);
    database = strtok(path, "/");
  }

  if (NULL == database || 0 == strlen(database)) {
    rb_raise(eConnectionError, "Database must be specified");
  }

  r_query        = rb_iv_get(self, "@query");

  search_path = get_uri_option(r_query, "search_path");

  db = PQsetdbLogin(
    host,
    port,
    NULL,
    NULL,
    database,
    user,
    password
  );

  if ( PQstatus(db) == CONNECTION_BAD ) {
    rb_raise(eConnectionError, "%s", PQerrorMessage(db));
  }

  if (search_path != NULL) {
    search_path_query = (char *)calloc(256, sizeof(char));
    snprintf(search_path_query, 256, "set search_path to %s;", search_path);
    r_query = rb_str_new2(search_path_query);
    result = cCommand_execute(self, db, r_query);

    if (PQresultStatus(result) != PGRES_COMMAND_OK) {
      free((void *)search_path_query);
      raise_error(self, result, r_query);
    }

    free((void *)search_path_query);
  }

  r_options = rb_str_new2(backslash_off);
  result = cCommand_execute(self, db, r_options);

  if (PQresultStatus(result) != PGRES_COMMAND_OK) {
    rb_warn("%s", PQresultErrorMessage(result));
  }

  r_options = rb_str_new2(standard_strings_on);
  result = cCommand_execute(self, db, r_options);

  if (PQresultStatus(result) != PGRES_COMMAND_OK) {
    rb_warn("%s", PQresultErrorMessage(result));
  }

  r_options = rb_str_new2(warning_messages);
  result = cCommand_execute(self, db, r_options);

  if (PQresultStatus(result) != PGRES_COMMAND_OK) {
    rb_warn("%s", PQresultErrorMessage(result));
  }

  encoding = rb_iv_get(self, "@encoding");

#ifdef HAVE_PQSETCLIENTENCODING
  VALUE pg_encoding = rb_hash_aref(CONST_GET(mEncoding, "MAP"), encoding);
  if(pg_encoding != Qnil) {
    if(PQsetClientEncoding(db, rb_str_ptr_readonly(pg_encoding))) {
      rb_raise(eConnectionError, "Couldn't set encoding: %s", rb_str_ptr_readonly(encoding));
    } else {
#ifdef HAVE_RUBY_ENCODING_H
      rb_iv_set(self, "@encoding_id", INT2FIX(rb_enc_find_index(rb_str_ptr_readonly(encoding))));
#endif
      rb_iv_set(self, "@pg_encoding", pg_encoding);
    }
  } else {
    rb_warn("Encoding %s is not a known Ruby encoding for PostgreSQL\n", rb_str_ptr_readonly(encoding));
    rb_iv_set(self, "@encoding", rb_str_new2("UTF-8"));
#ifdef HAVE_RUBY_ENCODING_H
    rb_iv_set(self, "@encoding_id", INT2FIX(rb_enc_find_index("UTF-8")));
#endif
    rb_iv_set(self, "@pg_encoding", rb_str_new2("UTF8"));
  }
#endif
  rb_iv_set(self, "@connection", Data_Wrap_Struct(rb_cObject, 0, 0, db));
}
Exemplo n.º 6
0
/*
 * call-seq:
 *   Watchcat.new([options])                      => watchcat_obj
 *   Watchcat.new([options]) { |watchcat| block } => watchcat_obj
 *
 * Create a new Watchcat object. The parameter hash may have the following
 * symbols:
 * +timeout+::
 *   If watchcatd doesn't receive a heartbeat after this period (in seconds),
 *   it will signal the process. (default: 60)
 * +signal+::
 *   Defines which signal will be sent to the process after the timeout
 *   expires. Can be a string like 'HUP' or 'SIGHUP' or an integer like 9.
 *   (default: 9)
 * +info+::
 *   Should be a string which is added to the log generated by watchcatd
 *   when it signals a process. (default: nil)
 * +device+::
 *   The watchcat device. (default: +/var/run/watchcat.socket+). Use for
 *   debugging purposes.
 *
 * If a block is given, the Watchcat object will be yielded and automatically
 * closed on block termination.
 */
static VALUE
rb_wcat_open(int argc, VALUE *argv, VALUE self)
{
    int sock, timeout, signal;
    char *signame;
    const char *info;
    VALUE opt, vtimeout, vsignal, vinfo, vdevice, vsiglist, mSignal;

    rb_scan_args(argc, argv, "01", &opt);
    if (NIL_P(opt)) {
        sock = cat_open();
        if (sock == -1)
            rb_sys_fail("cat_open");
        rb_iv_set(self, "@sock", INT2NUM(sock));
        return(self);
    }

    /* Defaults. */
    timeout = 60;
    signal = SIGKILL;
    info = NULL;
    
    vtimeout = rb_hash_aref(opt, SYMBOL("timeout"));
    if (!NIL_P(vtimeout)) {
        if (FIXNUM_P(vtimeout))
            timeout = NUM2INT(vtimeout);
        else
            rb_raise(rb_eArgError, "timeout must be an integer");
    }

    vsignal = rb_hash_aref(opt, SYMBOL("signal"));
    if (!NIL_P(vsignal)) {
        switch (TYPE(vsignal)) {
        case T_FIXNUM:
            signal = NUM2INT(vsignal);
            break;
        case T_STRING:
            signame = StringValuePtr(vsignal);
            if (strncmp("SIG", signame, 3) == 0) {
                signame += 3;
                vsignal = rb_str_new2(signame);
            }
            mSignal = rb_const_get(rb_cObject, rb_intern("Signal"));
            vsiglist = rb_funcall(mSignal, rb_intern("list"), 0);
            vsignal = rb_hash_aref(vsiglist, vsignal);
            if (NIL_P(vsignal))
                rb_raise(rb_eArgError, "invalid signal name");
            else
                signal = NUM2INT(vsignal);
            break;
        default:
            rb_raise(rb_eArgError, "signal must be an integer or a string");
        }
    }

    vinfo = rb_hash_aref(opt, SYMBOL("info"));
    if (!NIL_P(vinfo))
        info = StringValuePtr(vinfo);

    vdevice = rb_hash_aref(opt, SYMBOL("device"));
    if (!NIL_P(vdevice))
        cat_set_device(StringValuePtr(vdevice));

    sock = cat_open1(timeout, signal, info);
    if (sock == -1)
        rb_sys_fail("cat_open");

    rb_iv_set(self, "@sock", INT2NUM(sock));

    if (rb_block_given_p())
        rb_ensure(rb_yield, self, (void *)cat_close, sock);

    return(self);
}
Exemplo n.º 7
0
/*
 * call-seq:
 *    ctx.setup => Qtrue # first time
 *    ctx.setup => nil # thereafter
 *
 * This method is called automatically when a new SSLSocket is created.
 * Normally you do not need to call this method (unless you are writing an extension in C).
 */
static VALUE
ossl_sslctx_setup(VALUE self)
{
    SSL_CTX *ctx;
    X509 *cert = NULL, *client_ca = NULL;
    X509_STORE *store;
    EVP_PKEY *key = NULL;
    char *ca_path = NULL, *ca_file = NULL;
    int i, verify_mode;
    VALUE val;

    if(OBJ_FROZEN(self)) return Qnil;
    Data_Get_Struct(self, SSL_CTX, ctx);

#if !defined(OPENSSL_NO_DH)
    if (RTEST(ossl_sslctx_get_tmp_dh_cb(self))){
	SSL_CTX_set_tmp_dh_callback(ctx, ossl_tmp_dh_callback);
    }
    else{
	SSL_CTX_set_tmp_dh_callback(ctx, ossl_default_tmp_dh_callback);
    }
#endif
    SSL_CTX_set_ex_data(ctx, ossl_ssl_ex_ptr_idx, (void*)self);

    val = ossl_sslctx_get_cert_store(self);
    if(!NIL_P(val)){
	/*
         * WORKAROUND:
	 *   X509_STORE can count references, but
	 *   X509_STORE_free() doesn't care it.
	 *   So we won't increment it but mark it by ex_data.
	 */
        store = GetX509StorePtr(val); /* NO NEED TO DUP */
        SSL_CTX_set_cert_store(ctx, store);
        SSL_CTX_set_ex_data(ctx, ossl_ssl_ex_store_p, (void*)1);
    }

    val = ossl_sslctx_get_extra_cert(self);
    if(!NIL_P(val)){
	rb_block_call(val, rb_intern("each"), 0, 0, ossl_sslctx_add_extra_chain_cert_i, self);
    }

    /* private key may be bundled in certificate file. */
    val = ossl_sslctx_get_cert(self);
    cert = NIL_P(val) ? NULL : GetX509CertPtr(val); /* NO DUP NEEDED */
    val = ossl_sslctx_get_key(self);
    key = NIL_P(val) ? NULL : GetPKeyPtr(val); /* NO DUP NEEDED */
    if (cert && key) {
        if (!SSL_CTX_use_certificate(ctx, cert)) {
            /* Adds a ref => Safe to FREE */
            ossl_raise(eSSLError, "SSL_CTX_use_certificate:");
        }
        if (!SSL_CTX_use_PrivateKey(ctx, key)) {
            /* Adds a ref => Safe to FREE */
            ossl_raise(eSSLError, "SSL_CTX_use_PrivateKey:");
        }
        if (!SSL_CTX_check_private_key(ctx)) {
            ossl_raise(eSSLError, "SSL_CTX_check_private_key:");
        }
    }

    val = ossl_sslctx_get_client_ca(self);
    if(!NIL_P(val)){
	if(TYPE(val) == T_ARRAY){
	    for(i = 0; i < RARRAY_LEN(val); i++){
		client_ca = GetX509CertPtr(RARRAY_PTR(val)[i]);
        	if (!SSL_CTX_add_client_CA(ctx, client_ca)){
		    /* Copies X509_NAME => FREE it. */
        	    ossl_raise(eSSLError, "SSL_CTX_add_client_CA");
        	}
	    }
        }
	else{
	    client_ca = GetX509CertPtr(val); /* NO DUP NEEDED. */
            if (!SSL_CTX_add_client_CA(ctx, client_ca)){
		/* Copies X509_NAME => FREE it. */
        	ossl_raise(eSSLError, "SSL_CTX_add_client_CA");
            }
	}
    }

    val = ossl_sslctx_get_ca_file(self);
    ca_file = NIL_P(val) ? NULL : StringValuePtr(val);
    val = ossl_sslctx_get_ca_path(self);
    ca_path = NIL_P(val) ? NULL : StringValuePtr(val);
    if(ca_file || ca_path){
	if (!SSL_CTX_load_verify_locations(ctx, ca_file, ca_path))
	    rb_warning("can't set verify locations");
    }

    val = ossl_sslctx_get_verify_mode(self);
    verify_mode = NIL_P(val) ? SSL_VERIFY_NONE : NUM2INT(val);
    SSL_CTX_set_verify(ctx, verify_mode, ossl_ssl_verify_callback);
    if (RTEST(ossl_sslctx_get_client_cert_cb(self)))
	SSL_CTX_set_client_cert_cb(ctx, ossl_client_cert_cb);

    val = ossl_sslctx_get_timeout(self);
    if(!NIL_P(val)) SSL_CTX_set_timeout(ctx, NUM2LONG(val));

    val = ossl_sslctx_get_verify_dep(self);
    if(!NIL_P(val)) SSL_CTX_set_verify_depth(ctx, NUM2LONG(val));

    val = ossl_sslctx_get_options(self);
    if(!NIL_P(val)) SSL_CTX_set_options(ctx, NUM2LONG(val));
    rb_obj_freeze(self);

    val = ossl_sslctx_get_sess_id_ctx(self);
    if (!NIL_P(val)){
	StringValue(val);
	if (!SSL_CTX_set_session_id_context(ctx, RSTRING_PTR(val),
					    RSTRING_LEN(val))){
	    ossl_raise(eSSLError, "SSL_CTX_set_session_id_context:");
	}
    }

    if (RTEST(rb_iv_get(self, "@session_get_cb"))) {
	SSL_CTX_sess_set_get_cb(ctx, ossl_sslctx_session_get_cb);
	OSSL_Debug("SSL SESSION get callback added");
    }
    if (RTEST(rb_iv_get(self, "@session_new_cb"))) {
	SSL_CTX_sess_set_new_cb(ctx, ossl_sslctx_session_new_cb);
	OSSL_Debug("SSL SESSION new callback added");
    }
    if (RTEST(rb_iv_get(self, "@session_remove_cb"))) {
	SSL_CTX_sess_set_remove_cb(ctx, ossl_sslctx_session_remove_cb);
	OSSL_Debug("SSL SESSION remove callback added");
    }
    return Qtrue;
}
Exemplo n.º 8
0
/* call-seq: stmt.bind_param(key, value)
 *
 * Binds value to the named (or positional) placeholder. If +param+ is a
 * Fixnum, it is treated as an index for a positional placeholder.
 * Otherwise it is used as the name of the placeholder to bind to.
 *
 * See also #bind_params.
 */
static VALUE bind_param(VALUE self, VALUE key, VALUE value)
{
  sqlite3StmtRubyPtr ctx;
  int status;
  int index;

  Data_Get_Struct(self, sqlite3StmtRuby, ctx);
  REQUIRE_OPEN_STMT(ctx);

  switch(TYPE(key)) {
    case T_SYMBOL:
      key = rb_funcall(key, rb_intern("to_s"), 0);
    case T_STRING:
      if(RSTRING_PTR(key)[0] != ':') key = rb_str_plus(rb_str_new2(":"), key);
      index = sqlite3_bind_parameter_index(ctx->st, StringValuePtr(key));
      break;
    default:
      index = (int)NUM2INT(key);
  }

  if(index == 0)
    rb_raise(rb_path2class("SQLite3::Exception"), "no such bind parameter");

  switch(TYPE(value)) {
    case T_STRING:
      if(CLASS_OF(value) == cSqlite3Blob
#ifdef HAVE_RUBY_ENCODING_H
              || rb_enc_get_index(value) == rb_ascii8bit_encindex()
#endif
        ) {
        status = sqlite3_bind_blob(
            ctx->st,
            index,
            (const char *)StringValuePtr(value),
            (int)RSTRING_LEN(value),
            SQLITE_TRANSIENT
            );
      } else {
#ifdef HAVE_RUBY_ENCODING_H
        if(!UTF8_P(value)) {
              VALUE db          = rb_iv_get(self, "@connection");
              VALUE encoding    = rb_funcall(db, rb_intern("encoding"), 0);
              rb_encoding * enc = rb_to_encoding(encoding);
              value = rb_str_export_to_enc(value, enc);
          }
#endif

        status = sqlite3_bind_text(
            ctx->st,
            index,
            (const char *)StringValuePtr(value),
            (int)RSTRING_LEN(value),
            SQLITE_TRANSIENT
            );
      }
      break;
    case T_BIGNUM:
#if SIZEOF_LONG < 8
      if (RBIGNUM_LEN(value) * SIZEOF_BDIGITS <= 8) {
          status = sqlite3_bind_int64(ctx->st, index, (sqlite3_int64)NUM2LL(value));
          break;
      }
#endif
    case T_FLOAT:
      status = sqlite3_bind_double(ctx->st, index, NUM2DBL(value));
      break;
    case T_FIXNUM:
      status = sqlite3_bind_int64(ctx->st, index, (sqlite3_int64)FIX2LONG(value));
      break;
    case T_NIL:
      status = sqlite3_bind_null(ctx->st, index);
      break;
    default:
      rb_raise(rb_eRuntimeError, "can't prepare %s",
          rb_class2name(CLASS_OF(value)));
      break;
  }

  CHECK(sqlite3_db_handle(ctx->st), status);

  return self;
}
Exemplo n.º 9
0
static VALUE
string_to_r_internal(VALUE self)
{
    VALUE s, m;

    s = self;

    if (RSTRING_LEN(s) == 0)
	return rb_assoc_new(Qnil, self);

    m = f_match(rat_pat, s);

    if (!NIL_P(m)) {
	VALUE v, ifp, exp, ip, fp;
	VALUE si = f_aref(m, INT2FIX(1));
	VALUE nu = f_aref(m, INT2FIX(2));
	VALUE de = f_aref(m, INT2FIX(3));
	VALUE re = f_post_match(m);

	{
	    VALUE a;

	    a = f_split(nu, an_e_pat);
	    ifp = RARRAY_PTR(a)[0];
	    if (RARRAY_LEN(a) != 2)
		exp = Qnil;
	    else
		exp = RARRAY_PTR(a)[1];

	    a = f_split(ifp, a_dot_pat);
	    ip = RARRAY_PTR(a)[0];
	    if (RARRAY_LEN(a) != 2)
		fp = Qnil;
	    else
		fp = RARRAY_PTR(a)[1];
	}

	v = rb_rational_new1(f_to_i(ip));

	if (!NIL_P(fp)) {
	    char *p = StringValuePtr(fp);
	    long count = 0;
	    VALUE l;

	    while (*p) {
		if (rb_isdigit(*p))
		    count++;
		p++;
	    }

	    l = f_expt(INT2FIX(10), LONG2NUM(count));
	    v = f_mul(v, l);
	    v = f_add(v, f_to_i(fp));
	    v = f_div(v, l);
	}
	if (!NIL_P(si) && *StringValuePtr(si) == '-')
	    v = f_negate(v);
	if (!NIL_P(exp))
	    v = f_mul(v, f_expt(INT2FIX(10), f_to_i(exp)));
#if 0
	if (!NIL_P(de) && (!NIL_P(fp) || !NIL_P(exp)))
	    return rb_assoc_new(v, rb_usascii_str_new2("dummy"));
#endif
	if (!NIL_P(de))
	    v = f_div(v, f_to_i(de));

	return rb_assoc_new(v, re);
    }
    return rb_assoc_new(Qnil, self);
}
Exemplo n.º 10
0
int
weechat_ruby_print_exception (VALUE err)
{
    VALUE backtrace, tmp1, tmp2, tmp3;
    int i;
    int ruby_error;
    char* line;
    char* cline;
    char* err_msg;
    char* err_class;

    backtrace = rb_protect_funcall (err, rb_intern("backtrace"),
                                    &ruby_error, 0, NULL);

    tmp1 = rb_protect_funcall(err, rb_intern("message"), &ruby_error, 0, NULL);
    err_msg = StringValueCStr(tmp1);

    tmp2 = rb_protect_funcall(rb_protect_funcall(err, rb_intern("class"),
                                                 &ruby_error, 0, NULL),
                              rb_intern("name"), &ruby_error, 0, NULL);
    err_class = StringValuePtr(tmp2);

    if (strcmp (err_class, "SyntaxError") == 0)
    {
        tmp3 = rb_inspect(err);
        weechat_printf (NULL,
                        weechat_gettext ("%s%s: error: %s"),
                        weechat_prefix ("error"), RUBY_PLUGIN_NAME,
                        StringValuePtr(tmp3));
    }
    else
    {
        for (i = 0; i < RARRAY_LEN(backtrace); i++)
        {
            line = StringValuePtr(RARRAY_PTR(backtrace)[i]);
            cline = NULL;
            if (i == 0)
            {
                cline = (char *)calloc (strlen (line) + 2 + strlen (err_msg) +
                                        3 + strlen (err_class) + 1,
                                        sizeof (char));
                if (cline)
                {
                    strcat (cline, line);
                    strcat (cline, ": ");
                    strcat (cline, err_msg);
                    strcat (cline, " (");
                    strcat (cline, err_class);
                    strcat (cline, ")");
                }
            }
            else
            {
                cline = (char *)calloc(strlen (line) + strlen ("     from ") + 1,
                                       sizeof (char));
                if (cline)
                {
                    strcat (cline, "     from ");
                    strcat (cline, line);
                }
            }
            if (cline)
            {
                weechat_printf (NULL,
                                weechat_gettext ("%s%s: error: %s"),
                                weechat_prefix ("error"), RUBY_PLUGIN_NAME,
                                cline);
            }

            if (cline)
                free (cline);
        }
    }

    return 0;
}
Exemplo n.º 11
0
void *
weechat_ruby_exec (struct t_plugin_script *script,
                   int ret_type, const char *function,
                   const char *format, void **argv)
{
    VALUE rc, err;
    int ruby_error, i, argc, *ret_i;
    VALUE argv2[16];
    void *ret_value;
    struct t_plugin_script *old_ruby_current_script;

    old_ruby_current_script = ruby_current_script;
    ruby_current_script = script;

    argc = 0;
    if (format && format[0])
    {
        argc = strlen (format);
        for (i = 0; i < argc; i++)
        {
            switch (format[i])
            {
                case 's': /* string */
                    argv2[i] = rb_str_new2 ((char *)argv[i]);
                    break;
                case 'i': /* integer */
                    argv2[i] = INT2FIX (*((int *)argv[i]));
                    break;
                case 'h': /* hash */
                    argv2[i] = weechat_ruby_hashtable_to_hash (argv[i]);
                    break;
            }
        }
    }

    if (argc > 0)
    {
        rc = rb_protect_funcall ((VALUE) script->interpreter,
                                 rb_intern(function),
                                 &ruby_error, argc, argv2);
    }
    else
    {
        rc = rb_protect_funcall ((VALUE) script->interpreter,
                                 rb_intern(function),
                                 &ruby_error, 0, NULL);
    }

    if (ruby_error)
    {
        weechat_printf (NULL,
                        weechat_gettext ("%s%s: unable to run function \"%s\""),
                        weechat_prefix ("error"), RUBY_PLUGIN_NAME, function);

        err = rb_gv_get("$!");
        weechat_ruby_print_exception(err);

        return NULL;
    }

    if ((TYPE(rc) == T_STRING) && (ret_type == WEECHAT_SCRIPT_EXEC_STRING))
    {
        if (StringValuePtr (rc))
            ret_value = strdup (StringValuePtr (rc));
        else
            ret_value = NULL;
    }
    else if ((TYPE(rc) == T_FIXNUM) && (ret_type == WEECHAT_SCRIPT_EXEC_INT))
    {
        ret_i = malloc (sizeof (*ret_i));
        if (ret_i)
            *ret_i = NUM2INT(rc);
        ret_value = ret_i;
    }
    else if (ret_type == WEECHAT_SCRIPT_EXEC_HASHTABLE)
    {
        ret_value = weechat_ruby_hash_to_hashtable (rc,
                                                    WEECHAT_SCRIPT_HASHTABLE_DEFAULT_SIZE,
                                                    WEECHAT_HASHTABLE_STRING,
                                                    WEECHAT_HASHTABLE_STRING);
    }
    else
    {
        weechat_printf (NULL,
                        weechat_gettext ("%s%s: function \"%s\" must return a "
                                         "valid value"),
                        weechat_prefix ("error"), RUBY_PLUGIN_NAME, function);
        ruby_current_script = old_ruby_current_script;
        return WEECHAT_RC_OK;
    }

    if (ret_value == NULL)
    {
        weechat_printf (NULL,
                        weechat_gettext ("%s%s: not enough memory in function "
                                         "\"%s\""),
                        weechat_prefix ("error"), RUBY_PLUGIN_NAME, function);
        ruby_current_script = old_ruby_current_script;
        return NULL;
    }

    ruby_current_script = old_ruby_current_script;

    return ret_value;
}
Exemplo n.º 12
0
VALUE xmlsec_is_valid_by_x509_file(VALUE self, xmlDocPtr doc, VALUE x509_file ) {
  xmlSecKeysMngrPtr mngr;
  VALUE v;
  xmlNodePtr node = NULL;
  xmlSecDSigCtxPtr dsigCtx = NULL;
  long i;

  mngr = xmlSecKeysMngrCreate();

  if(mngr == NULL) {
    if(doc != NULL) xmlFreeDoc(doc);
    rb_raise(rb_eRuntimeError, "Error: failed to create keys manager.\n");
    return Qnil;
  }

  if(xmlSecCryptoAppDefaultKeysMngrInit(mngr) < 0) {
    if(doc != NULL) xmlFreeDoc(doc);
    if(mngr != NULL) xmlSecKeysMngrDestroy(mngr);
    rb_raise(rb_eRuntimeError, "Error: failed to initialize keys manager.\n");
    return Qnil;
  }
  if (TYPE(x509_file) == T_STRING){
    /* load trusted cert */
    if(xmlSecCryptoAppKeysMngrCertLoad(mngr, StringValuePtr(x509_file), xmlSecKeyDataFormatPem, xmlSecKeyDataTypeTrusted) < 0) {
      if(doc != NULL) xmlFreeDoc(doc);
      if(mngr != NULL) xmlSecKeysMngrDestroy(mngr);
      rb_raise(rb_eRuntimeError, "Error: failed to load pem certificate from \"%s\"\n", StringValuePtr(x509_file));
      return Qnil;
    }
  }
  if (TYPE(x509_file) == T_ARRAY) {
    for (i =0; i < RARRAY_LEN(x509_file); i++) {
      v = rb_ary_entry(x509_file, i);
      StringValue(v);
      if(xmlSecCryptoAppKeysMngrCertLoad(mngr, RSTRING_PTR(v), xmlSecKeyDataFormatPem, xmlSecKeyDataTypeTrusted) < 0) {
          if(doc != NULL) xmlFreeDoc(doc);
          if(mngr != NULL) xmlSecKeysMngrDestroy(mngr);
          rb_raise(rb_eRuntimeError, "Error: failed to load pem certificate from \"%s\"\n", RSTRING_PTR(v));
          return Qnil;
      }

    }
    //rb_ary_entry

  }


  /* find start node */
  node = xmlSecFindNode(xmlDocGetRootElement(doc), xmlSecNodeSignature, xmlSecDSigNs);
  if(node == NULL) {
    if(doc != NULL) xmlFreeDoc(doc);
    rb_raise(rb_eRuntimeError, "Error: start node not found\n");
    return Qnil;
  }

  /* create signature context*/
  dsigCtx = xmlSecDSigCtxCreate(mngr);
  if(dsigCtx == NULL) {
    if(doc != NULL) xmlFreeDoc(doc);
    if(mngr != NULL) xmlSecKeysMngrDestroy(mngr);
    rb_raise(rb_eRuntimeError, "Error: failed to create signature context\n");
    return Qnil;
  }

    /* limit the Reference URI attributes to empty or NULL */
  dsigCtx->enabledReferenceUris = xmlSecTransformUriTypeEmpty;

  /* Verify signature */
  if(xmlSecDSigCtxVerify(dsigCtx, node) < 0) {
    if(dsigCtx != NULL) xmlSecDSigCtxDestroy(dsigCtx);
    if(doc != NULL) xmlFreeDoc(doc);
    if(mngr != NULL) xmlSecKeysMngrDestroy(mngr);
    rb_raise(rb_eRuntimeError, "Error: signature verify \"%s\"\n");
    return Qnil;
  }

  /* verification result*/
  if(dsigCtx->status == xmlSecDSigStatusSucceeded) {
    if(dsigCtx != NULL) xmlSecDSigCtxDestroy(dsigCtx);
    if(doc != NULL) xmlFreeDoc(doc);
    if(mngr != NULL) xmlSecKeysMngrDestroy(mngr);
    return Qtrue;
  } else {
    if(dsigCtx != NULL) xmlSecDSigCtxDestroy(dsigCtx);
    if(doc != NULL) xmlFreeDoc(doc);
    if(mngr != NULL) xmlSecKeysMngrDestroy(mngr);
    return Qfalse;
  }

}
Exemplo n.º 13
0
/*
 * call-seq:
 *  new
 *
 * Create a new document
 */
static VALUE new(int argc, VALUE *argv, VALUE klass)
{
  VALUE uri, external_id, rest, rb_doc;

  rb_scan_args(argc, argv, "0*", &rest);
  uri         = rb_ary_entry(rest, 0);
  external_id = rb_ary_entry(rest, 1);

  htmlDocPtr doc = htmlNewDoc(
      RTEST(uri) ? (const xmlChar *)StringValuePtr(uri) : NULL,
      RTEST(external_id) ? (const xmlChar *)StringValuePtr(external_id) : NULL
  );
  rb_doc = Nokogiri_wrap_xml_document(klass, doc);
  rb_funcall2(rb_doc, rb_intern("initialize"), argc, argv);
  return rb_doc ;
}

/*
 * call-seq:
 *  read_io(io, url, encoding, options)
 *
 * Read the HTML document from +io+ with given +url+, +encoding+,
 * and +options+.  See Nokogiri::HTML.parse
 */
static VALUE read_io( VALUE klass,
Exemplo n.º 14
0
Arquivo: yab62.c Projeto: l4u/yab62
static VALUE alphadecimal_base62_decode(VALUE self, VALUE arg) {
  char* str = StringValuePtr(arg);
  long val = base62_decode(str);
  return ULL2NUM(val);
}
Exemplo n.º 15
0
VALUE kernel_spec_rb_warn(VALUE self, VALUE msg) {
  rb_warn("%s", StringValuePtr(msg));
  return Qnil;
}
Exemplo n.º 16
0
/**
 * This method creates a database parameter buffer to be used in creating a
 * database connection.
 *
 * @param  user      A reference to a string containing the user name to be used
 *                   in making the connection.
 * @param  password  A reference to a string containing the password to be used
 *                   in making the connection.
 * @param  options   A hash of the options to be used in making the connection
 *                   to the database.
 * @param  length    A pointer to a short integer that will be set to the
 *                   length of the buffer.
 *
 * @return  A pointer to an array of characters containing the database
 *          parameter buffer.
 *
 */
char *createDPB(VALUE user, VALUE password, VALUE options, short *length) {
  char *dpb = NULL;
  VALUE keys;
  VALUE entry;
  int i;
  short type;

  /* Determine the dpb length and allocate it. */
  *length = 1;
  if(user != Qnil) {
    *length += strlen(StringValuePtr(user)) + 2;
  }
  if(password != Qnil) {
    *length += strlen(StringValuePtr(password)) + 2;
  }
  if(options != Qnil) {
    keys = rb_funcall(options, rb_intern("keys"), 0);

    for(i = 0; i < RARRAY_LEN(keys); i++) {
      type = FIX2INT(rb_ary_entry(keys, i));

      switch (type) {
      case isc_dpb_sql_role_name:
      case isc_dpb_lc_messages:
      case isc_dpb_lc_ctype:
      case isc_dpb_reserved:
      {
        entry = rb_hash_aref(options, INT2FIX(type));
        *length += strlen(StringValuePtr(entry)) + 2;
        break;
      }
      default:
      {
        *length += 3;
      }
      }
    }
  }
  dpb = ALLOC_N(char, *length);

  /* Populate the buffer. */
  if(dpb != NULL) {
    char *ptr = NULL;
    int size = 0;

    /* Fill out the DPB. */
    memset(dpb, 0, *length);
    dpb[0] = isc_dpb_version1;
    ptr    = &dpb[1];

    if(user != Qnil) {
      char *username = StringValuePtr(user);

      size   = strlen(username);
      *ptr++ = isc_dpb_user_name;
      *ptr++ = (char)size;
      memcpy(ptr, username, size);
      ptr    = ptr + size;
    }

    if(password != Qnil) {
      char *userpwd  = StringValuePtr(password);

      size   = strlen(userpwd);
      *ptr++ = isc_dpb_password;
      *ptr++ = (char)size;
      memcpy(ptr, userpwd, size);
      ptr    = ptr + size;
    }

    if(options != Qnil) {
      for(i = 0; i < RARRAY_LEN(keys); i++) {
        type = FIX2INT(rb_ary_entry(keys, i));
        entry = rb_hash_aref(options, INT2FIX(type));

        switch (type) {
        case isc_dpb_sql_role_name:
        case isc_dpb_lc_messages:
        case isc_dpb_lc_ctype:
        case isc_dpb_reserved:
        {
          char *text = StringValuePtr(entry);

          size   = strlen(text);
          *ptr++ = type;
          *ptr++ = (char)size;
          memcpy(ptr, text, size);
          ptr    = ptr + size;
          break;
        }
        default:
        {
          short value;
          switch (TYPE(entry)) {
          case T_FIXNUM: value = FIX2INT(entry);
          case T_NIL: value = 0;
          case T_FALSE: value = 0;
          case T_TRUE: value = 1;
          case T_UNDEF: value = 0;
          case T_FLOAT: value = NUM2INT(entry);
          case T_BIGNUM: value = NUM2INT(entry);
          default: value = 0;
          }

          *ptr++ = type;
          *ptr++ = (char)1;
          *ptr++ = value;
        }
        }
      }
    }
  } else {
    /* Generate an error. */
    rb_raise(rb_eNoMemError,
             "Memory allocation failure creating database DPB.");
  }

  return(dpb);
}
Exemplo n.º 17
0
VALUE kernel_spec_rb_catch(VALUE self, VALUE sym, VALUE main_proc) {
  return rb_catch(StringValuePtr(sym), kernel_spec_call_proc_with_catch, main_proc);
}
Exemplo n.º 18
0
 // Used for our rb_protect calls.
 static VALUE evaluateSimpleImpl(VALUE arg) 
 {
   return rb_eval_string(StringValuePtr(arg));
 }
Exemplo n.º 19
0
}

/*
 * call-seq:
 *    XML::Schema.initialize(schema_uri) -> schema
 *
 * Create a new schema from the specified URI.
 */
static VALUE rxml_schema_init_from_uri(VALUE class, VALUE uri)
{
  xmlSchemaParserCtxtPtr xparser;
  xmlSchemaPtr xschema;

  Check_Type(uri, T_STRING);

  xparser = xmlSchemaNewParserCtxt(StringValuePtr(uri));
  xschema = xmlSchemaParse(xparser);
  xmlSchemaFreeParserCtxt(xparser);

  return Data_Wrap_Struct(cXMLSchema, NULL, rxml_schema_free, xschema);
}

/*
 * call-seq:
 *    XML::Schema.document(document) -> schema
 *
 * Create a new schema from the specified document.
 */
static VALUE rxml_schema_init_from_document(VALUE class, VALUE document)
{
  xmlDocPtr xdoc;
Exemplo n.º 20
0
static VALUE new(int argc, VALUE *argv, VALUE klass)
{
  xmlDocPtr xml_doc;
  xmlNodePtr node;
  VALUE document;
  VALUE content;
  VALUE rest;
  VALUE rb_node;

  rb_scan_args(argc, argv, "2*", &document, &content, &rest);

  Data_Get_Struct(document, xmlDoc, xml_doc);

  node = xmlNewDocComment(
      xml_doc,
      (const xmlChar *)StringValuePtr(content)
  );

  rb_node = Nokogiri_wrap_xml_node(klass, node);
  rb_obj_call_init(rb_node, argc, argv);

  nokogiri_root_node(node);

  if(rb_block_given_p()) rb_yield(rb_node);

  return rb_node;
}

VALUE cNokogiriXmlComment;
void init_xml_comment()
{
Exemplo n.º 21
0
char*
rb_compat_str2cstr(VALUE x)
{
  return StringValuePtr(x);
}
Exemplo n.º 22
0
static VALUE t_send_data (VALUE self, VALUE signature, VALUE data, VALUE data_length)
{
	int b = evma_send_data_to_connection (NUM2ULONG (signature), StringValuePtr (data), FIX2INT (data_length));
	return INT2NUM (b);
}
Exemplo n.º 23
0
Arquivo: ruby.c Projeto: 217/ruby
static void
process_sflag(int *sflag)
{
    if (*sflag > 0) {
	long n;
	VALUE *args;
	VALUE argv = rb_argv;

	n = RARRAY_LEN(argv);
	args = RARRAY_PTR(argv);
	while (n > 0) {
	    VALUE v = *args++;
	    char *s = StringValuePtr(v);
	    char *p;
	    int hyphen = FALSE;

	    if (s[0] != '-')
		break;
	    n--;
	    if (s[1] == '-' && s[2] == '\0')
		break;

	    v = Qtrue;
	    /* check if valid name before replacing - with _ */
	    for (p = s + 1; *p; p++) {
		if (*p == '=') {
		    *p++ = '\0';
		    v = rb_str_new2(p);
		    break;
		}
		if (*p == '-') {
		    hyphen = TRUE;
		}
		else if (*p != '_' && !ISALNUM(*p)) {
		    VALUE name_error[2];
		    name_error[0] =
			rb_str_new2("invalid name for global variable - ");
		    if (!(p = strchr(p, '='))) {
			rb_str_cat2(name_error[0], s);
		    }
		    else {
			rb_str_cat(name_error[0], s, p - s);
		    }
		    name_error[1] = args[-1];
		    rb_exc_raise(rb_class_new_instance(2, name_error, rb_eNameError));
		}
	    }
	    s[0] = '$';
	    if (hyphen) {
		for (p = s + 1; *p; ++p) {
		    if (*p == '-')
			*p = '_';
		}
	    }
	    rb_gv_set(s, v);
	}
	n = RARRAY_LEN(argv) - n;
	while (n--) {
	    rb_ary_shift(argv);
	}
	*sflag = -1;
    }
}
Exemplo n.º 24
0
static VALUE t_send_datagram (VALUE self, VALUE signature, VALUE data, VALUE data_length, VALUE address, VALUE port)
{
	int b = evma_send_datagram (NUM2ULONG (signature), StringValuePtr (data), FIX2INT (data_length), StringValuePtr(address), FIX2INT(port));
	return INT2NUM (b);
}
Exemplo n.º 25
0
Arquivo: load.c Projeto: 217/ruby
static int
rb_feature_p(const char *feature, const char *ext, int rb, int expanded, const char **fn)
{
    VALUE v, features, p, load_path = 0;
    const char *f, *e;
    long i, len, elen, n;
    st_table *loading_tbl;
    st_data_t data;
    int type;

    if (fn) *fn = 0;
    if (ext) {
	elen = strlen(ext);
	len = strlen(feature) - elen;
	type = rb ? 'r' : 's';
    }
    else {
	len = strlen(feature);
	elen = 0;
	type = 0;
    }
    features = get_loaded_features();
    for (i = 0; i < RARRAY_LEN(features); ++i) {
	v = RARRAY_PTR(features)[i];
	f = StringValuePtr(v);
	if ((n = RSTRING_LEN(v)) < len) continue;
	if (strncmp(f, feature, len) != 0) {
	    if (expanded) continue;
	    if (!load_path) load_path = rb_get_expanded_load_path();
	    if (!(p = loaded_feature_path(f, n, feature, len, type, load_path)))
		continue;
	    expanded = 1;
	    f += RSTRING_LEN(p) + 1;
	}
	if (!*(e = f + len)) {
	    if (ext) continue;
	    return 'u';
	}
	if (*e != '.') continue;
	if ((!rb || !ext) && (IS_SOEXT(e) || IS_DLEXT(e))) {
	    return 's';
	}
	if ((rb || !ext) && (IS_RBEXT(e))) {
	    return 'r';
	}
    }
    loading_tbl = get_loading_table();
    if (loading_tbl) {
	f = 0;
	if (!expanded) {
	    struct loaded_feature_searching fs;
	    fs.name = feature;
	    fs.len = len;
	    fs.type = type;
	    fs.load_path = load_path ? load_path : rb_get_load_path();
	    fs.result = 0;
	    st_foreach(loading_tbl, loaded_feature_path_i, (st_data_t)&fs);
	    if ((f = fs.result) != 0) {
		if (fn) *fn = f;
		goto loading;
	    }
	}
	if (st_get_key(loading_tbl, (st_data_t)feature, &data)) {
	    if (fn) *fn = (const char*)data;
	  loading:
	    if (!ext) return 'u';
	    return !IS_RBEXT(ext) ? 's' : 'r';
	}
	else {
	    VALUE bufstr;
	    char *buf;

	    if (ext && *ext) return 0;
	    bufstr = rb_str_tmp_new(len + DLEXT_MAXLEN);
	    buf = RSTRING_PTR(bufstr);
	    MEMCPY(buf, feature, char, len);
	    for (i = 0; (e = loadable_ext[i]) != 0; i++) {
		strlcpy(buf + len, e, DLEXT_MAXLEN + 1);
		if (st_get_key(loading_tbl, (st_data_t)buf, &data)) {
		    rb_str_resize(bufstr, 0);
		    if (fn) *fn = (const char*)data;
		    return i ? 's' : 'r';
		}
	    }
	    rb_str_resize(bufstr, 0);
	}
    }
    return 0;
}
Exemplo n.º 26
0
static VALUE t_setuid_string (VALUE self, VALUE username)
{
  evma_setuid_string (StringValuePtr (username));
  return Qnil;
}
Exemplo n.º 27
0
/*
 * Returns a nested hash based on the values passed to the constructor.  How
 * deeply that hash is nested depends on the values passed to the constructor.
 * The more specific your criterion, the less data you will receive.
 */
VALUE ks_record(VALUE self){
  volatile VALUE v_m_hash, v_i_hash, v_n_hash, v_s_hash;
  KstatStruct* ptr;
  kstat_io_t kio;
  kstat_timer_t kt;
  char* module;
  char* name;
  int instance = -1; // -1 represents all instances (the default)

  VALUE v_module, v_instance, v_name;

  Data_Get_Struct(self,KstatStruct,ptr);

  v_m_hash = rb_hash_new(); // Module name is key, holds v_i_hashes

  v_module   = rb_iv_get(self, "@module");
  v_instance = rb_iv_get(self, "@instance");
  v_name     = rb_iv_get(self, "@name");

  // Module is NULL by default (i.e. all modules are returned)
  if(NIL_P(v_module))
    module = NULL;
  else
    module = StringValuePtr(v_module);

  // Instance defaults to -1 (i.e. all instances are returned)
  if(!NIL_P(v_instance))
    instance = NUM2INT(v_instance);

  // Name is NULL by default (i.e. all names are returned)
  if(NIL_P(v_name))
    name = NULL;
  else
    name = StringValuePtr(v_name);

  // A failure probably means the module, instance or name doesn't exist
  if((ptr->kc = kstat_open()) == NULL)
    rb_raise(cKstatError, "kstat_open() failure: %s", strerror(errno));

  /*
   * Traverse the kstat chain, looking for matches based on supplied data.
   * A failure likely means a non-existant module or name was provided.
   */
  if((ptr->ksp = kstat_lookup(ptr->kc, module, instance, name)) == NULL)
    rb_raise(cKstatError, "kstat_lookup() failure: %s", strerror(errno));

  // Sync the chain with the kernel
  if(kstat_chain_update(ptr->kc) == -1)
    rb_raise(cKstatError, "kstat_chain_update() failure: %s", strerror(errno));

  while(ptr->ksp){
    // If a module is specified, ignore modules that don't match
    if((module) && (strcmp(module,ptr->ksp->ks_module))){
      ptr->ksp = ptr->ksp->ks_next;
      continue;
    }

    // If an instance is specified, ignore instances that don't match
    if((instance != -1) && (instance != ptr->ksp->ks_instance)){
      ptr->ksp = ptr->ksp->ks_next;
      continue;
    }

    // If a name is specified, ignore names that don't match
    if((name) && (strcmp(name,ptr->ksp->ks_name))){
      ptr->ksp = ptr->ksp->ks_next;
      continue;
    }

    // Call the appropriate data mapper based on ks_type
    switch(ptr->ksp->ks_type){
      case KSTAT_TYPE_NAMED:
        kstat_read(ptr->kc, ptr->ksp, NULL);
        v_s_hash = map_named_data_type(ptr->ksp);
        break;
      case KSTAT_TYPE_IO:
        kstat_read(ptr->kc, ptr->ksp, &kio);
        v_s_hash = map_io_data_type(&kio);
        break;
      case KSTAT_TYPE_TIMER:
        kstat_read(ptr->kc, ptr->ksp, &kt);
        v_s_hash = map_timer_data_type(&kt);
        break;
      case KSTAT_TYPE_INTR:
        kstat_read(ptr->kc, ptr->ksp, NULL);
        v_s_hash = map_intr_data_type(ptr->ksp);
        break;
      case KSTAT_TYPE_RAW:
        kstat_read(ptr->kc, ptr->ksp, NULL);
        v_s_hash = map_raw_data_type(ptr->ksp);   
        break;
      default:
        rb_raise(cKstatError,"Unknown data record type");
    }

    /* Set the class for this set of statistics */
    if(ptr->ksp->ks_class)
      rb_hash_aset(v_s_hash, rb_str_new2("class"), rb_str_new2(ptr->ksp->ks_class));

    v_i_hash = get_hash_for_key(v_m_hash, rb_str_new2(ptr->ksp->ks_module));
    v_n_hash = get_hash_for_key(v_i_hash, INT2FIX(ptr->ksp->ks_instance));

    rb_hash_aset(v_n_hash, rb_str_new2(ptr->ksp->ks_name), v_s_hash);
    rb_hash_aset(v_i_hash, INT2FIX(ptr->ksp->ks_instance),  v_n_hash);
    rb_hash_aset(v_m_hash, rb_str_new2(ptr->ksp->ks_module), v_i_hash);

    ptr->ksp = ptr->ksp->ks_next;
  }

  return v_m_hash;
}
Exemplo n.º 28
0
/**
 *  call-seq:
 *     23874.localize(:decimal, 'es_ES') => 23.874
 */
VALUE rb_numeric_localize(int argc, VALUE *argv, VALUE self)
{
	VALUE style, options;
	UNumberFormatStyle formatStyle;
	char *locale = NULL;

	UNumberFormat *format;
	UErrorCode status;

	UChar result[256];
	/* arguments */
	rb_scan_args(argc, argv, "02", &style, &options);
	if (style == Qnil) {
		formatStyle = UNUM_DECIMAL;
	} else {
		ID style_ID;

		Check_Type(style, T_SYMBOL);
		style_ID = SYM2ID(style);
		if (style_ID == rb_intern("decimal")) {
			formatStyle = UNUM_DECIMAL;
		} else if (style_ID == rb_intern("currency")) {
			formatStyle = UNUM_CURRENCY;
		} else if (style_ID == rb_intern("percent")) {
			formatStyle = UNUM_PERCENT;
		} else if (style_ID == rb_intern("scientific")) {
			formatStyle = UNUM_SCIENTIFIC;
		} else if (style_ID == rb_intern("spellout")) {
			formatStyle = UNUM_SPELLOUT;
		} else {
			rb_raise(rb_eArgError, "unsupported format style %s", rb_id2name(style_ID));
		}
	}
	if (options != Qnil) {
		VALUE rb_locale;

		Check_Type(options, T_HASH);
		rb_locale = rb_hash_aref(options, ID2SYM(rb_intern("locale")));
		if (rb_locale != Qnil) {
			locale = StringValuePtr(rb_locale);
		}
	}
	/* formatter */
	status = U_ZERO_ERROR;
    format = unum_open(formatStyle, NULL, 0, locale, NULL, &status);
    RAISE_ON_ERROR(status);
    /* set format attributes */
	if (options != Qnil) {
		VALUE currency, precision, round_mode, round_increment;

		switch (formatStyle) {
			case UNUM_CURRENCY:
				currency = rb_hash_aref(options, ID2SYM(rb_intern("currency")));
				if (currency != Qnil) {
					UChar *uStr;
					int32_t uStrLen;

					uStr = u_strFromRString(currency, &uStrLen);
					status = U_ZERO_ERROR;
					unum_setTextAttribute(format, UNUM_CURRENCY_CODE, uStr, uStrLen, &status);
					RAISE_ON_ERROR(status);
				}
			case UNUM_DECIMAL:
				/* precision */
				precision = rb_hash_aref(options, ID2SYM(rb_intern("precision")));
				if (precision != Qnil) {
					Check_Type(precision, T_FIXNUM);
					status = U_ZERO_ERROR;
					unum_setAttribute(format, UNUM_FRACTION_DIGITS, NUM2INT(precision));
					RAISE_ON_ERROR(status);
				}

				round_mode = rb_hash_aref(options, ID2SYM(rb_intern("round_mode")));
				if (round_mode != Qnil) {
					ID round_mode_ID;
					UNumberFormatRoundingMode rounding_mode;

					Check_Type(round_mode, T_SYMBOL);
					round_mode_ID = SYM2ID(round_mode);
					if (round_mode_ID == rb_intern("ceil")) {
						rounding_mode = UNUM_ROUND_CEILING;
					} else if (round_mode_ID == rb_intern("floor")) {
						rounding_mode = UNUM_ROUND_FLOOR;
					} else if (round_mode_ID == rb_intern("down")) {
						rounding_mode = UNUM_ROUND_DOWN;
					} else if (round_mode_ID == rb_intern("up")) {
						rounding_mode = UNUM_ROUND_UP;
					} else if (round_mode_ID == rb_intern("halfeven")) {
						rounding_mode = UNUM_FOUND_HALFEVEN;
					} else if (round_mode_ID == rb_intern("halfdown")) {
						rounding_mode = UNUM_ROUND_HALFDOWN;
					} else if (round_mode_ID == rb_intern("halfup")) {
						rounding_mode = UNUM_ROUND_HALFUP;
					} else {
						rb_raise(rb_eArgError, "unsupported rounding mode '%s'", rb_id2name(round_mode_ID));
					}
					status = U_ZERO_ERROR;
					unum_setAttribute(format, UNUM_ROUNDING_MODE, rounding_mode);
					RAISE_ON_ERROR(status);
				}
				round_increment = rb_hash_aref(options, ID2SYM(rb_intern("round_increment")));
				if (round_increment != Qnil) {
					Check_Type(round_increment, T_FLOAT);
					status = U_ZERO_ERROR;
					unum_setDoubleAttribute(format, UNUM_ROUNDING_INCREMENT, NUM2DBL(round_increment));
					RAISE_ON_ERROR(status);
				}
		}
	}
	/* format */
	status = U_ZERO_ERROR;
    switch (TYPE(self)) {
    	case T_FIXNUM:
    		unum_format(format, NUM2INT(self), result, 256, NULL, &status);
    		break;
    	case T_FLOAT:
    		unum_formatDouble(format, NUM2DBL(self), result, 256, NULL, &status);
    		break;
    	case T_BIGNUM:
			unum_formatInt64(format, rb_big2ll(self), result, 256, NULL, &status);
    		break;

    }
    RAISE_ON_ERROR(status);
    /* free resources */
    unum_close(format);

    return u_strToRString(result, -1);
}
Exemplo n.º 29
0
/* call-seq:
 *    client.query(sql, options = {})
 *
 * Query the database with +sql+, with optional +options+.  For the possible
 * options, see @@default_query_options on the Mysql2::Client class.
 */
static VALUE rb_mysql_client_query(int argc, VALUE * argv, VALUE self) {
#ifndef _WIN32
  struct async_query_args async_args;
#endif
  struct nogvl_send_query_args args;
  int async = 0;
  VALUE opts, current;
  VALUE thread_current = rb_thread_current();
#ifdef HAVE_RUBY_ENCODING_H
  rb_encoding *conn_enc;
#endif
  GET_CLIENT(self);

  REQUIRE_CONNECTED(wrapper);
  args.mysql = wrapper->client;

  current = rb_hash_dup(rb_iv_get(self, "@query_options"));
  RB_GC_GUARD(current);
  Check_Type(current, T_HASH);
  rb_iv_set(self, "@current_query_options", current);

  if (rb_scan_args(argc, argv, "11", &args.sql, &opts) == 2) {
    rb_funcall(current, intern_merge_bang, 1, opts);

    if (rb_hash_aref(current, sym_async) == Qtrue) {
      async = 1;
    }
  }

  Check_Type(args.sql, T_STRING);
#ifdef HAVE_RUBY_ENCODING_H
  conn_enc = rb_to_encoding(wrapper->encoding);
  /* ensure the string is in the encoding the connection is expecting */
  args.sql = rb_str_export_to_enc(args.sql, conn_enc);
#endif
  args.sql_ptr = StringValuePtr(args.sql);
  args.sql_len = RSTRING_LEN(args.sql);

  /* see if this connection is still waiting on a result from a previous query */
  if (NIL_P(wrapper->active_thread)) {
    /* mark this connection active */
    wrapper->active_thread = thread_current;
  } else if (wrapper->active_thread == thread_current) {
    rb_raise(cMysql2Error, "This connection is still waiting for a result, try again once you have the result");
  } else {
    VALUE inspect = rb_inspect(wrapper->active_thread);
    const char *thr = StringValueCStr(inspect);

    rb_raise(cMysql2Error, "This connection is in use by: %s", thr);
    RB_GC_GUARD(inspect);
  }

  args.wrapper = wrapper;

#ifndef _WIN32
  rb_rescue2(do_send_query, (VALUE)&args, disconnect_and_raise, self, rb_eException, (VALUE)0);

  if (!async) {
    async_args.fd = wrapper->client->net.fd;
    async_args.self = self;

    rb_rescue2(do_query, (VALUE)&async_args, disconnect_and_raise, self, rb_eException, (VALUE)0);

    return rb_mysql_client_async_result(self);
  } else {
    return Qnil;
  }
#else
  do_send_query(&args);

  /* this will just block until the result is ready */
  return rb_ensure(rb_mysql_client_async_result, self, finish_and_mark_inactive, self);
#endif
}
Exemplo n.º 30
0
static VALUE cConnection_initialize(VALUE self, VALUE uri) {
  VALUE r_host, r_user, r_password, r_path, r_query, r_port;

  char *host = "localhost", *user = "******", *password = NULL, *path;
  char *database = "", *socket = NULL;
  char *encoding = NULL;

  int port = 3306;
  unsigned long client_flags = 0;
  int encoding_error;

  MYSQL *db = 0, *result;
  db = (MYSQL *)mysql_init(NULL);

  rb_iv_set(self, "@using_socket", Qfalse);

  r_host = rb_funcall(uri, rb_intern("host"), 0);
  if (Qnil != r_host) {
    host = StringValuePtr(r_host);
  }

  r_user = rb_funcall(uri, rb_intern("user"), 0);
  if (Qnil != r_user) {
    user = StringValuePtr(r_user);
  }

  r_password = rb_funcall(uri, rb_intern("password"), 0);
  if (Qnil != r_password) {
    password = StringValuePtr(r_password);
  }

  r_path = rb_funcall(uri, rb_intern("path"), 0);
  path = StringValuePtr(r_path);
  if (Qnil != r_path) {
    database = strtok(path, "/");
  }

  if (NULL == database || 0 == strlen(database)) {
    rb_raise(eMysqlError, "Database must be specified");
  }

  // Pull the querystring off the URI
  r_query = rb_funcall(uri, rb_intern("query"), 0);

  // Check to see if we're on the db machine.  If so, try to use the socket
  if (0 == strcasecmp(host, "localhost")) {
    socket = get_uri_option(r_query, "socket");
    if (NULL != socket) {
      rb_iv_set(self, "@using_socket", Qtrue);
    }
  }

  r_port = rb_funcall(uri, rb_intern("port"), 0);
  if (Qnil != r_port) {
    port = NUM2INT(r_port);
  }

  encoding = get_uri_option(r_query, "encoding");
  if (!encoding) { encoding = get_uri_option(r_query, "charset"); }
  if (!encoding) { encoding = "utf8"; }

  // If ssl? {
  //   mysql_ssl_set(db, key, cert, ca, capath, cipher)
  // }

  my_bool reconnect = 1;
  mysql_options(db, MYSQL_OPT_RECONNECT, &reconnect);

  result = (MYSQL *)mysql_real_connect(
    db,
    host,
    user,
    password,
    database,
    port,
    socket,
    client_flags
  );

  if (NULL == result) {
    raise_mysql_error(Qnil, db, -1, NULL);
  }

  // Set the connections character set
  encoding_error = mysql_set_character_set(db, encoding);
  if (0 != encoding_error) {
    raise_mysql_error(Qnil, db, encoding_error, NULL);
  }

  rb_iv_set(self, "@uri", uri);
  rb_iv_set(self, "@connection", Data_Wrap_Struct(rb_cObject, 0, 0, db));

  return Qtrue;
}