Example #1
0
def EnumKey(space, w_hkey, index):
    """string = EnumKey(key, index) - Enumerates subkeys of an open registry key.

key is an already open key, or any one of the predefined HKEY_* constants.
index is an integer that identifies the index of the key to retrieve.

The function retrieves the name of one subkey each time it is called.
It is typically called repeatedly until an EnvironmentError exception is
raised, indicating no more values are available."""
    hkey = hkey_w(w_hkey, space)
    null_dword = lltype.nullptr(rwin32.LPDWORD.TO)

    # The Windows docs claim that the max key name length is 255
    # characters, plus a terminating nul character.  However,
    # empirical testing demonstrates that it is possible to
    # create a 256 character key that is missing the terminating
    # nul.  RegEnumKeyEx requires a 257 character buffer to
    # retrieve such a key name.
    with lltype.scoped_alloc(rffi.CCHARP.TO, 257) as buf:
        with lltype.scoped_alloc(rwin32.LPDWORD.TO, 1) as retValueSize:
            retValueSize[0] = r_uint(257) # includes NULL terminator
            ret = rwinreg.RegEnumKeyEx(hkey, index, buf, retValueSize,
                                       null_dword, None, null_dword,
                                       lltype.nullptr(rwin32.PFILETIME.TO))
            if ret != 0:
                raiseWindowsError(space, ret, 'RegEnumKeyEx')
            return space.wrap(rffi.charp2str(buf))
Example #2
0
def _operate(stream, data, flush, max_length, cfunc, while_doing):
    """Common code for compress() and decompress().
    """
    # Prepare the input buffer for the stream
    with lltype.scoped_alloc(rffi.CCHARP.TO, len(data)) as inbuf:
        for i in xrange(len(data)):
            inbuf[i] = data[i]
        stream.c_next_in = rffi.cast(Bytefp, inbuf)
        rffi.setintfield(stream, 'c_avail_in', len(data))

        # Prepare the output buffer
        with lltype.scoped_alloc(rffi.CCHARP.TO, OUTPUT_BUFFER_SIZE) as outbuf:
            # Strategy: we call deflate() to get as much output data as fits in
            # the buffer, then accumulate all output into a StringBuffer
            # 'result'.
            result = StringBuilder()

            while True:
                stream.c_next_out = rffi.cast(Bytefp, outbuf)
                bufsize = OUTPUT_BUFFER_SIZE
                if max_length < bufsize:
                    if max_length <= 0:
                        err = Z_OK
                        break
                    bufsize = max_length
                max_length -= bufsize
                rffi.setintfield(stream, 'c_avail_out', bufsize)
                err = cfunc(stream, flush)
                if err == Z_OK or err == Z_STREAM_END:
                    # accumulate data into 'result'
                    avail_out = rffi.cast(lltype.Signed, stream.c_avail_out)
                    result.append_charpsize(outbuf, bufsize - avail_out)
                    # if the output buffer is full, there might be more data
                    # so we need to try again.  Otherwise, we're done.
                    if avail_out > 0:
                        break
                    # We're also done if we got a Z_STREAM_END (which should
                    # only occur when flush == Z_FINISH).
                    if err == Z_STREAM_END:
                        break
                    else:
                        continue
                elif err == Z_BUF_ERROR:
                    avail_out = rffi.cast(lltype.Signed, stream.c_avail_out)
                    # When compressing, we will only get Z_BUF_ERROR if
                    # the output buffer was full but there wasn't more
                    # output when we tried again, so it is not an error
                    # condition.
                    if avail_out == bufsize:
                        break

                # fallback case: report this error
                raise RZlibError.fromstream(stream, err, while_doing)

    # When decompressing, if the compressed stream of data was truncated,
    # then the zlib simply returns Z_OK and waits for more.  If it is
    # complete it returns Z_STREAM_END.
    return (result.build(),
            err,
            rffi.cast(lltype.Signed, stream.c_avail_in))
Example #3
0
def QueryInfoKey(space, w_hkey):
    """tuple = QueryInfoKey(key) - Returns information about a key.

key is an already open key, or any one of the predefined HKEY_* constants.

The result is a tuple of 3 items:
An integer that identifies the number of sub keys this key has.
An integer that identifies the number of values this key has.
A long integer that identifies when the key was last modified (if available)
 as 100's of nanoseconds since Jan 1, 1600."""
    hkey = hkey_w(w_hkey, space)
    with lltype.scoped_alloc(rwin32.LPDWORD.TO, 1) as nSubKeys:
        with lltype.scoped_alloc(rwin32.LPDWORD.TO, 1) as nValues:
            with lltype.scoped_alloc(rwin32.PFILETIME.TO, 1) as ft:
                null_dword = lltype.nullptr(rwin32.LPDWORD.TO)
                ret = rwinreg.RegQueryInfoKey(
                    hkey, None, null_dword, null_dword,
                    nSubKeys, null_dword, null_dword,
                    nValues, null_dword, null_dword,
                    null_dword, ft)
                if ret != 0:
                    raiseWindowsError(space, ret, 'RegQueryInfoKey')
                l = ((lltype.r_longlong(ft[0].c_dwHighDateTime) << 32) +
                     lltype.r_longlong(ft[0].c_dwLowDateTime))
                return space.newtuple([space.wrap(nSubKeys[0]),
                                       space.wrap(nValues[0]),
                                       space.wrap(l)])
Example #4
0
def _decode_certificate(space, certificate, verbose=False):
    w_retval = space.newdict()

    w_peer = _create_tuple_for_X509_NAME(
        space, libssl_X509_get_subject_name(certificate))
    space.setitem(w_retval, space.wrap("subject"), w_peer)

    if verbose:
        w_issuer = _create_tuple_for_X509_NAME(
            space, libssl_X509_get_issuer_name(certificate))
        space.setitem(w_retval, space.wrap("issuer"), w_issuer)

        space.setitem(w_retval, space.wrap("version"),
                      space.wrap(libssl_X509_get_version(certificate)))

    biobuf = libssl_BIO_new(libssl_BIO_s_mem())
    try:

        if verbose:
            libssl_BIO_reset(biobuf)
            serialNumber = libssl_X509_get_serialNumber(certificate)
            libssl_i2a_ASN1_INTEGER(biobuf, serialNumber)
            # should not exceed 20 octets, 160 bits, so buf is big enough
            with lltype.scoped_alloc(rffi.CCHARP.TO, 100) as buf:
                length = libssl_BIO_gets(biobuf, buf, 99)
                if length < 0:
                    raise _ssl_seterror(space, None, length)

                w_serial = space.wrap(rffi.charpsize2str(buf, length))
            space.setitem(w_retval, space.wrap("serialNumber"), w_serial)

            libssl_BIO_reset(biobuf)
            notBefore = libssl_X509_get_notBefore(certificate)
            libssl_ASN1_TIME_print(biobuf, notBefore)
            with lltype.scoped_alloc(rffi.CCHARP.TO, 100) as buf:
                length = libssl_BIO_gets(biobuf, buf, 99)
                if length < 0:
                    raise _ssl_seterror(space, None, length)
                w_date = space.wrap(rffi.charpsize2str(buf, length))
            space.setitem(w_retval, space.wrap("notBefore"), w_date)

        libssl_BIO_reset(biobuf)
        notAfter = libssl_X509_get_notAfter(certificate)
        libssl_ASN1_TIME_print(biobuf, notAfter)
        with lltype.scoped_alloc(rffi.CCHARP.TO, 100) as buf:
            length = libssl_BIO_gets(biobuf, buf, 99)
            if length < 0:
                raise _ssl_seterror(space, None, length)
            w_date = space.wrap(rffi.charpsize2str(buf, length))
        space.setitem(w_retval, space.wrap("notAfter"), w_date)
    finally:
        libssl_BIO_free(biobuf)

    # Now look for subjectAltName
    w_alt_names = _get_peer_alt_names(space, certificate)
    if w_alt_names is not space.w_None:
        space.setitem(w_retval, space.wrap("subjectAltName"), w_alt_names)

    return w_retval
