Пример #1
0
  @JRubyMethod(name = "initialize", rest = true)
  public IRubyObject _initialize(IRubyObject[] args, Block block) {
    store.setVerifyCallbackFunction(ossl_verify_cb);
    this.set_verify_callback(getRuntime().getNil());
    this.setInstanceVariable("@flags", RubyFixnum.zero(getRuntime()));
    this.setInstanceVariable("@purpose", RubyFixnum.zero(getRuntime()));
    this.setInstanceVariable("@trust", RubyFixnum.zero(getRuntime()));

    this.setInstanceVariable("@error", getRuntime().getNil());
    this.setInstanceVariable("@error_string", getRuntime().getNil());
    this.setInstanceVariable("@chain", getRuntime().getNil());
    this.setInstanceVariable("@time", getRuntime().getNil());
    return this;
  }
Пример #2
0
  private IRubyObject shutdownInternal(ThreadContext context, int how)
      throws BadDescriptorException {
    Ruby runtime = context.runtime;
    Channel channel;

    switch (how) {
      case 0:
        channel = getOpenChannel();
        try {
          SocketType.forChannel(channel).shutdownInput(channel);

        } catch (IOException e) {
          throw runtime.newIOError(e.getMessage());
        }

        if (openFile.getPipeStream() != null) {
          openFile.setMainStream(openFile.getPipeStream());
          openFile.setPipeStream(null);
        }

        openFile.setMode(openFile.getMode() & ~OpenFile.READABLE);

        return RubyFixnum.zero(runtime);

      case 1:
        channel = getOpenChannel();
        try {
          SocketType.forChannel(channel).shutdownOutput(channel);

        } catch (IOException e) {
          throw runtime.newIOError(e.getMessage());
        }

        openFile.setPipeStream(null);
        openFile.setMode(openFile.getMode() & ~OpenFile.WRITABLE);

        return RubyFixnum.zero(runtime);

      case 2:
        shutdownInternal(context, 0);
        shutdownInternal(context, 1);

        return RubyFixnum.zero(runtime);

      default:
        throw runtime.newArgumentError("`how' should be either :SHUT_RD, :SHUT_WR, :SHUT_RDWR");
    }
  }
Пример #3
0
  @JRubyMethod(required = 1, optional = 1)
  public IRubyObject seek(ThreadContext context, IRubyObject[] args) {
    Ruby runtime = context.runtime;

    checkFrozen();
    checkFinalized();

    int offset = RubyNumeric.num2int(args[0]);
    IRubyObject whence = context.nil;

    if (args.length > 1 && !args[0].isNil()) whence = args[1];

    checkOpen();

    switch (whence.isNil() ? 0 : RubyNumeric.num2int(whence)) {
      case 0:
        break;
      case 1:
        offset += ptr.pos;
        break;
      case 2:
        offset += ptr.string.size();
        break;
      default:
        throw runtime.newErrnoEINVALError("invalid whence");
    }

    if (offset < 0) throw runtime.newErrnoEINVALError("invalid seek value");

    ptr.pos = offset;

    return RubyFixnum.zero(runtime);
  }
Пример #4
0
  @JRubyMethod(required = 1, optional = 1)
  @Override
  public IRubyObject seek(IRubyObject[] args) {
    checkOpen();
    checkFinalized();
    long amount = RubyNumeric.num2long(args[0]);
    int whence = Stream.SEEK_SET;
    long newPosition = data.pos;

    if (args.length > 1 && !args[0].isNil()) whence = RubyNumeric.fix2int(args[1]);

    if (whence == Stream.SEEK_CUR) {
      newPosition += amount;
    } else if (whence == Stream.SEEK_END) {
      newPosition = data.internal.getByteList().length() + amount;
    } else if (whence == Stream.SEEK_SET) {
      newPosition = amount;
    } else {
      throw getRuntime().newErrnoEINVALError("invalid whence");
    }

    if (newPosition < 0) throw getRuntime().newErrnoEINVALError("invalid seek value");

    data.pos = newPosition;
    data.eof = false;

    return RubyFixnum.zero(getRuntime());
  }
