Create a Unix domain socket connection
324087
def _connect(self):
        ""
        sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        sock.settimeout(self.socket_timeout)
        sock.connect(self.path)
        return sock
261407
async def unixconnect(path):
    '''
    
    '''
    reader, writer = await asyncio.open_unix_connection(path=path)
    info = {'path': path, 'unix': True}
    return await Link.anit(reader, writer, info=info)
652097
def connect(self, host=HOST, port=GPSD_PORT):
        
        for alotta_stuff in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
            family, socktype, proto, _canonname, host_port = alotta_stuff
            try:
                self.streamSock = socket.socket(family, socktype, proto)
                self.streamSock.connect(host_port)
                self.streamSock.setblocking(False)
            except (OSError, IOError) as error:
                sys.stderr.write('\r\nGPSDSocket.connect exception is--> {}'.format(error))
                sys.stderr.write('\r\nGPS3 gpsd connection at \'{0}\' on port \'{1}\' failed\r\n'.format(host, port))
152502
def main(server):
    """"""

    if 'REQUEST_METHOD' in os.environ:
        start_cgi(server)

    stdin_sock = socket.fromfd(0, socket.AF_UNIX, socket.SOCK_STREAM)
    try:
        stdin_sock.getpeername()
    except socket.error as e:
        if e.errno == errno.ENOTCONN:
            start_fcgi(server)

    start_standalone(server)
511209
def connect(self):
        
        try:
            self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)

            if has_timeout(self.timeout):
                self.sock.settimeout(self.timeout)

            self.sock.connect(unquote(self.host))
        except socket.error as msg:
            if self.sock:
                self.sock.close()
            self.sock = None

            raise socket.error(msg)
1111876
def _make_socket(cls, ip, port):
    
    bound_socket = bind_sockets(port, address=ip)[0]
    ip, port = bound_socket.getsockname()

    if not ip or ip == '0.0.0.0':
      ip = socket.gethostbyname(socket.gethostname())

    return bound_socket, ip, port
32164
def unix_domain_socket_server(sock_path):
    
    log.debug('serving on %s', sock_path)
    remove_file(sock_path)

    server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    server.bind(sock_path)
    server.listen(1)
    try:
        yield server
    finally:
        remove_file(sock_path)