Example #5
0
def _decode_certificate(space, certificate, verbose=False):
    w_retval = space.newdict()

    w_peer = _create_tuple_for_X509_NAME(
        space, libssl_X509_get_subject_name(certificate))
    space.setitem(w_retval, space.wrap("subject"), w_peer)

    if verbose:
        w_issuer = _create_tuple_for_X509_NAME(
            space, libssl_X509_get_issuer_name(certificate))
        space.setitem(w_retval, space.wrap("issuer"), w_issuer)

        space.setitem(w_retval, space.wrap("version"),
                      space.wrap(libssl_X509_get_version(certificate)))

    biobuf = libssl_BIO_new(libssl_BIO_s_mem())
    try:

        if verbose:
            libssl_BIO_reset(biobuf)
            serialNumber = libssl_X509_get_serialNumber(certificate)
            libssl_i2a_ASN1_INTEGER(biobuf, serialNumber)
            # should not exceed 20 octets, 160 bits, so buf is big enough
            with lltype.scoped_alloc(rffi.CCHARP.TO, 100) as buf:
                length = libssl_BIO_gets(biobuf, buf, 99)
                if length < 0:
                    raise _ssl_seterror(space, None, length)

                w_serial = space.wrap(rffi.charpsize2str(buf, length))
            space.setitem(w_retval, space.wrap("serialNumber"), w_serial)

            libssl_BIO_reset(biobuf)
            notBefore = libssl_X509_get_notBefore(certificate)
            libssl_ASN1_TIME_print(biobuf, notBefore)
            with lltype.scoped_alloc(rffi.CCHARP.TO, 100) as buf:
                length = libssl_BIO_gets(biobuf, buf, 99)
                if length < 0:
                    raise _ssl_seterror(space, None, length)
                w_date = space.wrap(rffi.charpsize2str(buf, length))
            space.setitem(w_retval, space.wrap("notBefore"), w_date)

        libssl_BIO_reset(biobuf)
        notAfter = libssl_X509_get_notAfter(certificate)
        libssl_ASN1_TIME_print(biobuf, notAfter)
        with lltype.scoped_alloc(rffi.CCHARP.TO, 100) as buf:
            length = libssl_BIO_gets(biobuf, buf, 99)
            if length < 0:
                raise _ssl_seterror(space, None, length)
            w_date = space.wrap(rffi.charpsize2str(buf, length))
        space.setitem(w_retval, space.wrap("notAfter"), w_date)
    finally:
        libssl_BIO_free(biobuf)

    # Now look for subjectAltName
    w_alt_names = _get_peer_alt_names(space, certificate)
    if w_alt_names is not space.w_None:
        space.setitem(w_retval, space.wrap("subjectAltName"), w_alt_names)

    return w_retval
Example #6
0
def _operate(stream, data, flush, max_length, cfunc, while_doing):
    """Common code for compress() and decompress().
    """
    # Prepare the input buffer for the stream
    with lltype.scoped_alloc(rffi.CCHARP.TO, len(data)) as inbuf:
        for i in xrange(len(data)):
            inbuf[i] = data[i]
        stream.c_next_in = rffi.cast(Bytefp, inbuf)
        rffi.setintfield(stream, 'c_avail_in', len(data))

        # Prepare the output buffer
        with lltype.scoped_alloc(rffi.CCHARP.TO, OUTPUT_BUFFER_SIZE) as outbuf:
            # Strategy: we call deflate() to get as much output data as fits in
            # the buffer, then accumulate all output into a StringBuffer
            # 'result'.
            result = StringBuilder()

            while True:
                stream.c_next_out = rffi.cast(Bytefp, outbuf)
                bufsize = OUTPUT_BUFFER_SIZE
                if max_length < bufsize:
                    if max_length <= 0:
                        err = Z_OK
                        break
                    bufsize = max_length
                max_length -= bufsize
                rffi.setintfield(stream, 'c_avail_out', bufsize)
                err = cfunc(stream, flush)
                if err == Z_OK or err == Z_STREAM_END:
                    # accumulate data into 'result'
                    avail_out = rffi.cast(lltype.Signed, stream.c_avail_out)
                    result.append_charpsize(outbuf, bufsize - avail_out)
                    # if the output buffer is full, there might be more data
                    # so we need to try again.  Otherwise, we're done.
                    if avail_out > 0:
                        break
                    # We're also done if we got a Z_STREAM_END (which should
                    # only occur when flush == Z_FINISH).
                    if err == Z_STREAM_END:
                        break
                    else:
                        continue
                elif err == Z_BUF_ERROR:
                    avail_out = rffi.cast(lltype.Signed, stream.c_avail_out)
                    # When compressing, we will only get Z_BUF_ERROR if
                    # the output buffer was full but there wasn't more
                    # output when we tried again, so it is not an error
                    # condition.
                    if avail_out == bufsize:
                        break

                # fallback case: report this error
                raise RZlibError.fromstream(stream, err, while_doing)

    # When decompressing, if the compressed stream of data was truncated,
    # then the zlib simply returns Z_OK and waits for more.  If it is
    # complete it returns Z_STREAM_END.
    return (result.build(), err, rffi.cast(lltype.Signed, stream.c_avail_in))
Example #7
0
 def _digest(self, space):
     with lltype.scoped_alloc(ropenssl.EVP_MD_CTX.TO) as ctx:
         with self.lock:
             ropenssl.EVP_MD_CTX_copy(ctx, self.ctx)
         digest_size = self.digest_size
         with lltype.scoped_alloc(rffi.CCHARP.TO, digest_size) as digest:
             ropenssl.EVP_DigestFinal(ctx, digest, None)
             ropenssl.EVP_MD_CTX_cleanup(ctx)
             return rffi.charpsize2str(digest, digest_size)
Example #8
0
 def _digest(self, space):
     with lltype.scoped_alloc(ropenssl.EVP_MD_CTX.TO) as ctx:
         with self.lock:
             ropenssl.EVP_MD_CTX_copy(ctx, self.ctx)
         digest_size = self.digest_size
         with lltype.scoped_alloc(rffi.CCHARP.TO, digest_size) as digest:
             ropenssl.EVP_DigestFinal(ctx, digest, None)
             ropenssl.EVP_MD_CTX_cleanup(ctx)
             return rffi.charpsize2str(digest, digest_size)
Example #9
0
 def main(n):
     with lltype.scoped_alloc(rffi.CArray(POINT), n) as points:
         with lltype.scoped_alloc(rffi.CArray(POINT), 1) as result_point:
             for i in xrange(n):
                 points[i].x = i * 2
                 points[i].y = i * 2 + 1
             points = rffi.cast(rffi.CArrayPtr(lltype.Char), points)
             result_point[0].x = 0
             result_point[0].y = 0
             result_point = rffi.cast(rffi.CArrayPtr(lltype.Char), result_point)
             f(points, result_point, n)
             result_point = rffi.cast(rffi.CArrayPtr(POINT), result_point)
             return result_point[0].x * result_point[0].y