Пример #5
0
  public void load(Ruby runtime, boolean wrap) throws IOException {
    RubyModule timeout = runtime.defineModule("Timeout");
    RubyClass superclass = runtime.getRuntimeError();
    RubyClass timeoutError =
        runtime.defineClassUnder("Error", superclass, superclass.getAllocator(), timeout);
    runtime.defineClassUnder(
        "ExitException", runtime.getException(), runtime.getException().getAllocator(), timeout);

    // Here we create an "anonymous" exception type used for unrolling the stack.
    // MRI creates a new one for *every call* to timeout, which can be costly.
    // We opt to use a single exception type for all cases to avoid this overhead.
    RubyClass anonEx =
        runtime.defineClassUnder(
            "AnonymousException",
            runtime.getException(),
            runtime.getException().getAllocator(),
            timeout);
    anonEx.setBaseName(null); // clear basename so it's anonymous when raising

    // These are not really used by timeout, but exposed for compatibility
    timeout.defineConstant(
        "THIS_FILE", RubyRegexp.newRegexp(runtime, "timeout\\.rb", new RegexpOptions()));
    timeout.defineConstant("CALLER_OFFSET", RubyFixnum.newFixnum(runtime, 0));

    // Timeout module methods
    timeout.defineAnnotatedMethods(Timeout.class);

    // Toplevel defines
    runtime.getObject().defineConstant("TimeoutError", timeoutError);
    runtime.getObject().defineAnnotatedMethods(TimeoutToplevel.class);
  }
Пример #6
0
 public final RubyFixnum getFixnum(Ruby runtime, int index, long value) {
   RubyFixnum fixnum = fixnums[index];
   if (fixnum == null) {
     return fixnums[index] = RubyFixnum.newFixnum(runtime, value);
   }
   return fixnum;
 }
Пример #7
0
  @JRubyMethod(name = "rewind")
  public IRubyObject rewind(ThreadContext context) {
    checkInitialized();

    this.ptr.pos = 0;
    this.ptr.lineno = 0;
    return RubyFixnum.zero(context.runtime);
  }
Пример #8
0
  @JRubyMethod()
  public IRubyObject bind(ThreadContext context, IRubyObject addr, IRubyObject backlog) {
    final InetSocketAddress iaddr;

    if (addr instanceof Addrinfo) {
      Addrinfo addrInfo = (Addrinfo) addr;
      if (!addrInfo.ip_p(context).isTrue()) {
        throw context.runtime.newTypeError("not an INET or INET6 address: " + addrInfo);
      }
      iaddr = new InetSocketAddress(addrInfo.getInetAddress().getHostAddress(), addrInfo.getPort());
    } else {
      iaddr = Sockaddr.addressFromSockaddr_in(context, addr);
    }
    doBind(context, getChannel(), iaddr, RubyFixnum.fix2int(backlog));

    return RubyFixnum.zero(context.runtime);
  }
Пример #9
0
  @JRubyMethod(
      name = {"write"},
      required = 1)
  public IRubyObject write(ThreadContext context, IRubyObject arg) {
    checkWritable();

    Ruby runtime = context.runtime;

    RubyString str = arg.asString();
    int len, olen;
    Encoding enc, enc2;

    enc = ptr.string.getEncoding();
    enc2 = str.getEncoding();
    if (enc != enc2
        && enc != EncodingUtils.ascii8bitEncoding(runtime)
        // this is a hack because we don't seem to handle incoming ASCII-8BIT properly in transcoder
        && enc2 != ASCIIEncoding.INSTANCE) {
      str = runtime.newString(Transcoder.strConvEnc(context, str.getByteList(), enc2, enc));
    }
    len = str.size();
    if (len == 0) return RubyFixnum.zero(runtime);
    checkModifiable();
    olen = ptr.string.size();
    if ((ptr.flags & OpenFile.APPEND) != 0) {
      ptr.pos = olen;
    }
    if (ptr.pos == olen
        // this is a hack because we don't seem to handle incoming ASCII-8BIT properly in transcoder
        && enc2 != ASCIIEncoding.INSTANCE) {
      EncodingUtils.encStrBufCat(runtime, ptr.string, str.getByteList(), enc);
    } else {
      strioExtend(ptr.pos, len);
      ByteList ptrByteList = ptr.string.getByteList();
      System.arraycopy(
          str.getByteList().getUnsafeBytes(),
          str.getByteList().getBegin(),
          ptrByteList.getUnsafeBytes(),
          ptrByteList.begin + ptr.pos,
          len);
      ptr.string.infectBy(str);
    }
    ptr.string.infectBy(this);
    ptr.pos += len;
    return RubyFixnum.newFixnum(runtime, len);
  }
