Exemple #1
0
static VALUE check_app_file_exist(VALUE dir, VALUE fname1, const char* szPlatform)
{
    VALUE res = rb_str_dup(dir);
    //RAWLOG_INFO1("find_file: check dir %s", RSTRING_PTR(dir));

    #ifdef __SYMBIAN32__
        if(*RSTRING_PTR(res) == '/')
            res = rb_str_substr(res,1,RSTRING_LEN(res) - 1);
    #endif

    rb_str_cat(res,"/",1);
    rb_str_cat(res,RSTRING_PTR(fname1),RSTRING_LEN(fname1));
    if (szPlatform)
    {
        rb_str_cat(res,".",1);
        rb_str_cat(res,szPlatform,strlen(szPlatform));
    }

    rb_str_cat(res,RHO_RB_EXT,strlen(RHO_RB_EXT));
    //RAWLOG_INFO1("find_file: check file: %s", RSTRING_PTR(res));

    return eaccess(RSTRING_PTR(res), R_OK) == 0 ? res : 0;
}
Exemple #2
0
static VALUE
range_to_s(VALUE range)
{
    VALUE str, str2;

    str = rb_obj_as_string(RANGE_BEG(range));
    str2 = rb_obj_as_string(RANGE_END(range));
    str = rb_str_dup(str);
    rb_str_cat(str, "...", EXCL(range) ? 3 : 2);
    rb_str_append(str, str2);
    OBJ_INFECT(str, str2);

    return str;
}
Exemple #3
0
static void _concat_char(VALUE s, char c, bool ispath) {
  static char buf[3] = {'%', 0, 0};
  static char plus[1] = {'+'};

  if (ispath) {
    if (_should_escape(c) && c != '+' && c != '/') {
      buf[1] = _hex_char((unsigned char)c / 16);
      buf[2] = _hex_char((unsigned char)c % 16);
      rb_str_cat(s, buf, 3);
    } else {
      rb_str_cat(s, &c, 1);
    }
  } else {
    if (c == ' ') {
      rb_str_cat(s, plus, 1);
    } else if (_should_escape(c)) {
      buf[1] = _hex_char((unsigned char)c / 16);
      buf[2] = _hex_char((unsigned char)c % 16);
      rb_str_cat(s, buf, 3);
    } else {
      rb_str_cat(s, &c, 1);
    }
  }
}
/**
 * Convert the Ruby integer into a BSON as per the 64 bit specification,
 * which is 8 bytes.
 *
 * @example Convert the integer to 64bit BSON.
 *    rb_integer_to_bson_int64(128, encoded);
 *
 * @param [ Integer ] self The Ruby integer.
 * @param [ String ] encoded The Ruby binary string to append to.
 *
 * @return [ String ] encoded Ruby binary string with BSON raw bytes appended.
 *
 * @since 2.0.0
 */