Example #10
0
def setitimer(space, which, first, interval=0):
    with lltype.scoped_alloc(itimervalP.TO, 1) as new:

        timeval_from_double(first, new[0].c_it_value)
        timeval_from_double(interval, new[0].c_it_interval)

        with lltype.scoped_alloc(itimervalP.TO, 1) as old:

            ret = c_setitimer(which, new, old)
            if ret != 0:
                raise exception_from_errno(space, get_itimer_error(space))

            return itimer_retval(space, old[0])
Example #11
0
def setitimer(space, which, first, interval=0):
    with lltype.scoped_alloc(itimervalP.TO, 1) as new:

        timeval_from_double(first, new[0].c_it_value)
        timeval_from_double(interval, new[0].c_it_interval)

        with lltype.scoped_alloc(itimervalP.TO, 1) as old:

            ret = c_setitimer(which, new, old)
            if ret != 0:
                raise exception_from_errno(space, get_itimer_error(space))


            return itimer_retval(space, old[0])
Example #12
0
def _create_tuple_for_attribute(space, name, value):
    with lltype.scoped_alloc(rffi.CCHARP.TO, X509_NAME_MAXLEN) as buf:
        length = libssl_OBJ_obj2txt(buf, X509_NAME_MAXLEN, name, 0)
        if length < 0:
            raise _ssl_seterror(space, None, 0)
        w_name = space.wrap(rffi.charpsize2str(buf, length))

    with lltype.scoped_alloc(rffi.CCHARPP.TO, 1) as buf_ptr:
        length = libssl_ASN1_STRING_to_UTF8(buf_ptr, value)
        if length < 0:
            raise _ssl_seterror(space, None, 0)
        w_value = space.wrap(rffi.charpsize2str(buf_ptr[0], length))
        w_value = space.call_method(w_value, "decode", space.wrap("utf-8"))

    return space.newtuple([w_name, w_value])
Example #13
0
def _create_tuple_for_attribute(space, name, value):
    with lltype.scoped_alloc(rffi.CCHARP.TO, X509_NAME_MAXLEN) as buf:
        length = libssl_OBJ_obj2txt(buf, X509_NAME_MAXLEN, name, 0)
        if length < 0:
            raise _ssl_seterror(space, None, 0)
        w_name = space.wrap(rffi.charpsize2str(buf, length))

    with lltype.scoped_alloc(rffi.CCHARPP.TO, 1) as buf_ptr:
        length = libssl_ASN1_STRING_to_UTF8(buf_ptr, value)
        if length < 0:
            raise _ssl_seterror(space, None, 0)
        w_value = space.wrap(rffi.charpsize2str(buf_ptr[0], length))
        w_value = space.call_method(w_value, "decode", space.wrap("utf-8"))

    return space.newtuple([w_name, w_value])
Example #14
0
 def main(n):
     with lltype.scoped_alloc(rffi.CArray(POINT), n) as points:
         with lltype.scoped_alloc(rffi.CArray(POINT),
                                  1) as result_point:
             for i in xrange(n):
                 points[i].x = i * 2
                 points[i].y = i * 2 + 1
             points = rffi.cast(rffi.CArrayPtr(lltype.Char), points)
             result_point[0].x = 0
             result_point[0].y = 0
             result_point = rffi.cast(rffi.CArrayPtr(lltype.Char),
                                      result_point)
             f(points, result_point, n)
             result_point = rffi.cast(rffi.CArrayPtr(POINT),
                                      result_point)
             return result_point[0].x * result_point[0].y
Example #15
0
    def peer_certificate(self, der=False):
        """peer_certificate([der=False]) -> certificate

        Returns the certificate for the peer.  If no certificate was provided,
        returns None.  If a certificate was provided, but not validated, returns
        an empty dictionary.  Otherwise returns a dict containing information
        about the peer certificate.

        If the optional argument is True, returns a DER-encoded copy of the
        peer certificate, or None if no certificate was provided.  This will
        return the certificate even if it wasn't validated."""
        if not self.peer_cert:
            return self.space.w_None

        if der:
            # return cert in DER-encoded format
            with lltype.scoped_alloc(rffi.CCHARPP.TO, 1) as buf_ptr:
                buf_ptr[0] = lltype.nullptr(rffi.CCHARP.TO)
                length = libssl_i2d_X509(self.peer_cert, buf_ptr)
                if length < 0:
                    raise _ssl_seterror(self.space, self, length)
                try:
                    # this is actually an immutable bytes sequence
                    return self.space.wrap(rffi.charp2str(buf_ptr[0]))
                finally:
                    libssl_OPENSSL_free(buf_ptr[0])
        else:
            verification = libssl_SSL_CTX_get_verify_mode(
                libssl_SSL_get_SSL_CTX(self.ssl))
            if not verification & SSL_VERIFY_PEER:
                return self.space.newdict()
            else:
                return _decode_certificate(self.space, self.peer_cert)
Example #16
0
    def _sem_timedwait_save(sem, deadline):
        delay = 0
        void = lltype.nullptr(rffi.VOIDP.TO)
        with lltype.scoped_alloc(TIMEVALP.TO, 1) as tvdeadline:
            while True:
                # poll
                if _sem_trywait(sem) == 0:
                    return 0
                elif rposix.get_errno() != errno.EAGAIN:
                    return -1

                now = gettimeofday()
                c_tv_sec = rffi.getintfield(deadline[0], 'c_tv_sec')
                c_tv_nsec = rffi.getintfield(deadline[0], 'c_tv_nsec')
                if (c_tv_sec < now[0]
                        or (c_tv_sec == now[0] and c_tv_nsec <= now[1])):
                    rposix.set_errno(errno.ETIMEDOUT)
                    return -1

                # calculate how much time is left
                difference = ((c_tv_sec - now[0]) * 1000000 +
                              (c_tv_nsec - now[1]))

                # check delay not too long -- maximum is 20 msecs
                if delay > 20000:
                    delay = 20000
                if delay > difference:
                    delay = difference
                delay += 1000

                # sleep
                rffi.setintfield(tvdeadline[0], 'c_tv_sec', delay / 1000000)
                rffi.setintfield(tvdeadline[0], 'c_tv_usec', delay % 1000000)
                if _select(0, void, void, void, tvdeadline) < 0:
                    return -1
Example #17
0
    def peer_certificate(self, der=False):
        """peer_certificate([der=False]) -> certificate

        Returns the certificate for the peer.  If no certificate was provided,
        returns None.  If a certificate was provided, but not validated, returns
        an empty dictionary.  Otherwise returns a dict containing information
        about the peer certificate.

        If the optional argument is True, returns a DER-encoded copy of the
        peer certificate, or None if no certificate was provided.  This will
        return the certificate even if it wasn't validated."""
        if not self.peer_cert:
            return self.space.w_None

        if der:
            # return cert in DER-encoded format
            with lltype.scoped_alloc(rffi.CCHARPP.TO, 1) as buf_ptr:
                buf_ptr[0] = lltype.nullptr(rffi.CCHARP.TO)
                length = libssl_i2d_X509(self.peer_cert, buf_ptr)
                if length < 0:
                    raise _ssl_seterror(self.space, self, length)
                try:
                    # this is actually an immutable bytes sequence
                    return self.space.wrap(rffi.charp2str(buf_ptr[0]))
                finally:
                    libssl_OPENSSL_free(buf_ptr[0])
        else:
            verification = libssl_SSL_CTX_get_verify_mode(
                libssl_SSL_get_SSL_CTX(self.ssl))
            if not verification & SSL_VERIFY_PEER:
                return self.space.newdict()
            else:
                return _decode_certificate(self.space, self.peer_cert)