Пример #10
0
  @JRubyMethod(name = {"size", "length"})
  public IRubyObject size(ThreadContext context) {
    if (!isClosed()) {
      flush();
      return context.getRuntime().newFileStat(path, false).size();
    }

    return RubyFixnum.zero(context.getRuntime());
  }
Пример #11
0
 private IRubyObject shutdownInternal(ThreadContext context, int how) {
   Channel socketChannel;
   switch (how) {
     case 0:
       socketChannel = openFile.getMainStream().getDescriptor().getChannel();
       try {
         if (socketChannel instanceof SocketChannel || socketChannel instanceof DatagramChannel) {
           asSocket().shutdownInput();
         } else if (socketChannel instanceof Shutdownable) {
           ((Shutdownable) socketChannel).shutdownInput();
         }
       } catch (IOException e) {
         throw context.getRuntime().newIOError(e.getMessage());
       }
       if (openFile.getPipeStream() != null) {
         openFile.setMainStream(openFile.getPipeStream());
         openFile.setPipeStream(null);
       }
       openFile.setMode(openFile.getMode() & ~OpenFile.READABLE);
       return RubyFixnum.zero(context.getRuntime());
     case 1:
       socketChannel = openFile.getMainStream().getDescriptor().getChannel();
       try {
         if (socketChannel instanceof SocketChannel || socketChannel instanceof DatagramChannel) {
           asSocket().shutdownOutput();
         } else if (socketChannel instanceof Shutdownable) {
           ((Shutdownable) socketChannel).shutdownOutput();
         }
       } catch (IOException e) {
         throw context.getRuntime().newIOError(e.getMessage());
       }
       openFile.setPipeStream(null);
       openFile.setMode(openFile.getMode() & ~OpenFile.WRITABLE);
       return RubyFixnum.zero(context.getRuntime());
     case 2:
       shutdownInternal(context, 0);
       shutdownInternal(context, 1);
       return RubyFixnum.zero(context.getRuntime());
     default:
       throw context.getRuntime().newArgumentError("`how' should be either 0, 1, 2");
   }
 }
Пример #12
0
 @JRubyMethod(
     name = {"new_out", "alloc_out", "__alloc_out"},
     meta = true)
 public static Buffer allocateOutput(
     ThreadContext context,
     IRubyObject recv,
     IRubyObject sizeArg,
     IRubyObject countArg,
     IRubyObject clearArg) {
   return allocate(context, recv, sizeArg, RubyFixnum.fix2int(countArg), OUT);
 }
Пример #13
0
 private void removeNamespceRecursively(ThreadContext context, XmlNode xmlNode) {
   Node node = xmlNode.node;
   if (node.getNodeType() == Node.ELEMENT_NODE) {
     node.setPrefix(null);
     node.getOwnerDocument().renameNode(node, null, node.getLocalName());
   }
   XmlNodeSet nodeSet = (XmlNodeSet) xmlNode.children(context);
   for (long i = 0; i < nodeSet.length(); i++) {
     XmlNode childNode =
         (XmlNode) nodeSet.slice(context, RubyFixnum.newFixnum(context.getRuntime(), i));
     removeNamespceRecursively(context, childNode);
   }
 }
Пример #14
0
  @JRubyMethod(
      name = {"initialize"},
      visibility = PRIVATE)
  public IRubyObject initialize(ThreadContext context, IRubyObject type, IRubyObject address) {
    setMemoryIO(
        address instanceof Pointer
            ? ((Pointer) address).getMemoryIO()
            : Factory.getInstance()
                .wrapDirectMemory(context.runtime, RubyFixnum.num2long(address)));
    size = Long.MAX_VALUE;
    typeSize = calculateTypeSize(context, type);

    return this;
  }