163827
def serve_client(session, io)
      # 
      begin
        begin
          # ON CONNECTION
          # 220 <domain> Service ready
          # 421 <domain> Service not available, closing transmission channel
          # Reset and initialize message
          process_reset_session(session, true)

          # get local address info
          _, session[:ctx][:server][:local_port], session[:ctx][:server][:local_host], session[:ctx][:server][:local_ip] = @do_dns_reverse_lookup ? io.addr(:hostname) : io.addr(:numeric)
          # get remote partner hostname and address
          _, session[:ctx][:server][:remote_port], session[:ctx][:server][:remote_host], session[:ctx][:server][:remote_ip] = @do_dns_reverse_lookup ? io.peeraddr(:hostname) : io.peeraddr(:numeric)

          # save connection date/time
          session[:ctx][:server][:connected] = Time.now.utc

          # build and save the local welcome and greeting response strings
          session[:ctx][:server][:local_response] = "#{session[:ctx][:server][:local_host]} says welcome!"
          session[:ctx][:server][:helo_response] = "#{session[:ctx][:server][:local_host]} at your service!"

          # check if we want to let this remote station connect us
          on_connect_event(session[:ctx])

          # drop connection (respond 421) if too busy
          raise 'Abort connection while too busy, exceeding max_connections!' if max_connections && connections > max_connections

          # check active processings for new client
          @connections_mutex.synchronize do
            # when processings exceed maximum number of simultaneous allowed processings, then wait for next free slot
            while processings >= max_processings
              @connections_cv.wait(@connections_mutex)
            end
          end

          # append this to list of processings
          @processings << Thread.current

          # reply local welcome message
          output = "220 #{session[:ctx][:server][:local_response].to_s.strip}\r\n"

          # log and show to client
          logger.debug('>>> ' + output)
          io.print output unless io.closed?

          # initialize \r\n for line_break, this is used for CRLF_ENSURE and CRLF_STRICT
          line_break = "\r\n"

          # initialize io_buffer for input data
          io_buffer = ''

          # initialize io_buffer_line_lf index
          io_buffer_line_lf = nil

          # initialze timeout timestamp
          timestamp_timeout = Time.now.to_i

          # while input data handle communication
          loop do
            # test if STARTTLS sequence
            if session[:cmd_sequence] == :CMD_STARTTLS
              # start ssl tunnel
              io = @tls.start(io)
              # save enabled tls
              session[:ctx][:server][:encrypted] = Time.now.utc
              # set sequence back to HELO/EHLO
              session[:cmd_sequence] = :CMD_HELO
              # reset timeout timestamp
              timestamp_timeout = Time.now.to_i
            end

            # read input data from Socket / SSLSocket into io_buffer
            # by non-blocking action until \n is found
            begin
              unless io_buffer_line_lf
                # check for timeout on IO
                raise SmtpdIOTimeoutException if @io_cmd_timeout && Time.now.to_i - timestamp_timeout > @io_cmd_timeout
                # read chunks of input data until line-feed
                io_buffer << io.read_nonblock(@io_buffer_chunk_size)
                # check for buffersize
                raise SmtpdIOBufferOverrunException if @io_buffer_max_size && io_buffer.length > @io_buffer_max_size
                # check for lf in current io_buffer
                io_buffer_line_lf = io_buffer.index("\n")
              end

            # ignore exception when no input data is available yet
            rescue IO::WaitReadable
              # but wait a few moment to slow down system utilization
              sleep 0.1
            end

            # check if io_buffer is filled and contains already a line-feed
            while io_buffer_line_lf
              # extract line (containing \n) from io_buffer and slice io_buffer
              line = io_buffer.slice!(0, io_buffer_line_lf + 1)

              # check for next line-feed already in io_buffer
              io_buffer_line_lf = io_buffer.index("\n")

              # process commands and handle special SmtpdExceptions
              begin
                # check for pipelining extension or violation
                raise Smtpd500PipeliningException unless @pipelining_extension || !io_buffer_line_lf || (session[:cmd_sequence] == :CMD_DATA)

                # handle input line based on @crlf_mode
                case crlf_mode
                  when :CRLF_ENSURE
                    # remove any \r or \n occurence from line
                    line.delete!("\r\n")
                    # log line, verbosity based on log severity and command sequence
                    logger.debug('<<< ' << line << "\n") if session[:cmd_sequence] != :CMD_DATA

                  when :CRLF_LEAVE
                    # use input line_break for line_break
                    line_break = line[-2..-1] == "\r\n" ? "\r\n" : "\n"
                    # check to override session crlf info, only when CRLF_LEAVE is used and in DATA mode
                    session[:ctx][:message][:crlf] = line_break if session[:cmd_sequence] == :CMD_DATA
                    # remove any line_break from line
                    line.chomp!
                    # log line, verbosity based on log severity and command sequence
                    logger.debug('<<< ' << line.gsub("\r", '[\r]') << "\n") if session[:cmd_sequence] != :CMD_DATA

                  when :CRLF_STRICT
                    # check line ends up by \r\n
                    raise Smtpd500CrLfSequenceException unless line[-2..-1] == "\r\n"
                    # remove any line_break from line
                    line.chomp!
                    # check line for additional \r
                    raise Smtpd500Exception, 'Line contains additional CR chars!' if line.index("\r")
                    # log line, verbosity based on log severity and command sequence
                    logger.debug('<<< ' << line << "\n") if session[:cmd_sequence] != :CMD_DATA
                end

                # process line
                output = process_line(session, line, line_break)

              # defined abort channel exception
              rescue Smtpd421Exception => e
                # just re-raise this exception and exit loop and communication
                raise

              # defined SmtpdException
              rescue SmtpdException => e
                # inc number of detected exceptions during this session
                session[:ctx][:server][:exceptions] += 1
                # log error info if logging
                logger.error("#{e}")
                # get the given smtp dialog result
                output = "#{e.smtpd_result}"

              # Unknown general Exception during processing
              rescue StandardError => e
                # inc number of detected exceptions during this session
                session[:ctx][:server][:exceptions] += 1
                # log error info if logging
                logger.error("#{e}")
                # set default smtp server dialog error
                output = "#{Smtpd500Exception.new.smtpd_result}"
              end

              # check result
              unless output.empty?
                # log smtp dialog // message data is stored separate
                logger.debug('>>> ' + output)
                # append line feed
                output << "\r\n"
                # smtp dialog response
                io.print(output) unless io.closed? || shutdown?
              end

              # reset timeout timestamp
              timestamp_timeout = Time.now.to_i
            end

            # check for valid quit or broken communication
            break if (session[:cmd_sequence] == :CMD_QUIT) || io.closed? || shutdown?
          end
          # graceful end of connection
          output = "221 Service closing transmission channel\r\n"
          # smtp dialog response
          io.print(output) unless io.closed?

        # connection was simply closed / aborted by remote closing socket
        rescue EOFError
          # log info but only while debugging otherwise ignore message
          logger.debug('EOFError - Connection lost due abort by client!')

        rescue StandardError => e
          # log error info if logging
          logger.error("#{e}")
          # power down connection
          # ignore IOErrors when sending final smtp abort return code 421
          begin
            output = "#{Smtpd421Exception.new.smtpd_result}\r\n"
            # smtp dialog response
            io.print(output) unless io.closed?
          rescue StandardError
            logger.debug('IOError - Can\'t send 421 abort code!')
          end
        end

      ensure
        # event for cleanup at end of communication
        on_disconnect_event(session[:ctx])
      end

      # return socket handler, maybe replaced with ssl
      return io
    end