Example #18
0
def setupterm_func(vm):
    mod = vm.get_funcs_mod()
    (term_o, file_o), _ = vm.decode_args(opt="sO")
    
    if HAVE_CURSES:
        if term_o:
            assert isinstance(term_o, Con_String)
            raise Exception("XXX")
        else:
            term = None

        if file_o:
            fd = type_check_int(vm, vm.get_slot_apply(file_o, "fileno")).v
        else:
            fd = STDOUT_FILENO

        with lltype.scoped_alloc(rffi.INTP.TO, 1) as erret:
            if setupterm(term, fd, erret) != OK:
                ec = int(erret[0])
                if ec == -1:
                    msg = "Can't find terminfo database."
                elif ec == 0:
                    msg = "Terminal not found or not enough information known about it."
                elif ec == 1:
                    msg = "Terminal is hardcopy."
                else:
                    raise Exception("XXX")

                cex_class = mod.get_defn(vm, "Curses_Exception")
                vm.raise_(vm.get_slot_apply(cex_class, "new", [Con_String(vm, msg)]))
    else:
        raise Exception("XXX")
    
    return vm.get_builtin(BUILTIN_NULL_OBJ)
Example #19
0
    def descr_poll(self, space, timeout=-1.0, maxevents=-1):
        self.check_closed(space)
        if timeout < 0:
            timeout = -1.0
        else:
            timeout *= 1000.0

        if maxevents == -1:
            maxevents = FD_SETSIZE - 1
        elif maxevents < 1:
            raise operationerrfmt(space.w_ValueError,
                                  "maxevents must be greater than 0, not %d",
                                  maxevents)

        with lltype.scoped_alloc(rffi.CArray(epoll_event), maxevents) as evs:
            nfds = epoll_wait(self.epfd, evs, maxevents, int(timeout))
            if nfds < 0:
                raise exception_from_errno(space, space.w_IOError)

            elist_w = [None] * nfds
            for i in xrange(nfds):
                event = evs[i]
                elist_w[i] = space.newtuple([
                    space.wrap(event.c_data.c_fd),
                    space.wrap(event.c_events)
                ])
            return space.newlist(elist_w)
Example #20
0
    def descr_poll(self, space, timeout=-1.0, maxevents=-1):
        self.check_closed(space)
        if timeout < 0:
            timeout = -1.0
        else:
            timeout *= 1000.0

        if maxevents == -1:
            maxevents = FD_SETSIZE - 1
        elif maxevents < 1:
            raise operationerrfmt(space.w_ValueError,
                "maxevents must be greater than 0, not %d", maxevents
            )

        with lltype.scoped_alloc(rffi.CArray(epoll_event), maxevents) as evs:
            nfds = epoll_wait(self.epfd, evs, maxevents, int(timeout))
            if nfds < 0:
                raise exception_from_errno(space, space.w_IOError)

            elist_w = [None] * nfds
            for i in xrange(nfds):
                event = evs[i]
                elist_w[i] = space.newtuple(
                    [space.wrap(event.c_data.c_fd), space.wrap(event.c_events)]
                )
            return space.newlist(elist_w)
Example #21
0
def File_read(vm):
    (self, rsize_o),_ = vm.decode_args(mand="!", opt="I", self_of=File)
    assert isinstance(self, File)
    _check_open(vm, self)
    
    flockfile(self.filep)
    fsize = os.fstat(fileno(self.filep)).st_size
    if rsize_o is None:
        rsize = fsize
    else:
        assert isinstance(rsize_o, Con_Int)
        rsize = rsize_o.v
        if rsize < 0:
            vm.raise_helper("File_Exception", \
              [Con_String(vm, "Can not read less than 0 bytes from file.")])
        elif rsize > fsize:
            rsize = fsize

    if objectmodel.we_are_translated():
        with lltype.scoped_alloc(rffi.CCHARP.TO, rsize) as buf:
            r = fread(buf, 1, rsize, self.filep)
            if r < rffi.r_size_t(rsize) and ferror(self.filep) != 0:
                vm.raise_helper("File_Exception", [Con_String(vm, "Read error.")])
            s = rffi.charpsize2str(buf, rarithmetic.intmask(r))
    else:
        # rffi.charpsize2str is so slow (taking minutes for big strings) that it's worth bypassing
        # it when things are run untranslated.
        s = os.read(fileno(self.filep), rsize)
    funlockfile(self.filep)

    return Con_String(vm, s)
Example #22
0
def wrap_getreadbuffer(space, w_self, w_args, func):
    func_target = rffi.cast(readbufferproc, func)
    with lltype.scoped_alloc(rffi.VOIDPP.TO, 1) as ptr:
        index = rffi.cast(Py_ssize_t, 0)
        size = generic_cpy_call(space, func_target, w_self, index, ptr)
        if size < 0:
            space.fromcache(State).check_and_raise_exception(always=True)
        return space.wrap(CPyBuffer(ptr[0], size, w_self))
Example #23
0
def wrap_getreadbuffer(space, w_self, w_args, func):
    func_target = rffi.cast(readbufferproc, func)
    with lltype.scoped_alloc(rffi.VOIDPP.TO, 1) as ptr:
        index = rffi.cast(Py_ssize_t, 0)
        size = generic_cpy_call(space, func_target, w_self, index, ptr)
        if size < 0:
            space.fromcache(State).check_and_raise_exception(always=True)
        return space.wrap(CPyBuffer(ptr[0], size, w_self))
Example #24
0
def compress(space, data, compresslevel=9):
    """compress(data [, compresslevel=9]) -> string

    Compress data in one shot. If you want to compress data sequentially,
    use an instance of BZ2Compressor instead. The compresslevel parameter, if
    given, must be a number between 1 and 9."""

    if compresslevel < 1 or compresslevel > 9:
        raise OperationError(
            space.w_ValueError,
            space.wrap("compresslevel must be between 1 and 9"))

    with lltype.scoped_alloc(bz_stream.TO, zero=True) as bzs:
        in_bufsize = len(data)

        with lltype.scoped_alloc(rffi.CCHARP.TO, in_bufsize) as in_buf:
            for i in range(in_bufsize):
                in_buf[i] = data[i]
            bzs.c_next_in = in_buf
            rffi.setintfield(bzs, 'c_avail_in', in_bufsize)

            # conforming to bz2 manual, this is large enough to fit compressed
            # data in one shot. We will check it later anyway.
            with OutBuffer(bzs,
                           in_bufsize + (in_bufsize / 100 + 1) + 600) as out:

                bzerror = BZ2_bzCompressInit(bzs, compresslevel, 0, 0)
                if bzerror != BZ_OK:
                    _catch_bz2_error(space, bzerror)

                while True:
                    bzerror = BZ2_bzCompress(bzs, BZ_FINISH)
                    if bzerror == BZ_STREAM_END:
                        break
                    elif bzerror != BZ_FINISH_OK:
                        BZ2_bzCompressEnd(bzs)
                        _catch_bz2_error(space, bzerror)

                    if rffi.getintfield(bzs, 'c_avail_out') == 0:
                        out.prepare_next_chunk()

                res = out.make_result_string()
                BZ2_bzCompressEnd(bzs)
                return space.wrap(res)
Example #25
0
def current(vm):
    _,_ = vm.decode_args()

    with lltype.scoped_alloc(TIMEVAL) as tp:
        if gettimeofday(tp, lltype.nullptr(TIMEZONEP.TO)) != 0:
            raise Exception("XXX")
        sec = rarithmetic.r_int(tp.c_tv_sec)
        usec = rarithmetic.r_int(tp.c_tv_usec)

    return Con_List(vm, [Con_Int(vm, sec), Con_Int(vm, usec * 1000)])