Пример #15
0
  @JRubyMethod(name = "truncate", required = 1)
  public IRubyObject truncate(IRubyObject len) {
    checkWritable();

    int l = RubyFixnum.fix2int(len);
    int plen = ptr.string.size();
    if (l < 0) {
      throw getRuntime().newErrnoEINVALError("negative legnth");
    }
    ptr.string.resize(l);
    ByteList buf = ptr.string.getByteList();
    if (plen < l) {
      // zero the gap
      Arrays.fill(buf.getUnsafeBytes(), buf.getBegin() + plen, buf.getBegin() + l, (byte) 0);
    }
    return len;
  }
Пример #16
0
  @JRubyMethod(name = "truncate", required = 1)
  @Override
  public IRubyObject truncate(IRubyObject arg) {
    checkWritable();

    int len = RubyFixnum.fix2int(arg);
    if (len < 0) {
      throw getRuntime().newErrnoEINVALError("negative legnth");
    }

    data.internal.modify();
    ByteList buf = data.internal.getByteList();
    if (len < buf.length()) {
      Arrays.fill(buf.getUnsafeBytes(), len, buf.length(), (byte) 0);
    }
    buf.length(len);
    return arg;
  }
Пример #17
0
  private void strioInit(ThreadContext context, IRubyObject[] args) {
    Ruby runtime = context.runtime;
    RubyString string;
    IRubyObject mode;
    boolean trunc = false;

    switch (args.length) {
      case 2:
        mode = args[1];
        if (mode instanceof RubyFixnum) {
          int flags = RubyFixnum.fix2int(mode);
          ptr.flags = ModeFlags.getOpenFileFlagsFor(flags);
          trunc = (flags & ModeFlags.TRUNC) != 0;
        } else {
          String m = args[1].convertToString().toString();
          ptr.flags = OpenFile.ioModestrFmode(runtime, m);
          trunc = m.charAt(0) == 'w';
        }
        string = args[0].convertToString();
        if ((ptr.flags & OpenFile.WRITABLE) != 0 && string.isFrozen()) {
          throw runtime.newErrnoEACCESError("Permission denied");
        }
        if (trunc) {
          string.resize(0);
        }
        break;
      case 1:
        string = args[0].convertToString();
        ptr.flags = string.isFrozen() ? OpenFile.READABLE : OpenFile.READWRITE;
        break;
      case 0:
        string = RubyString.newEmptyString(runtime, runtime.getDefaultExternalEncoding());
        ptr.flags = OpenFile.READWRITE;
        break;
      default:
        throw runtime.newArgumentError(args.length, 2);
    }

    ptr.string = string;
    ptr.pos = 0;
    ptr.lineno = 0;
    // funky way of shifting readwrite flags into object flags
    flags |= (ptr.flags & OpenFile.READWRITE) * (STRIO_READABLE / OpenFile.READABLE);
  }
Пример #18
0
  @Override
  protected IRubyObject fillCommon(ThreadContext context, int beg, long len, Block block) {
    if (!packed()) return super.fillCommon(context, beg, len, block);

    modifyCheck();

    // See [ruby-core:17483]
    if (len <= 0) return this;

    if (len > Integer.MAX_VALUE - beg) throw context.runtime.newArgumentError("argument too big");

    if (len > 1) {
      unpack();
      return super.fillCommon(context, beg, len, block);
    }

    value = block.yield(context, RubyFixnum.zero(context.runtime));

    return this;
  }
Пример #19
0
  @JRubyMethod(optional = 2, visibility = PRIVATE)
  @Override
  public IRubyObject initialize(IRubyObject[] args, Block unusedBlock) {
    Object modeArgument = null;
    Ruby runtime = getRuntime();

    switch (args.length) {
      case 0:
        data.internal =
            runtime.is1_9()
                ? RubyString.newEmptyString(runtime, runtime.getDefaultExternalEncoding())
                : RubyString.newEmptyString(getRuntime());
        modeArgument = "r+";
        break;
      case 1:
        data.internal = args[0].convertToString();
        modeArgument = data.internal.isFrozen() ? "r" : "r+";
        break;
      case 2:
        data.internal = args[0].convertToString();
        if (args[1] instanceof RubyFixnum) {
          modeArgument = RubyFixnum.fix2long(args[1]);
        } else {
          modeArgument = args[1].convertToString().toString();
        }
        break;
    }

    initializeModes(modeArgument);

    if (data.modes.isWritable() && data.internal.isFrozen()) {
      throw getRuntime().newErrnoEACCESError("Permission denied");
    }

    if (data.modes.isTruncate()) {
      data.internal.modifyCheck();
      data.internal.empty();
    }

    return this;
  }
