Python socket._socketobject() Examples

The following are 19 code examples of socket._socketobject(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module socket , or try the search function .
Example #1
Source File: __init__.py    From pylgbst with MIT License 6 votes vote down vote up
def _handle_conn(self, conn):
        """
        :type conn: socket._socketobject
        """
        buf = ""
        while True:
            data = conn.recv(1024)
            log.debug("Recv: %s", data.strip())
            if not data:
                break

            buf += data

            if "\n" in buf:
                line = buf[:buf.index("\n")]
                buf = buf[buf.index("\n") + 1:]

                if line:
                    log.debug("Cmd line: %s", line)
                    try:
                        self._handle_cmd(json.loads(line))
                    except KeyboardInterrupt:
                        raise
                    except BaseException:
                        log.error("Failed to handle cmd: %s", traceback.format_exc()) 
Example #2
Source File: test_urllib2net.py    From CTFCrackTools with GNU General Public License v3.0 6 votes vote down vote up
def test_close(self):
        import httplib

        # calling .close() on urllib2's response objects should close the
        # underlying socket

        # delve deep into response to fetch socket._socketobject
        response = _urlopen_with_retry("http://www.python.org/")
        abused_fileobject = response.fp
        self.assertTrue(abused_fileobject.__class__ is socket._fileobject)
        httpresponse = abused_fileobject._sock
        self.assertTrue(httpresponse.__class__ is httplib.HTTPResponse)
        fileobject = httpresponse.fp
        self.assertTrue(fileobject.__class__ is socket._fileobject)

        self.assertTrue(not fileobject.closed)
        response.close()
        self.assertTrue(fileobject.closed) 
Example #3
Source File: test_urllib2net.py    From CTFCrackTools-V2 with GNU General Public License v3.0 6 votes vote down vote up
def test_close(self):
        import httplib

        # calling .close() on urllib2's response objects should close the
        # underlying socket

        # delve deep into response to fetch socket._socketobject
        response = _urlopen_with_retry("http://www.python.org/")
        abused_fileobject = response.fp
        self.assertTrue(abused_fileobject.__class__ is socket._fileobject)
        httpresponse = abused_fileobject._sock
        self.assertTrue(httpresponse.__class__ is httplib.HTTPResponse)
        fileobject = httpresponse.fp
        self.assertTrue(fileobject.__class__ is socket._fileobject)

        self.assertTrue(not fileobject.closed)
        response.close()
        self.assertTrue(fileobject.closed) 
Example #4
Source File: test_urllib2net.py    From medicare-demo with Apache License 2.0 6 votes vote down vote up
def test_close(self):
        import socket, httplib, gc

        # calling .close() on urllib2's response objects should close the
        # underlying socket

        # delve deep into response to fetch socket._socketobject
        response = urllib2.urlopen("http://www.python.org/")
        abused_fileobject = response.fp
        self.assert_(abused_fileobject.__class__ is socket._fileobject)
        httpresponse = abused_fileobject._sock
        self.assert_(httpresponse.__class__ is httplib.HTTPResponse)
        fileobject = httpresponse.fp
        self.assert_(fileobject.__class__ is socket._fileobject)

        self.assert_(not fileobject.closed)
        response.close()
        self.assert_(fileobject.closed) 
Example #5
Source File: test_urllib2net.py    From gcblue with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_close(self):
        import httplib

        # calling .close() on urllib2's response objects should close the
        # underlying socket

        # delve deep into response to fetch socket._socketobject
        response = _urlopen_with_retry("http://www.example.com/")
        abused_fileobject = response.fp
        self.assertIs(abused_fileobject.__class__, socket._fileobject)
        httpresponse = abused_fileobject._sock
        self.assertIs(httpresponse.__class__, httplib.HTTPResponse)
        fileobject = httpresponse.fp
        self.assertIs(fileobject.__class__, socket._fileobject)

        self.assertTrue(not fileobject.closed)
        response.close()
        self.assertTrue(fileobject.closed) 
Example #6
Source File: tcp.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def _finishInit(self, whenDone, skt, error, reactor):
        """
        Called by subclasses to continue to the stage of initialization where
        the socket connect attempt is made.

        @param whenDone: A 0-argument callable to invoke once the connection is
            set up.  This is L{None} if the connection could not be prepared
            due to a previous error.

        @param skt: The socket object to use to perform the connection.
        @type skt: C{socket._socketobject}

        @param error: The error to fail the connection with.

        @param reactor: The reactor to use for this client.
        @type reactor: L{twisted.internet.interfaces.IReactorTime}
        """
        if whenDone:
            self._commonConnection.__init__(self, skt, None, reactor)
            reactor.callLater(0, whenDone)
        else:
            reactor.callLater(0, self.failIfNotConnected, error) 
Example #7
Source File: server.py    From testplan with Apache License 2.0 6 votes vote down vote up
def __init__(
        self, connection, name=None, queue=None, in_seqno=1, out_seqno=1
    ):
        """
        Create a new ConnectionDetails. Only the connection is required
        initially, as the rest of the details are set later.

        :param connection: The connection
        :type connection: ``socket._socketobject``
        :param name: Name of connection (tuple of sender and target)
        :type name: ``tuple`` of ``str`` and ``str``
        :param queue: Queue of receiving messages
        :type queue: ``queue``
        :param in_seqno: Input messages sequence number
        :type in_seqno: ``int``
        :param out_seqno: Output messages sequence number
        :type out_seqno: ``int``
        """
        self.connection = connection
        self.name = name
        self.queue = queue
        self.in_seqno = in_seqno
        self.out_seqno = out_seqno 
Example #8
Source File: tcp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _finishInit(self, whenDone, skt, error, reactor):
        """
        Called by subclasses to continue to the stage of initialization where
        the socket connect attempt is made.

        @param whenDone: A 0-argument callable to invoke once the connection is
            set up.  This is L{None} if the connection could not be prepared
            due to a previous error.

        @param skt: The socket object to use to perform the connection.
        @type skt: C{socket._socketobject}

        @param error: The error to fail the connection with.

        @param reactor: The reactor to use for this client.
        @type reactor: L{twisted.internet.interfaces.IReactorTime}
        """
        if whenDone:
            self._commonConnection.__init__(self, skt, None, reactor)
            reactor.callLater(0, whenDone)
        else:
            reactor.callLater(0, self.failIfNotConnected, error) 
Example #9
Source File: test_urllib2net.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_close(self):
        import httplib

        # calling .close() on urllib2's response objects should close the
        # underlying socket

        # delve deep into response to fetch socket._socketobject
        response = _urlopen_with_retry("http://www.example.com/")
        abused_fileobject = response.fp
        self.assertIs(abused_fileobject.__class__, socket._fileobject)
        httpresponse = abused_fileobject._sock
        self.assertIs(httpresponse.__class__, httplib.HTTPResponse)
        fileobject = httpresponse.fp
        self.assertIs(fileobject.__class__, socket._fileobject)

        self.assertTrue(not fileobject.closed)
        response.close()
        self.assertTrue(fileobject.closed) 
Example #10
Source File: test_urllib2net.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_close(self):
        import httplib

        # calling .close() on urllib2's response objects should close the
        # underlying socket

        # delve deep into response to fetch socket._socketobject
        response = _urlopen_with_retry("http://www.python.org/")
        abused_fileobject = response.fp
        self.assertTrue(abused_fileobject.__class__ is socket._fileobject)
        httpresponse = abused_fileobject._sock
        self.assertTrue(httpresponse.__class__ is httplib.HTTPResponse)
        fileobject = httpresponse.fp
        self.assertTrue(fileobject.__class__ is socket._fileobject)

        self.assertTrue(not fileobject.closed)
        response.close()
        self.assertTrue(fileobject.closed) 
Example #11
Source File: test_urllib2net.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_close(self):
        import httplib

        # calling .close() on urllib2's response objects should close the
        # underlying socket

        # delve deep into response to fetch socket._socketobject
        response = _urlopen_with_retry(test_support.TEST_HTTP_URL)
        abused_fileobject = response.fp
        self.assertIs(abused_fileobject.__class__, socket._fileobject)
        httpresponse = abused_fileobject._sock
        self.assertIs(httpresponse.__class__, httplib.HTTPResponse)
        fileobject = httpresponse.fp
        self.assertIs(fileobject.__class__, socket._fileobject)

        self.assertTrue(not fileobject.closed)
        response.close()
        self.assertTrue(fileobject.closed) 
Example #12
Source File: nsrlsvr.py    From plaso with Apache License 2.0 5 votes vote down vote up
def _QueryHash(self, nsrl_socket, digest):
    """Queries nsrlsvr for a specific hash.

    Args:
      nsrl_socket (socket._socketobject): socket of connection to nsrlsvr.
      digest (str): hash to look up.

    Returns:
      bool: True if the hash was found, False if not or None on error.
    """
    try:
      query = 'QUERY {0:s}\n'.format(digest).encode('ascii')
    except UnicodeDecodeError:
      logger.error('Unable to encode digest: {0!s} to ASCII.'.format(digest))
      return False

    response = None

    try:
      nsrl_socket.sendall(query)
      response = nsrl_socket.recv(self._RECEIVE_BUFFER_SIZE)

    except socket.error as exception:
      logger.error('Unable to query nsrlsvr with error: {0!s}.'.format(
          exception))

    if not response:
      return False

    # Strip end-of-line characters since they can differ per platform on which
    # nsrlsvr is running.
    response = response.strip()
    # nsrlsvr returns "OK 1" if the has was found or "OK 0" if not.
    return response == b'OK 1' 
Example #13
Source File: nsrlsvr.py    From plaso with Apache License 2.0 5 votes vote down vote up
def _GetSocket(self):
    """Establishes a connection to an nsrlsvr instance.

    Returns:
      socket._socketobject: socket connected to an nsrlsvr instance or None if
          a connection cannot be established.
    """
    try:
      return socket.create_connection(
          (self._host, self._port), self._SOCKET_TIMEOUT)

    except socket.error as exception:
      logger.error(
          'Unable to connect to nsrlsvr with error: {0!s}.'.format(exception)) 
Example #14
Source File: test_tacacs_plus.py    From tacacs_plus with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def fake_socket(tmpdir_factory, request):
    packets = request.node.callspec.params.get('packets')

    # write data to the "socket"; this must be an actual file, because
    # select.select()() expects a real file descriptor
    filename = str(tmpdir_factory.mktemp('fake-socket').join(str(uuid4())))
    f = open(filename, 'w')
    request.addfinalizer(f.close)

    sockobj = socket._socket.socket if six.PY3 else socket._socketobject

    class fakesocket(sockobj):
        buff = six.BytesIO()

    def _send(self, data):
        self.buff.write(data)
        return len(data)  # number of bytes sent

    sock = fakesocket()
    sock.f = six.BytesIO(packets)
    # socket.socket overrides these at instantiation time to the underlying
    # C implementation; set them here so that we can mock send() and recv()
    # calls
    sock.send = types.MethodType(_send, sock)
    sock.recv = types.MethodType(
        lambda self, _bytes: self.f.read(_bytes),
        sock
    )
    sock.fileno = types.MethodType(lambda self: f.fileno(), sock)
    return sock 
Example #15
Source File: fdunix.py    From pth-toolkit with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def send_socket(socket, sobject):
    """This function sends a filedescriptor.

    socket: must be a unix socket
    fd: must be a socket of a socket object

    Returns True on success, False otherwise

    """

    if not isinstance(sobject, _socketobject):
        raise TypeError("'sobject' must either be a file or a socket object")

    iov = IOVec()
    iov.iov_base = "A"
    iov.iov_len = 1

    cmsg = CMSG()
    cmsg.cmsg_hdr.cmsg_len = CMSG_LEN(sizeof(c_int))
    cmsg.cmsg_hdr.cmsg_level = SOL_SOCKET
    cmsg.cmsg_hdr.cmsg_type = SCM_RIGHTS
    pack_into("i", cmsg.cmsg_data, 0, sobject.fileno())

    msgh = MSGHdr()
    msgh.msg_name = None
    msgh.msg_namelen = 0
    msgh.msg_iov = (iov,)
    msgh.msg_iovlen = 1
    msgh.msg_control = pointer(cmsg)
    msgh.msg_controllen = CMSG_SPACE(sizeof(c_int))
    msgh.msg_flags = 0

    rc = sendmsg(socket.fileno(), pointer(msgh), 0)
    if rc == -1:
        errno = get_errno()
        raise OSError(errno, strerror(errno))

    return True 
Example #16
Source File: server.py    From cheroot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, server, sock, makefile=MakeFile):
        """Initialize HTTPConnection instance.

        Args:
            server (HTTPServer): web server object receiving this request
            sock (socket._socketobject): the raw socket object (usually
                TCP) for this connection
            makefile (file): a fileobject class for reading from the socket
        """
        self.server = server
        self.socket = sock
        self.rfile = makefile(sock, 'rb', self.rbufsize)
        self.wfile = makefile(sock, 'wb', self.wbufsize)
        self.requests_seen = 0

        self.peercreds_enabled = self.server.peercreds_enabled
        self.peercreds_resolve_enabled = self.server.peercreds_resolve_enabled

        # LRU cached methods:
        # Ref: https://stackoverflow.com/a/14946506/595220
        self.resolve_peer_creds = (
            lru_cache(maxsize=1)(self.resolve_peer_creds)
        )
        self.get_peer_creds = (
            lru_cache(maxsize=1)(self.get_peer_creds)
        ) 