Example #26
0
 def test_cmp(self, space, api):
     w = space.wrap
     with lltype.scoped_alloc(rffi.INTP.TO, 1) as ptr:
         assert api.PyObject_Cmp(w(42), w(72), ptr) == 0
         assert ptr[0] == -1
         assert api.PyObject_Cmp(w("a"), w("a"), ptr) == 0
         assert ptr[0] == 0
         assert api.PyObject_Cmp(w(u"\xe9"), w("\xe9"), ptr) < 0
         assert api.PyErr_Occurred()
         api.PyErr_Clear()
Example #27
0
def compress(space, data, compresslevel=9):
    """compress(data [, compresslevel=9]) -> string

    Compress data in one shot. If you want to compress data sequentially,
    use an instance of BZ2Compressor instead. The compresslevel parameter, if
    given, must be a number between 1 and 9."""

    if compresslevel < 1 or compresslevel > 9:
        raise OperationError(space.w_ValueError,
            space.wrap("compresslevel must be between 1 and 9"))

    with lltype.scoped_alloc(bz_stream.TO, zero=True) as bzs:
        in_bufsize = len(data)

        with lltype.scoped_alloc(rffi.CCHARP.TO, in_bufsize) as in_buf:
            for i in range(in_bufsize):
                in_buf[i] = data[i]
            bzs.c_next_in = in_buf
            rffi.setintfield(bzs, 'c_avail_in', in_bufsize)

            # conforming to bz2 manual, this is large enough to fit compressed
            # data in one shot. We will check it later anyway.
            with OutBuffer(bzs,
                           in_bufsize + (in_bufsize / 100 + 1) + 600) as out:

                bzerror = BZ2_bzCompressInit(bzs, compresslevel, 0, 0)
                if bzerror != BZ_OK:
                    _catch_bz2_error(space, bzerror)

                while True:
                    bzerror = BZ2_bzCompress(bzs, BZ_FINISH)
                    if bzerror == BZ_STREAM_END:
                        break
                    elif bzerror != BZ_FINISH_OK:
                        BZ2_bzCompressEnd(bzs)
                        _catch_bz2_error(space, bzerror)

                    if rffi.getintfield(bzs, 'c_avail_out') == 0:
                        out.prepare_next_chunk()

                res = out.make_result_string()
                BZ2_bzCompressEnd(bzs)
                return space.wrap(res)
Example #28
0
def current_mono(vm):
    _,_ = vm.decode_args()

    with lltype.scoped_alloc(TIMESPEC) as ts:
        if clock_gettime(CLOCK_MONOTONIC, ts) != 0:
            raise Exception("XXX")
        sec = rarithmetic.r_int(ts.c_tv_sec)
        nsec = rarithmetic.r_int(ts.c_tv_nsec)

    return Con_List(vm, [Con_Int(vm, sec), Con_Int(vm, nsec)])
Example #29
0
 def test_cmp(self, space, api):
     w = space.wrap
     with lltype.scoped_alloc(rffi.INTP.TO, 1) as ptr:
         assert api.PyObject_Cmp(w(42), w(72), ptr) == 0
         assert ptr[0] == -1
         assert api.PyObject_Cmp(w("a"), w("a"), ptr) == 0
         assert ptr[0] == 0
         assert api.PyObject_Cmp(w(u"\xe9"), w("\xe9"), ptr) < 0
         assert api.PyErr_Occurred()
         api.PyErr_Clear()
Example #30
0
    def epoll_ctl(self, space, ctl, w_fd, eventmask, ignore_ebadf=False):
        fd = space.c_filedescriptor_w(w_fd)
        with lltype.scoped_alloc(epoll_event) as ev:
            ev.c_events = rffi.cast(rffi.UINT, eventmask)
            rffi.setintfield(ev.c_data, "c_fd", fd)

            result = epoll_ctl(self.epfd, ctl, fd, ev)
            if ignore_ebadf and get_errno() == errno.EBADF:
                result = 0
            if result < 0:
                raise exception_from_errno(space, space.w_IOError)
Example #31
0
    def epoll_ctl(self, space, ctl, w_fd, eventmask, ignore_ebadf=False):
        fd = space.c_filedescriptor_w(w_fd)
        with lltype.scoped_alloc(epoll_event) as ev:
            ev.c_events = rffi.cast(rffi.UINT, eventmask)
            rffi.setintfield(ev.c_data, 'c_fd', fd)

            result = epoll_ctl(self.epfd, ctl, fd, ev)
            if ignore_ebadf and get_errno() == errno.EBADF:
                result = 0
            if result < 0:
                raise exception_from_errno(space, space.w_IOError)
Example #32
0
def canon_path(vm):
    (p_o,),_ = vm.decode_args("S")
    assert isinstance(p_o, Con_String)

    with lltype.scoped_alloc(rffi.CCHARP.TO, PATH_MAX) as resolved:
        r = realpath(p_o.v, resolved)
        if not r:
            _errno_raise(vm, p_o)
        rp = rffi.charpsize2str(resolved, rarithmetic.intmask(strlen(resolved)))

    return Con_String(vm, rp)
Example #33
0
def decompress(space, data):
    """decompress(data) -> decompressed data

    Decompress data in one shot. If you want to decompress data sequentially,
    use an instance of BZ2Decompressor instead."""

    in_bufsize = len(data)
    if in_bufsize == 0:
        return space.wrap("")

    with lltype.scoped_alloc(bz_stream.TO, zero=True) as bzs:
        with lltype.scoped_alloc(rffi.CCHARP.TO, in_bufsize) as in_buf:
            for i in range(in_bufsize):
                in_buf[i] = data[i]
            bzs.c_next_in = in_buf
            rffi.setintfield(bzs, 'c_avail_in', in_bufsize)

            with OutBuffer(bzs) as out:
                bzerror = BZ2_bzDecompressInit(bzs, 0, 0)
                if bzerror != BZ_OK:
                    _catch_bz2_error(space, bzerror)

                while True:
                    bzerror = BZ2_bzDecompress(bzs)
                    if bzerror == BZ_STREAM_END:
                        break
                    if bzerror != BZ_OK:
                        BZ2_bzDecompressEnd(bzs)
                    _catch_bz2_error(space, bzerror)

                    if rffi.getintfield(bzs, 'c_avail_in') == 0:
                        BZ2_bzDecompressEnd(bzs)
                        raise OperationError(
                            space.w_ValueError,
                            space.wrap("couldn't find end of stream"))
                    elif rffi.getintfield(bzs, 'c_avail_out') == 0:
                        out.prepare_next_chunk()

                res = out.make_result_string()
                BZ2_bzDecompressEnd(bzs)
                return space.wrap(res)
Example #34
0
def decompress(space, data):
    """decompress(data) -> decompressed data

    Decompress data in one shot. If you want to decompress data sequentially,
    use an instance of BZ2Decompressor instead."""

    in_bufsize = len(data)
    if in_bufsize == 0:
        return space.wrap("")

    with lltype.scoped_alloc(bz_stream.TO, zero=True) as bzs:
        with lltype.scoped_alloc(rffi.CCHARP.TO, in_bufsize) as in_buf:
            for i in range(in_bufsize):
                in_buf[i] = data[i]
            bzs.c_next_in = in_buf
            rffi.setintfield(bzs, 'c_avail_in', in_bufsize)

            with OutBuffer(bzs) as out:
                bzerror = BZ2_bzDecompressInit(bzs, 0, 0)
                if bzerror != BZ_OK:
                    _catch_bz2_error(space, bzerror)

                while True:
                    bzerror = BZ2_bzDecompress(bzs)
                    if bzerror == BZ_STREAM_END:
                        break
                    if bzerror != BZ_OK:
                        BZ2_bzDecompressEnd(bzs)
                    _catch_bz2_error(space, bzerror)

                    if rffi.getintfield(bzs, 'c_avail_in') == 0:
                        BZ2_bzDecompressEnd(bzs)
                        raise OperationError(space.w_ValueError, space.wrap(
                            "couldn't find end of stream"))
                    elif rffi.getintfield(bzs, 'c_avail_out') == 0:
                        out.prepare_next_chunk()

                res = out.make_result_string()
                BZ2_bzDecompressEnd(bzs)
                return space.wrap(res)
