handle connection
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
587635
def handle(self):
        ""
        if self.TELNET_ISSUE:
            self.writeline(self.TELNET_ISSUE)
        if not self.authentication_ok():
            return
        if self.DOECHO:
            self.writeline(self.WELCOME)

        self.session_start()
        while self.RUNSHELL:
            raw_input = self.readline(prompt=self.PROMPT).strip()
            self.input = self.input_reader(self, raw_input)
            self.raw_input = self.input.raw
            if self.input.cmd:
                cmd = self.input.cmd.upper()
                params = self.input.params
                if self.COMMANDS.has_key(cmd):
                    try:
                        self.COMMANDS[cmd](params)
                    except:
                        log.exception('Error calling %s.' % cmd)
                        (t, p, tb) = sys.exc_info()
                        if self.handleException(t, p, tb):
                            break
                else:
                    self.writeerror("Unknown command '%s'" % cmd)
        log.debug("Exiting handler")
155750
public void handleConnection(Socket socket) throws IOException
    {
        // Check acceptable remote servers
        if (_remoteServers!=null&&_remoteServers.length>0)
        {
            boolean match=false;
            InetAddress inetAddress=socket.getInetAddress();
            String hostAddr=inetAddress.getHostAddress();
            String hostName=inetAddress.getHostName();
            for (int i=0; i<_remoteServers.length; i++)
            {
                if (hostName.equals(_remoteServers[i])||hostAddr.equals(_remoteServers[i]))
                {
                    match=true;
                    break;
                }
            }
            if (!match)
            {
                log.warn("AJP13 Connection from un-approved host: "+inetAddress);
                return;
            }
        }

        // Handle the connection
        socket.setTcpNoDelay(true);
        socket.setSoTimeout(getMaxIdleTimeMs());
        AJP13Connection connection=createConnection(socket);
        try
        {
            connection.handle();
        }
        finally
        {
            connection.destroy();
        }
    }
973776
function _handleConnection(client) {
	client.on('message', curry(_handleMessage, client))
	client.on('disconnect', curry(_handleDisconnect, client))
	client.pubsub = _engine.getPubSub()
	_emitter.emit('client_connect', client)
}
450286
def handle(self, sock, read_data, path, headers):
        ""
        if "://" not in self.redirect_to:
            destination = "http%s://%s" % (
                "s" if headers.get('X-Forwarded-Protocol', headers.get('X-Forwarded-Proto', "")).lower() in ("https", "ssl") else "",
                self.redirect_to
            )
        else:
            destination = self.redirect_to
        try:
            sock.sendall("HTTP/1.0 302 Found\r\nLocation: %s/%s\r\n\r\n" % (
                destination.rstrip("/"),
                path.lstrip("/"),
            ))
        except socket.error, e:
            if e.errno != errno.EPIPE:
                raise
1241424
function connection(socket){
	this.socket = socket;
	if (!!this.options.encoding) socket.setEncoding(this.options.encoding);
	socket.on('data', this.emit.bind(this, 'data'));
	this.emit('connection', socket);
}
718041
public void handleConnect(HttpServletRequest request,
                              HttpServletResponse response)
        throws IOException
    {
        String uri = request.getRequestURI();
        
        context.log("CONNECT: "+uri);
        
        InetAddrPort addrPort=new InetAddrPort(uri);
        
        //if (isForbidden(HttpMessage.__SSL_SCHEME,addrPort.getHost(),addrPort.getPort(),false))
        //{
        //    sendForbid(request,response,uri);
        //}
        //else
        {
            InputStream in=request.getInputStream();
            OutputStream out=response.getOutputStream();
            
            Socket socket = new Socket(addrPort.getInetAddress(),addrPort.getPort());
            context.log("Socket: "+socket);
            
            response.setStatus(200);
            response.setHeader("Connection","close");
            response.flushBuffer();
            
            System.err.println(response);

            context.log("out<-in");
            IO.copyThread(socket.getInputStream(),out);
            context.log("in->out");
            IO.copy(in,socket.getOutputStream());
        }
    }