static VALUE rb_integer_to_bson_int64(VALUE self, VALUE encoded)
{
  const int64_t v = NUM2INT64(self);
  const char bytes[8] = {
    v & 255,
    (v >> 8) & 255,
    (v >> 16) & 255,
    (v >> 24) & 255,
    (v >> 32) & 255,
    (v >> 40) & 255,
    (v >> 48) & 255,
    (v >> 56) & 255
  };
  return rb_str_cat(encoded, bytes, 8);
}
Exemple #5
0
static int on_header_value(http_parser* parser, const char* s, size_t len) {
  Request* p = (Request*)parser;
  if (p->last_field == Qnil) {
    if (p->last_value == Qnil) {
      p->parse_state = PS_ERROR;
      return 1;
    }
    rb_str_cat(p->last_value, s, len);
  } else {
    nyara_headerlize(p->last_field);
    p->last_value = rb_enc_str_new(s, len, u8_encoding);
    rb_hash_aset(p->header, p->last_field, p->last_value);
    p->last_field = Qnil;
  }
  return 0;
}
Exemple #6
0
static VALUE
inspect_range(VALUE range, VALUE dummy, int recur)
{
    VALUE str, str2;

    if (recur) {
	return rb_str_new2(EXCL(range) ? "(... ... ...)" : "(... .. ...)");
    }
    str = rb_inspect(RANGE_BEG(range));
    str2 = rb_inspect(RANGE_END(range));
    str = rb_str_dup(str);
    rb_str_cat(str, "...", EXCL(range) ? 3 : 2);
    rb_str_append(str, str2);
    OBJ_INFECT(str, str2);

    return str;
}
int on_header_value(ryah_http_parser *parser, const char *at, size_t length) {
  GET_WRAPPER(wrapper, parser);

  if (wrapper->last_field_name == Qnil) {
    wrapper->last_field_name = rb_str_new(wrapper->last_field_name_at, wrapper->last_field_name_length);

    VALUE val = rb_hash_aref(wrapper->headers, wrapper->last_field_name);
    if (val != Qnil) {
      rb_str_cat(val, ", ", 2);
    }

    wrapper->last_field_name_at = NULL;
    wrapper->last_field_name_length = 0;
  }

  HASH_CAT(wrapper->headers, wrapper->last_field_name, at, length);

  return 0;
}
Exemple #8
0
VALUE grpc_rb_byte_buffer_to_s(grpc_byte_buffer *buffer) {
  VALUE rb_string;
  grpc_byte_buffer_reader reader;
  grpc_slice next;
  if (buffer == NULL) {
    return Qnil;
  }
  rb_string = rb_str_buf_new(grpc_byte_buffer_length(buffer));
  if (!grpc_byte_buffer_reader_init(&reader, buffer)) {
    rb_raise(rb_eRuntimeError, "Error initializing byte buffer reader.");
    return Qnil;
  }
  while (grpc_byte_buffer_reader_next(&reader, &next) != 0) {
    rb_str_cat(rb_string, (const char *) GRPC_SLICE_START_PTR(next),
               GRPC_SLICE_LENGTH(next));
    grpc_slice_unref(next);
  }
  grpc_byte_buffer_reader_destroy(&reader);
  return rb_string;
}
Exemple #9
0
VALUE
rb_id2str(ID id)
{
    LOCK();
    VALUE sym = (VALUE)CFDictionaryGetValue(id_str, (const void *)id);
    UNLOCK();
    if (sym != 0) {
//printf("lookup %ld -> %s\n", id, rb_sym2name(sym));
	return sym;
    }

    if (is_attrset_id(id)) {
	// Attribute assignment.
	ID id2 = (id & ~ID_SCOPE_MASK) | ID_LOCAL;

	while ((sym = rb_id2str(id2)) == 0) {
	    if (!is_local_id(id2)) {
//printf("lookup %ld -> FAIL\n", id);
		return 0;
	    }
	    id2 = (id & ~ID_SCOPE_MASK) | ID_CONST;
	}

	VALUE str = rb_str_dup(RSYM(sym)->str);
	rb_str_cat(str, "=", 1);
	rb_intern_str(str);

	// Retry one more time.
	LOCK();
	sym = (VALUE)CFDictionaryGetValue(id_str, (const void *)id);
	UNLOCK();
	if (sym != 0) {
//printf("lookup %ld -> %s\n", id, rb_sym2name(sym));
	    return sym;
	}
    }
//printf("lookup %ld -> FAIL\n", id);
    return 0;
}
Exemple #10
0
static VALUE fcgi_stream_read(int argc, VALUE *argv, VALUE self)
{
  VALUE num,str;
  FCGX_Stream *stream;
  char *buff;
  int n;

  if (rb_safe_level() >= 4 && !OBJ_TAINTED(self)) {
    rb_raise(rb_eSecurityError, "Insecure: operation on untainted IO");
  }

  Data_Get_Struct(self, FCGX_Stream, stream);

  if (argc==0) {
    buff = ALLOC_N(char, 16384);
    n = FCGX_GetStr(buff, 16384, stream);
    CHECK_STREAM_ERROR(stream);
    if (n == 0) {
      free(buff);
      return  Qnil;
    }
    str = rb_str_new(buff, n);
    OBJ_TAINT(str);

    while(!FCGX_HasSeenEOF(stream)) {
      n = FCGX_GetStr(buff, 16384, stream);
      CHECK_STREAM_ERROR(stream);
      if (n > 0) {
        rb_str_cat(str, buff, n);
      } else {
        free(buff);
        return Qnil;
      }
    }
    free(buff);
    return str;
  }
Exemple #11
0
VALUE CRbWin32API::initialize(int argc, VALUE * argv, VALUE obj)
{
	VALUE dllname, proc, _import, _export;
	rb_scan_args(argc, argv, "4", &dllname, &proc, &_import, &_export);

	SafeStringValue(dllname);
	SafeStringValue(proc);
	m_hDll = LoadLibraryA(RSTRING_PTR(dllname));
	if (!m_hDll)
		rb_raise(rb_eSinError, "LoadLibrary: %s\n", RSTRING_PTR(dllname));
	
	HANDLE hproc = (HANDLE)GetProcAddress(m_hDll, RSTRING_PTR(proc));
	if (!hproc) 
	{
		VALUE str = rb_str_new3(proc); str = rb_str_cat(str, "A", 1);
		hproc = (HANDLE)GetProcAddress(m_hDll, RSTRING_PTR(str));
		if (!hproc)
		{
			rb_raise(rb_eSinError, "GetProcAddress: %s or %s\n", RSTRING_PTR(proc), RSTRING_PTR(str));
		}
	}
	rb_iv_set(obj, "__dll__",		rb_uint2inum((u32)m_hDll));
	rb_iv_set(obj, "__dllname__",	dllname);
	rb_iv_set(obj, "__proc__",		rb_uint2inum((u32)hproc));

	VALUE ary_import = SinParseImportArgs(_import);
	if (16 < RARRAY_LEN(ary_import))
	{
		rb_raise(rb_eSinError, "too many parameters: %ld\n", RARRAY_LEN(ary_import));
	}
	rb_iv_set(obj, "__import__", ary_import);

	rb_iv_set(obj, "__export__", INT2FIX(SinParseExportArgs(_export)));

	return obj;
}
VALUE Parser_execute(VALUE self, VALUE data) {
  ParserWrapper *wrapper = NULL;

  Check_Type(data, T_STRING);
  char *ptr = RSTRING_PTR(data);
  long len = RSTRING_LEN(data);

  DATA_GET(self, ParserWrapper, wrapper);

  wrapper->stopped = Qfalse;
  size_t nparsed = ryah_http_parser_execute(&wrapper->parser, &settings, ptr, len);

  if (wrapper->parser.upgrade) {
    rb_str_cat(wrapper->upgrade_data, ptr + nparsed + 1, len - nparsed - 1);

  } else if (nparsed != (size_t)len) {
    if (!RTEST(wrapper->stopped) && !RTEST(wrapper->completed))
      rb_raise(eParserError, "Could not parse data entirely");
    else
      nparsed += 1; // error states fail on the current character
  }

  return INT2FIX(nparsed);
}
Exemple #13
0
/**
 * Encode a true value to bson.
 *
 * @example Encode the true value.
 *    rb_true_class_to_bson(0, true);
 *
 * @param [ int ] argc The number or arguments.
 * @param [ Array<Object> ] argv The arguments.
 * @param [ TrueClass ] self The true value.
 *
 * @return [ String ] The encoded string.
 *
 * @since 2.0.0
 */
static VALUE rb_true_class_to_bson(int argc, VALUE *argv, VALUE self)
{
  VALUE encoded = rb_get_default_encoded(argc, argv);
  rb_str_cat(encoded, &rb_bson_true_byte, 1);
  return encoded;
}
Exemple #14
0
/**
 * Convert the ruby string to a BSON string.
 *
 * @example Convert the Ruby string to a BSON string.
 *    rb_string_to_bson_string(0, Qnil, "test");
 *
 * @param [ String ] self The string value.
 * @param [ String ] encoded The encoded string to append to.
 *
 * @return [ String ] The encoded string.
 *
 * @since 2.0.0
 */
static VALUE rb_string_to_bson_string(VALUE self, VALUE encoded)
{
  const VALUE binary = rb_bson_to_utf8_binary(self);
  rb_str_cat(encoded, RSTRING_PTR(binary), RSTRING_LEN(binary));
  return encoded;
}
Exemple #15
0
/*RHO static*/ VALUE
eval_string_with_cref(VALUE self, VALUE src, VALUE scope, NODE *cref, const char *file, int line)
{
    int state;
    VALUE result = Qundef;
    VALUE envval;
    rb_binding_t *bind = 0;
    rb_thread_t *th = GET_THREAD();
    rb_env_t *env = NULL;
    rb_block_t block;
    volatile int parse_in_eval;
    volatile int mild_compile_error;

    if (file == 0) {
	file = rb_sourcefile();
	line = rb_sourceline();
    }

    parse_in_eval = th->parse_in_eval;
    mild_compile_error = th->mild_compile_error;
    PUSH_TAG();
    if ((state = EXEC_TAG()) == 0) {
	rb_iseq_t *iseq;
	volatile VALUE iseqval;

	if (scope != Qnil) {
	    if (rb_obj_is_kind_of(scope, rb_cBinding)) {
		GetBindingPtr(scope, bind);
		envval = bind->env;
	    }
	    else {
		rb_raise(rb_eTypeError,
			 "wrong argument type %s (expected Binding)",
			 rb_obj_classname(scope));
	    }
	    GetEnvPtr(envval, env);
	    th->base_block = &env->block;
	}
	else {
	    rb_control_frame_t *cfp = rb_vm_get_ruby_level_next_cfp(th, th->cfp);

	    if (cfp != 0) {
		block = *RUBY_VM_GET_BLOCK_PTR_IN_CFP(cfp);
		th->base_block = &block;
		th->base_block->self = self;
		th->base_block->iseq = cfp->iseq;	/* TODO */
	    }
	    else {
		rb_raise(rb_eRuntimeError, "Can't eval on top of Fiber or Thread");
	    }
	}

    //RHO
    if ( TYPE(src) != T_STRING ){
        iseqval = src;
    }else
    //RHO
    {
	    /* make eval iseq */
	    th->parse_in_eval++;
	    th->mild_compile_error++;
	    iseqval = rb_iseq_compile(src, rb_str_new2(file), INT2FIX(line));
	    th->mild_compile_error--;
	    th->parse_in_eval--;
    }

	vm_set_eval_stack(th, iseqval, cref);
	th->base_block = 0;

	if (0) {		/* for debug */
	    printf("%s\n", RSTRING_PTR(rb_iseq_disasm(iseqval)));
	}

	/* save new env */
	GetISeqPtr(iseqval, iseq);
	if (bind && iseq->local_size > 0) {
	    bind->env = rb_vm_make_env_object(th, th->cfp);
	}

	/* kick */
	CHECK_STACK_OVERFLOW(th->cfp, iseq->stack_max);
	result = vm_exec(th);
    }
    POP_TAG();
    th->mild_compile_error = mild_compile_error;
    th->parse_in_eval = parse_in_eval;

    if (state) {
	if (state == TAG_RAISE) {
	    VALUE errinfo = th->errinfo;
	    if (strcmp(file, "(eval)") == 0) {
		VALUE mesg, errat, bt2;
		extern VALUE rb_get_backtrace(VALUE info);
		ID id_mesg;

		CONST_ID(id_mesg, "mesg");
		errat = rb_get_backtrace(errinfo);
		mesg = rb_attr_get(errinfo, id_mesg);
		if (!NIL_P(errat) && TYPE(errat) == T_ARRAY &&
		    (bt2 = vm_backtrace(th, -2), RARRAY_LEN(bt2) > 0)) {
		    if (!NIL_P(mesg) && TYPE(mesg) == T_STRING && !RSTRING_LEN(mesg)) {
			if (OBJ_FROZEN(mesg)) {
			    VALUE m = rb_str_cat(rb_str_dup(RARRAY_PTR(errat)[0]), ": ", 2);
			    rb_ivar_set(errinfo, id_mesg, rb_str_append(m, mesg));
			}
			else {
			    rb_str_update(mesg, 0, 0, rb_str_new2(": "));
			    rb_str_update(mesg, 0, 0, RARRAY_PTR(errat)[0]);
			}
		    }
		    RARRAY_PTR(errat)[0] = RARRAY_PTR(bt2)[0];
		}
	    }
	    rb_exc_raise(errinfo);
	}
	JUMP_TAG(state);
    }
    return result;
}
Exemple #16
0
/*
 * call-seq:
 *    Win32::API.new(function, prototype='V', return='L', dll='kernel32')
 *
 * Creates and returns a new Win32::API object. The +function+ is the name
 * of the Windows function.
 *
 * The +prototype+ is the function prototype for +function+. This can be a
 * string or an array of characters.  The possible valid characters are 'I'
 * (integer), 'L' (long), 'V' (void), 'P' (pointer), 'K' (callback) or 'S'
 * (string).
 *
 * The default is void ('V').
 *
 * Constant (const char*) strings should use 'S'. Pass by reference string
 * buffers should use 'P'. The former is faster, but cannot be modified.
 *
 * The +return+ argument is the return type for the function.  The valid
 * characters are the same as for the +prototype+.  The default is 'L' (long).
 *
 * The +dll+ is the name of the DLL file that the function is exported from.
 * The default is 'kernel32'.
 *
 * If the function cannot be found then an API::Error is raised (a subclass
 * of RuntimeError).
 *
 * Example:
 *
 *    require 'win32/api'
 *    include Win32
 *
 *    buf = 0.chr * 260
 *    len = [buf.length].pack('L')
 *
 *    GetUserName = API.new('GetUserName', 'PP', 'I', 'advapi32')
 *    GetUserName.call(buf, len)
 *
 *    puts buf.strip
 */
static VALUE api_init(int argc, VALUE* argv, VALUE self)
{
   HMODULE hLibrary;
   FARPROC fProc;
   Win32API* ptr;
   int i;
   char* first  = "A";
   char* second = "W";
   VALUE v_proc, v_proto, v_return, v_dll;

   rb_scan_args(argc, argv, "13", &v_proc, &v_proto, &v_return, &v_dll);

   Data_Get_Struct(self, Win32API, ptr);

   // Convert a string prototype to an array of characters
   if(rb_respond_to(v_proto, rb_intern("split")))
      v_proto = rb_str_split(v_proto, "");

   // Convert a nil or empty prototype to 'V' (void) automatically
   if(NIL_P(v_proto) || RARRAY_LEN(v_proto) == 0){
      v_proto = rb_ary_new();
      rb_ary_push(v_proto, rb_str_new2("V"));
   }

   // Set an arbitrary limit of 20 parameters
   if(20 < RARRAY_LEN(v_proto))
      rb_raise(rb_eArgError, "too many parameters: %d\n", RARRAY_LEN(v_proto));

   // Set the default dll to 'kernel32'
   if(NIL_P(v_dll))
      v_dll = rb_str_new2("kernel32");

   // Set the default return type to 'L' (DWORD)
   if(NIL_P(v_return))
      v_return = rb_str_new2("L");

   SafeStringValue(v_dll);
   SafeStringValue(v_proc);

   hLibrary = LoadLibrary(TEXT(RSTRING_PTR(v_dll)));

   // The most likely cause of failure is a bad DLL load path
   if(!hLibrary){
      rb_raise(cAPILoadError, "LoadLibrary() function failed for '%s': %s",
         RSTRING_PTR(v_dll),
         StringError(GetLastError())
      );
   }

   ptr->library = hLibrary;

   /* Attempt to get the function.  If it fails, try again with an 'A'
    * appended.  If that fails, try again with a 'W' appended. If that
    * still fails, raise an API::LoadLibraryError.
    */

   fProc = GetProcAddress(hLibrary, TEXT(RSTRING_PTR(v_proc)));

   // Skip the ANSI and Wide function checks for MSVCRT functions.
   if(!fProc){
      if(strstr(RSTRING_PTR(v_dll), "msvcr")){
         rb_raise(
            cAPILoadError,
            "Unable to load function '%s'",
            RSTRING_PTR(v_proc)
         );
      }
      else{
         VALUE v_ascii = rb_str_new3(v_proc);
         v_ascii = rb_str_cat(v_ascii, first, 1);
         fProc = GetProcAddress(hLibrary, TEXT(RSTRING_PTR(v_ascii)));

         if(!fProc){
            VALUE v_unicode = rb_str_new3(v_proc);
            v_unicode = rb_str_cat(v_unicode, second, 1);
            fProc = GetProcAddress(hLibrary, TEXT(RSTRING_PTR(v_unicode)));

            if(!fProc){
               rb_raise(
                  cAPILoadError,
                  "Unable to load function '%s', '%s', or '%s'",
                  RSTRING_PTR(v_proc),
                  RSTRING_PTR(v_ascii),
                  RSTRING_PTR(v_unicode)
               );
            }
            else{
               rb_iv_set(self, "@effective_function_name", v_unicode);
            }
         }
         else{
            rb_iv_set(self, "@effective_function_name", v_ascii);
         }
      }
   }
   else{
      rb_iv_set(self, "@effective_function_name", v_proc);
   }

   ptr->function = fProc;

   // Push the numeric prototypes onto our int array for later use.

   for(i = 0; i < RARRAY_LEN(v_proto); i++){
      SafeStringValue(RARRAY_PTR(v_proto)[i]);
      switch(*(char*)StringValuePtr(RARRAY_PTR(v_proto)[i])){
         case 'L':
            ptr->prototype[i] = _T_LONG;
            break;
         case 'P':
            ptr->prototype[i] = _T_POINTER;
            break;
         case 'I': case 'B':
            ptr->prototype[i] = _T_INTEGER;
            break;
         case 'V':
            ptr->prototype[i] = _T_VOID;
            break;
         case 'K':
            ptr->prototype[i] = _T_CALLBACK;
            break;
         case 'S':
            ptr->prototype[i] = _T_STRING;
            break;
         default:
            rb_raise(cAPIProtoError, "Illegal prototype '%s'",
               StringValuePtr(RARRAY_PTR(v_proto)[i])
            );
      }
   }

   // Store the return type for later use.

   // Automatically convert empty strings or nil to type void.
   if(NIL_P(v_return) || RSTRING_LEN(v_return) == 0){
      v_return = rb_str_new2("V");
      ptr->return_type = _T_VOID;
   }
   else{
      SafeStringValue(v_return);
      switch(*RSTRING_PTR(v_return)){
         case 'L':
            ptr->return_type = _T_LONG;
            break;
         case 'P':
            ptr->return_type = _T_POINTER;
            break;
         case 'I': case 'B':
            ptr->return_type = _T_INTEGER;
            break;
         case 'V':
            ptr->return_type = _T_VOID;
            break;
         case 'S':
            ptr->return_type = _T_STRING;
            break;
         default:
            rb_raise(cAPIProtoError, "Illegal return type '%s'",
               RSTRING_PTR(v_return)
            );
      }
   }

   rb_iv_set(self, "@dll_name", v_dll);
   rb_iv_set(self, "@function_name", v_proc);
   rb_iv_set(self, "@prototype", v_proto);
   rb_iv_set(self, "@return_type", v_return);

   return self;
}
Exemple #17
0
      {
      if (post_readline_pos >= post_readline_watermark)
         {
         post_readline_pos = post_readline_watermark = U_NULLPTR; // all the readline buffer has been consumed

         U_RETURN(Qnil);
         }

      U_INTERNAL_DUMP("hint = %ld", NUM2LONG(RARRAY_PTR(args)[0]))
      }

   if (post_readline_pos < post_readline_watermark)
      {
      // If buffer is given, then the read data will be placed into buffer instead of a newly created String object

      VALUE result = (RARRAY_LEN(args) > 1 ? rb_str_cat(RARRAY_PTR(args)[1], post_readline_pos, post_readline_watermark - post_readline_pos)
                                           : rb_str_new(                     post_readline_pos, post_readline_watermark - post_readline_pos));

      post_readline_pos = post_readline_watermark = U_NULLPTR; // all the readline buffer has been consumed

      U_RETURN(result);
      }

   U_RETURN(Qnil);
}