Example #35
0
def QueryValueEx(space, w_hkey, w_subkey):
    """value,type_id = QueryValueEx(key, value_name) - Retrieves the type and data for a specified value name associated with an open registry key.

key is an already open key, or any one of the predefined HKEY_* constants.
value_name is a string indicating the value to query"""
    hkey = hkey_w(w_hkey, space)
    if space.is_w(w_subkey, space.w_None):
        subkey = None
    else:
        subkey = space.str_w(w_subkey)
    null_dword = lltype.nullptr(rwin32.LPDWORD.TO)
    with lltype.scoped_alloc(rwin32.LPDWORD.TO, 1) as retDataSize:
        ret = rwinreg.RegQueryValueEx(hkey, subkey, null_dword, null_dword,
                                      None, retDataSize)
        bufSize = intmask(retDataSize[0])
        if ret == rwinreg.ERROR_MORE_DATA:
            bufSize = 256
        elif ret != 0:
            raiseWindowsError(space, ret, 'RegQueryValueEx')

        while True:
            with lltype.scoped_alloc(rffi.CCHARP.TO, bufSize) as databuf:
                with lltype.scoped_alloc(rwin32.LPDWORD.TO, 1) as retType:

                    ret = rwinreg.RegQueryValueEx(hkey, subkey, null_dword,
                                                  retType, databuf, retDataSize)
                    if ret == rwinreg.ERROR_MORE_DATA:
                        # Resize and retry
                        bufSize *= 2
                        retDataSize[0] = rffi.cast(rwin32.DWORD, bufSize)
                        continue
                    if ret != 0:
                        raiseWindowsError(space, ret, 'RegQueryValueEx')
                    length = intmask(retDataSize[0])
                    return space.newtuple([
                        convert_from_regdata(space, databuf,
                                             length, retType[0]),
                        space.wrap(retType[0]),
                        ])
Example #36
0
def File_readln(vm):
    (self,),_ = vm.decode_args(mand="!", self_of=File)
    assert isinstance(self, File)
    _check_open(vm, self)
    
    while 1:
        with lltype.scoped_alloc(rffi.SIZE_TP.TO, 1) as lenp:
            l = fgetln(self.filep, lenp)
            if not l:
                if feof(self.filep) != 0:
                    break
                _errno_raise(vm, self.get_slot(vm, "path"))
            l_o = Con_String(vm, rffi.charpsize2str(l, rarithmetic.intmask(lenp[0])))
            yield l_o
Example #37
0
def QueryValue(space, w_hkey, w_subkey):
    """string = QueryValue(key, sub_key) - retrieves the unnamed value for a key.

key is an already open key, or any one of the predefined HKEY_* constants.
sub_key is a string that holds the name of the subkey with which the value
 is associated.  If this parameter is None or empty, the function retrieves
 the value set by the SetValue() method for the key identified by key.

Values in the registry have name, type, and data components. This method
retrieves the data for a key's first value that has a NULL name.
But the underlying API call doesn't return the type, Lame Lame Lame, DONT USE THIS!!!"""
    hkey = hkey_w(w_hkey, space)
    if space.is_w(w_subkey, space.w_None):
        subkey = None
    else:
        subkey = space.str_w(w_subkey)
    with lltype.scoped_alloc(rwin32.PLONG.TO, 1) as bufsize_p:
        ret = rwinreg.RegQueryValue(hkey, subkey, None, bufsize_p)
        bufSize = intmask(bufsize_p[0])
        if ret == rwinreg.ERROR_MORE_DATA:
            bufSize = 256
        elif ret != 0:
            raiseWindowsError(space, ret, 'RegQueryValue')

        while True:
            with lltype.scoped_alloc(rffi.CCHARP.TO, bufSize) as buf:
                ret = rwinreg.RegQueryValue(hkey, subkey, buf, bufsize_p)
                if ret == rwinreg.ERROR_MORE_DATA:
                    # Resize and retry
                    bufSize *= 2
                    bufsize_p[0] = bufSize
                    continue

                if ret != 0:
                    raiseWindowsError(space, ret, 'RegQueryValue')
                length = intmask(bufsize_p[0] - 1)
                return space.wrap(rffi.charp2strn(buf, length))
Example #38
0
    def do_recv_string(self, space, buflength, maxlength):
        with lltype.scoped_alloc(rffi.CArrayPtr(rffi.UINT).TO, 1) as length_ptr:
            self._recvall(space, rffi.cast(rffi.CCHARP, length_ptr), 4)
            length = intmask(length_ptr[0])
        if length > maxlength:  # bad message, close connection
            self.flags &= ~READABLE
            if self.flags == 0:
                self.close()
            raise OperationError(space.w_IOError, space.wrap("bad message length"))

        if length <= buflength:
            self._recvall(space, self.buffer, length)
            return length, lltype.nullptr(rffi.CCHARP.TO)
        else:
            newbuf = lltype.malloc(rffi.CCHARP.TO, length, flavor="raw")
            self._recvall(space, newbuf, length)
            return length, newbuf
Example #39
0
def OpenKey(space, w_hkey, subkey, res=0, sam=rwinreg.KEY_READ):
    """key = OpenKey(key, sub_key, res = 0, sam = KEY_READ) - Opens the specified key.

key is an already open key, or any one of the predefined HKEY_* constants.
sub_key is a string that identifies the sub_key to open
res is a reserved integer, and must be zero.  Default is zero.
sam is an integer that specifies an access mask that describes the desired
 security access for the key.  Default is KEY_READ

The result is a new handle to the specified key
If the function fails, an EnvironmentError exception is raised."""
    hkey = hkey_w(w_hkey, space)
    with lltype.scoped_alloc(rwinreg.PHKEY.TO, 1) as rethkey:
        ret = rwinreg.RegOpenKeyEx(hkey, subkey, res, sam, rethkey)
        if ret != 0:
            raiseWindowsError(space, ret, 'RegOpenKeyEx')
        return space.wrap(W_HKEY(rethkey[0]))
Example #40
0
    def decompress(self, data):
        """decompress(data) -> string

        Provide more data to the decompressor object. It will return chunks
        of decompressed data whenever possible. If you try to decompress data
        after the end of stream is found, EOFError will be raised. If any data
        was found after the end of stream, it'll be ignored and saved in
        unused_data attribute."""

        if data == '':
            return self.space.wrap('')
        if not self.running:
            raise OperationError(
                self.space.w_EOFError,
                self.space.wrap("end of stream was already found"))

        in_bufsize = len(data)

        with lltype.scoped_alloc(rffi.CCHARP.TO, in_bufsize) as in_buf:
            for i in range(in_bufsize):
                in_buf[i] = data[i]
            self.bzs.c_next_in = in_buf
            rffi.setintfield(self.bzs, 'c_avail_in', in_bufsize)

            with OutBuffer(self.bzs) as out:
                while True:
                    bzerror = BZ2_bzDecompress(self.bzs)
                    if bzerror == BZ_STREAM_END:
                        if rffi.getintfield(self.bzs, 'c_avail_in') != 0:
                            unused = [
                                self.bzs.c_next_in[i] for i in range(
                                    rffi.getintfield(self.bzs, 'c_avail_in'))
                            ]
                            self.unused_data = "".join(unused)
                        self.running = False
                        break
                    if bzerror != BZ_OK:
                        _catch_bz2_error(self.space, bzerror)

                    if rffi.getintfield(self.bzs, 'c_avail_in') == 0:
                        break
                    elif rffi.getintfield(self.bzs, 'c_avail_out') == 0:
                        out.prepare_next_chunk()

                res = out.make_result_string()
                return self.space.wrap(res)
