Ejemplo n.º 1
0
/*
 * call-seq:
 *   change_password(old_password, new_password)
 *
 * Allow user to change their Kerberos password, providing the +old_password+ 
 * and the +new_password+.
 * 
 * Returns true on success, raises a Krb5Auth::Krb5::Exception on failure.
 */
static VALUE Krb5_change_password(VALUE self, VALUE v_old, VALUE v_new)
{
  char *oldpass;
  char *newpass;
  int pw_result;
  struct ruby_krb5 *kerb;
  krb5_error_code krbret;
  krb5_data pw_res_string, res_string;

  Check_Type(v_old, T_STRING);
  Check_Type(v_new, T_STRING);

  oldpass = StringValueCStr(v_old);
  newpass = StringValueCStr(v_new);

  Data_Get_Struct(self, struct ruby_krb5, kerb);

  if(!kerb){
    NOSTRUCT_EXCEPT();
    return Qfalse;
  }

  krbret = krb5_get_init_creds_password(
    kerb->ctx,
    &kerb->creds,
    kerb->princ,
    oldpass,
    NULL,
    NULL,
    0,
    "kadmin/changepw",
    NULL
  );

  if(krbret){
    Krb5_register_error(krbret);
    return Qfalse; 
  }

  krbret = krb5_change_password(
    kerb->ctx,
    &kerb->creds,
    newpass,
    &pw_result,
    &pw_res_string,
    &res_string    
  );
  
  // 0 is success. Anything else is failure.

  if(krbret){
    Krb5_register_error(krbret);
    return Qfalse; 
  }

  if(pw_result){
    switch(pw_result) {
      case KRB5_KPASSWD_MALFORMED:
        rb_raise(cKrb5_Exception, "Request Packet Incorrect");
      break;
      
      case KRB5_KPASSWD_HARDERROR:
        rb_raise(cKrb5_Exception, "Password Server Error");
      break;
      
      case KRB5_KPASSWD_AUTHERROR:
        rb_raise(cKrb5_Exception, "Authentication Error");
      break;
      
      case KRB5_KPASSWD_SOFTERROR:
        rb_raise(cKrb5_Exception, "Password change rejected");
      break;
      
      default:
        rb_raise(cKrb5_Exception, "Unknown error, code: %d", pw_result);
      break;
    }

    return Qfalse; 
  }
  return Qtrue;
}
Ejemplo n.º 2
0
static VALUE Graph_init(VALUE self)
{
    Check_Type(self, T_DATA);
    DATA_PTR(self) = (void *)vxCreateGraph(context);
    return Qnil;
}
Ejemplo n.º 3
0
Archivo: oj.c Proyecto: dbussink/oj
/* call-seq: default_options=(opts)
 *
 * Sets the default options for load and dump.
 * @param [Hash] opts options to change
 * @param [Fixnum] :indent number of spaces to indent each element in an JSON document
 * @param [true|false|nil] :circular support circular references while dumping
 * @param [true|false|nil] :auto_define automatically define classes if they do not exist
 * @param [true|false|nil] :symbol_keys convert hash keys to symbols
 * @param [true|false|nil] :class_cache cache classes for faster parsing
 * @param [true|false|nil] :ascii_only encode all high-bit characters as escaped sequences if true
 * @param [true|false|nil] :bigdecimal_as_decimal dump BigDecimal as a decimal number or as a String
 * @param [true|false|nil] :bigdecimal_load load decimals as a BigDecimal instead of as a Float
 * @param [:object|:strict|:compat|:null] load and dump mode to use for JSON
 *	  :strict raises an exception when a non-supported Object is
 *	  encountered. :compat attempts to extract variable values from an
 *	  Object using to_json() or to_hash() then it walks the Object's
 *	  variables if neither is found. The :object mode ignores to_hash()
 *	  and to_json() methods and encodes variables using code internal to
 *	  the Oj gem. The :null mode ignores non-supported Objects and
 *	  replaces them with a null.
 * @param [:unix|:xmlschema|:ruby] time format when dumping in :compat mode
 *        :unix decimal number denoting the number of seconds since 1/1/1970,
 *        :xmlschema date-time format taken from XML Schema as a String,
 *        :ruby Time.to_s formatted String
 * @param [String|nil] :create_id create id for json compatible object encoding
 * @param [Fixnum|nil] :second_precision number of digits after the decimal when dumping the seconds portion of time
 * @return [nil]
 */