958071
def bind_unix_socket(self, bind_addr):
        """"""
        if IS_WINDOWS:
            """
            Trying to access socket.AF_UNIX under Windows
            causes an AttributeError.
            """
            raise ValueError(  # or RuntimeError?
                'AF_UNIX sockets are not supported under Windows.',
            )

        fs_permissions = 0o777  # TODO: allow changing mode

        try:
            # Make possible reusing the socket...
            os.unlink(self.bind_addr)
        except OSError:
            """
            File does not exist, which is the primary goal anyway.
            """

        sock = self.prepare_socket(
            bind_addr=bind_addr,
            family=socket.AF_UNIX, type=socket.SOCK_STREAM, proto=0,
            nodelay=self.nodelay, ssl_adapter=self.ssl_adapter,
        )

        try:
            """Linux way of pre-populating fs mode permissions."""
            # Allow everyone access the socket...
            os.fchmod(sock.fileno(), fs_permissions)
            FS_PERMS_SET = True
        except OSError:
            FS_PERMS_SET = False

        try:
            sock = self.bind_socket(sock, bind_addr)
        except socket.error:
            sock.close()
            raise

        bind_addr = self.resolve_real_bind_addr(sock)

        try:
            """FreeBSD/macOS pre-populating fs mode permissions."""
            if not FS_PERMS_SET:
                try:
                    os.lchmod(bind_addr, fs_permissions)
                except AttributeError:
                    os.chmod(bind_addr, fs_permissions, follow_symlinks=False)
                FS_PERMS_SET = True
        except OSError:
            pass

        if not FS_PERMS_SET:
            self.error_log(
                'Failed to set socket fs mode permissions',
                level=logging.WARNING,
            )

        self.bind_addr = bind_addr
        self.socket = sock
        return sock
516342
def _bind_socket(self, bindaddr):
        """"""
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.setblocking(0)
        try:
            sock.bind(bindaddr)
        except Exception:
            self._logger.exception("Unable to bind to %s" % str(bindaddr))
            raise
        sock.listen(self.BACKLOG)
        return sock