Example #41
0
    def decompress(self, data):
        """decompress(data) -> string

        Provide more data to the decompressor object. It will return chunks
        of decompressed data whenever possible. If you try to decompress data
        after the end of stream is found, EOFError will be raised. If any data
        was found after the end of stream, it'll be ignored and saved in
        unused_data attribute."""

        if data == '':
            return self.space.wrap('')
        if not self.running:
            raise OperationError(self.space.w_EOFError,
                self.space.wrap("end of stream was already found"))

        in_bufsize = len(data)

        with lltype.scoped_alloc(rffi.CCHARP.TO, in_bufsize) as in_buf:
            for i in range(in_bufsize):
                in_buf[i] = data[i]
            self.bzs.c_next_in = in_buf
            rffi.setintfield(self.bzs, 'c_avail_in', in_bufsize)

            with OutBuffer(self.bzs) as out:
                while True:
                    bzerror = BZ2_bzDecompress(self.bzs)
                    if bzerror == BZ_STREAM_END:
                        if rffi.getintfield(self.bzs, 'c_avail_in') != 0:
                            unused = [self.bzs.c_next_in[i]
                                      for i in range(
                                          rffi.getintfield(self.bzs,
                                                           'c_avail_in'))]
                            self.unused_data = "".join(unused)
                        self.running = False
                        break
                    if bzerror != BZ_OK:
                        _catch_bz2_error(self.space, bzerror)

                    if rffi.getintfield(self.bzs, 'c_avail_in') == 0:
                        break
                    elif rffi.getintfield(self.bzs, 'c_avail_out') == 0:
                        out.prepare_next_chunk()

                res = out.make_result_string()
                return self.space.wrap(res)
Example #42
0
def ConnectRegistry(space, w_machine, w_hkey):
    """key = ConnectRegistry(computer_name, key)

Establishes a connection to a predefined registry handle on another computer.

computer_name is the name of the remote computer, of the form \\\\computername.
 If None, the local computer is used.
key is the predefined handle to connect to.

The return value is the handle of the opened key.
If the function fails, an EnvironmentError exception is raised."""
    machine = str_or_None_w(space, w_machine)
    hkey = hkey_w(w_hkey, space)
    with lltype.scoped_alloc(rwinreg.PHKEY.TO, 1) as rethkey:
        ret = rwinreg.RegConnectRegistry(machine, hkey, rethkey)
        if ret != 0:
            raiseWindowsError(space, ret, 'RegConnectRegistry')
        return space.wrap(W_HKEY(rethkey[0]))
Example #43
0
def parse(vm):
    (xml_o, nodes_mod),_ = vm.decode_args("SM")
    assert isinstance(xml_o, Con_String)
    
    with lltype.scoped_alloc(xmlSAXHandler, zero=True) as h:
        h.c_initialized = rffi.r_uint(XML_SAX2_MAGIC)
        h.c_characters = llhelper(charactersSAXFuncP, _characters)
        h.c_startElementNs = llhelper(startElementNsSAX2FuncP, _start_element)
        h.c_endElementNs = llhelper(endElementNsSAX2FuncP, _end_element)
        docs_eo = Con_List(vm, [])
        _storage_hack.push(_Store(vm, [docs_eo], nodes_mod))
        r = xmlSAXUserParseMemory(h, lltype.nullptr(rffi.VOIDP.TO), xml_o.v, len(xml_o.v))
    if r < 0 or len(_storage_hack.peek().elems_stack) != 1:
        raise Exception("XXX")
    _storage_hack.pop()
    doc_o = vm.get_slot_apply(nodes_mod.get_defn(vm, "Doc"), "new", [docs_eo])
    
    return doc_o
Example #44
0
def CreateKey(space, w_hkey, subkey):
    """key = CreateKey(key, sub_key) - Creates or opens the specified key.

key is an already open key, or one of the predefined HKEY_* constants
sub_key is a string that names the key this method opens or creates.
 If key is one of the predefined keys, sub_key may be None. In that case,
 the handle returned is the same key handle passed in to the function.

If the key already exists, this function opens the existing key

The return value is the handle of the opened key.
If the function fails, an exception is raised."""
    hkey = hkey_w(w_hkey, space)
    with lltype.scoped_alloc(rwinreg.PHKEY.TO, 1) as rethkey:
        ret = rwinreg.RegCreateKey(hkey, subkey, rethkey)
        if ret != 0:
            raiseWindowsError(space, ret, 'CreateKey')
        return space.wrap(W_HKEY(rethkey[0]))
Example #45
0
    def do_recv_string(self, space, buflength, maxlength):
        with lltype.scoped_alloc(rffi.CArrayPtr(rffi.UINT).TO,
                                 1) as length_ptr:
            self._recvall(space, rffi.cast(rffi.CCHARP, length_ptr), 4)
            length = intmask(
                rsocket.ntohl(rffi.cast(lltype.Unsigned, length_ptr[0])))
        if length > maxlength:  # bad message, close connection
            self.flags &= ~READABLE
            if self.flags == 0:
                self.close()
            raise OperationError(space.w_IOError,
                                 space.wrap("bad message length"))

        if length <= buflength:
            self._recvall(space, self.buffer, length)
            return length, lltype.nullptr(rffi.CCHARP.TO)
        else:
            newbuf = lltype.malloc(rffi.CCHARP.TO, length, flavor='raw')
            self._recvall(space, newbuf, length)
            return length, newbuf
Example #46
0
    def compress(self, data):
        """compress(data) -> string

        Provide more data to the compressor object. It will return chunks of
        compressed data whenever possible. When you've finished providing data
        to compress, call the flush() method to finish the compression process,
        and return what is left in the internal buffers."""

        datasize = len(data)

        if datasize == 0:
            return self.space.wrap("")

        if not self.running:
            raise OperationError(
                self.space.w_ValueError,
                self.space.wrap("this object was already flushed"))

        in_bufsize = datasize

        with OutBuffer(self.bzs) as out:
            with lltype.scoped_alloc(rffi.CCHARP.TO, in_bufsize) as in_buf:

                for i in range(datasize):
                    in_buf[i] = data[i]

                self.bzs.c_next_in = in_buf
                rffi.setintfield(self.bzs, 'c_avail_in', in_bufsize)

                while True:
                    bzerror = BZ2_bzCompress(self.bzs, BZ_RUN)
                    if bzerror != BZ_RUN_OK:
                        _catch_bz2_error(self.space, bzerror)

                    if rffi.getintfield(self.bzs, 'c_avail_in') == 0:
                        break
                    elif rffi.getintfield(self.bzs, 'c_avail_out') == 0:
                        out.prepare_next_chunk()

                res = out.make_result_string()
                return self.space.wrap(res)