static VALUE
set_def_opts(VALUE self, VALUE opts) {
    struct _YesNoOpt	ynos[] = {
	{ circular_sym, &oj_default_options.circular },
	{ auto_define_sym, &oj_default_options.auto_define },
	{ symbol_keys_sym, &oj_default_options.sym_key },
	{ class_cache_sym, &oj_default_options.class_cache },
	{ ascii_only_sym, &oj_default_options.ascii_only },
	{ bigdecimal_as_decimal_sym, &oj_default_options.bigdec_as_num },
	{ bigdecimal_load_sym, &oj_default_options.bigdec_load },
	{ Qnil, 0 }
    };
    YesNoOpt	o;
    VALUE	v;
    
    Check_Type(opts, T_HASH);
    v = rb_hash_aref(opts, indent_sym);
    if (Qnil != v) {
	Check_Type(v, T_FIXNUM);
	oj_default_options.indent = FIX2INT(v);
    }
    v = rb_hash_aref(opts, sec_prec_sym);
    if (Qnil != v) {
	int	n;

	Check_Type(v, T_FIXNUM);
	n = FIX2INT(v);
	if (0 > n) {
	    n = 0;
	} else if (9 < n) {
	    n = 9;
	}
	oj_default_options.sec_prec = n;
    }

    v = rb_hash_lookup(opts, mode_sym);
    if (Qnil == v) {
	// ignore
    } else if (object_sym == v) {
	oj_default_options.mode = ObjectMode;
    } else if (strict_sym == v) {
	oj_default_options.mode = StrictMode;
    } else if (compat_sym == v) {
	oj_default_options.mode = CompatMode;
    } else if (null_sym == v) {
	oj_default_options.mode = NullMode;
    } else {
	rb_raise(rb_eArgError, ":mode must be :object, :strict, :compat, or :null.");
    }

    v = rb_hash_lookup(opts, time_format_sym);
    if (Qnil == v) {
	// ignore
    } else if (unix_sym == v) {
	oj_default_options.time_format = UnixTime;
    } else if (xmlschema_sym == v) {
	oj_default_options.time_format = XmlTime;
    } else if (ruby_sym == v) {
	oj_default_options.time_format = RubyTime;
    } else {
	rb_raise(rb_eArgError, ":time_format must be :unix, :xmlschema, or :ruby.");
    }

    if (Qtrue == rb_funcall(opts, rb_intern("has_key?"), 1, create_id_sym)) {
	if (0 != oj_default_options.create_id) {
	    if (json_class != oj_default_options.create_id) {
		xfree((char*)oj_default_options.create_id);
	    }
	    oj_default_options.create_id = 0;
	    oj_default_options.create_id_len = 0;
	}
	v = rb_hash_lookup(opts, create_id_sym);
	if (Qnil != v) {
	    size_t	len = RSTRING_LEN(v) + 1;

	    oj_default_options.create_id = ALLOC_N(char, len);
	    strcpy((char*)oj_default_options.create_id, StringValuePtr(v));
	    oj_default_options.create_id_len = len - 1;
	}
    }
Ejemplo n.º 4
0
Archivo: math.c Proyecto: Fudge/rb-gsl
static VALUE rb_gsl_math_eval2(double (*func)(const double, const double), VALUE xx,
			       VALUE yy)
{
  VALUE x, y, ary;
  size_t i, j, size;
  gsl_vector *v = NULL, *v2 = NULL, *vnew = NULL;
  gsl_matrix *m = NULL, *m2 = NULL, *mnew = NULL;
#ifdef HAVE_NARRAY_H
  struct NARRAY *nax, *nay;
  double *ptr1, *ptr2, *ptr3;
#endif
  if (CLASS_OF(xx) == rb_cRange) xx = rb_gsl_range2ary(xx);
  switch (TYPE(xx)) {
  case T_FIXNUM:
  case T_BIGNUM:
  case T_FLOAT:
    Need_Float(yy);
    return rb_float_new((*func)(NUM2DBL(xx), NUM2DBL(yy)));
    break;
  case T_ARRAY:
    Check_Type(yy, T_ARRAY);
    size = RARRAY_LEN(xx);
    if (size != RARRAY_LEN(yy)) rb_raise(rb_eRuntimeError, "array sizes are different.");
    ary = rb_ary_new2(size);
    for (i = 0; i < size; i++) {
      x = rb_ary_entry(xx, i);
      y = rb_ary_entry(yy, i);
      Need_Float(x); Need_Float(y);
      rb_ary_store(ary, i, rb_float_new((*func)(RFLOAT_VALUE(x), RFLOAT_VALUE(y))));
    }
    return ary;
    break;
  default:
#ifdef HAVE_NARRAY_H
    if (NA_IsNArray(xx)) {
      GetNArray(xx, nax);
      GetNArray(yy, nay);
      ptr1 = (double*) nax->ptr;
      ptr2 = (double*) nay->ptr;
      size = nax->total;
      ary = na_make_object(NA_DFLOAT, nax->rank, nax->shape, CLASS_OF(xx));
      ptr3 = NA_PTR_TYPE(ary, double*);
      for (i = 0; i < size; i++) ptr3[i] = (*func)(ptr1[i], ptr2[i]);
      return ary;
    }
#endif
    if (VECTOR_P(xx)) {
      CHECK_VECTOR(yy);
      Data_Get_Struct(xx, gsl_vector, v);
      Data_Get_Struct(yy, gsl_vector, v2);
      vnew = gsl_vector_alloc(v->size);
      for (i = 0; i < v->size; i++) {
	gsl_vector_set(vnew, i, (*func)(gsl_vector_get(v, i), gsl_vector_get(v2, i)));
      }
      return Data_Wrap_Struct(cgsl_vector, 0, gsl_vector_free, vnew);
    } else if (MATRIX_P(xx)) {
      CHECK_MATRIX(yy);
      Data_Get_Struct(xx, gsl_matrix, m);
      Data_Get_Struct(yy, gsl_matrix, m2);
      mnew = gsl_matrix_alloc(m->size1, m->size2);
      for (i = 0; i < m->size1; i++) {
	for (j = 0; j < m->size2; j++) {
	  gsl_matrix_set(mnew, i, j, (*func)(gsl_matrix_get(m, i, j), gsl_matrix_get(m2, i, j)));
	}
      }
      return Data_Wrap_Struct(cgsl_matrix, 0, gsl_matrix_free, mnew);
    } else {
      rb_raise(rb_eTypeError, 
	       "wrong argument type %s "
	       "(Array or Vector or Matrix expected)", rb_class2name(CLASS_OF(xx)));
    }
    break;
  }
  /* never reach here */
  return Qnil;
}
Ejemplo n.º 5
0
/*
 * call-seq:
 * 		XML.catalog_remove(catalog) -> true
 *
 * Remove the specified resource catalog.
 */
static VALUE rxml_catalog_remove(VALUE self, VALUE cat)
{
  Check_Type(cat, T_STRING);
  xmlCatalogRemove((xmlChar *) StringValuePtr(cat));
  return (Qtrue);
}
Ejemplo n.º 6
0
static VALUE
fntype_initialize(int argc, VALUE* argv, VALUE self)
{
    FunctionType *fnInfo;
    ffi_status status;
    VALUE rbReturnType = Qnil, rbParamTypes = Qnil, rbOptions = Qnil;
    VALUE rbEnums = Qnil, rbConvention = Qnil, rbBlocking = Qnil;
#if defined(_WIN32) || defined(__WIN32__)
    VALUE rbConventionStr;
#endif
    int i, nargs;

    nargs = rb_scan_args(argc, argv, "21", &rbReturnType, &rbParamTypes, &rbOptions);
    if (nargs >= 3 && rbOptions != Qnil) {
        rbConvention = rb_hash_aref(rbOptions, ID2SYM(rb_intern("convention")));
        rbEnums = rb_hash_aref(rbOptions, ID2SYM(rb_intern("enums")));
        rbBlocking = rb_hash_aref(rbOptions, ID2SYM(rb_intern("blocking")));
    }

    Check_Type(rbParamTypes, T_ARRAY);

    Data_Get_Struct(self, FunctionType, fnInfo);
    fnInfo->parameterCount = (int) RARRAY_LEN(rbParamTypes);
    fnInfo->parameterTypes = xcalloc(fnInfo->parameterCount, sizeof(*fnInfo->parameterTypes));
    fnInfo->ffiParameterTypes = xcalloc(fnInfo->parameterCount, sizeof(ffi_type *));
    fnInfo->nativeParameterTypes = xcalloc(fnInfo->parameterCount, sizeof(*fnInfo->nativeParameterTypes));
    fnInfo->rbParameterTypes = rb_ary_new2(fnInfo->parameterCount);
    fnInfo->rbEnums = rbEnums;
    fnInfo->blocking = RTEST(rbBlocking);
    fnInfo->hasStruct = false;

    for (i = 0; i < fnInfo->parameterCount; ++i) {
        VALUE entry = rb_ary_entry(rbParamTypes, i);
        VALUE type = rbffi_Type_Lookup(entry);

        if (!RTEST(type)) {
            VALUE typeName = rb_funcall2(entry, rb_intern("inspect"), 0, NULL);
            rb_raise(rb_eTypeError, "Invalid parameter type (%s)", RSTRING_PTR(typeName));
        }

        if (rb_obj_is_kind_of(type, rbffi_FunctionTypeClass)) {
            REALLOC_N(fnInfo->callbackParameters, VALUE, fnInfo->callbackCount + 1);
            fnInfo->callbackParameters[fnInfo->callbackCount++] = type;
        }

        if (rb_obj_is_kind_of(type, rbffi_StructByValueClass)) {
            fnInfo->hasStruct = true;
        }

        rb_ary_push(fnInfo->rbParameterTypes, type);
        Data_Get_Struct(type, Type, fnInfo->parameterTypes[i]);
        fnInfo->ffiParameterTypes[i] = fnInfo->parameterTypes[i]->ffiType;
        fnInfo->nativeParameterTypes[i] = fnInfo->parameterTypes[i]->nativeType;
    }

    fnInfo->rbReturnType = rbffi_Type_Lookup(rbReturnType);
    if (!RTEST(fnInfo->rbReturnType)) {
        VALUE typeName = rb_funcall2(rbReturnType, rb_intern("inspect"), 0, NULL);
        rb_raise(rb_eTypeError, "Invalid return type (%s)", RSTRING_PTR(typeName));
    }
    
    if (rb_obj_is_kind_of(fnInfo->rbReturnType, rbffi_StructByValueClass)) {
        fnInfo->hasStruct = true;
    }

    Data_Get_Struct(fnInfo->rbReturnType, Type, fnInfo->returnType);
    fnInfo->ffiReturnType = fnInfo->returnType->ffiType;


#if defined(_WIN32) || defined(__WIN32__)
    rbConventionStr = (rbConvention != Qnil) ? rb_funcall2(rbConvention, rb_intern("to_s"), 0, NULL) : Qnil;
    fnInfo->abi = (rbConventionStr != Qnil && strcmp(StringValueCStr(rbConventionStr), "stdcall") == 0)
            ? FFI_STDCALL : FFI_DEFAULT_ABI;
#else
    fnInfo->abi = FFI_DEFAULT_ABI;
#endif

    status = ffi_prep_cif(&fnInfo->ffi_cif, fnInfo->abi, fnInfo->parameterCount,
            fnInfo->ffiReturnType, fnInfo->ffiParameterTypes);
    switch (status) {
        case FFI_BAD_ABI:
            rb_raise(rb_eArgError, "Invalid ABI specified");
        case FFI_BAD_TYPEDEF:
            rb_raise(rb_eArgError, "Invalid argument type specified");
        case FFI_OK:
            break;
        default:
            rb_raise(rb_eArgError, "Unknown FFI error");
    }

    fnInfo->invoke = rbffi_GetInvoker(fnInfo);

    return self;
}
Ejemplo n.º 7
0
/* Returns the numeric form of an IP address.
 *
 * For example:
 * 24.24.24.24 => 404232216
 *
 * This is used in order to be able to perform searches in CSV versions of the
 * data files or in SQL records if the data has been put there.
 */
VALUE rb_geoip_addr_to_num(VALUE self, VALUE addr) {
  Check_Type(addr, T_STRING);
  return UINT2NUM((unsigned int)GeoIP_addr_to_num(StringValuePtr(addr)));
}
Ejemplo n.º 8
0
/*
 * call-seq: json_create(o)
 *
 * Raw Strings are JSON Objects (the raw bytes are stored in an array for the
 * key "raw"). The Ruby String can be created by this module method.
 */
static VALUE mString_Extend_json_create(VALUE self, VALUE o) {
    VALUE ary;
    Check_Type(o, T_HASH);
    ary = rb_hash_aref(o, rb_str_new2("raw"));
    return rb_funcall(ary, i_pack, 1, rb_str_new2("C*"));
}
Ejemplo n.º 9
0
/*
 * call-seq: indent=(indent)
 *
 * This string is used to indent levels in the JSON text.
 */
static VALUE cState_indent_set(VALUE self, VALUE indent)
{
    GET_STATE(self);
    Check_Type(indent, T_STRING);
    return state->indent = indent;
}
Ejemplo n.º 10
0
/*
 * call-seq: configure(opts)
 *
 * Configure this State instance with the Hash _opts_, and return
 * itself.
 */
static VALUE cState_configure(VALUE self, VALUE opts)
{
    VALUE tmp;
    GET_STATE(self);
    tmp = rb_convert_type(opts, T_HASH, "Hash", "to_hash");
    if (NIL_P(tmp)) tmp = rb_convert_type(opts, T_HASH, "Hash", "to_h");
    if (NIL_P(tmp)) {
        rb_raise(rb_eArgError, "opts has to be hash like or convertable into a hash");
    }
    opts = tmp;
    tmp = rb_hash_aref(opts, ID2SYM(i_indent));
    if (RTEST(tmp)) {
        unsigned long len;
        Check_Type(tmp, T_STRING);
        len = RSTRING_LEN(tmp);
        state->indent = fstrndup(RSTRING_PTR(tmp), len + 1);
        state->indent_len = len;
    }
    tmp = rb_hash_aref(opts, ID2SYM(i_space));
    if (RTEST(tmp)) {
        unsigned long len;
        Check_Type(tmp, T_STRING);
        len = RSTRING_LEN(tmp);
        state->space = fstrndup(RSTRING_PTR(tmp), len + 1);
        state->space_len = len;
    }
    tmp = rb_hash_aref(opts, ID2SYM(i_space_before));
    if (RTEST(tmp)) {
        unsigned long len;
        Check_Type(tmp, T_STRING);
        len = RSTRING_LEN(tmp);
        state->space_before = fstrndup(RSTRING_PTR(tmp), len + 1);
        state->space_before_len = len;
    }
    tmp = rb_hash_aref(opts, ID2SYM(i_array_nl));
    if (RTEST(tmp)) {
        unsigned long len;
        Check_Type(tmp, T_STRING);
        len = RSTRING_LEN(tmp);
        state->array_nl = fstrndup(RSTRING_PTR(tmp), len + 1);
        state->array_nl_len = len;
    }
    tmp = rb_hash_aref(opts, ID2SYM(i_object_nl));
    if (RTEST(tmp)) {
        unsigned long len;
        Check_Type(tmp, T_STRING);
        len = RSTRING_LEN(tmp);
        state->object_nl = fstrndup(RSTRING_PTR(tmp), len + 1);
        state->object_nl_len = len;
    }
    tmp = ID2SYM(i_max_nesting);
    state->max_nesting = 100;
    if (option_given_p(opts, tmp)) {
        VALUE max_nesting = rb_hash_aref(opts, tmp);
        if (RTEST(max_nesting)) {
            Check_Type(max_nesting, T_FIXNUM);
            state->max_nesting = FIX2LONG(max_nesting);
        } else {
            state->max_nesting = 0;
        }
    }
    tmp = ID2SYM(i_depth);
    state->depth = 0;
    if (option_given_p(opts, tmp)) {
        VALUE depth = rb_hash_aref(opts, tmp);
        if (RTEST(depth)) {
            Check_Type(depth, T_FIXNUM);
            state->depth = FIX2LONG(depth);
        } else {
            state->depth = 0;
        }
    }
    tmp = ID2SYM(i_buffer_initial_length);
    if (option_given_p(opts, tmp)) {
        VALUE buffer_initial_length = rb_hash_aref(opts, tmp);
        if (RTEST(buffer_initial_length)) {
            long initial_length;
            Check_Type(buffer_initial_length, T_FIXNUM);
            initial_length = FIX2LONG(buffer_initial_length);
            if (initial_length > 0) state->buffer_initial_length = initial_length;
        }
    }
    tmp = rb_hash_aref(opts, ID2SYM(i_allow_nan));
    state->allow_nan = RTEST(tmp);
    tmp = rb_hash_aref(opts, ID2SYM(i_ascii_only));
    state->ascii_only = RTEST(tmp);
    tmp = rb_hash_aref(opts, ID2SYM(i_quirks_mode));
    state->quirks_mode = RTEST(tmp);
    return self;
}
Ejemplo n.º 11
0
inline static VALUE mArray_json_transfrom(VALUE self, VALUE Vstate, VALUE Vdepth) {
    long i, len = RARRAY_LEN(self);
    VALUE shift, result;
    long depth = NIL_P(Vdepth) ? 0 : FIX2LONG(Vdepth);
    VALUE delim = rb_str_new2(",");
    GET_STATE(Vstate);

    check_max_nesting(state, depth);
    if (state->check_circular) {
        VALUE self_id = rb_obj_id(self);
        rb_hash_aset(state->seen, self_id, Qtrue);
        result = rb_str_buf_new(len);
        if (RSTRING_LEN(state->array_nl)) rb_str_append(delim, state->array_nl);
        shift = rb_str_times(state->indent, LONG2FIX(depth + 1));

        rb_str_buf_cat2(result, "[");
        OBJ_INFECT(result, self);
        rb_str_buf_append(result, state->array_nl);
        for (i = 0;  i < len; i++) {
            VALUE element = RARRAY_PTR(self)[i];
            if (RTEST(rb_hash_aref(state->seen, rb_obj_id(element)))) {
                rb_raise(eCircularDatastructure,
                        "circular data structures not supported!");
            }
            OBJ_INFECT(result, element);
            if (i > 0) rb_str_buf_append(result, delim);
            rb_str_buf_append(result, shift);
            element = rb_funcall(element, i_to_json, 2, Vstate, LONG2FIX(depth + 1));
            Check_Type(element, T_STRING);
            rb_str_buf_append(result, element);
        }
        if (RSTRING_LEN(state->array_nl)) {
            rb_str_buf_append(result, state->array_nl);
            rb_str_buf_append(result, rb_str_times(state->indent, LONG2FIX(depth)));
        }
        rb_str_buf_cat2(result, "]");
        rb_hash_delete(state->seen, self_id);
    } else {
        result = rb_str_buf_new(len);
        OBJ_INFECT(result, self);
        if (RSTRING_LEN(state->array_nl)) rb_str_append(delim, state->array_nl);
        shift = rb_str_times(state->indent, LONG2FIX(depth + 1));

        rb_str_buf_cat2(result, "[");
        rb_str_buf_append(result, state->array_nl);
        for (i = 0;  i < len; i++) {
            VALUE element = RARRAY_PTR(self)[i];
            OBJ_INFECT(result, element);
            if (i > 0) rb_str_buf_append(result, delim);
            rb_str_buf_append(result, shift);
            element = rb_funcall(element, i_to_json, 2, Vstate, LONG2FIX(depth + 1));
            Check_Type(element, T_STRING);
            rb_str_buf_append(result, element);
        }
        rb_str_buf_append(result, state->array_nl);
        if (RSTRING_LEN(state->array_nl)) {
            rb_str_buf_append(result, rb_str_times(state->indent, LONG2FIX(depth)));
        }
        rb_str_buf_cat2(result, "]");
    }
    return result;
}
Ejemplo n.º 12
0
/*
 * call-seq: to_json_raw(*args)
 *
 * This method creates a JSON text from the result of a call to
 * to_json_raw_object of this String.
 */
static VALUE mString_to_json_raw(int argc, VALUE *argv, VALUE self)
{
    VALUE obj = mString_to_json_raw_object(self);
    Check_Type(obj, T_HASH);
    return mHash_to_json(argc, argv, obj);
}
Ejemplo n.º 13
0
/*
 * call-seq: max_nesting=(depth)
 *
 * This sets the maximum level of data structure nesting in the generated JSON
 * to the integer depth, max_nesting = 0 if no maximum should be checked.
 */
static VALUE cState_max_nesting_set(VALUE self, VALUE depth)
{
    GET_STATE(self);
    Check_Type(depth, T_FIXNUM);
    return state->max_nesting = FIX2LONG(depth);
}
Ejemplo n.º 14
0
VALUE nifti_image_set_data(VALUE self, VALUE r_index, VALUE r_value) {
    char *str_value;
    nifti_image *img = to_nifti_image(self);
    int index = NUM2INT(r_index);

    // Types nifti1.h
    switch(img->datatype) {
    case DT_BINARY: // DT_UINT8
        if (r_value == Qtrue) {
            ((bool *) img->data)[index] = true;
        } else {
            ((bool *) img->data)[index] = false;
        }
        break;
    case DT_UNSIGNED_CHAR:
        Check_Type(r_value, T_STRING);
        StringValue(r_value);
        str_value = StringValuePtr(r_value);

        ((unsigned char *) img->data)[index] = ((unsigned char) str_value[0]);
        break;
    case DT_SIGNED_SHORT: // DT_INT16
        ((short *) img->data)[index] = ((short) NUM2INT(r_value));
        break;
    case DT_SIGNED_INT: // DT_INT32
        ((int *) img->data)[index] = NUM2INT(r_value);
        break;
    case DT_FLOAT: // DT_FLOAT32
        ((float *) img->data)[index] = ((float) NUM2DBL(r_value));
        break;
    case DT_DOUBLE: // DT_FLOAT64
        ((double *) img->data)[index] = NUM2DBL(r_value);
        break;
    case DT_INT8:
        Check_Type(r_value, T_STRING);
        StringValue(r_value);
        str_value = StringValuePtr(r_value);

        ((char *) img->data)[index] = ((char) str_value[0]);
        break;
    case DT_UINT16:
        ((unsigned short *) img->data)[index] = ((unsigned short) NUM2INT(r_value));
        break;
    case DT_UINT32:
        ((unsigned int *) img->data)[index] = ((unsigned int) NUM2INT(r_value));
        break;
    case DT_INT64:
        ((long long *) img->data)[index] = ((long long) NUM2LONG(r_value));
        break;
    case DT_UINT64:
        ((unsigned long long *) img->data)[index] = ((unsigned long long) NUM2LONG(r_value));
        break;
    case DT_FLOAT128:
        ((long double *) img->data)[index] = ((long double) NUM2DBL(r_value));
        break;
    default: // Unsupported types: DT_COMPLEX, DT_RGB, DT_ALL, DT_COMPLEX128, DT_COMPLEX256, DT_RGBA32
        rb_raise(rb_eTypeError, "Unsupported datatype");
    }

    return r_value;
}
Ejemplo n.º 15
0
/* call-seq: emitter.start_document(version, tags, implicit)
 *
 * Start a document emission with YAML +version+, +tags+, and an +implicit+
 * start.
 *
 * See Psych::Handler#start_document
 */
static VALUE start_document(VALUE self, VALUE version, VALUE tags, VALUE imp)
{
    yaml_emitter_t * emitter;
    yaml_tag_directive_t * head = NULL;
    yaml_tag_directive_t * tail = NULL;
    yaml_event_t event;
    yaml_version_directive_t version_directive;
    Data_Get_Struct(self, yaml_emitter_t, emitter);


    Check_Type(version, T_ARRAY);

    if(RARRAY_LEN(version) > 0) {
        VALUE major = rb_ary_entry(version, (long)0);
        VALUE minor = rb_ary_entry(version, (long)1);

        version_directive.major = NUM2INT(major);
        version_directive.minor = NUM2INT(minor);
    }

    if(RTEST(tags)) {
        int i = 0;
#ifdef HAVE_RUBY_ENCODING_H
        rb_encoding * encoding = rb_utf8_encoding();
#endif

        Check_Type(tags, T_ARRAY);

        head  = xcalloc((size_t)RARRAY_LEN(tags), sizeof(yaml_tag_directive_t));
        tail  = head;

        for(i = 0; i < RARRAY_LEN(tags); i++) {
            VALUE tuple = rb_ary_entry(tags, i);
            VALUE name;
            VALUE value;

            Check_Type(tuple, T_ARRAY);

            if(RARRAY_LEN(tuple) < 2) {
                xfree(head);
                rb_raise(rb_eRuntimeError, "tag tuple must be of length 2");
            }
            name  = rb_ary_entry(tuple, 0);
            value = rb_ary_entry(tuple, 1);
#ifdef HAVE_RUBY_ENCODING_H
            name = rb_str_export_to_enc(name, encoding);
            value = rb_str_export_to_enc(value, encoding);
#endif

            tail->handle = (yaml_char_t *)StringValuePtr(name);
            tail->prefix = (yaml_char_t *)StringValuePtr(value);

            tail++;
        }
    }

    yaml_document_start_event_initialize(
        &event,
        (RARRAY_LEN(version) > 0) ? &version_directive : NULL,
        head,
        tail,
        imp ? 1 : 0
    );

    emit(emitter, &event);

    if(head) xfree(head);

    return self;
}
Ejemplo n.º 16
0
/*
 * call-seq: space_before=(space_before)
 *
 * This string is used to insert a space before the ':' in JSON objects.
 */
static VALUE cState_space_before_set(VALUE self, VALUE space_before)
{
    GET_STATE(self);
    Check_Type(space_before, T_STRING);
    return state->space_before = space_before;
}
Ejemplo n.º 17
0
Archivo: ox.c Proyecto: sriedel/ox
/* call-seq: ox_default_options=(opts)
 *
 * Sets the default options for load and dump.
 * @param [Hash] opts options to change
 * @param [Fixnum] :indent number of spaces to indent each element in an XML document
 * @param [Fixnum] :trace trace level where 0 is silent
 * @param [String] :encoding character encoding for the XML file
 * @param [true|false|nil] :with_dtd include DTD in the dump
 * @param [true|false|nil] :with_instruct include instructions in the dump
 * @param [true|false|nil] :with_xml include XML prolog in the dump
 * @param [true|false|nil] :circular support circular references while dumping
 * @param [true|false|nil] :xsd_date use XSD date format instead of decimal format
 * @param [:object|:generic|:limited|nil] :mode load method to use for XML
 * @param [:strict|:tolerant|:auto_define] :effort set the tolerance level for loading
 * @param [true|false|nil] :symbolize_keys symbolize element attribute keys or leave as Strings
 * @param [:skip_none|:skip_return|:skip_white] determines how to handle white space in text
 * @param [nil|String] :invalid_replace replacement string for invalid XML characters on dump. nil indicates include anyway as hex. A string, limited to 10 characters will replace the invalid character with the replace.
 * @param [nil|String|true|false] :strip_namespace "" or false result in no namespace stripping. A string of "*" or true will strip all namespaces. Any other non-empty string indicates that matching namespaces will be stripped.
 * @return [nil]
 */
static VALUE
set_def_opts(VALUE self, VALUE opts) {
    struct _YesNoOpt	ynos[] = {
	{ with_xml_sym, &ox_default_options.with_xml },
	{ with_dtd_sym, &ox_default_options.with_dtd },
	{ with_instruct_sym, &ox_default_options.with_instruct },
	{ xsd_date_sym, &ox_default_options.xsd_date },
	{ circular_sym, &ox_default_options.circular },
	{ symbolize_keys_sym, &ox_default_options.sym_keys },
	{ smart_sym, &ox_default_options.smart },
	{ Qnil, 0 }
    };
    YesNoOpt	o;
    VALUE	v;
    
    Check_Type(opts, T_HASH);

    v = rb_hash_aref(opts, ox_encoding_sym);
    if (Qnil == v) {
	*ox_default_options.encoding = '\0';
    } else {
	Check_Type(v, T_STRING);
	strncpy(ox_default_options.encoding, StringValuePtr(v), sizeof(ox_default_options.encoding) - 1);
#if HAS_ENCODING_SUPPORT
	ox_default_options.rb_enc = rb_enc_find(ox_default_options.encoding);
#elif HAS_PRIVATE_ENCODING
	ox_default_options.rb_enc = rb_str_new2(ox_default_options.encoding);
	rb_gc_register_address(&ox_default_options.rb_enc);
#endif
    }

    v = rb_hash_aref(opts, indent_sym);
    if (Qnil != v) {
	Check_Type(v, T_FIXNUM);
	ox_default_options.indent = FIX2INT(v);
    }

    v = rb_hash_aref(opts, trace_sym);
    if (Qnil != v) {
	Check_Type(v, T_FIXNUM);
	ox_default_options.trace = FIX2INT(v);
    }

    v = rb_hash_aref(opts, mode_sym);
    if (Qnil == v) {
	ox_default_options.mode = NoMode;
    } else if (object_sym == v) {
	ox_default_options.mode = ObjMode;
    } else if (generic_sym == v) {
	ox_default_options.mode = GenMode;
    } else if (limited_sym == v) {
	ox_default_options.mode = LimMode;
    } else {
	rb_raise(ox_parse_error_class, ":mode must be :object, :generic, :limited, or nil.\n");
    }

    v = rb_hash_aref(opts, effort_sym);
    if (Qnil == v) {
	ox_default_options.effort = NoEffort;
    } else if (strict_sym == v) {
	ox_default_options.effort = StrictEffort;
    } else if (tolerant_sym == v) {
	ox_default_options.effort = TolerantEffort;
    } else if (auto_define_sym == v) {
	ox_default_options.effort = AutoEffort;
    } else {
	rb_raise(ox_parse_error_class, ":effort must be :strict, :tolerant, :auto_define, or nil.\n");
    }

    v = rb_hash_aref(opts, skip_sym);
    if (Qnil == v) {
	ox_default_options.skip = NoSkip;
    } else if (skip_none_sym == v) {
	ox_default_options.skip = NoSkip;
    } else if (skip_return_sym == v) {
	ox_default_options.skip = CrSkip;
    } else if (skip_white_sym == v) {
	ox_default_options.skip = SpcSkip;
    } else {
	rb_raise(ox_parse_error_class, ":skip must be :skip_none, :skip_return, :skip_white, or nil.\n");
    }

    v = rb_hash_lookup(opts, convert_special_sym);
    if (Qnil == v) {
	// no change
    } else if (Qtrue == v) {
	ox_default_options.convert_special = 1;
    } else if (Qfalse == v) {
	ox_default_options.convert_special = 0;
    } else {
	rb_raise(ox_parse_error_class, ":convert_special must be true or false.\n");
    }

    v = rb_hash_aref(opts, invalid_replace_sym);
    if (Qnil == v) {
	ox_default_options.allow_invalid = Yes;
    } else {
	long	slen;

	Check_Type(v, T_STRING);
	slen = RSTRING_LEN(v);
	if (sizeof(ox_default_options.inv_repl) - 2 < slen) {
	    rb_raise(ox_parse_error_class, ":invalid_replace can be no longer than %ld characters.",
		     sizeof(ox_default_options.inv_repl) - 2);
	}
	strncpy(ox_default_options.inv_repl + 1, StringValuePtr(v), sizeof(ox_default_options.inv_repl) - 1);
	ox_default_options.inv_repl[sizeof(ox_default_options.inv_repl) - 1] = '\0';
	*ox_default_options.inv_repl = (char)slen;
	ox_default_options.allow_invalid = No;
    }

    v = rb_hash_aref(opts, strip_namespace_sym);
    if (Qfalse == v) {
	*ox_default_options.strip_ns = '\0';
    } else if (Qtrue == v) {
	*ox_default_options.strip_ns = '*';
	ox_default_options.strip_ns[1] = '\0';
    } else if (Qnil != v) {
	long	slen;

	Check_Type(v, T_STRING);
	slen = RSTRING_LEN(v);
	if (sizeof(ox_default_options.strip_ns) - 1 < slen) {
	    rb_raise(ox_parse_error_class, ":strip_namespace can be no longer than %ld characters.",
		     sizeof(ox_default_options.strip_ns) - 1);
	}
	strncpy(ox_default_options.strip_ns, StringValuePtr(v), sizeof(ox_default_options.strip_ns) - 1);
	ox_default_options.strip_ns[sizeof(ox_default_options.strip_ns) - 1] = '\0';
    }

    for (o = ynos; 0 != o->attr; o++) {
	v = rb_hash_lookup(opts, o->sym);
	if (Qnil == v) {
	    *o->attr = NotSet;
	} else if (Qtrue == v) {
	    *o->attr = Yes;
	} else if (Qfalse == v) {
	    *o->attr = No;
	} else {
	    rb_raise(ox_parse_error_class, "%s must be true or false.\n", rb_id2name(SYM2ID(o->sym)));
	}
    }
    return Qnil;
}
Ejemplo n.º 18
0
/*
 * call-seq: object_nl=(object_nl)
 *
 * This string is put at the end of a line that holds a JSON object (or
 * Hash).
 */
static VALUE cState_object_nl_set(VALUE self, VALUE object_nl)
{
    GET_STATE(self);
    Check_Type(object_nl, T_STRING);
    return state->object_nl = object_nl;
}
Ejemplo n.º 19
0
/* Pass this function an IP address as a string, it will return a hash
 * containing all the information that the database knows about the IP:
 *    db.look_up('24.24.24.24')
 *    => {:domain => "rr.com"}
 */
VALUE rb_geoip_domain_look_up(VALUE self, VALUE addr) {
  GeoIP *gi;
  Check_Type(addr, T_STRING);
  Data_Get_Struct(self, GeoIP, gi);
  return generic_single_value_lookup_response("domain", GeoIP_name_by_addr(gi, StringValuePtr(addr)));
}
Ejemplo n.º 20
0
/*
 * call-seq: array_nl=(array_nl)
 *
 * This string is put at the end of a line that holds a JSON array.
 */
static VALUE cState_array_nl_set(VALUE self, VALUE array_nl)
{
    GET_STATE(self);
    Check_Type(array_nl, T_STRING);
    return state->array_nl = array_nl;
}
Ejemplo n.º 21
0
static VALUE rb_redcarpet_html_init(int argc, VALUE *argv, VALUE self)
{
	struct rb_redcarpet_rndr *rndr;
	unsigned int render_flags = 0;
	VALUE hash, link_attr = Qnil;

	Data_Get_Struct(self, struct rb_redcarpet_rndr, rndr);

	if (rb_scan_args(argc, argv, "01", &hash) == 1) {
		Check_Type(hash, T_HASH);

		/* escape_html */
		if (rb_hash_aref(hash, CSTR2SYM("escape_html")) == Qtrue)
			render_flags |= HTML_ESCAPE;

		/* filter_html */
		if (rb_hash_aref(hash, CSTR2SYM("filter_html")) == Qtrue)
			render_flags |= HTML_SKIP_HTML;

		/* no_image */
		if (rb_hash_aref(hash, CSTR2SYM("no_images")) == Qtrue)
			render_flags |= HTML_SKIP_IMAGES;

		/* no_links */
		if (rb_hash_aref(hash, CSTR2SYM("no_links")) == Qtrue)
			render_flags |= HTML_SKIP_LINKS;

		/* prettify */
		if (rb_hash_aref(hash, CSTR2SYM("prettify")) == Qtrue)
			render_flags |= HTML_PRETTIFY;

		/* filter_style */
		if (rb_hash_aref(hash, CSTR2SYM("no_styles")) == Qtrue)
			render_flags |= HTML_SKIP_STYLE;

		/* safelink */
		if (rb_hash_aref(hash, CSTR2SYM("safe_links_only")) == Qtrue)
			render_flags |= HTML_SAFELINK;

		if (rb_hash_aref(hash, CSTR2SYM("with_toc_data")) == Qtrue)
			render_flags |= HTML_TOC;

		if (rb_hash_aref(hash, CSTR2SYM("hard_wrap")) == Qtrue)
			render_flags |= HTML_HARD_WRAP;

		if (rb_hash_aref(hash, CSTR2SYM("xhtml")) == Qtrue)
			render_flags |= HTML_USE_XHTML;

		link_attr = rb_hash_aref(hash, CSTR2SYM("link_attributes"));
	}

	sdhtml_renderer(&rndr->callbacks, (struct html_renderopt *)&rndr->options.html, render_flags);
	rb_redcarpet__overload(self, rb_cRenderHTML);

	if (!NIL_P(link_attr)) {
		rndr->options.link_attributes = link_attr;
		rndr->options.html.link_attributes = &rndr_link_attributes;
	}

	return Qnil;
}
Ejemplo n.º 22
0
VALUE method_atomic_fixnum_value_set(VALUE self, VALUE value) {
  Check_Type(value, T_FIXNUM);
  DATA_PTR(self) = (void *) value;
  return(value);
}
Ejemplo n.º 23
0
/* @overload crc16(buf)
 *   Calculate CRC16 checksum of a string
 *   
 *   @param buf [String] the string to be checksummed
 *   @return [Fixnum] the CRC16 value
 */
static VALUE mm_gps_CRC16(VALUE klass, VALUE str)
{
  Check_Type(str, T_STRING);
  return rb_fix_new(CRC16(RSTRING_PTR(str), RSTRING_LEN(str)));
}
Ejemplo n.º 24
0
VALUE method_atomic_fixnum_compare_and_set(VALUE self, VALUE rb_expect, VALUE rb_update) {
  Check_Type(rb_expect, T_FIXNUM);
  Check_Type(rb_update, T_FIXNUM);
  return ir_compare_and_set(self, rb_expect, rb_update);
}
Ejemplo n.º 25
0
/*
 * call-seq:
 *    XML.default_tree_indent_string = "string"
 *
 * Set the default string used by parsers to indent the XML tree
 * for output.
 */
static VALUE rxml_default_tree_indent_string_set(VALUE klass, VALUE string)
{
  Check_Type(string, T_STRING);
  xmlTreeIndentString = (const char *)xmlStrdup((xmlChar *)StringValuePtr(string));
  return (string);
}
Ejemplo n.º 26
0
Archivo: rdo.c Proyecto: d11wtq/rdo
/**
 * Takes String stmt, which contains ? markers and interpolates the values in Array params.
 *
 * Each value in Array params that is not NilClass, Fixnum or Float is passed
 * to #quote on the Driver.
 *
 * Non-numeric values are surrounded by String quote.
 *
 * @param VALUE (String) stmt
 *   SQL, possibly containining '?' markers.
 *
 * @param VALUE (Array) params
 *   arguments to interpolate in place of the ? markers
 *
 * @return VALUE (String)
 *   the same SQL with the parameters interpolated.
 */
static VALUE rdo_driver_interpolate(VALUE self, VALUE stmt, VALUE params) {
  Check_Type(stmt,   T_STRING);
  Check_Type(params, T_ARRAY);

  int  argc   = RARRAY_LEN(params);
  long buflen = 0;
  char ** quoted_params = rdo_driver_quote_params(
      self,
      RARRAY_PTR(params), argc,
      &buflen);
  char buffer[buflen + RSTRING_LEN(stmt) + 1];

  char * b = buffer;
  char * s = RSTRING_PTR(stmt);
  int    n = 0;

  int insquote = 0;
  int indquote = 0;
  int inmlcmt  = 0;
  int inslcmt  = 0;

  // this loop is intentionally kept procedural (for performance)
  for (; *s; ++s, ++b) {
    switch (*s) {
      case '\\':
        if (!insquote && !indquote && !inmlcmt && !inslcmt && *(s + 1) == '?')
          ++s;

        *b = *s;
        break;

      case '?':
        if (insquote || indquote || inmlcmt || inslcmt) {
          *b = *s;
        } else {
          if (n < argc) {
            strcpy(b, quoted_params[n]);
            b += strlen(quoted_params[n]) - 1;
          } else {
            *b = *s;
          }
          ++n;
        }
        break;

      case '-':
        if (!insquote && !indquote && !inmlcmt && *(s + 1) == '-') {
          inslcmt = 1;
          *(b++) = *(s++);
        }
        *b = *s;
        break;

      case '\r':
      case '\n':
        inslcmt = 0;
        *b = *s;
        break;

      case '/':
        if (!insquote && !indquote && !inslcmt && *(s + 1) == '*') {
          ++inmlcmt;
          *(b++) = *(s++);
        }
        *b = *s;
        break;

      case '*':
        if (inmlcmt && *(s + 1) == '/') {
          --inmlcmt;
          *(b++) = *(s++);
        }
        *b = *s;
        break;

      case '\'':
        if (!indquote && !inmlcmt && !inslcmt) insquote = !insquote;
        *b = *s;
        break;

      case '"':
        if (!insquote && !inmlcmt && !inslcmt) indquote = !indquote;
        *b = *s;
        break;

      default:
        *b = *s;
    }
  }

  *b = '\0';

  rdo_driver_free_params(quoted_params, argc);

  if (n != argc) {
    rb_raise(rb_eArgError,
        "Bind parameter mismatch (%i for %i) in query %s",
        argc, n, RSTRING_PTR(stmt));
  }

  return rb_str_new2(buffer);
}
Ejemplo n.º 27
0
static VALUE Node_init(int argc, VALUE *args, VALUE self)
{
    vx_graph graph = 0;
    vx_kernel kernel = 0;
    VALUE w,h,f;
    Check_Type(self, T_DATA);

    if (argc <= 1)
        rb_raise(rb_eArgError, "Not enough arguments");

    graph = (vx_graph)DATA_PTR(args[0]);

    if (argc == 2) // Kernel
    {
        Check_Type(args[1], T_DATA);
        kernel = (vx_kernel)DATA_PTR(args[1]);
        DATA_PTR(self) = (void *)vxCreateNode(graph, kernel);
    }
    else if (argc == 3) // graph, [string|enum], array of hashes
    {
        vx_node node = 0;
        vx_uint32 p = 0;
        VALUE kern = args[1];
        VALUE array = args[2];
        long param = 0;

        if (TYPE(kern) == T_STRING)
            kernel = vxGetKernelByName(context, RSTRING(kern)->ptr);
        else if (TYPE(kern) == T_FIXNUM)
            kernel = vxGetKernelByEnum(context, FIX2INT(kern));
        else if (TYPE(kern) == T_DATA) // a OpenVX::Kernel
            kernel = (vx_kernel)DATA_PTR(kern);
        else
            rb_raise(rb_eTypeError, "kernel must be a string, fixnum, or OpenVX::Kernel");

        if (kernel == 0)
            rb_raise(rb_eNameError, "kernel could not be found in OpenVX");

        Check_Type(array, T_ARRAY);

        node = vxCreateNode(graph, kernel);
        if (node == 0)
            rb_raise(rb_eTypeError, "node could not be created!");

        REXT_PRINT("Array of parameters has len = %ld\n", RARRAY(array)->len);
        for (param = 0; param < RARRAY(array)->len ; param++)
        {
            VALUE dir,ref,hash;
            vx_reference ref2 = 0;
            vx_status status = 0;
            vx_enum type = VX_TYPE_INVALID;
            const char *name;

            hash = rb_ary_entry(array, param);
            Check_Type(hash, T_HASH);
            dir = rb_hash_aref(hash, ID2SYM(rb_intern("dir")));
            ref = rb_hash_aref(hash, ID2SYM(rb_intern("ref")));
            name = rb_obj_classname(ref);

            REXT_PRINT("rb_type(dir)=0x%x\n", TYPE(dir));
            REXT_PRINT("ref class = %s\n", name);

            Check_Type(dir, T_FIXNUM);
            Check_Type(ref, T_DATA);

            REXT_PRINT("dir=%ld\n", FIX2UINT(dir));

            ref2 = (vx_reference)DATA_PTR(ref);
            if (strcmp("OpenVX::Image", name) == 0)
                type = VX_TYPE_IMAGE;
            else if (strcmp("OpenVX::Buffer", name) == 0)
                type = VX_TYPE_BUFFER;
            else if (strcmp("OpenVX::Scalar", name) == 0)
                type = VX_TYPE_MAX;

            REXT_PRINT("vx type = %d (0x%08x)\n", type, type);
            if (type == VX_TYPE_IMAGE) // replace with format
                status = vxQueryImage(ref2, VX_QUERY_IMAGE_FORMAT, &type, sizeof(vx_fourcc));
            else if (type == VX_TYPE_MAX)
                status = vxQueryReference(ref2, VX_QUERY_REF_TYPE, &type, sizeof(type));
            REXT_PRINT("status = %d vx type = %d (0x%08x)\n", status, type, type);

            status = vxSetParameterByIndex(node, param, FIX2UINT(dir), type, ref2);
            REXT_PRINT("status = %d\n", status);

        }
        DATA_PTR(self) = (void *)node;
    }
    else
    {
        rb_raise(rb_eArgError, "incorrect number of arguments");
    }
    return Qnil;
}
Ejemplo n.º 28
0
/* call-seq:
 *   krb5.get_init_creds_keytab(principal = nil, keytab = nil, service = nil, ccache = nil)
 *
 * Acquire credentials for +principal+ from +keytab+ using +service+. If
 * no principal is specified, then a principal is derived from the service
 * name. If no service name is specified, kerberos defaults to "host".
 *
 * If no keytab file is provided, the default keytab file is used. This is
 * typically /etc/krb5.keytab.
 *
 * If +ccache+ is supplied and is a Kerberos::Krb5::CredentialsCache, the
 * resulting credentials will be stored in the credential cache.
 */
static VALUE rkrb5_get_init_creds_keytab(int argc, VALUE* argv, VALUE self){
  RUBY_KRB5* ptr;
  VALUE v_user, v_keytab_name, v_service, v_ccache;
  char* user;
  char* service;
  char keytab_name[MAX_KEYTAB_NAME_LEN];

  krb5_error_code kerror;
  krb5_get_init_creds_opt* opt;
  krb5_creds cred;

  Data_Get_Struct(self, RUBY_KRB5, ptr); 

  if(!ptr->ctx)
    rb_raise(cKrb5Exception, "no context has been established");

  kerror = krb5_get_init_creds_opt_alloc(ptr->ctx, &opt);
  if(kerror)
    rb_raise(cKrb5Exception, "krb5_get_init_creds_opt_alloc: %s", error_message(kerror));

  rb_scan_args(argc, argv, "04", &v_user, &v_keytab_name, &v_service, &v_ccache);

  // We need the service information for later.
  if(NIL_P(v_service)){
    service = NULL;
  }
  else{
    Check_Type(v_service, T_STRING);
    service = StringValuePtr(v_service);
  }

  // Convert the name (or service name) to a kerberos principal.
  if(NIL_P(v_user)){
    kerror = krb5_sname_to_principal(
      ptr->ctx,
      NULL,
      service,
      KRB5_NT_SRV_HST,
      &ptr->princ
    );

    if(kerror) {
      krb5_get_init_creds_opt_free(ptr->ctx, opt);
      rb_raise(cKrb5Exception, "krb5_sname_to_principal: %s", error_message(kerror));
    }
  }
  else{
    Check_Type(v_user, T_STRING);
    user = StringValuePtr(v_user);

    kerror = krb5_parse_name(ptr->ctx, user, &ptr->princ); 

    if(kerror) {
      krb5_get_init_creds_opt_free(ptr->ctx, opt);
      rb_raise(cKrb5Exception, "krb5_parse_name: %s", error_message(kerror));
    }
  }

  // Use the default keytab if none is specified.
  if(NIL_P(v_keytab_name)){
    kerror = krb5_kt_default_name(ptr->ctx, keytab_name, MAX_KEYTAB_NAME_LEN);

    if(kerror) {
      krb5_get_init_creds_opt_free(ptr->ctx, opt);
      rb_raise(cKrb5Exception, "krb5_kt_default_name: %s", error_message(kerror));
    }
  }
  else{
    Check_Type(v_keytab_name, T_STRING);
    strncpy(keytab_name, StringValuePtr(v_keytab_name), MAX_KEYTAB_NAME_LEN);
  }

  kerror = krb5_kt_resolve(
    ptr->ctx,
    keytab_name,
    &ptr->keytab
  );

  if(kerror) {
    krb5_get_init_creds_opt_free(ptr->ctx, opt);
    rb_raise(cKrb5Exception, "krb5_kt_resolve: %s", error_message(kerror));
  }

  // Set the credential cache from the supplied Kerberos::Krb5::CredentialsCache
  if(!NIL_P(v_ccache)){
    RUBY_KRB5_CCACHE* ccptr;
    Data_Get_Struct(v_ccache, RUBY_KRB5_CCACHE, ccptr);

    kerror = krb5_get_init_creds_opt_set_out_ccache(ptr->ctx, opt, ccptr->ccache);
    if(kerror) {
      krb5_get_init_creds_opt_free(ptr->ctx, opt);
      rb_raise(cKrb5Exception, "krb5_get_init_creds_opt_set_out_ccache: %s", error_message(kerror));
    }
  }

  kerror = krb5_get_init_creds_keytab(
    ptr->ctx,
    &cred,
    ptr->princ,
    ptr->keytab,
    0,
    service,
    opt
  );

  if(kerror) {
    krb5_get_init_creds_opt_free(ptr->ctx, opt);
    rb_raise(cKrb5Exception, "krb5_get_init_creds_keytab: %s", error_message(kerror));
  }

  krb5_get_init_creds_opt_free(ptr->ctx, opt);

  return self; 
}
Ejemplo n.º 29
0
static GEOSCoordSequence* coord_seq_from_array(VALUE factory, VALUE array, char close)
{
  Check_Type(array, T_ARRAY);
  RGeo_FactoryData* factory_data = RGEO_FACTORY_DATA_PTR(factory);
  VALUE point_type = factory_data->globals->feature_point;
  unsigned int len = (unsigned int)RARRAY_LEN(array);
  char has_z = (char)(RGEO_FACTORY_DATA_PTR(factory)->flags & RGEO_FACTORYFLAGS_SUPPORTS_Z_OR_M);
  unsigned int dims = has_z ? 3 : 2;
  double* coords = ALLOC_N(double, len == 0 ? 1 : len * dims);
  if (!coords) {
    return NULL;
  }
  GEOSContextHandle_t context = factory_data->geos_context;
  unsigned int i;
  for (i=0; i<len; ++i) {
    char good = 0;
    const GEOSGeometry* entry_geom = rgeo_convert_to_geos_geometry(factory, rb_ary_entry(array, i), point_type);
    if (entry_geom) {
      const GEOSCoordSequence* entry_cs = GEOSGeom_getCoordSeq_r(context, entry_geom);
      if (entry_cs) {
        double x;
        if (GEOSCoordSeq_getX_r(context, entry_cs, 0, &x)) {
          coords[i*dims] = x;
          if (GEOSCoordSeq_getY_r(context, entry_cs, 0, &x)) {
            coords[i*dims+1] = x;
            good = 1;
            if (has_z) {
              if (GEOSCoordSeq_getZ_r(context, entry_cs, 0, &x)) {
                coords[i*dims+2] = x;
              }
              else {
                good = 0;
              }
            }
          }
        }
      }
    }
    if (!good) {
      free(coords);
      return NULL;
    }
  }
  if (len > 0 && close) {
    if (coords[0] == coords[(len-1)*dims] && coords[1] == coords[(len-1)*dims+1]) {
      close = 0;
    }
  }
  else {
    close = 0;
  }
  GEOSCoordSequence* coord_seq = GEOSCoordSeq_create_r(context, len + close, 3);
  if (coord_seq) {
    for (i=0; i<len; ++i) {
      GEOSCoordSeq_setX_r(context, coord_seq, i, coords[i*dims]);
      GEOSCoordSeq_setY_r(context, coord_seq, i, coords[i*dims+1]);
      GEOSCoordSeq_setZ_r(context, coord_seq, i, has_z ? coords[i*dims+2] : 0);
    }
    if (close) {
      GEOSCoordSeq_setX_r(context, coord_seq, len, coords[0]);
      GEOSCoordSeq_setY_r(context, coord_seq, len, coords[1]);
      GEOSCoordSeq_setZ_r(context, coord_seq, len, has_z ? coords[2] : 0);
    }
  }
  free(coords);
  return coord_seq;
}
Ejemplo n.º 30
0
static VALUE rb_mysql_result_each(int argc, VALUE * argv, VALUE self) {
  result_each_args args;
  VALUE defaults, opts, block, (*fetch_row_func)(VALUE, MYSQL_FIELD *fields, const result_each_args *args);
  ID db_timezone, app_timezone, dbTz, appTz;
  int symbolizeKeys, asArray, castBool, cacheRows, cast;

  GET_RESULT(self);

  if (wrapper->stmt_wrapper && wrapper->stmt_wrapper->closed) {
    rb_raise(cMysql2Error, "Statement handle already closed");
  }

  defaults = rb_iv_get(self, "@query_options");
  Check_Type(defaults, T_HASH);
  if (rb_scan_args(argc, argv, "01&", &opts, &block) == 1) {
    opts = rb_funcall(defaults, intern_merge, 1, opts);
  } else {
    opts = defaults;
  }

  symbolizeKeys = RTEST(rb_hash_aref(opts, sym_symbolize_keys));
  asArray       = rb_hash_aref(opts, sym_as) == sym_array;
  castBool      = RTEST(rb_hash_aref(opts, sym_cast_booleans));
  cacheRows     = RTEST(rb_hash_aref(opts, sym_cache_rows));
  cast          = RTEST(rb_hash_aref(opts, sym_cast));

  if (wrapper->is_streaming && cacheRows) {
    rb_warn(":cache_rows is ignored if :stream is true");
  }

  if (wrapper->stmt_wrapper && !cacheRows && !wrapper->is_streaming) {
    rb_warn(":cache_rows is forced for prepared statements (if not streaming)");
    cacheRows = 1;
  }

  if (wrapper->stmt_wrapper && !cast) {
    rb_warn(":cast is forced for prepared statements");
  }

  dbTz = rb_hash_aref(opts, sym_database_timezone);
  if (dbTz == sym_local) {
    db_timezone = intern_local;
  } else if (dbTz == sym_utc) {
    db_timezone = intern_utc;
  } else {
    if (!NIL_P(dbTz)) {
      rb_warn(":database_timezone option must be :utc or :local - defaulting to :local");
    }
    db_timezone = intern_local;
  }

  appTz = rb_hash_aref(opts, sym_application_timezone);
  if (appTz == sym_local) {
    app_timezone = intern_local;
  } else if (appTz == sym_utc) {
    app_timezone = intern_utc;
  } else {
    app_timezone = Qnil;
  }

  if (wrapper->rows == Qnil && !wrapper->is_streaming) {
    wrapper->numberOfRows = wrapper->stmt_wrapper ? mysql_stmt_num_rows(wrapper->stmt_wrapper->stmt) : mysql_num_rows(wrapper->result);
    wrapper->rows = rb_ary_new2(wrapper->numberOfRows);
  } else if (wrapper->rows && !cacheRows) {
    if (wrapper->resultFreed) {
      rb_raise(cMysql2Error, "Result set has already been freed");
    }
    mysql_data_seek(wrapper->result, 0);
    wrapper->lastRowProcessed = 0;
    wrapper->rows = rb_ary_new2(wrapper->numberOfRows);
  }

  // Backward compat
  args.symbolizeKeys = symbolizeKeys;
  args.asArray = asArray;
  args.castBool = castBool;
  args.cacheRows = cacheRows;
  args.cast = cast;
  args.db_timezone = db_timezone;
  args.app_timezone = app_timezone;
  args.block_given = block;

  if (wrapper->stmt_wrapper) {
    fetch_row_func = rb_mysql_result_fetch_row_stmt;
  } else {
    fetch_row_func = rb_mysql_result_fetch_row;
  }

  return rb_mysql_result_each_(self, fetch_row_func, &args);
}