Example #17
Source File: sockets.py    From Doga with MIT License 5 votes vote down vote up
def capture(self, sock):
        """ Capture packets in traffic

        param: sock(socket._socketobject): raw socket that listen for traffic
        """

        while True:
            # socket.recvfrom() method returns tuple object
            packet_tuple = sock.recvfrom(65565)
            packet_str = packet_tuple[0]

            self.packet_parser.parse(self.ip, packet_str) 
Example #18
Source File: server.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, server, sock, makefile=MakeFile):
        """Initialize HTTPConnection instance.

        Args:
            server (HTTPServer): web server object receiving this request
            sock (socket._socketobject): the raw socket object (usually
                TCP) for this connection
            makefile (file): a fileobject class for reading from the socket
        """
        self.server = server
        self.socket = sock
        self.rfile = makefile(sock, 'rb', self.rbufsize)
        self.wfile = makefile(sock, 'wb', self.wbufsize)
        self.requests_seen = 0

        self.peercreds_enabled = self.server.peercreds_enabled
        self.peercreds_resolve_enabled = self.server.peercreds_resolve_enabled

        # LRU cached methods:
        # Ref: https://stackoverflow.com/a/14946506/595220
        self.resolve_peer_creds = (
            lru_cache(maxsize=1)(self.resolve_peer_creds)
        )
        self.get_peer_creds = (
            lru_cache(maxsize=1)(self.get_peer_creds)
        ) 