988516
def handle(self):
        """"""
        data = self.request[0]
        sock = self.request[1]

        frame = KNXIPFrame.from_frame(data)

        if frame.service_type_id == KNXIPFrame.TUNNELING_REQUEST:
            req = KNXTunnelingRequest.from_body(frame.body)
            msg = CEMIMessage.from_body(req.cemi)
            send_ack = False

            tunnel = self.server.tunnel

            if msg.code == 0x29:
                # LData.req
                send_ack = True
            elif msg.code == 0x2e:
                # LData.con
                send_ack = True
            else:
                problem = "Unimplemented cEMI message code {}".format(msg.code)
                logging.error(problem)
                raise KNXException(problem)

            # Cache data
            if (msg.cmd == CEMIMessage.CMD_GROUP_WRITE) or (
                    msg.cmd == CEMIMessage.CMD_GROUP_RESPONSE):
                    # saw a value for a group address on the bus
                tunnel.received_message(msg.dst_addr, msg.data)

            # Put RESPONSES into the result queue
            if msg.cmd == CEMIMessage.CMD_GROUP_RESPONSE:
                tunnel.result_queue.put(msg.data)

            if send_ack:
                bodyack = [0x04, req.channel, req.seq, E_NO_ERROR]
                ack = KNXIPFrame(KNXIPFrame.TUNNELLING_ACK)
                ack.body = bodyack
                sock.sendto(ack.to_frame(), self.client_address)

        elif frame.service_type_id == KNXIPFrame.TUNNELLING_ACK:
            logging.debug("Received tunneling ACK")
            self.server.tunnel.ack_semaphore.release()
        elif frame.service_type_id == KNXIPFrame.DISCONNECT_RESPONSE:
            logging.debug("Disconnected")
            self.channel = None
            tunnel = self.server.tunnel
            tunnel.data_server.shutdown()
            tunnel.data_server = None
        elif frame.service_type_id == KNXIPFrame.CONNECTIONSTATE_RESPONSE:
            logging.debug("Connection state response")
            tunnel.connection_state = frame.body[2]
        else:
            logging.info(
                "Message type %s not yet implemented", frame.service_type_id)
452146
public void handle(ServerHttpRequest request, ServerHttpResponse response)
			throws IOException {
		handle(new HttpConnection(request, response));
	}
327797
public void handle(String pathInContext, String pathParams, HttpRequest request, HttpResponse response) throws HttpException, IOException
    {
        URI uri = request.getURI();

        // Is this a CONNECT request?
        if (HttpRequest.__CONNECT.equalsIgnoreCase(request.getMethod()))
        {
            response.setField(HttpFields.__Connection, "close"); // TODO Needed for IE????
            handleConnect(pathInContext, pathParams, request, response);
            return;
        }

        try
        {
            // Do we proxy this?
            URL url = isProxied(uri);
            if (url == null)
            {
                if (isForbidden(uri))
                    sendForbid(request, response, uri);
                return;
            }

            if (log.isDebugEnabled())
                log.debug("PROXY URL=" + url);

            URLConnection connection = url.openConnection();
            connection.setAllowUserInteraction(false);

            // Set method
            HttpURLConnection http = null;
            if (connection instanceof HttpURLConnection)
            {
                http = (HttpURLConnection) connection;
                http.setRequestMethod(request.getMethod());
                http.setInstanceFollowRedirects(false);
            }

            // check connection header
            String connectionHdr = request.getField(HttpFields.__Connection);
            if (connectionHdr != null && (connectionHdr.equalsIgnoreCase(HttpFields.__KeepAlive) || connectionHdr.equalsIgnoreCase(HttpFields.__Close)))
                connectionHdr = null;

            // copy headers
            boolean xForwardedFor = false;
            boolean hasContent = false;
            Enumeration enm = request.getFieldNames();
            while (enm.hasMoreElements())
            {
                // TODO could be better than this!
                String hdr = (String) enm.nextElement();

                if (_DontProxyHeaders.containsKey(hdr) || !_chained && _ProxyAuthHeaders.containsKey(hdr))
                    continue;
                if (connectionHdr != null && connectionHdr.indexOf(hdr) >= 0)
                    continue;

                if (HttpFields.__ContentType.equals(hdr))
                    hasContent = true;

                Enumeration vals = request.getFieldValues(hdr);
                while (vals.hasMoreElements())
                {
                    String val = (String) vals.nextElement();
                    if (val != null)
                    {
                        connection.addRequestProperty(hdr, val);
                        xForwardedFor |= HttpFields.__XForwardedFor.equalsIgnoreCase(hdr);
                    }
                }
            }

            // Proxy headers
            if (!_anonymous)
                connection.setRequestProperty("Via", "1.1 (jetty)");
            if (!xForwardedFor)
                connection.addRequestProperty(HttpFields.__XForwardedFor, request.getRemoteAddr());

            // a little bit of cache control
            String cache_control = request.getField(HttpFields.__CacheControl);
            if (cache_control != null && (cache_control.indexOf("no-cache") >= 0 || cache_control.indexOf("no-store") >= 0))
                connection.setUseCaches(false);

            // customize Connection
            customizeConnection(pathInContext, pathParams, request, connection);

            try
            {
                connection.setDoInput(true);

                // do input thang!
                InputStream in = request.getInputStream();
                if (hasContent)
                {
                    connection.setDoOutput(true);
                    IO.copy(in, connection.getOutputStream());
                }

                // Connect
                connection.connect();
            }
            catch (Exception e)
            {
                LogSupport.ignore(log, e);
            }

            InputStream proxy_in = null;

            // handler status codes etc.
            int code = HttpResponse.__500_Internal_Server_Error;
            if (http != null)
            {
                proxy_in = http.getErrorStream();

                code = http.getResponseCode();
                response.setStatus(code);
                response.setReason(http.getResponseMessage());
            }

            if (proxy_in == null)
            {
                try
                {
                    proxy_in = connection.getInputStream();
                }
                catch (Exception e)
                {
                    LogSupport.ignore(log, e);
                    proxy_in = http.getErrorStream();
                }
            }

            // clear response defaults.
            response.removeField(HttpFields.__Date);
            response.removeField(HttpFields.__Server);

            // set response headers
            int h = 0;
            String hdr = connection.getHeaderFieldKey(h);
            String val = connection.getHeaderField(h);
            while (hdr != null || val != null)
            {
                if (hdr != null && val != null && !_DontProxyHeaders.containsKey(hdr) && (_chained || !_ProxyAuthHeaders.containsKey(hdr)))
                    response.addField(hdr, val);
                h++;
                hdr = connection.getHeaderFieldKey(h);
                val = connection.getHeaderField(h);
            }
            if (!_anonymous)
                response.setField("Via", "1.1 (jetty)");

            // Handled
            request.setHandled(true);
            if (proxy_in != null)
                IO.copy(proxy_in, response.getOutputStream());

        }
        catch (Exception e)
        {
            log.warn(e.toString());
            LogSupport.ignore(log, e);
            if (!response.isCommitted())
                response.sendError(HttpResponse.__400_Bad_Request);
        }
    }