Пример #20
0
  private IRubyObject unmarshalObjectDirectly(int type, MarshalState state, boolean callProc)
      throws IOException {
    IRubyObject rubyObj = null;
    switch (type) {
      case 'I':
        MarshalState childState = new MarshalState(true);
        rubyObj = unmarshalObject(childState);
        if (childState.isIvarWaiting()) {
          defaultVariablesUnmarshal(rubyObj);
        }
        return rubyObj;
      case '0':
        rubyObj = runtime.getNil();
        break;
      case 'T':
        rubyObj = runtime.getTrue();
        break;
      case 'F':
        rubyObj = runtime.getFalse();
        break;
      case '"':
        rubyObj = RubyString.unmarshalFrom(this);
        break;
      case 'i':
        rubyObj = RubyFixnum.unmarshalFrom(this);
        break;
      case 'f':
        rubyObj = RubyFloat.unmarshalFrom(this);
        break;
      case '/':
        rubyObj = RubyRegexp.unmarshalFrom(this);
        break;
      case ':':
        rubyObj = RubySymbol.unmarshalFrom(this);
        break;
      case '[':
        rubyObj = RubyArray.unmarshalFrom(this);
        break;
      case '{':
        rubyObj = RubyHash.unmarshalFrom(this, false);
        break;
      case '}':
        // "hashdef" object, a hash with a default
        rubyObj = RubyHash.unmarshalFrom(this, true);
        break;
      case 'c':
        rubyObj = RubyClass.unmarshalFrom(this);
        break;
      case 'm':
        rubyObj = RubyModule.unmarshalFrom(this);
        break;
      case 'e':
        RubySymbol moduleName = (RubySymbol) unmarshalObject();
        RubyModule tp = null;
        try {
          tp = runtime.getClassFromPath(moduleName.asJavaString());
        } catch (RaiseException e) {
          if (runtime.getModule("NameError").isInstance(e.getException())) {
            throw runtime.newArgumentError("undefined class/module " + moduleName.asJavaString());
          }
          throw e;
        }

        rubyObj = unmarshalObject();

        tp.extend_object(rubyObj);
        tp.callMethod(runtime.getCurrentContext(), "extended", rubyObj);
        break;
      case 'l':
        rubyObj = RubyBignum.unmarshalFrom(this);
        break;
      case 'S':
        rubyObj = RubyStruct.unmarshalFrom(this);
        break;
      case 'o':
        rubyObj = defaultObjectUnmarshal();
        break;
      case 'u':
        rubyObj = userUnmarshal(state);
        break;
      case 'U':
        rubyObj = userNewUnmarshal();
        break;
      case 'C':
        rubyObj = uclassUnmarshall();
        break;
      default:
        throw getRuntime().newArgumentError("dump format error(" + (char) type + ")");
    }

    if (callProc) {
      return doCallProcForObj(rubyObj);
    }

    return rubyObj;
  }
Пример #21
0
 @JRubyMethod(name = "fsync")
 @Override
 public IRubyObject fsync() {
   return RubyFixnum.zero(getRuntime());
 }
Пример #22
0
 @JRubyMethod(name = {"fsync"})
 public IRubyObject strioZero(ThreadContext context) {
   return RubyFixnum.zero(context.runtime);
 }
Пример #23
0
 @JRubyMethod(name = "size", meta = true, visibility = PUBLIC)
 public static IRubyObject size(ThreadContext context, IRubyObject recv) {
   return RubyFixnum.newFixnum(
       context.getRuntime(), Factory.getInstance().sizeOf(NativeType.POINTER));
 }
Пример #24
0
 @JRubyMethod(name = "rewind")
 @Override
 public IRubyObject rewind() {
   doRewind();
   return RubyFixnum.zero(getRuntime());
 }