Example #47
0
def import_(vm):
    (mod,),_ = vm.decode_args("O")

    if HAS_SRANDOMDEV and HAS_RANDOM:
        srandomdev()
    else:
        with lltype.scoped_alloc(TIMEVAL) as tp:
            if gettimeofday(tp, lltype.nullptr(TIMEZONEP.TO)) != 0:
                raise Exception("XXX")
            seed = rarithmetic.r_int(tp.c_tv_sec) ^ rarithmetic.r_int(tp.c_tv_usec)
        
        if HAS_RANDOM:
            srandom(seed)
        else:
            srand(seed)

    new_c_con_func_for_mod(vm, "pluck", pluck, mod)
    new_c_con_func_for_mod(vm, "random", random_func, mod)
    new_c_con_func_for_mod(vm, "shuffle", shuffle, mod)
    
    return vm.get_builtin(BUILTIN_NULL_OBJ)
Example #48
0
 def setitem__Array_Slice_Array(space, self, w_idx, w_item):
     start, stop, step, size = self.space.decode_index4(w_idx, self.len)
     assert step != 0
     if w_item.len != size:
         w_lst = array_tolist__Array(space, self)
         w_item = space.call_method(w_item, 'tolist')
         space.setitem(w_lst, w_idx, w_item)
         self.setlen(0)
         self.fromsequence(w_lst)
     else:
         if self is w_item:
             with lltype.scoped_alloc(mytype.arraytype,
                                      self.allocated) as new_buffer:
                 for i in range(self.len):
                     new_buffer[i] = w_item.buffer[i]
                 j = 0
                 for i in range(start, stop, step):
                     self.buffer[i] = new_buffer[j]
                     j += 1
         else:
             j = 0
             for i in range(start, stop, step):
                 self.buffer[i] = w_item.buffer[j]
                 j += 1
Example #49
0
    def descr_control(self, space, w_changelist, max_events, w_timeout=None):

        self.check_closed(space)

        if max_events < 0:
            raise operationerrfmt(
                space.w_ValueError,
                "Length of eventlist must be 0 or positive, got %d",
                max_events)

        if space.is_w(w_changelist, space.w_None):
            changelist_len = 0
        else:
            changelist_len = space.len_w(w_changelist)

        with lltype.scoped_alloc(rffi.CArray(kevent),
                                 changelist_len) as changelist:
            with lltype.scoped_alloc(rffi.CArray(kevent),
                                     max_events) as eventlist:
                with lltype.scoped_alloc(timespec) as timeout:

                    if not space.is_w(w_timeout, space.w_None):
                        _timeout = space.float_w(w_timeout)
                        if _timeout < 0:
                            raise operationerrfmt(
                                space.w_ValueError,
                                "Timeout must be None or >= 0, got %s",
                                str(_timeout))
                        sec = int(_timeout)
                        nsec = int(1e9 * (_timeout - sec))
                        rffi.setintfield(timeout, 'c_tv_sec', sec)
                        rffi.setintfield(timeout, 'c_tv_nsec', nsec)
                        ptimeout = timeout
                    else:
                        ptimeout = lltype.nullptr(timespec)

                    if not space.is_w(w_changelist, space.w_None):
                        i = 0
                        for w_ev in space.listview(w_changelist):
                            ev = space.interp_w(W_Kevent, w_ev)
                            changelist[i].c_ident = ev.event.c_ident
                            changelist[i].c_filter = ev.event.c_filter
                            changelist[i].c_flags = ev.event.c_flags
                            changelist[i].c_fflags = ev.event.c_fflags
                            changelist[i].c_data = ev.event.c_data
                            changelist[i].c_udata = ev.event.c_udata
                            i += 1
                        pchangelist = changelist
                    else:
                        pchangelist = lltype.nullptr(rffi.CArray(kevent))

                    nfds = syscall_kevent(self.kqfd, pchangelist,
                                          changelist_len, eventlist,
                                          max_events, ptimeout)
                    if nfds < 0:
                        raise exception_from_errno(space, space.w_IOError)
                    else:
                        elist_w = [None] * nfds
                        for i in xrange(nfds):

                            evt = eventlist[i]

                            w_event = W_Kevent(space)
                            w_event.event = lltype.malloc(kevent, flavor="raw")
                            w_event.event.c_ident = evt.c_ident
                            w_event.event.c_filter = evt.c_filter
                            w_event.event.c_flags = evt.c_flags
                            w_event.event.c_fflags = evt.c_fflags
                            w_event.event.c_data = evt.c_data
                            w_event.event.c_udata = evt.c_udata

                            elist_w[i] = w_event

                    return space.newlist(elist_w)
Example #50
0
def getitimer(space, which):
    with lltype.scoped_alloc(itimervalP.TO, 1) as old:

        c_getitimer(which, old)

        return itimer_retval(space, old[0])
Example #51
0
 def main(n):
     with lltype.scoped_alloc(rffi.CArray(TYPE), 1) as data:
         data[0] = rffi.cast(TYPE, 200)
         return f(data, n)
Example #52
0
def _get_peer_alt_names(space, certificate):
    # this code follows the procedure outlined in
    # OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
    # function to extract the STACK_OF(GENERAL_NAME),
    # then iterates through the stack to add the
    # names.

    if not certificate:
        return space.w_None

    # get a memory buffer
    biobuf = libssl_BIO_new(libssl_BIO_s_mem())

    try:
        alt_names_w = []
        i = 0
        while True:
            i = libssl_X509_get_ext_by_NID(certificate, NID_subject_alt_name,
                                           i)
            if i < 0:
                break

            # now decode the altName
            ext = libssl_X509_get_ext(certificate, i)
            method = libssl_X509V3_EXT_get(ext)
            if not method:
                raise ssl_error(
                    space, "No method for internalizing subjectAltName!'")

            with lltype.scoped_alloc(rffi.CCHARPP.TO, 1) as p_ptr:
                p_ptr[0] = ext[0].c_value.c_data
                length = intmask(ext[0].c_value.c_length)
                null = lltype.nullptr(rffi.VOIDP.TO)
                if method[0].c_it:
                    names = rffi.cast(
                        GENERAL_NAMES,
                        libssl_ASN1_item_d2i(
                            null, p_ptr, length,
                            libssl_ASN1_ITEM_ptr(method[0].c_it)))
                else:
                    names = rffi.cast(GENERAL_NAMES,
                                      method[0].c_d2i(null, p_ptr, length))

            for j in range(libssl_sk_GENERAL_NAME_num(names)):
                # Get a rendering of each name in the set of names

                name = libssl_sk_GENERAL_NAME_value(names, j)
                if intmask(name[0].c_type) == GEN_DIRNAME:

                    # we special-case DirName as a tuple of tuples of attributes
                    dirname = libssl_pypy_GENERAL_NAME_dirn(name)
                    w_t = space.newtuple([
                        space.wrap("DirName"),
                        _create_tuple_for_X509_NAME(space, dirname)
                    ])
                else:

                    # for everything else, we use the OpenSSL print form

                    libssl_BIO_reset(biobuf)
                    libssl_GENERAL_NAME_print(biobuf, name)
                    with lltype.scoped_alloc(rffi.CCHARP.TO, 2048) as buf:
                        length = libssl_BIO_gets(biobuf, buf, 2047)
                        if length < 0:
                            raise _ssl_seterror(space, None, 0)

                        v = rffi.charpsize2str(buf, length)
                    v1, v2 = v.split(':', 1)
                    w_t = space.newtuple([space.wrap(v1), space.wrap(v2)])

                alt_names_w.append(w_t)
    finally:
        libssl_BIO_free(biobuf)

    if alt_names_w:
        return space.newtuple(list(alt_names_w))
    else:
        return space.w_None
Example #53
0
 def f():
     x = 0
     with scoped_alloc(T, 1) as array:
         array[0] = -42
         x = array[0]
     assert x == -42