1052519
public function handleConnect($conn) {
        $conn->decor = new IoConnection($conn);
        $conn->decor->resourceId = (int)$conn->stream;

        $uri = $conn->getRemoteAddress();
        $conn->decor->remoteAddress = trim(
            parse_url((strpos($uri, '://') === false ? 'tcp://' : '') . $uri, PHP_URL_HOST),
            '[]'
        );

        $this->app->onOpen($conn->decor);

        $conn->on('data', function ($data) use ($conn) {
            $this->handleData($data, $conn);
        });
        $conn->on('close', function () use ($conn) {
            $this->handleEnd($conn);
        });
        $conn->on('error', function (\Exception $e) use ($conn) {
            $this->handleError($e, $conn);
        });
    }
1258715
def handle(self):
        """"""
        rv = None
        try:
            rv = BaseHTTPRequestHandler.handle(self)
        except (_ConnectionError, socket.timeout) as e:
            self.connection_dropped(e)
        except Exception as e:
            if self.server.ssl_context is None or not is_ssl_error(e):
                raise
        if self.server.shutdown_signal:
            self.initiate_shutdown()
        return rv
545838
void handleCommunicationIssue(Exception io) {
        // If we are connecting or disconnecting, note exception and leave
        statusLock.lock();
        try {
            if (this.connecting || this.disconnecting || this.status == Status.CLOSED || this.isDraining()) {
                this.exceptionDuringConnectChange = io;
                return;
            }
        } finally {
            statusLock.unlock();
        }

        processException(io);

        // Spawn a thread so we don't have timing issues with
        // waiting on read/write threads
        executor.submit(() -> {
            try {
                this.closeSocket(true);
            } catch (InterruptedException e) {
                processException(e);
            }
        });
    }
492949
def _subthread_handle_accepted(self, client):
        

        conn, addr = client
        if self.handle_incoming(conn, addr):
            logging.info('Accepted connection from client: {}'.format(addr))
            conn.setblocking(False)
            self.clients[conn] = addr
            self.register(conn)
        else:
            logging.info('Refused connection from client: {}'.format(addr))
            self.disconnect(conn)
243432
def __handler(self, connection, event):
        
        try:
            # Find local handler
            method = getattr(self, "on_{0}".format(event.type))
        except AttributeError:
            pass
        else:
            try:
                # Call it
                return method(connection, event)
            except Exception as ex:
                logging.exception("Error calling handler: %s", ex)
729781
public void handle(Object job)
    {
        Socket socket = (Socket) job;
        try
        {
            if (_tcpNoDelay) socket.setTcpNoDelay(true);
            handleConnection(socket);
        }
        catch (Exception e)
        {
            log.debug("Connection problem", e);
        }
        finally
        {
            try
            {
                socket.close();
            }
            catch (Exception e)
            {
                log.debug("Connection problem", e);
            }
        }
    }
483724
def handle_connack(self):
        """"""
        self.logger.info("CONNACK reveived")
        ret, flags = self.in_packet.read_byte()
        if ret != NC.ERR_SUCCESS:
            self.logger.error("error read byte")
            return ret
        
        # useful for v3.1.1 only
        session_present = flags & 0x01

        ret, retcode = self.in_packet.read_byte()
        if ret != NC.ERR_SUCCESS:
            return ret
        
        evt = event.EventConnack(retcode, session_present)
        self.push_event(evt)
        
        if retcode == NC.CONNECT_ACCEPTED:
            self.state = NC.CS_CONNECTED
            return NC.ERR_SUCCESS
        
        elif retcode >= 1 and retcode <= 5:
            return NC.ERR_CONN_REFUSED
        else:
            return NC.ERR_PROTOCOL