Пример #25
0
 public static Integer integerOrNull(IRubyObject obj) {
     return (!obj.isNil()) ? RubyFixnum.fix2int(obj) : null;
 }
Пример #26
0
 public static int intOrMinusOne(IRubyObject obj) {
     return (!obj.isNil()) ? RubyFixnum.fix2int(obj) : -1;
 }
Пример #27
0
 @JRubyMethod(name = "listen", required = 1)
 public IRubyObject listen(ThreadContext context, IRubyObject backlog) {
   return RubyFixnum.zero(context.getRuntime());
 }
Пример #28
0
 private static final int getCount(IRubyObject countArg) {
   return countArg instanceof RubyFixnum ? RubyFixnum.fix2int(countArg) : 1;
 }
Пример #29
0
  public static void buildAddrinfoList(
      ThreadContext context, IRubyObject[] args, AddrinfoCallback callback) {
    Ruby runtime = context.runtime;
    IRubyObject host = args[0];
    IRubyObject port = args[1];
    boolean emptyHost = host.isNil() || host.convertToString().isEmpty();

    try {
      if (port instanceof RubyString) {
        port = getservbyname(context, new IRubyObject[] {port});
      }

      IRubyObject family = args.length > 2 ? args[2] : context.nil;
      IRubyObject socktype = args.length > 3 ? args[3] : context.nil;
      // IRubyObject protocol = args[4];
      IRubyObject flags = args.length > 5 ? args[5] : context.nil;
      IRubyObject reverseArg = args.length > 6 ? args[6] : context.nil;

      // The Ruby Socket.getaddrinfo function supports boolean/nil/Symbol values for the
      // reverse_lookup parameter. We need to massage all valid inputs to true/false/null.
      Boolean reverseLookup = null;
      if (reverseArg instanceof RubyBoolean) {
        reverseLookup = reverseArg.isTrue();
      } else if (reverseArg instanceof RubySymbol) {
        String reverseString = reverseArg.toString();
        if ("hostname".equals(reverseString)) {
          reverseLookup = true;
        } else if ("numeric".equals(reverseString)) {
          reverseLookup = false;
        } else {
          throw runtime.newArgumentError("invalid reverse_lookup flag: :" + reverseString);
        }
      }

      AddressFamily addressFamily = AF_INET;
      if (!family.isNil()) {
        addressFamily = addressFamilyFromArg(family);
      }
      boolean is_ipv6 = addressFamily == AddressFamily.AF_INET6;
      boolean sock_stream = true;
      boolean sock_dgram = true;

      Sock sock = SOCK_STREAM;
      if (!socktype.isNil()) {
        sockFromArg(socktype);

        if (sock == SOCK_STREAM) {
          sock_dgram = false;

        } else if (sock == SOCK_DGRAM) {
          sock_stream = false;
        }
      }

      // When Socket::AI_PASSIVE and host is nil, return 'any' address.
      InetAddress[] addrs = null;

      if (!flags.isNil() && RubyFixnum.fix2int(flags) > 0) {
        // The value of 1 is for Socket::AI_PASSIVE.
        int flag = RubyNumeric.fix2int(flags);

        if ((flag == 1) && emptyHost) {
          // use RFC 2732 style string to ensure that we get Inet6Address
          addrs = InetAddress.getAllByName(is_ipv6 ? "[::]" : "0.0.0.0");
        }
      }

      if (addrs == null) {
        addrs =
            InetAddress.getAllByName(
                emptyHost ? (is_ipv6 ? "[::1]" : null) : host.convertToString().toString());
      }

      for (int i = 0; i < addrs.length; i++) {
        int p = port.isNil() ? 0 : (int) port.convertToInteger().getLongValue();
        callback.addrinfo(addrs[i], p, sock, reverseLookup);
      }

    } catch (UnknownHostException e) {
      throw sockerr(runtime, "getaddrinfo: name or service not known");
    }
  }
Пример #30
0
 @JRubyMethod()
 public IRubyObject bind(ThreadContext context, IRubyObject addr) {
   return bind(context, addr, RubyFixnum.zero(context.runtime));
 }