Python HTTP proxy code

Source: Internet
Author: User

googlecode:https://code.google.com/archive/p/python-proxy/source/default/Source#-*-coding:cp1252-*-#<PythonProxy.py>##Copyright (c) <2009> <f 醔 io domingues-fnds3000 in gmail.com>##Permission is hereby granted, free of charge#obtaining a copy of this software and associated documentation#files (the "software"), to deal in the software without#restriction, including without limitation the rights to use,#copy, modify, merge, publish, distribute, sublicense, and/or sell#copies of the software, and to permit persons to whom the#software is furnished to doing so, subject to the following#conditions:##the above copyright notice and this permission notice shall be#included in all copies or substantial portions of the Software.##the software is provided ' as is ', without WARRANTY of any KIND,#EXPRESS OR implied, including but not LIMITED to the warranties#of merchantability, FITNESS for A particular PURPOSE and#Noninfringement. In NO EVENT shall the AUTHORS OR COPYRIGHT#holders is liable for any CLAIM, damages OR other liability,#WHETHER in an ACTION of contract, TORT OR OTHERWISE, arising#from , out of or in CONNECTION with the software or the use or#Other dealings in the Software."""Copyright (c) <2009> <f 醔 io domingues-fnds3000 in gmail.com> <mit licence> *********** Python proxy-a Fast HTTP Proxy * * * ******************** Neste momento este proxy? um Elie proxy.suporta os m 閠 Odos HTTP:-OPTIONS; -GET; -HEAD; -POST; -PUT; -DELETE; -TRACE; -conenct. Suporta:-conex fukiensis s dos cliente em IPv4 ou IPv6; -conex fukiensis s ao alvo em IPv4 e IPv6; -conex fukiensis s todo o tipo de transmiss 鉶 de dados TCP (CONNECT tunneling), P.E. liga hun es SSL, como o caso do HTTPS.   A fazer:-verificar se o input vindo do cliente est?correcto; -enviar os devidos HTTP erros se n 鉶, ou simplesmente quebrar a Liga porphyrite o; -criar um gestor de erros; -criar Ficheiro log de erros; -colocar excep hun es nos s behind iOS onde? Previs 韛 el a Ocorr address CIA de erros, p.e.sockets e ficheiros; -rever tudo e melhorar a Estrutura do programar e colocar nomes adequados nas vari 醰 eis e m 閠 odos; -comentar o PRograma decentemente; -Doc strings.funcionalidades Futuras:-adiconar A funcionalidade de proxy an importance hygiene IMO e transparente; -suportar FTP?. (!) Aten porphyrite o o que se segue s?tem efeito em Conex fukiensis s n 鉶 CONNECT, para estas o proxy? sempre elite.qual a diferen 鏰 entre um proxy Elite, an importance hygiene IMO e transparente? -Um Proxy Elite Totalmente an importance hygiene imo, o servidor que o recebe n 鉶 consegue ter conhecimento da exist address CIA do proxy e n 鉶 r Ecebe o endere 鏾 IP do cliente;      -quando? Usado um proxy a importance hygiene imo o servidor sabe que o cliente est?a usar um proxy mas n 鉶 sabe o endere 鏾 IP do cliente; ? enviado o cabe 鏰 lho HTTP "proxy-agent".     -um proxy transparente fornece ao servidor o IP do cliente e um informa porphyrite o que se est?a usar Um proxy. s 鉶 enviados os cabe 鏰 lhos HTTP "proxy-agent" e "http_x_forwarded_for"."""Importsocket, thread, Select__version__='0.1.0 Draft 1'Buflen= 8192VERSION='Python proxy/'+__version__Httpver='http/1.1'classconnectionhandler:def __init__(self, connection, address, timeout): self.client=Connection Self.client_buffer="'Self.timeout=timeout self.method, self.path, self.protocol=Self.get_base_header ()ifself.method=='CONNECT': Self.method_connect ()elifSelf.methodinch('OPTIONS','GET','HEAD','POST','PUT',                             'DELETE','TRACE'): self.method_others () self.client.close () self.target.close ()defGet_base_header (self): while1: Self.client_buffer+=self.client.recv (buflen) End= Self.client_buffer.find ('\ n')            ifEnd!=-1:                 break        Print '%s'%self.client_buffer[:end]#Debugdata = (self.client_buffer[:end+1]). split () self.client_buffer= Self.client_buffer[end+1:]        returnDatadefmethod_connect (self): self._connect_target (self.path) self.client.send (httpver+'Connection established\n'+'proxy-agent:%s\n\n'%VERSION) Self.client_buffer="'Self._read_write ()defmethod_others (self): Self.path= Self.path[7:] i= Self.path.find ('/') Host=self.path[:i] Path=self.path[i:] self._connect_target (host) self.target.send ('%s%s%s\n'% (self.method, path, Self.protocol) +self.client_buffer) Self.client_buffer="'Self._read_write ()def_connect_target (self, host): i= Host.find (':')        ifI!=-1: Port= int (host[i+1:]) Host=host[:i]Else: Port= 80(soc_family, _, _, _, address)=socket.getaddrinfo (host, port) [0] self.target=socket.socket (soc_family) self.target.connect (address)def_read_write (self): Time_out_max= SELF.TIMEOUT/3SoCs=[self.client, self.target] Count=0 while1: Count+ = 1(recv, _, Error)= Select.select (socs, [], socs, 3)            iferror: break            ifRecv: forIn_inchRecv:data=in_.recv (buflen)ifIn_ isSelf.client:out=Self.targetElse: out=self.clientifdata:out.send (data) Count=0ifCount = =time_out_max: breakdefStart_server (host="', port=8080, ipv6=false, timeout=60, Handler=connectionhandler):ifipv6==True:soc_type=Socket.af_inet6Else: Soc_type=Socket.af_inet Soc=socket.socket (soc_type) soc.bind ((host, port))Print "Serving On%s:%d."% (host, port)#DebugSoc.listen (0) while1: Thread.start_new_thread (handler, soc.accept ()+(timeout,))if __name__=='__main__': Start_server ()

Python HTTP proxy code

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.