Example #19
Source File: packets.py    From pth-toolkit with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def from_file(input_file, logger=None):
        """This static method acts as a constructor and returns an input
        packet with the proper class, based on the packet headers.
        The "input_file" parameter must either be a file or a sockect object.

        """

        if isinstance(input_file, _socketobject):
            def read_file(count):
                return input_file.recv(count, MSG_WAITALL)
        elif hasattr(file, "read") and callable(file.read):
            def read_file(count):
                return input_file.read(count)
        else:
            raise ValueError("'input_file' must either be a socket object or"
                             " provide a 'read' method")

        fields = ("rpc_vers", "rpc_vers_minor", "ptype", "pfc_flags", "drep",
                  "frag_length", "auth_length", "call_id")

        header_data = read_file(16)
        # len_header_data = len(header_data)
        # if len_header_data < 16:
        #     raise RTSParsingException("read only %d header bytes from input"
        #                               % len_header_data)

        # TODO: value validation
        values = unpack_from("<bbbblhhl", header_data)
        if values[2] == DCERPC_PKT_FAULT:
            packet_class = RPCFaultPacket
        elif values[2] == DCERPC_PKT_BIND_ACK:
            packet_class = RPCBindACKPacket
        elif values[2] == DCERPC_PKT_BIND_NAK:
            packet_class = RPCBindNAKPacket
        elif values[2] == DCERPC_PKT_RTS:
            packet_class = RPCRTSPacket
        else:
            packet_class = RPCPacket
        body_data = read_file(values[5] - 16)
        # len_body_data = len(body_data)
        # if len_body_data < (values[5] - 16):
        #     raise RTSParsingException("read only %d body bytes from input"
        #                               % len_body_data)

        packet = packet_class(header_data + body_data, logger)
        packet.header = dict(zip(fields, values))
        packet.offset = 16
        packet.size = values[5]
        packet.parse()

        return packet