import time
import socket
import struct
import urlparse
import select

import utils
from xlog import getLogger
xlog = getLogger("x_tunnel")

import global_var as g
import proxy_session


def netloc_to_host_port(netloc, default_port=80):
    if ":" in netloc:
        host, _, port = netloc.rpartition(':')
        port = int(port)
    else:
        host = netloc
        port = default_port
    return host, port


class Socks5Server():
    handle_num = 0

    def __init__(self, sock, client, args):
        self.connection = sock
        self.rfile = socket._fileobject(self.connection, "rb", -1)
        self.wfile = socket._fileobject(self.connection, "wb", 0)
        self.client_address = client
        self.read_buffer = ""
        self.buffer_start = 0
        self.args = args

    def handle(self):
        self.__class__.handle_num += 1
        try:
            r, w, e = select.select([self.connection], [], [])
            socks_version = self.read_bytes(1)
            if not socks_version:
                return

            if socks_version == "\x04":
                self.socks4_handler()