630956
def connect(ipAddr, port, password):
    """"""

    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.connect((ipAddr, port))
    sock.settimeout(2)

    # Make sure it pongs.
    sock.send(b'd1:q4:pinge')
    data = sock.recv(BUFFER_SIZE)
    if not data.endswith(b'1:q4:ponge'):
        raise exceptions.NotACjdnsAdminSocket("Looks like %s:%d is to a non-cjdns socket.",
                                              (ipAddr, port))

    # Get the functions and make the object
    page = 0
    availableFunctions = {}
    while True:
        sock.send(bytearray(
            'd1:q24:Admin_availableFunctions4:argsd4:pagei%seee' % page,
            'utf-8'))
        data = sock.recv(BUFFER_SIZE)
        benc = bdecode(data)
        for func in benc['availableFunctions']:
            availableFunctions[func] = benc['availableFunctions'][func]
        if 'more' not in benc:
            break
        page = page+1

    funcArgs = {}
    funcOargs = {}

    for (i, func) in availableFunctions.items():
        items = func.items()

        # grab all the required args first
        # append all the optional args
        rargList = [arg for arg, atts in items if atts['required']]
        argList = rargList + [
            arg for arg, atts in items if not atts['required']]

        # for each optional arg setup a default value with
        # a type which will be ignored by the core.
        oargList = {}
        for (arg, atts) in items:
            if not atts['required']:
                oargList[arg] = (
                    "''" if func[arg]['type'] == 'Int'
                    else "")

        setattr(Session, i, _functionFabric(
            i, argList, oargList, password))

        funcArgs[i] = rargList
        funcOargs[i] = oargList

    session = Session(sock)

    kat = threading.Thread(target=_receiverThread, args=[session])
    kat.setDaemon(True)
    kat.start()

    # Check our password.
    ret = _callFunc(session, "ping", password, {})
    if 'error' in ret:
        raise exceptions.InvalidAdminPassword(ret.get("error"))

    session._functions = ""

    funcOargs_c = {}
    for func in funcOargs:
        funcOargs_c[func] = list([
            key + "=" + str(value) for (key, value) in funcOargs[func].items()
        ])

    for func in availableFunctions:
        session._functions += (
            func + "(" + ', '.join(funcArgs[func] + funcOargs_c[func]) + ")\n")

    return session
1167755
function Client(arg, port) {
  if (this instanceof Client === false) {
    return new Client(arg, port);
  }

  if (arg === undefined) {
    throw new TypeError('arg should be a host address, name or universe');
  }

  this.host = Number.isInteger(arg) ? e131.getMulticastGroup(arg) : arg;
  this.port = port || e131.DEFAULT_PORT;
  this._socket = dgram.createSocket('udp4');
}
1140912
def bind(self, family, type, proto=0):
        """"""
        self.socket = socket.socket(family, type, proto)
        prevent_socket_inheritance(self.socket)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        if self.nodelay and not isinstance(self.bind_addr, str):
            self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        
        if self.ssl_adapter is not None:
            self.socket = self.ssl_adapter.bind(self.socket)
        
        # If listening on the IPV6 any address ('::' = IN6ADDR_ANY),
        # activate dual-stack. See http://www.cherrypy.org/ticket/871.
        if (family == socket.AF_INET6
            and self.bind_addr[0] in ('::', '::0', '::0.0.0.0')):
            try:
                self.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
            except (AttributeError, socket.error):
                # Apparently, the socket option is not available in
                # this machine's TCP stack
                pass
        
        self.socket.bind(self.bind_addr)
776822
def create_connection():
    """"""
    # REDIS_URL is defined in .env and loaded into the environment by Honcho
    redis_url = os.getenv('REDIS_URL')
    # If it's not defined, use the Redis default
    if not redis_url:
        redis_url = 'redis://localhost:6379'
    urlparse.uses_netloc.append('redis')
    url = urlparse.urlparse(redis_url)
    return redis.StrictRedis(
        host=url.hostname,
        port=url.port,
        db=0,
        password=url.password
    )
1018050
def connect(self):
        """"""
        self.socket = socket.create_connection(self.address, self.timeout)
38360
def spawn_gdb(pid, address=DFLT_ADDRESS, gdb='gdb', verbose=False,
              ctx=None, proc_iut=None):
    """"""

    parent, child = socket.socketpair()
    proc = Popen([gdb, '--interpreter=mi', '-nx'],
                    bufsize=0, stdin=child, stdout=child, stderr=STDOUT)
    child.close()

    connections = {}
    gdb = GdbSocket(ctx, address, proc, proc_iut, parent, verbose,
                    connections)
    gdb.mi_command('-target-attach %d' % pid)
    gdb.cli_command('python import pdb_clone.bootstrappdb_gdb')
    asyncore.loop(map=connections)
    proc.wait()
    return gdb.error
1059878
def create_tcp_socket (self, host):
        """"""
        port = int(self['TCPSocket'])
        sockinfo = get_sockinfo(host, port=port)
        sock = create_socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            sock.connect(sockinfo[0][4])
        except socket.error:
            sock.close()
            raise
        return sock