static VALUE URUBY_io_gets(VALUE obj, VALUE args)
{
   U_TRACE(0, "URUBY_io_gets(%llu,%llu)", obj, args)

   U_INTERNAL_DUMP("post_readline_pos = %p post_readline_watermark = %p", post_readline_pos, post_readline_watermark)
Exemple #18
0
static VALUE
optimized_unescape(VALUE str, VALUE encoding)
{
    long i, len, beg = 0;
    VALUE dest = 0;
    const char *cstr;
    int cr, origenc, encidx = rb_to_encoding_index(encoding);

    len  = RSTRING_LEN(str);
    cstr = RSTRING_PTR(str);

    for (i = 0; i < len; ++i) {
	char buf[1];
	const char c = cstr[i];
	int clen = 0;
	if (c == '%') {
	    if (i + 3 > len) break;
	    if (!ISXDIGIT(cstr[i+1])) continue;
	    if (!ISXDIGIT(cstr[i+2])) continue;
	    buf[0] = ((char_to_number(cstr[i+1]) << 4)
		      | char_to_number(cstr[i+2]));
	    clen = 2;
	}
	else if (c == '+') {
	    buf[0] = ' ';
	}
	else {
	    continue;
	}

	if (!dest) {
	    dest = rb_str_buf_new(len);
	}

	rb_str_cat(dest, cstr + beg, i - beg);
	i += clen;
	beg = i + 1;

	rb_str_cat(dest, buf, 1);
    }

    if (dest) {
	rb_str_cat(dest, cstr + beg, len - beg);
	preserve_original_state(str, dest);
	cr = ENC_CODERANGE_UNKNOWN;
    }
    else {
	dest = rb_str_dup(str);
	cr = ENC_CODERANGE(str);
    }
    origenc = rb_enc_get_index(str);
    if (origenc != encidx) {
	rb_enc_associate_index(dest, encidx);
	if (!ENC_CODERANGE_CLEAN_P(rb_enc_str_coderange(dest))) {
	    rb_enc_associate_index(dest, origenc);
	    if (cr != ENC_CODERANGE_UNKNOWN)
		ENC_CODERANGE_SET(dest, cr);
	}
    }
    return dest;
}
Exemple #19
0
static VALUE defout_write(VALUE self, VALUE str)
{
    str = rb_obj_as_string(str);
    rb_str_cat(self, RSTRING_PTR(str), RSTRING_LEN(str));
    return Qnil;
}
int on_query_string(ryah_http_parser *parser, const char *at, size_t length) {
  GET_WRAPPER(wrapper, parser);
  rb_str_cat(wrapper->query_string, at, length);
  return 0;
}
Exemple #21
0
VALUE require_compiled(VALUE fname, VALUE* result, int bLoad)
{
    VALUE path;
    char* szName1 = 0;
    VALUE retval = Qtrue;
    
    if (TYPE(fname) != T_STRING)
        rb_raise(rb_eLoadError, "can not load non-string");

    szName1 = RSTRING_PTR(fname);

    if ( String_endsWith(szName1,".rb") ) 
    {
        rb_str_chop_bang(fname); rb_str_chop_bang(fname); rb_str_chop_bang(fname);
    }
    //rb_funcall(fname, rb_intern("sub!"), 2, rb_str_new2(".rb"), rb_str_new2("") );
    szName1 = RSTRING_PTR(fname);

    if ( strcmp("strscan",szName1)==0 || strcmp("enumerator",szName1)==0 ||
        strcmp("stringio",szName1)==0 || strcmp("socket",szName1)==0 )
        return Qtrue;

    RHO_LOCK(require_lock);

    if ( !bLoad && isAlreadyLoaded(fname) == Qtrue )
        goto RCompExit;

    path = find_file(fname);

    if ( path != 0 )
    {
        VALUE seq;

        RAWLOG_INFO1("require_compiled: %s", szName1);

        //optimize require
        //rb_ary_push(GET_VM()->loaded_features, path);
        rb_ary_push(GET_VM()->loaded_features, fname);

#ifdef RHODES_EMULATOR
        if ( strstr( RSTRING_PTR(path), ".rb") == 0 )
            rb_str_cat(path,".rb",3);

        GET_VM()->src_encoding_index = rb_utf8_encindex();
        rb_load(path, 0);

        if( rho_simconf_getBool("reload_app_changes") )
        {
            if ( strncmp( RSTRING_PTR(path), rho_native_rhopath(), strlen(rho_native_rhopath()) ) == 0 )
                rb_ary_delete(GET_VM()->loaded_features, fname);
        }
#else
        //rb_gc_disable();
        seq = loadISeqFromFile(path);
        

        //*result = rb_funcall(seq, rb_intern("eval"), 0 );
        *result = rb_iseq_eval(seq);
        
        //rb_gc_enable();
#endif
        goto RCompExit;
    }

    RAWLOG_ERROR1("require_compiled: error: can not find %s", RSTRING_PTR(fname));
    retval = Qnil;

RCompExit:
    RHO_UNLOCK(require_lock);
    return retval;
}
Exemple #22
0
static VALUE find_file(VALUE fname)
{
    VALUE res = 0;
    int nOK = 0;

    //RAWLOG_INFO1("find_file: fname: %s", RSTRING_PTR(fname));
#ifdef RHODES_EMULATOR
    if ( strncmp(RSTRING_PTR(fname), rho_simconf_getRhodesPath(), strlen(rho_simconf_getRhodesPath())) == 0 )
        res = fname;
    else
#endif

    if ( strncmp(RSTRING_PTR(fname), rho_native_rhopath(), strlen(rho_native_rhopath())) == 0 ){
        res = rb_str_dup(fname);
        rb_str_cat(res,RHO_RB_EXT,strlen(RHO_RB_EXT));
        //RAWLOG_INFO1("find_file: res: %s", RSTRING_PTR(res));
    } else if ( strncmp(RSTRING_PTR(fname), rho_native_reruntimepath(), strlen(rho_native_reruntimepath())) == 0 ){
        res = rb_str_dup(fname);
        rb_str_cat(res,RHO_RB_EXT,strlen(RHO_RB_EXT));
        //RAWLOG_INFO1("find_file: res: %s", RSTRING_PTR(res));
    }else{
        int i = 0;
        VALUE load_path = GET_VM()->load_path;
        //VALUE dir;
        VALUE fname1 = checkRhoBundleInPath(fname);
        //RAWLOG_INFO1("find_file: fname after checkRhoBundleInPath: %s", RSTRING_PTR(fname));

        //TODO: support document relative require in case of multiple apps
        if (RARRAY_LEN(load_path)>1){
            for( ; i < RARRAY_LEN(load_path); i++ ){
                VALUE dir = RARRAY_PTR(load_path)[i];

#ifdef RHODES_EMULATOR
                res = check_app_file_exist(dir, fname1, rho_simconf_getString("platform"));
#endif
                if ( !res )
                    res = check_app_file_exist(dir, fname1, 0 );

                if (res)
                {
                    nOK = 1;
                    break;
                }
            }
            if ( !nOK )
            {
#ifdef RHODES_EMULATOR
                //check for extensions
/*                res = rb_str_new2(rho_simconf_getRhodesPath() );
                rb_str_cat2(res,"/lib/extensions/");

                res = check_extension(res, fname, 1);
                if ( !res )
                {
                    res = rb_str_new2(rho_native_rhopath() );
                    rb_str_cat2(res,"/extensions/");

                    res = check_extension(res, fname,1);
                }

                if ( !res )
                {
                    res = rb_str_new2( rho_simconf_getString("ext_path") );
                    res = check_extension(res, fname, 0);
                }
*/
                const char* szPaths = rho_simconf_getString("ext_path");
                const char* szPath = szPaths;
                const char* szSep = strchr(szPath, ';');
                res = 0;
                for( ; szSep; szSep = strchr(szPath, ';') )
                {
                    res = rb_str_new( szPath, szSep-szPath);
                    rb_str_cat2(res,"/");
                    rb_str_append(res,fname);
                    rb_str_cat2(res,RHO_RB_EXT);

                    if ( eaccess(RSTRING_PTR(res), R_OK) == 0 )
                        break;

                    res = rb_str_new( szPath, szSep-szPath);
                    rb_str_cat2(res,"/app/");
                    rb_str_append(res,fname);
                    rb_str_cat2(res,RHO_RB_EXT);

                    if ( eaccess(RSTRING_PTR(res), R_OK) == 0 )
                        break;

                    res = 0;
                    szPath = szSep+1;
                }

                if( res )
                    nOK = 1;
                else
                    return 0;
#else
                return 0;
#endif
                
            }
        } /*else {
            dir = RARRAY_PTR(load_path)[RARRAY_LEN(load_path)-1];

            res = rb_str_dup(dir);
            rb_str_cat(res,"/",1);
            rb_str_cat(res,RSTRING_PTR(fname),RSTRING_LEN(fname));
            rb_str_cat(res,RHO_RB_EXT,strlen(RHO_RB_EXT));

            if ( g_curAppPath != 0 && eaccess(RSTRING_PTR(res), R_OK) != 0 ){
                res = rb_str_new2(g_curAppPath);
                rb_str_cat(res,"/",1);
                rb_str_cat(res,RSTRING_PTR(fname),RSTRING_LEN(fname));
                rb_str_cat(res,RHO_RB_EXT,strlen(RHO_RB_EXT));
            }
        } */
    }

    //RAWLOG_INFO1("find_file: RhoPreparePath: %s", RSTRING_PTR(res));
    res = RhoPreparePath(res);
    if ( !nOK )
        nOK = 1;//eaccess(RSTRING_PTR(res), R_OK) == 0 ? 1 : 0;

    return nOK ? res : 0;
}
int on_fragment(ryah_http_parser *parser, const char *at, size_t length) {
  GET_WRAPPER(wrapper, parser);
  rb_str_cat(wrapper->fragment, at, length);
  return 0;
}
Exemple #24
0
VALUE ss_cat_as_question(VALUE self, VALUE str) {
  return rb_str_cat(str, "?", 1);
}
Exemple #25
0
VALUE
asn1_encode_object(asn_TYPE_descriptor_t *td, VALUE encoder_v, void *object)
{
	VALUE encoded;
	bufferInfo_t	bi;
	asn_enc_rval_t	er;

	char *encoder = encoder_string(encoder_v);

	/*
	 * Setup buffer
	 */
	bi.buffer = (char *)malloc(512);
    bi.offset = 0;
    bi.length = 512;

	/*
	 * Encode
	 */
	if (strcmp(encoder, "der") == 0)
	{
		er = td->der_encoder(td, object, 0, 0, (asn_app_consume_bytes_f *)consumeBytes, (void *)&bi);
		if (er.encoded == -1)
		{
			rb_raise(rb_eException, "Can't encode type");
		}
		/* Free memory */
	}
	else if (strcmp(encoder, "per") == 0)
	{
		size_t	bit_length;
		size_t	bits_to_flush;
		int		byte_length;

		char *b = (char *)calloc(512, sizeof(char));
		asn_per_outp_t apo;
		apo.buffer        = apo.tmpspace;
		apo.nboff         = 0;
		apo.nbits         = 32 * 8;
		apo.outper        = per_bytes;
		apo.op_key        = (void *)b;
		apo.flushed_bytes = 0;

		er = td->uper_encoder(td, td->per_constraints, object, &apo);
		if (er.encoded == -1)
		{
			rb_raise(rb_eException, "Can't encode type");
			/* Free memory */
		}

		/* Relies on knowledge of internals - XXXXX - bad */
        bits_to_flush = ((apo.buffer - apo.tmpspace) << 3) + apo.nboff;
        bit_length	  = (apo.flushed_bytes << 3) + bits_to_flush;
		byte_length	  = bit_length % 8 != 0 ? bit_length / 8 + 1 : bit_length / 8;

		encoded = rb_str_new(b, apo.flushed_bytes);
		rb_str_cat(encoded, apo.tmpspace, byte_length - apo.flushed_bytes);

		return encoded;
	}
	else if (strcmp(encoder, "xer") == 0)
	{
		xer_encode(td, object, XER_F_CANONICAL, (asn_app_consume_bytes_f *)consumeBytes, (void *)&bi);
		if (er.encoded == -1)
		{
			rb_raise(rb_eException, "Can't encode type");
		}
		/* Free memory */
	}

	encoded = rb_str_new(bi.buffer, bi.offset);
	return encoded;
}
Exemple #26
0
static
int _parse_http_request(char *buf, ssize_t buf_len, VALUE env) {
  const char* method;
  size_t method_len;
  const char* path;
  size_t path_len;
  int minor_version;
  struct phr_header headers[MAX_HEADERS];
  size_t num_headers, question_at;
  size_t i;
  int ret;
  char tmp[MAX_HEADER_NAME_LEN + sizeof("HTTP_") - 1];
  VALUE last_value;

  num_headers = MAX_HEADERS;
  ret = phr_parse_request(buf, buf_len, &method, &method_len, &path,
                          &path_len, &minor_version, headers, &num_headers, 0);
  if (ret < 0)
    goto done;

  rb_hash_aset(env, request_method_key, rb_str_new(method,method_len));
  rb_hash_aset(env, request_uri_key, rb_str_new(path, path_len));
  rb_hash_aset(env, script_name_key, rb_str_new2(""));
  strcpy(tmp, "HTTP/1.");
  tmp[7] = 48 + ((minor_version > 1 || minor_version < 0 ) ? 0 : minor_version);
  rb_hash_aset(env, server_protocol_key, rb_str_new(tmp, sizeof("HTTP/1.0") - 1));

  /* PATH_INFO QUERY_STRING */
  path_len = find_ch(path, path_len, '#'); /* strip off all text after # after storing request_uri */
  question_at = find_ch(path, path_len, '?');
  if ( store_path_info(env, path, question_at) < 0 ) {
    rb_hash_clear(env);
    ret = -1;
    goto done;
  }
  if (question_at != path_len) ++question_at;
  rb_hash_aset(env, query_string_key, rb_str_new(path + question_at, path_len - question_at));
  last_value = Qnil;
  for (i = 0; i < num_headers; ++i) {
    if (headers[i].name != NULL) {
      const char* name;
      size_t name_len;
      VALUE slot;
      VALUE env_key;
      env_key = find_common_header(headers + i);
      if ( env_key == Qnil ) {
        const char* s;
        char* d;
        size_t n;
        if (sizeof(tmp) - 5 < headers[i].name_len) {
          rb_hash_clear(env);
          ret = -1;
          goto done;
        }
        strcpy(tmp, "HTTP_");
        for (s = headers[i].name, n = headers[i].name_len, d = tmp + 5;
          n != 0;
          s++, --n, d++) {
            *d = *s == '-' ? '_' : TOU(*s);
            name = tmp;
            name_len = headers[i].name_len + 5;
            env_key = rb_str_new(name, name_len);
        }
      }
      slot = rb_hash_aref(env, env_key);
      if ( slot != Qnil ) {
        rb_str_cat2(slot, ", ");
        rb_str_cat(slot, headers[i].value, headers[i].value_len);
      } else {
        slot = rb_str_new(headers[i].value, headers[i].value_len);
        rb_hash_aset(env, env_key, slot);
        last_value = slot;
      }
    } else {
      /* continuing lines of a mulitiline header */
      if ( last_value != Qnil )
        rb_str_cat(last_value, headers[i].value, headers[i].value_len);
    }
  }

 done:
  return ret;
}
Exemple #27
0
static void
process_sflag(struct cmdline_options *opt)
{
    if (opt->sflag) {
	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 = Qfalse;

	    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 = Qtrue;
		}
		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);
	}
    }
    opt->sflag = 0;
}
Exemple #28
0
VALUE string_spec_rb_str_cat(VALUE self, VALUE str) {
  return rb_str_cat(str, "?", 1);
}
Exemple #29
0
VALUE oily_png_encode_png_image_pass_to_stream(VALUE self, VALUE stream, VALUE color_mode, VALUE bit_depth, VALUE filtering) {
  
  UNUSED_PARAMETER(bit_depth);
  
  // Get the data
  char depth      = (char) FIX2INT(bit_depth);
  long width      = FIX2LONG(rb_funcall(self, rb_intern("width"), 0));
  long height     = FIX2LONG(rb_funcall(self, rb_intern("height"), 0));
  VALUE pixels    = rb_funcall(self, rb_intern("pixels"), 0);
  
  if (RARRAY_LEN(pixels) != width * height) {
    rb_raise(rb_eRuntimeError, "The number of pixels does not match the canvas dimensions.");
  }

  // Get the encoding palette if we're encoding to an indexed bytestream.
  VALUE encoding_palette = Qnil;
  if (FIX2INT(color_mode) == OILY_PNG_COLOR_INDEXED) {
    encoding_palette = oily_png_encode_palette(self);
  }
  
  char pixel_size = oily_png_pixel_bytesize(FIX2INT(color_mode), depth);
  long line_size  = oily_png_scanline_bytesize(FIX2INT(color_mode), depth, width);
  long pass_size  = oily_png_pass_bytesize(FIX2INT(color_mode), depth, width, height);

  // Allocate memory for the byte array.
  BYTE* bytes = ALLOC_N(BYTE, pass_size);
  
  // Get the scanline encoder function.
  scanline_encoder_func scanline_encoder = oily_png_encode_scanline_func(FIX2INT(color_mode), depth);
  if (scanline_encoder == NULL) {
    rb_raise(rb_eRuntimeError, "No encoder for color mode %d and bit depth %d", FIX2INT(color_mode), depth);
  }

  long y, pos;
  for (y = height - 1; y >= 0; y--) {
    pos = line_size * y;
    bytes[pos] = (BYTE) FIX2INT(filtering);
    scanline_encoder(bytes + pos + 1, pixels, y, width, encoding_palette);
  }
  
  if (FIX2INT(filtering) != OILY_PNG_FILTER_NONE) {

    // Get the scanline filter function
    void (*scanline_filter)(BYTE*, long, long, char) = NULL;
    switch (FIX2INT(filtering)) {
      case OILY_PNG_FILTER_SUB:     scanline_filter = &oily_png_encode_filter_sub; break;
      case OILY_PNG_FILTER_UP:      scanline_filter = &oily_png_encode_filter_up; break;
      case OILY_PNG_FILTER_AVERAGE: scanline_filter = &oily_png_encode_filter_average; break;
      case OILY_PNG_FILTER_PAETH:   scanline_filter = &oily_png_encode_filter_paeth; break;
      default: rb_raise(rb_eRuntimeError, "Unsupported filter type: %d", FIX2INT(filtering));
    }

    for (y = height - 1; y >= 0; y--) {
      scanline_filter(bytes, line_size * y, line_size, pixel_size);
    }
  }
  
  // Append to encoded image pass to the output stream.
  rb_str_cat(stream, (char*) bytes, pass_size);
  xfree(bytes);
  return Qnil;
}
Exemple #30
0
static VALUE
optimized_unescape_html(VALUE str)
{
    enum {UNICODE_MAX = 0x10ffff};
    rb_encoding *enc = rb_enc_get(str);
    unsigned long charlimit = (strcasecmp(rb_enc_name(enc), "UTF-8") == 0 ? UNICODE_MAX :
			       strcasecmp(rb_enc_name(enc), "ISO-8859-1") == 0 ? 256 :
			       128);
    long i, len, beg = 0;
    size_t clen, plen;
    int overflow;
    const char *cstr;
    char buf[6];
    VALUE dest = 0;

    len  = RSTRING_LEN(str);
    cstr = RSTRING_PTR(str);

    for (i = 0; i < len; i++) {
	unsigned long cc;
	char c = cstr[i];
	if (c != '&') continue;
	plen = i - beg;
	if (++i >= len) break;
	c = (unsigned char)cstr[i];
	switch (c) {
	  case 'a':
	    ++i;
	    if (len - i >= 4 && memcmp(&cstr[i], "pos;", 4) == 0) {
		c = '\'';
		i += 3;
	    }
	    else if (len - i >= 3 && memcmp(&cstr[i], "mp;", 3) == 0) {
		c = '&';
		i += 2;
	    }
	    else continue;
	    break;
	  case 'q':
	    ++i;
	    if (len - i >= 4 && memcmp(&cstr[i], "uot;", 4) == 0) {
		c = '"';
		i += 3;
	    }
	    else continue;
	    break;
	  case 'g':
	    ++i;
	    if (len - i >= 2 && memcmp(&cstr[i], "t;", 2) == 0) {
		c = '>';
		i += 1;
	    }
	    else continue;
	    break;
	  case 'l':
	    ++i;
	    if (len - i >= 2 && memcmp(&cstr[i], "t;", 2) == 0) {
		c = '<';
		i += 1;
	    }
	    else continue;
	    break;
	  case '#':
	    if (len - ++i >= 2 && ISDIGIT(cstr[i])) {
		cc = ruby_scan_digits(&cstr[i], len-i, 10, &clen, &overflow);
	    }
	    else if ((cstr[i] == 'x' || cstr[i] == 'X') && len - ++i >= 2 && ISXDIGIT(cstr[i])) {
		cc = ruby_scan_digits(&cstr[i], len-i, 16, &clen, &overflow);
	    }
	    else continue;
	    i += clen;
	    if (overflow || cc >= charlimit || cstr[i] != ';') continue;
	    if (!dest) {
		dest = rb_str_buf_new(len);
	    }
	    rb_str_cat(dest, cstr + beg, plen);
	    if (charlimit > 256) {
		rb_str_cat(dest, buf, rb_enc_mbcput((OnigCodePoint)cc, buf, enc));
	    }
	    else {
		c = (unsigned char)cc;
		rb_str_cat(dest, &c, 1);
	    }
	    beg = i + 1;
	    continue;
	  default:
	    --i;
	    continue;
	}
	if (!dest) {
	    dest = rb_str_buf_new(len);
	}
	rb_str_cat(dest, cstr + beg, plen);
	rb_str_cat(dest, &c, 1);
	beg = i + 1;
    }

    if (dest) {
	rb_str_cat(dest, cstr + beg, len - beg);
	preserve_original_state(str, dest);
	return dest;
    }
    else {
	return rb_str_dup(str);
    }
}