oe-git-proxy-socks.c 89 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982
  1. /***********************************************************************
  2. * connect.c -- Make socket connection using SOCKS4/5 and HTTP tunnel.
  3. *
  4. * Copyright (c) 2000-2006 Shun-ichi Goto
  5. * Copyright (c) 2002, J. Grant (English Corrections)
  6. *
  7. * This program is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU General Public License
  9. * as published by the Free Software Foundation; either version 2
  10. * of the License, or (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  20. *
  21. * ---------------------------------------------------------
  22. * PROJECT: My Test Program
  23. * AUTHOR: Shun-ichi GOTO <gotoh@taiyo.co.jp>
  24. * CREATE: Wed Jun 21, 2000
  25. * REVISION: $Revision: 100 $
  26. * ---------------------------------------------------------
  27. *
  28. * Getting Source
  29. * ==============
  30. *
  31. * Recent version of 'connect.c' is available from
  32. * http://www.taiyo.co.jp/~gotoh/ssh/connect.c
  33. *
  34. * Related tool, ssh-askpass.exe (alternative ssh-askpass on UNIX)
  35. * is available:
  36. * http://www.taiyo.co.jp/~gotoh/ssh/ssh-askpass.exe.gz
  37. *
  38. * See more detail:
  39. * http://www.taiyo.co.jp/~gotoh/ssh/connect.html
  40. *
  41. * How To Compile
  42. * ==============
  43. *
  44. * On UNIX environment:
  45. * $ gcc connect.c -o connect
  46. *
  47. * On SOLARIS:
  48. * $ gcc -o connect -lresolv -lsocket -lnsl connect.c
  49. *
  50. * on Win32 environment:
  51. * $ cl connect.c wsock32.lib advapi32.lib
  52. * or
  53. * $ bcc32 connect.c wsock32.lib advapi32.lib
  54. * or
  55. * $ gcc connect.c -o connect
  56. *
  57. * on Mac OS X environment:
  58. * $ gcc connect.c -o connect -lresolv
  59. * or
  60. * $ gcc connect.c -o connect -DBIND_8_COMPAT=1
  61. *
  62. * How To Use
  63. * ==========
  64. *
  65. * You can specify proxy method in an environment variable or in a
  66. * command line option.
  67. *
  68. * usage: connect [-dnhst45] [-R resolve] [-p local-port] [-w sec]
  69. * [-H [user@]proxy-server[:port]]
  70. * [-S [user@]socks-server[:port]]
  71. * [-T proxy-server[:port]]
  72. * [-c telnet proxy command]
  73. * host port
  74. *
  75. * "host" and "port" is for the target hostname and port-number to
  76. * connect to.
  77. *
  78. * The -H option specifys a hostname and port number of the http proxy
  79. * server to relay. If port is omitted, 80 is used. You can specify this
  80. * value in the environment variable HTTP_PROXY and pass the -h option
  81. * to use it.
  82. *
  83. * The -S option specifys the hostname and port number of the SOCKS
  84. * server to relay. Like -H, port number can be omitted and the default
  85. * is 1080. You can also specify this value pair in the environment
  86. * variable SOCKS5_SERVER and give the -s option to use it.
  87. *
  88. * The '-4' and the '-5' options are for specifying SOCKS relaying and
  89. * indicates protocol version to use. It is valid only when used with
  90. * '-s' or '-S'. Default is '-5' (protocol version 5)
  91. *
  92. * The '-R' option is for specifying method to resolve the
  93. * hostname. Three keywords ("local", "remote", "both") or dot-notation
  94. * IP address are acceptable. The keyword "both" means, "Try local
  95. * first, then remote". If a dot-notation IP address is specified, use
  96. * this host as nameserver. The default is "remote" for SOCKS5 or
  97. * "local" for others. On SOCKS4 protocol, remote resolving method
  98. * ("remote" and "both") requires protocol 4a supported server.
  99. *
  100. * The '-p' option will forward a local TCP port instead of using the
  101. * standard input and output.
  102. *
  103. * The '-P' option is same to '-p' except keep remote session. The
  104. * program repeats waiting the port with holding remote session without
  105. * disconnecting. To disconnect the remote session, send EOF to stdin or
  106. * kill the program.
  107. *
  108. * The '-w' option specifys timeout seconds for making connection with
  109. * TARGET host.
  110. *
  111. * The '-d' option is used for debug. If you fail to connect, use this
  112. * and check request to and response from server.
  113. *
  114. * You can omit the "port" argument when program name is special format
  115. * containing port number itself. For example,
  116. * $ ln -s connect connect-25
  117. * means this connect-25 command is spcifying port number 25 already
  118. * so you need not 2nd argument (and ignored if specified).
  119. *
  120. * To use proxy, this example is for SOCKS5 connection to connect to
  121. * 'host' at port 25 via SOCKS5 server on 'firewall' host.
  122. * $ connect -S firewall host 25
  123. * or
  124. * $ SOCKS5_SERVER=firewall; export SOCKS5_SERVER
  125. * $ connect -s host 25
  126. *
  127. * For a HTTP-PROXY connection:
  128. * $ connect -H proxy-server:8080 host 25
  129. * or
  130. * $ HTTP_PROXY=proxy-server:8080; export HTTP_PROXY
  131. * $ connect -h host 25
  132. * To forward a local port, for example to use ssh:
  133. * $ connect -p 5550 -H proxy-server:8080 host 22
  134. * ($ ssh -l user -p 5550 localhost )
  135. *
  136. * TIPS
  137. * ====
  138. *
  139. * Connect.c doesn't have any configuration to specify the SOCKS server.
  140. * If you are a mobile user, this limitation might bother you. However,
  141. * You can compile connect.c and link with other standard SOCKS library
  142. * like the NEC SOCKS5 library or Dante. This means connect.c is
  143. * socksified and uses a configration file like to other SOCKSified
  144. * network commands and you can switch configuration file any time
  145. * (ex. when ppp startup) that brings you switching of SOCKS server for
  146. * connect.c in same way with other commands. For this case, you can
  147. * write ~/.ssh/config like this:
  148. *
  149. * ProxyCommand connect -n %h %p
  150. *
  151. * SOCKS5 authentication
  152. * =====================
  153. *
  154. * Only USER/PASS authentication is supported.
  155. *
  156. * Proxy authentication
  157. * ====================
  158. *
  159. * Only BASIC scheme is supported.
  160. *
  161. * Authentication informations
  162. * ===========================
  163. *
  164. * User name for authentication is specifed by an environment variable
  165. * or system login name. And password is specified from environment
  166. * variable or external program (specified in $SSH_ASKPASS) or tty.
  167. *
  168. * Following environment variable is used for specifying user name.
  169. * SOCKS: $SOCKS5_USER, $LOGNAME, $USER
  170. * HTTP Proxy: $HTTP_PROXY_USER, $LOGNAME, $USER
  171. *
  172. * ssh-askpass support
  173. * ===================
  174. *
  175. * You can use ssh-askpass (came from OpenSSH or else) to specify
  176. * password on graphical environment (X-Window or MS Windows). To use
  177. * this, set program name to environment variable SSH_ASKPASS. On UNIX,
  178. * X-Window must be required, so $DISPLAY environment variable is also
  179. * needed. On Win32 environment, $DISPLAY is not mentioned.
  180. *
  181. * Related Informations
  182. * ====================
  183. *
  184. * SOCKS5 -- RFC 1928, RFC 1929, RFC 1961
  185. * NEC SOCKS Reference Implementation is available from:
  186. * http://www.socks.nec.com
  187. * DeleGate version 5 or earlier can be SOCKS4 server,
  188. * and version 6 can be SOCKS5 and SOCKS4 server.
  189. * and version 7.7.0 or later can be SOCKS5 and SOCKS4a server.
  190. * http://www.delegate.org/delegate/
  191. *
  192. * HTTP-Proxy --
  193. * Many http proxy servers supports this, but https should
  194. * be allowed as configuration on your host.
  195. * For example on DeleGate, you should add "https" to the
  196. * "REMITTABLE" parameter to allow HTTP-Proxy like this:
  197. * delegated -Pxxxx ...... REMITTABLE="+,https" ...
  198. *
  199. * Hypertext Transfer Protocol -- HTTP/1.1 -- RFC 2616
  200. * HTTP Authentication: Basic and Digest Access Authentication -- RFC 2617
  201. * For proxy authentication, refer these documents.
  202. *
  203. ***********************************************************************/
  204. #include <stdio.h>
  205. #include <stdlib.h>
  206. #include <string.h>
  207. #include <ctype.h>
  208. #include <memory.h>
  209. #include <errno.h>
  210. #include <assert.h>
  211. #include <sys/types.h>
  212. #include <stdarg.h>
  213. #include <fcntl.h>
  214. #include <signal.h>
  215. #ifdef __CYGWIN32__
  216. #undef _WIN32
  217. #endif
  218. #ifdef _WIN32
  219. #include <windows.h>
  220. #include <winsock.h>
  221. #include <sys/stat.h>
  222. #include <io.h>
  223. #include <conio.h>
  224. #else /* !_WIN32 */
  225. #include <unistd.h>
  226. #include <pwd.h>
  227. #include <termios.h>
  228. #include <sys/time.h>
  229. #ifndef __hpux
  230. #include <sys/select.h>
  231. #endif /* __hpux */
  232. #include <sys/socket.h>
  233. #include <netinet/in.h>
  234. #include <arpa/inet.h>
  235. #include <netdb.h>
  236. #if !defined(_WIN32) && !defined(__CYGWIN32__)
  237. #define WITH_RESOLVER 1
  238. #include <arpa/nameser.h>
  239. #include <resolv.h>
  240. #else /* not ( not _WIN32 && not __CYGWIN32__) */
  241. #undef WITH_RESOLVER
  242. #endif /* not ( not _WIN32 && not __CYGWIN32__) */
  243. #endif /* !_WIN32 */
  244. #ifdef _WIN32
  245. #define ECONNRESET WSAECONNRESET
  246. #endif /* _WI32 */
  247. #ifndef LINT
  248. static char *vcid = "$Id: connect.c 100 2007-07-03 10:48:26Z gotoh $";
  249. #endif
  250. /* Microsoft Visual C/C++ has _snprintf() and _vsnprintf() */
  251. #ifdef _MSC_VER
  252. #define snprintf _snprintf
  253. #define vsnprintf _vsnprintf
  254. #endif
  255. /* consider Borland C */
  256. #ifdef __BORLANDC__
  257. #define _kbhit kbhit
  258. #define _setmode setmode
  259. #endif
  260. /* help message.
  261. Win32 environment does not support -R option (vc and cygwin)
  262. Win32 native compilers does not support -w option, yet (vc)
  263. */
  264. static char *usage = "usage: %s [-dnhst45] [-p local-port]"
  265. #ifdef _WIN32
  266. #ifdef __CYGWIN32__
  267. "[-w timeout] \n" /* cygwin cannot -R */
  268. #else /* not __CYGWIN32__ */
  269. " \n" /* VC cannot -w nor -R */
  270. #endif /* not __CYGWIN32__ */
  271. #else /* not _WIN32 */
  272. /* help message for UNIX */
  273. "[-R resolve] [-w timeout] \n"
  274. #endif /* not _WIN32 */
  275. " [-H proxy-server[:port]] [-S [user@]socks-server[:port]] \n"
  276. " [-T proxy-server[:port]]\n"
  277. " [-c telnet-proxy-command]\n"
  278. " host port\n";
  279. /* name of this program */
  280. char *progname = NULL;
  281. char *progdesc = "connect --- simple relaying command via proxy.";
  282. char *rcs_revstr = "$Revision: 100 $";
  283. char *revstr = NULL;
  284. int major_version = 1;
  285. int minor_version = 0;
  286. /* set of character for strspn() */
  287. const char *digits = "0123456789";
  288. const char *dotdigits = "0123456789.";
  289. /* options */
  290. int f_debug = 0;
  291. /* report flag to hide secure information */
  292. int f_report = 1;
  293. int connect_timeout = 0;
  294. /* local input type */
  295. #define LOCAL_STDIO 0
  296. #define LOCAL_SOCKET 1
  297. char *local_type_names[] = { "stdio", "socket" };
  298. int local_type = LOCAL_STDIO;
  299. u_short local_port = 0; /* option 'p' */
  300. int f_hold_session = 0; /* option 'P' */
  301. char *telnet_command = "telnet %h %p";
  302. /* utiity types, pair holder of number and string */
  303. typedef struct {
  304. int num;
  305. const char *str;
  306. } LOOKUP_ITEM;
  307. /* relay method, server and port */
  308. #define METHOD_UNDECIDED 0
  309. #define METHOD_DIRECT 1
  310. #define METHOD_SOCKS 2
  311. #define METHOD_HTTP 3
  312. #define METHOD_TELNET 4
  313. char *method_names[] = { "UNDECIDED", "DIRECT", "SOCKS", "HTTP", "TELNET" };
  314. int relay_method = METHOD_UNDECIDED; /* relaying method */
  315. char *relay_host = NULL; /* hostname of relay server */
  316. u_short relay_port = 0; /* port of relay server */
  317. char *relay_user = NULL; /* user name for auth */
  318. /* destination target host and port */
  319. char *dest_host = NULL;
  320. struct sockaddr_in dest_addr;
  321. u_short dest_port = 0;
  322. /* informations for SOCKS */
  323. #define SOCKS5_REP_SUCCEEDED 0x00 /* succeeded */
  324. #define SOCKS5_REP_FAIL 0x01 /* general SOCKS serer failure */
  325. #define SOCKS5_REP_NALLOWED 0x02 /* connection not allowed by ruleset */
  326. #define SOCKS5_REP_NUNREACH 0x03 /* Network unreachable */
  327. #define SOCKS5_REP_HUNREACH 0x04 /* Host unreachable */
  328. #define SOCKS5_REP_REFUSED 0x05 /* connection refused */
  329. #define SOCKS5_REP_EXPIRED 0x06 /* TTL expired */
  330. #define SOCKS5_REP_CNOTSUP 0x07 /* Command not supported */
  331. #define SOCKS5_REP_ANOTSUP 0x08 /* Address not supported */
  332. #define SOCKS5_REP_INVADDR 0x09 /* Inalid address */
  333. LOOKUP_ITEM socks5_rep_names[] = {
  334. { SOCKS5_REP_SUCCEEDED, "succeeded"},
  335. { SOCKS5_REP_FAIL, "general SOCKS server failure"},
  336. { SOCKS5_REP_NALLOWED, "connection not allowed by ruleset"},
  337. { SOCKS5_REP_NUNREACH, "Network unreachable"},
  338. { SOCKS5_REP_HUNREACH, "Host unreachable"},
  339. { SOCKS5_REP_REFUSED, "connection refused"},
  340. { SOCKS5_REP_EXPIRED, "TTL expired"},
  341. { SOCKS5_REP_CNOTSUP, "Command not supported"},
  342. { SOCKS5_REP_ANOTSUP, "Address not supported"},
  343. { SOCKS5_REP_INVADDR, "Invalid address"},
  344. { -1, NULL }
  345. };
  346. /* SOCKS5 authentication methods */
  347. #define SOCKS5_AUTH_REJECT 0xFF /* No acceptable auth method */
  348. #define SOCKS5_AUTH_NOAUTH 0x00 /* without authentication */
  349. #define SOCKS5_AUTH_GSSAPI 0x01 /* GSSAPI */
  350. #define SOCKS5_AUTH_USERPASS 0x02 /* User/Password */
  351. #define SOCKS5_AUTH_CHAP 0x03 /* Challenge-Handshake Auth Proto. */
  352. #define SOCKS5_AUTH_EAP 0x05 /* Extensible Authentication Proto. */
  353. #define SOCKS5_AUTH_MAF 0x08 /* Multi-Authentication Framework */
  354. #define SOCKS4_REP_SUCCEEDED 90 /* rquest granted (succeeded) */
  355. #define SOCKS4_REP_REJECTED 91 /* request rejected or failed */
  356. #define SOCKS4_REP_IDENT_FAIL 92 /* cannot connect identd */
  357. #define SOCKS4_REP_USERID 93 /* user id not matched */
  358. LOOKUP_ITEM socks4_rep_names[] = {
  359. { SOCKS4_REP_SUCCEEDED, "request granted (succeeded)"},
  360. { SOCKS4_REP_REJECTED, "request rejected or failed"},
  361. { SOCKS4_REP_IDENT_FAIL, "cannot connect identd"},
  362. { SOCKS4_REP_USERID, "user id not matched"},
  363. { -1, NULL }
  364. };
  365. #define RESOLVE_UNKNOWN 0
  366. #define RESOLVE_LOCAL 1
  367. #define RESOLVE_REMOTE 2
  368. #define RESOLVE_BOTH 3
  369. char *resolve_names[] = { "UNKNOWN", "LOCAL", "REMOTE", "BOTH" };
  370. int socks_version = 5; /* SOCKS protocol version */
  371. int socks_resolve = RESOLVE_UNKNOWN;
  372. struct sockaddr_in socks_ns;
  373. char *socks5_auth = NULL;
  374. /* Environment variable names */
  375. #define ENV_SOCKS_SERVER "SOCKS_SERVER" /* SOCKS server */
  376. #define ENV_SOCKS5_SERVER "SOCKS5_SERVER"
  377. #define ENV_SOCKS4_SERVER "SOCKS4_SERVER"
  378. #define ENV_SOCKS_RESOLVE "SOCKS_RESOLVE" /* resolve method */
  379. #define ENV_SOCKS5_RESOLVE "SOCKS5_RESOLVE"
  380. #define ENV_SOCKS4_RESOLVE "SOCKS4_RESOLVE"
  381. #define ENV_SOCKS5_USER "SOCKS5_USER" /* auth user for SOCKS5 */
  382. #define ENV_SOCKS4_USER "SOCKS4_USER" /* auth user for SOCKS4 */
  383. #define ENV_SOCKS_USER "SOCKS_USER" /* auth user for SOCKS */
  384. #define ENV_SOCKS5_PASSWD "SOCKS5_PASSWD" /* auth password for SOCKS5 */
  385. #define ENV_SOCKS5_PASSWORD "SOCKS5_PASSWORD" /* old style */
  386. #define ENV_HTTP_PROXY "HTTP_PROXY" /* common env var */
  387. #define ENV_HTTP_PROXY_USER "HTTP_PROXY_USER" /* auth user */
  388. #define ENV_HTTP_PROXY_PASSWORD "HTTP_PROXY_PASSWORD" /* auth password */
  389. #define ENV_TELNET_PROXY "TELNET_PROXY" /* common env var */
  390. #define ENV_CONNECT_USER "CONNECT_USER" /* default auth user name */
  391. #define ENV_CONNECT_PASSWORD "CONNECT_PASSWORD" /* default auth password */
  392. #define ENV_SOCKS_DIRECT "SOCKS_DIRECT" /* addr-list for non-proxy */
  393. #define ENV_SOCKS5_DIRECT "SOCKS5_DIRECT"
  394. #define ENV_SOCKS4_DIRECT "SOCKS4_DIRECT"
  395. #define ENV_HTTP_DIRECT "HTTP_DIRECT"
  396. #define ENV_CONNECT_DIRECT "CONNECT_DIRECT"
  397. #define ENV_SOCKS5_AUTH "SOCKS5_AUTH"
  398. #define ENV_SSH_ASKPASS "SSH_ASKPASS" /* askpass program */
  399. /* Prefix string of HTTP_PROXY */
  400. #define HTTP_PROXY_PREFIX "http://"
  401. #define PROXY_AUTH_NONE 0
  402. #define PROXY_AUTH_BASIC 1
  403. #define PROXY_AUTH_DIGEST 2
  404. int proxy_auth_type = PROXY_AUTH_NONE;
  405. /* reason of end repeating */
  406. #define REASON_UNK -2
  407. #define REASON_ERROR -1
  408. #define REASON_CLOSED_BY_LOCAL 0
  409. #define REASON_CLOSED_BY_REMOTE 1
  410. /* return value of relay start function. */
  411. #define START_ERROR -1
  412. #define START_OK 0
  413. #define START_RETRY 1
  414. /* socket related definitions */
  415. #ifndef _WIN32
  416. #define SOCKET int
  417. #endif
  418. #ifndef SOCKET_ERROR
  419. #define SOCKET_ERROR -1
  420. #endif
  421. #ifdef _WIN32
  422. #define socket_errno() WSAGetLastError()
  423. #else /* !_WIN32 */
  424. #define closesocket close
  425. #define socket_errno() (errno)
  426. #endif /* !_WIN32 */
  427. #ifdef _WIN32
  428. #define popen _popen
  429. #endif /* WIN32 */
  430. /* packet operation macro */
  431. #define PUT_BYTE(ptr,data) (*(unsigned char*)ptr = data)
  432. /* debug message output */
  433. void
  434. debug( const char *fmt, ... )
  435. {
  436. va_list args;
  437. if ( f_debug ) {
  438. va_start( args, fmt );
  439. fprintf(stderr, "DEBUG: ");
  440. vfprintf( stderr, fmt, args );
  441. va_end( args );
  442. }
  443. }
  444. void
  445. debug_( const char *fmt, ... ) /* without prefix */
  446. {
  447. va_list args;
  448. if ( f_debug ) {
  449. va_start( args, fmt );
  450. vfprintf( stderr, fmt, args );
  451. va_end( args );
  452. }
  453. }
  454. /* error message output */
  455. void
  456. error( const char *fmt, ... )
  457. {
  458. va_list args;
  459. va_start( args, fmt );
  460. fprintf(stderr, "ERROR: ");
  461. vfprintf( stderr, fmt, args );
  462. va_end( args );
  463. }
  464. void
  465. fatal( const char *fmt, ... )
  466. {
  467. va_list args;
  468. va_start( args, fmt );
  469. fprintf(stderr, "FATAL: ");
  470. vfprintf( stderr, fmt, args );
  471. va_end( args );
  472. exit (EXIT_FAILURE);
  473. }
  474. void *
  475. xmalloc (size_t size)
  476. {
  477. void *ret = malloc(size);
  478. if (ret == NULL)
  479. fatal("Cannot allocate memory: %d bytes.\n", size);
  480. return ret;
  481. }
  482. char *
  483. downcase( char *str )
  484. {
  485. char *buf = str;
  486. while ( *buf ) {
  487. if ( isupper(*buf) )
  488. *buf += 'a'-'A';
  489. buf++;
  490. }
  491. return str; /* return converted arg */
  492. }
  493. char *
  494. expand_host_and_port (const char *fmt, const char *host, int port)
  495. {
  496. const char *src;
  497. char *buf, *dst, *ptr;
  498. size_t len = strlen(fmt) + strlen(host) + 20;
  499. buf = xmalloc (len);
  500. dst = buf;
  501. src = fmt;
  502. while (*src) {
  503. if (*src == '%') {
  504. switch (src[1]) {
  505. case 'h':
  506. strcpy (dst, host);
  507. src += 2;
  508. break;
  509. case 'p':
  510. snprintf (dst, len, "%d", port);
  511. src += 2;
  512. break;
  513. default:
  514. src ++;
  515. break;
  516. }
  517. dst = buf + strlen (buf);
  518. } else if (*src == '\\') {
  519. switch (src[1]) {
  520. case 'r': /* CR */
  521. *dst++ = '\r';
  522. src += 2;
  523. break;
  524. case 'n': /* LF */
  525. *dst++ = '\n';
  526. src += 2;
  527. break;
  528. case 't': /* TAB */
  529. *dst++ = '\t';
  530. src += 2;
  531. break;
  532. default:
  533. src ++;
  534. break;
  535. }
  536. } else {
  537. /* usual */
  538. *dst++ = *src++;
  539. }
  540. *dst = '\0';
  541. }
  542. assert (strlen(buf) < len);
  543. return buf;
  544. }
  545. int
  546. lookup_resolve( const char *str )
  547. {
  548. char *buf = strdup( str );
  549. int ret;
  550. downcase( buf );
  551. if ( strcmp( buf, "both" ) == 0 )
  552. ret = RESOLVE_BOTH;
  553. else if ( strcmp( buf, "remote" ) == 0 )
  554. ret = RESOLVE_REMOTE;
  555. else if ( strcmp( buf, "local" ) == 0 )
  556. ret = RESOLVE_LOCAL;
  557. else if ( strspn(buf, dotdigits) == strlen(buf) ) {
  558. #ifndef WITH_RESOLVER
  559. fatal("Sorry, you can't specify to resolve the hostname with the -R option on Win32 environment.");
  560. #endif /* not WITH_RESOLVER */
  561. ret = RESOLVE_LOCAL; /* this case is also 'local' */
  562. socks_ns.sin_addr.s_addr = inet_addr(buf);
  563. socks_ns.sin_family = AF_INET;
  564. }
  565. else
  566. ret = RESOLVE_UNKNOWN;
  567. free(buf);
  568. return ret;
  569. }
  570. char *
  571. getusername(void)
  572. {
  573. #ifdef _WIN32
  574. static char buf[1024];
  575. DWORD size = sizeof(buf);
  576. buf[0] = '\0';
  577. GetUserName( buf, &size);
  578. return buf;
  579. #else /* not _WIN32 */
  580. struct passwd *pw = getpwuid(getuid());
  581. if ( pw == NULL )
  582. fatal("getpwuid() failed for uid: %d\n", getuid());
  583. return pw->pw_name;
  584. #endif /* not _WIN32 */
  585. }
  586. /* expect
  587. check STR is begin with substr with case-ignored comparison.
  588. Return 1 if matched, otherwise 0.
  589. */
  590. int
  591. expect( char *str, char *substr)
  592. {
  593. int len = strlen(substr);
  594. while ( 0 < len-- ) {
  595. if ( toupper(*str) != toupper(*substr) )
  596. return 0; /* not matched */
  597. str++, substr++;
  598. }
  599. return 1; /* good, matched */
  600. }
  601. /** PARAMETER operation **/
  602. #define PARAMETER_FILE "/etc/connectrc"
  603. #define PARAMETER_DOTFILE ".connectrc"
  604. typedef struct {
  605. char* name;
  606. char* value;
  607. } PARAMETER_ITEM;
  608. PARAMETER_ITEM parameter_table[] = {
  609. { ENV_SOCKS_SERVER, NULL },
  610. { ENV_SOCKS5_SERVER, NULL },
  611. { ENV_SOCKS4_SERVER, NULL },
  612. { ENV_SOCKS_RESOLVE, NULL },
  613. { ENV_SOCKS5_RESOLVE, NULL },
  614. { ENV_SOCKS4_RESOLVE, NULL },
  615. { ENV_SOCKS5_USER, NULL },
  616. { ENV_SOCKS5_PASSWD, NULL },
  617. { ENV_SOCKS5_PASSWORD, NULL },
  618. { ENV_HTTP_PROXY, NULL },
  619. { ENV_HTTP_PROXY_USER, NULL },
  620. { ENV_HTTP_PROXY_PASSWORD, NULL },
  621. { ENV_CONNECT_USER, NULL },
  622. { ENV_CONNECT_PASSWORD, NULL },
  623. { ENV_SSH_ASKPASS, NULL },
  624. { ENV_SOCKS5_DIRECT, NULL },
  625. { ENV_SOCKS4_DIRECT, NULL },
  626. { ENV_SOCKS_DIRECT, NULL },
  627. { ENV_HTTP_DIRECT, NULL },
  628. { ENV_CONNECT_DIRECT, NULL },
  629. { ENV_SOCKS5_AUTH, NULL },
  630. { NULL, NULL }
  631. };
  632. PARAMETER_ITEM*
  633. find_parameter_item(const char* name)
  634. {
  635. int i;
  636. for( i = 0; parameter_table[i].name != NULL; i++ ){
  637. if ( strcmp(name, parameter_table[i].name) == 0 )
  638. return &parameter_table[i];
  639. }
  640. return NULL;
  641. }
  642. void
  643. read_parameter_file_1(const char* name)
  644. {
  645. FILE* f;
  646. int line;
  647. char lbuf[1025];
  648. f = fopen(name, "r");
  649. if( f ){
  650. debug("Reading parameter file(%s)\n", name);
  651. for ( line = 1; fgets(lbuf, 1024, f); line++ ) {
  652. char *p, *q, *param, *value;
  653. p = strchr(lbuf, '\n');
  654. if ( p == NULL )
  655. fatal("%s:%d: buffer overflow\n", name, line);
  656. *p = '\0';
  657. p = strchr(lbuf, '#');
  658. if ( p )
  659. *p = '\0';
  660. for ( p = lbuf; *p; p++ )
  661. if( *p != ' ' && *p != '\t' ) break;
  662. if ( *p == '\0' ) continue;
  663. param = p;
  664. p = strchr(p, '=');
  665. if ( p == NULL ) {
  666. error("%s:%d: missing equal sign\n", name, line);
  667. continue;
  668. }
  669. for ( q = p - 1; q >= lbuf; q-- )
  670. if ( *q != ' ' && *q != '\t' ) break;
  671. *++q = '\0';
  672. for ( ++p; *p; p++ )
  673. if ( *p != ' ' && *p != '\t' ) break;
  674. value = p;
  675. for ( ; *p; p++ );
  676. for ( p--; p >= lbuf; p-- )
  677. if ( *p != ' ' && *p != '\t' ) break;
  678. *++p = '\0';
  679. if ( param && value ) {
  680. PARAMETER_ITEM *item;
  681. item = find_parameter_item(param);
  682. if ( item == NULL ) {
  683. error("%s:%d: unknown parameter `%s'\n", name, line, param);
  684. continue;
  685. }
  686. item->value = strdup(value);
  687. debug("Parameter `%s' is set to `%s'\n", param, value);
  688. }
  689. }
  690. }
  691. }
  692. void
  693. read_parameter_file(void)
  694. {
  695. #if !defined(_WIN32) || defined(cygwin)
  696. char *name;
  697. struct passwd *pw;
  698. #endif
  699. read_parameter_file_1(PARAMETER_FILE);
  700. #if !defined(_WIN32) || defined(cygwin)
  701. pw = getpwuid(getuid());
  702. if ( pw == NULL )
  703. fatal("getpwuid() failed for uid: %d\n", getuid());
  704. name = xmalloc(strlen(pw->pw_dir) + strlen(PARAMETER_DOTFILE) + 2);
  705. strcpy(name, pw->pw_dir);
  706. strcat(name, "/" PARAMETER_DOTFILE);
  707. read_parameter_file_1(name);
  708. free(name);
  709. #endif /* _WIN32 */
  710. }
  711. char*
  712. getparam(const char* name)
  713. {
  714. char *value = getenv(name);
  715. if ( value == NULL ){
  716. PARAMETER_ITEM *item = find_parameter_item(name);
  717. if ( item != NULL )
  718. value = item->value;
  719. }
  720. return value;
  721. }
  722. /** DIRECT connection **/
  723. #define MAX_DIRECT_ADDR_LIST 256
  724. struct ADDRPAIR {
  725. struct in_addr addr;
  726. struct in_addr mask;
  727. char *name;
  728. int negative;
  729. };
  730. struct ADDRPAIR direct_addr_list[MAX_DIRECT_ADDR_LIST];
  731. int n_direct_addr_list = 0;
  732. void
  733. mask_addr (void *addr, void *mask, int addrlen)
  734. {
  735. char *a, *m;
  736. a = addr;
  737. m = mask;
  738. while ( 0 < addrlen-- )
  739. *a++ &= *m++;
  740. }
  741. int
  742. add_direct_addr (struct in_addr *addr, struct in_addr *mask, int negative)
  743. {
  744. struct in_addr iaddr;
  745. char *s;
  746. if ( MAX_DIRECT_ADDR_LIST <= n_direct_addr_list ) {
  747. error("direct address table is full!\n");
  748. return -1;
  749. }
  750. iaddr = *addr;
  751. mask_addr(&iaddr, mask, sizeof(iaddr));
  752. s = strdup(inet_ntoa(iaddr));
  753. debug("adding direct addr entry: %s%s/%s\n",
  754. negative? "!": "", s, inet_ntoa(*mask));
  755. free(s);
  756. memcpy( &direct_addr_list[n_direct_addr_list].addr,
  757. &iaddr, sizeof(iaddr));
  758. memcpy( &direct_addr_list[n_direct_addr_list].mask,
  759. mask, sizeof(*mask));
  760. direct_addr_list[n_direct_addr_list].name = NULL;
  761. direct_addr_list[n_direct_addr_list].negative = negative;
  762. n_direct_addr_list++;
  763. return 0;
  764. }
  765. /* add domain/host name entry to direct name table */
  766. int
  767. add_direct_host( const char *name, int negative)
  768. {
  769. if ( MAX_DIRECT_ADDR_LIST <= n_direct_addr_list ) {
  770. error("direct address table is full!\n");
  771. return -1;
  772. }
  773. if (*name == '*')
  774. name++;
  775. if (*name == '.')
  776. name++;
  777. debug("adding direct name entry: %s%s\n", negative? "!": "", name);
  778. direct_addr_list[n_direct_addr_list].name = downcase(strdup(name));
  779. direct_addr_list[n_direct_addr_list].negative = negative;
  780. n_direct_addr_list++;
  781. return 0;
  782. }
  783. int
  784. parse_addr_pair (const char *str, struct in_addr *addr, struct in_addr *mask)
  785. {
  786. /* NOTE: */
  787. /* Assume already be splitted by separator
  788. and formatted as folowing:
  789. 1) 12.34.56.789/255.255.255.0
  790. 2) 12.34.56.789/24
  791. 3) 12.34.56.
  792. All above generates same addr/mask pair 12.34.56.0 and 255.255.255.0
  793. */
  794. const char *ptr;
  795. u_char *dsta, *dstm;
  796. int i, n;
  797. assert( str != NULL );
  798. addr->s_addr = 0;
  799. mask->s_addr = 0;
  800. ptr = str;
  801. dsta = (u_char*)&addr->s_addr;
  802. dstm = (u_char*)&mask->s_addr;
  803. for (i=0; i<4; i++ ) {
  804. if ( *ptr == '\0' )
  805. break; /* case of format #3 */
  806. if ( !isdigit(*ptr) )
  807. return -1; /* format error: */
  808. *dsta++ = atoi( ptr );
  809. *dstm++ = 255; /* automatic mask for format #3 */
  810. while ( isdigit(*ptr) ) /* skip digits */
  811. ptr++;
  812. if ( *ptr == '.' )
  813. ptr++;
  814. else
  815. break;
  816. }
  817. /* At this point, *ptr points '/' or EOS ('\0') */
  818. if ( *ptr == '\0' )
  819. return 0; /* complete as format #3 */
  820. if ( *ptr != '/' )
  821. return -1; /* format error */
  822. /* Now parse mask for format #1 or #2 */
  823. ptr++;
  824. mask->s_addr = 0; /* clear automatic mask */
  825. if ( strchr( ptr, '.') ) {
  826. /* case of format #1 */
  827. dstm = (u_char*)&mask->s_addr;
  828. for (i=0; i<4; i++) {
  829. if ( !isdigit(*ptr) )
  830. return -1; /* format error: */
  831. *dstm++ = atoi(ptr);
  832. while ( isdigit(*ptr) ) /* skip digits */
  833. ptr++;
  834. if ( *ptr == '.' )
  835. ptr++;
  836. else
  837. break; /* from for loop */
  838. }
  839. /* complete as format #1 */
  840. } else {
  841. /* case of format #2 */
  842. if ( !isdigit(*ptr) )
  843. return -1; /* format error: */
  844. n = atoi(ptr);
  845. if ( n<0 || 32<n)
  846. return -1; /* format error */
  847. mask->s_addr = (n==0)? 0: htonl(((u_long)0xFFFFFFFF)<<(32-n));
  848. /* complete as format #1 */
  849. }
  850. return 0;
  851. }
  852. void
  853. initialize_direct_addr (void)
  854. {
  855. int negative;
  856. int n_entries;
  857. char *env = NULL, *beg, *next, *envkey = NULL;
  858. struct in_addr addr, mask;
  859. if ( relay_method == METHOD_SOCKS ){
  860. if ( socks_version == 5 )
  861. envkey = ENV_SOCKS5_DIRECT;
  862. else
  863. envkey = ENV_SOCKS4_DIRECT;
  864. env = getparam(envkey);
  865. if ( env == NULL )
  866. env = getparam(ENV_SOCKS_DIRECT);
  867. } else if ( relay_method == METHOD_HTTP ){
  868. env = getparam(ENV_HTTP_DIRECT);
  869. }
  870. if ( env == NULL )
  871. env = getparam(ENV_CONNECT_DIRECT);
  872. if ( env == NULL )
  873. return; /* no entry */
  874. debug("making direct addr list from: '%s'\n", env);
  875. env = strdup( env ); /* reallocate to modify */
  876. beg = next = env;
  877. n_entries = 0;
  878. do {
  879. if ( MAX_DIRECT_ADDR_LIST <= n_entries ) {
  880. error("too many entries in %s", envkey);
  881. break; /* from do loop */
  882. }
  883. next = strchr( beg, ',');
  884. if ( next != NULL )
  885. *next++ = '\0';
  886. addr.s_addr = 0;
  887. mask.s_addr = 0;
  888. if (*beg == '!') {
  889. negative = 1;
  890. beg++;
  891. } else
  892. negative = 0;
  893. if ( !parse_addr_pair( beg, &addr, &mask ) ) {
  894. add_direct_addr( &addr, &mask, negative );
  895. } else {
  896. add_direct_host( beg, negative );
  897. }
  898. if ( next != NULL )
  899. beg = next;
  900. } while ( next != NULL );
  901. free( env );
  902. return;
  903. }
  904. int
  905. cmp_addr (void *addr1, void *addr2, int addrlen)
  906. {
  907. return memcmp( addr1, addr2, addrlen );
  908. }
  909. int
  910. is_direct_address (const struct in_addr addr)
  911. {
  912. int i, neg;
  913. struct in_addr iaddr;
  914. /* Note: assume IPV4 address !! */
  915. for (i=0; i<n_direct_addr_list; i++ ) {
  916. if (direct_addr_list[i].name != NULL)
  917. continue; /* it's name entry */
  918. neg = direct_addr_list[i].negative;
  919. iaddr = addr;
  920. mask_addr( &iaddr, &direct_addr_list[i].mask,
  921. sizeof(struct in_addr));
  922. if (cmp_addr(&iaddr, &direct_addr_list[i].addr,
  923. sizeof(struct in_addr)) == 0) {
  924. char *a, *m;
  925. a = strdup(inet_ntoa(direct_addr_list[i].addr));
  926. m = strdup(inet_ntoa(direct_addr_list[i].mask));
  927. debug("match with: %s/%s%s\n", a, m, neg? " (negative)": "");
  928. free(a);
  929. free(m);
  930. return !neg? 1: 0;
  931. }
  932. }
  933. debug("not matched, addr to be relayed: %s\n", inet_ntoa(addr));
  934. return 0; /* not direct */
  935. }
  936. /* check s1 is ends with s2.
  937. return 1 if exact match or domain part match.
  938. return 0 if s1 is shorter than s2 or partial match.
  939. For example,
  940. ends_with("bar.com", "bar.com") => 1 (exact match)
  941. ends_with("foo.bar.com", "bar.com") => 1 (domain match)
  942. ends_with("foo.beebar.com", "bar.com") => 0 (partial match)
  943. ends_with("bar", "bar.com") => 0 (shorter)
  944. */
  945. domain_match(const char *s1, const char *s2)
  946. {
  947. int len1, len2;
  948. const char *tail1, *tail2;
  949. len1 = strlen(s1);
  950. len2 = strlen(s2);
  951. if (len1 < len2 || len1 == 0 || len2 == 0)
  952. return 0; /* not match */
  953. tail1 = s1 + len1;
  954. tail2 = s2 + len2;
  955. while (0 < len1 && 0 < len2) {
  956. if (*--tail1 != *--tail2)
  957. break; /* not match */
  958. len1--, len2--;
  959. }
  960. if (len2 != 0)
  961. return 0; /* not match */
  962. /* Now exact match, domain match or partial match.
  963. Return true if exact or domain match.
  964. Or continue checking. */
  965. if (tail1 == s1 || tail1[-1] == '.')
  966. return 1; /* match! */
  967. return 0; /* not match */
  968. }
  969. /* Check given NAME is ends with one of
  970. registered direct name entry.
  971. Return 1 if matched, or 0.
  972. */
  973. int
  974. is_direct_name (const char *name)
  975. {
  976. int len, i;
  977. const char *tail;
  978. debug("checking %s is for direct?\n", name);
  979. name = downcase(strdup(name));
  980. len = strlen(name);
  981. if (len < 1)
  982. return 0; /* false */
  983. tail = &name[len];
  984. for (i=0; i<n_direct_addr_list; i++ ) {
  985. int dlen, neg;
  986. const char *dname;
  987. const char *n, *d;
  988. dname = direct_addr_list[i].name;
  989. if (dname == NULL)
  990. continue; /* it's addr/mask entry */
  991. neg = direct_addr_list[i].negative;
  992. if (domain_match(name, dname)) {
  993. debug("match with: %s%s\n", dname, neg? " (negative)": "");
  994. if (neg) {
  995. return 0; /* not direct */
  996. } else {
  997. return 1; /* direct*/
  998. }
  999. }
  1000. }
  1001. return 0; /* not matched */
  1002. }
  1003. /* check to connect to HOST directyly?
  1004. return 1 if to be direct, 0 for else. */
  1005. int
  1006. check_direct(const char *host)
  1007. {
  1008. struct in_addr addr;
  1009. addr.s_addr = inet_addr(host);
  1010. if (addr.s_addr != INADDR_NONE) {
  1011. /* case of IP address */
  1012. if (is_direct_address(addr)) {
  1013. debug("%s is for direct.\n", host);
  1014. return 1; /* true */
  1015. }
  1016. } else {
  1017. /* case of hostname */
  1018. if (is_direct_name(host)) {
  1019. debug("%s is for direct.\n", host);
  1020. return 1; /* true */
  1021. }
  1022. }
  1023. debug("%s is for not direct.\n", host);
  1024. return 0; /* false */
  1025. }
  1026. /** TTY operation **/
  1027. int intr_flag = 0;
  1028. #ifndef _WIN32
  1029. void
  1030. intr_handler(int sig)
  1031. {
  1032. intr_flag = 1;
  1033. }
  1034. void
  1035. tty_change_echo(int fd, int enable)
  1036. {
  1037. static struct termios ntio, otio; /* new/old termios */
  1038. static sigset_t nset, oset; /* new/old sigset */
  1039. static struct sigaction nsa, osa; /* new/old sigaction */
  1040. static int disabled = 0;
  1041. if ( disabled && enable ) {
  1042. /* enable echo */
  1043. tcsetattr(fd, TCSANOW, &otio);
  1044. disabled = 0;
  1045. /* resotore sigaction */
  1046. sigprocmask(SIG_SETMASK, &oset, NULL);
  1047. sigaction(SIGINT, &osa, NULL);
  1048. if ( intr_flag != 0 ) {
  1049. /* re-generate signal */
  1050. kill(getpid(), SIGINT);
  1051. sigemptyset(&nset);
  1052. sigsuspend(&nset);
  1053. intr_flag = 0;
  1054. }
  1055. } else if (!disabled && !enable) {
  1056. /* set SIGINTR handler and break syscall on singal */
  1057. sigemptyset(&nset);
  1058. sigaddset(&nset, SIGTSTP);
  1059. sigprocmask(SIG_BLOCK, &nset, &oset);
  1060. intr_flag = 0;
  1061. memset(&nsa, 0, sizeof(nsa));
  1062. nsa.sa_handler = intr_handler;
  1063. sigaction(SIGINT, &nsa, &osa);
  1064. /* disable echo */
  1065. if (tcgetattr(fd, &otio) == 0 && (otio.c_lflag & ECHO)) {
  1066. disabled = 1;
  1067. ntio = otio;
  1068. ntio.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL);
  1069. (void) tcsetattr(fd, TCSANOW, &ntio);
  1070. }
  1071. }
  1072. return;
  1073. }
  1074. #define TTY_NAME "/dev/tty"
  1075. int
  1076. tty_readpass( const char *prompt, char *buf, size_t size )
  1077. {
  1078. int tty, ret = 0;
  1079. tty = open(TTY_NAME, O_RDWR);
  1080. if ( tty < 0 ) {
  1081. error("Unable to open %s\n", TTY_NAME);
  1082. return -1; /* can't open tty */
  1083. }
  1084. if ( size <= 0 )
  1085. return -1; /* no room */
  1086. write(tty, prompt, strlen(prompt));
  1087. buf[0] = '\0';
  1088. tty_change_echo(tty, 0); /* disable echo */
  1089. ret = read(tty,buf, size-1);
  1090. tty_change_echo(tty, 1); /* restore */
  1091. write(tty, "\n", 1); /* new line */
  1092. close(tty);
  1093. if ( strchr(buf,'\n') == NULL )
  1094. return -1;
  1095. if ( 0 < ret )
  1096. buf[ret] = '\0';
  1097. return ret;
  1098. }
  1099. #else /* _WIN32 */
  1100. BOOL __stdcall
  1101. w32_intr_handler(DWORD dwCtrlType)
  1102. {
  1103. if ( dwCtrlType == CTRL_C_EVENT ) {
  1104. intr_flag = 1;
  1105. return TRUE;
  1106. } else {
  1107. return FALSE;
  1108. }
  1109. }
  1110. #define tty_readpass w32_tty_readpass
  1111. int
  1112. w32_tty_readpass( const char *prompt, char *buf, size_t size )
  1113. {
  1114. HANDLE in = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
  1115. 0, NULL, OPEN_EXISTING, 0, NULL);
  1116. HANDLE out = CreateFile("CONOUT$", GENERIC_WRITE,
  1117. 0, NULL, OPEN_EXISTING, 0, NULL);
  1118. DWORD mode;
  1119. DWORD ret, bytes;
  1120. if (in == INVALID_HANDLE_VALUE || out == INVALID_HANDLE_VALUE)
  1121. fatal("Cannot open console. (errno=%d)", GetLastError());
  1122. WriteFile(out, prompt, strlen(prompt), &bytes, 0);
  1123. SetConsoleCtrlHandler(w32_intr_handler, TRUE ); /* add handler */
  1124. GetConsoleMode(in, &mode);
  1125. SetConsoleMode(in, mode&~ENABLE_ECHO_INPUT); /* disable echo */
  1126. ret = ReadFile(in, buf, size, &bytes, 0);
  1127. SetConsoleMode(in, mode); /* enable echo */
  1128. SetConsoleCtrlHandler( w32_intr_handler, FALSE ); /* remove handler */
  1129. if ( intr_flag )
  1130. GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0); /* re-signal */
  1131. WriteFile(out,"\n", 1, &bytes, 0);
  1132. CloseHandle(in);
  1133. CloseHandle(out);
  1134. return ret;
  1135. }
  1136. #endif /* _WIN32 */
  1137. /*** User / Password ***/
  1138. /* SOCKS5 and HTTP Proxy authentication may requires username and
  1139. password. We ll give it via environment variable or tty.
  1140. Username and password for authentication are decided by
  1141. following rules:
  1142. Username is taken from
  1143. 1) server location spec (i.e. user@host:port)
  1144. 2) environment variables (see tables.1)
  1145. 3) system account name currently logged in.
  1146. Table.1 Order of environment variables for username
  1147. | SOCKS v5 | SOCKS v4 | HTTP proxy |
  1148. --+-------------+-------------+-----------------+
  1149. 1 | SOCKS45_USER | SOCKS4_USER | HTTP_PROXY_USER |
  1150. --+-------------+-------------+ |
  1151. 2 | SOCKS_USER | |
  1152. --+---------------------------+-----------------+
  1153. 3 | CONNECT_USER |
  1154. --+---------------------------------------------+
  1155. Password is taken from
  1156. 1) by environment variables (see table.2)
  1157. 2) by entering from tty.
  1158. Table.2 Order of environment variables for password
  1159. | SOCKS v5 | HTTP proxy |
  1160. --+-----------------+---------------------+
  1161. 1 | SOCKS5_PASSWD | |
  1162. --+-----------------+ HTTP_PROXY_PASSWORD |
  1163. 2 | SOCKS5_PASSWORD | |
  1164. --+-----------------+---------------------+
  1165. 3 | CONNECT_PASSWORD |
  1166. --+---------------------------------------+
  1167. Note: SOCKS5_PASSWD which is added in rev. 1.79
  1168. to share value with NEC SOCKS implementation.
  1169. */
  1170. char *
  1171. determine_relay_user ()
  1172. {
  1173. char *user = NULL;
  1174. /* get username from environment variable, or system. */
  1175. if (relay_method == METHOD_SOCKS) {
  1176. if (user == NULL && socks_version == 5)
  1177. user = getparam (ENV_SOCKS5_USER);
  1178. if (user == NULL && socks_version == 4)
  1179. user = getparam (ENV_SOCKS4_USER);
  1180. if (user == NULL)
  1181. user = getparam (ENV_SOCKS_USER);
  1182. } else if (relay_method == METHOD_HTTP) {
  1183. if (user == NULL)
  1184. user = getparam (ENV_HTTP_PROXY_USER);
  1185. }
  1186. if (user == NULL)
  1187. user = getparam (ENV_CONNECT_USER);
  1188. /* determine relay user by system call if not yet. */
  1189. if (user == NULL)
  1190. user = getusername();
  1191. return user;
  1192. }
  1193. char *
  1194. determine_relay_password ()
  1195. {
  1196. char *pass = NULL;
  1197. if (pass == NULL && relay_method == METHOD_HTTP)
  1198. pass = getparam(ENV_HTTP_PROXY_PASSWORD);
  1199. if (pass == NULL && relay_method == METHOD_SOCKS)
  1200. pass = getparam(ENV_SOCKS5_PASSWD);
  1201. if (pass == NULL && relay_method == METHOD_SOCKS)
  1202. pass = getparam(ENV_SOCKS5_PASSWORD);
  1203. if (pass == NULL)
  1204. pass = getparam(ENV_CONNECT_PASSWORD);
  1205. return pass;
  1206. }
  1207. /*** network operations ***/
  1208. /* set_relay()
  1209. Determine relay informations:
  1210. method, host, port, and username.
  1211. 1st arg, METHOD should be METHOD_xxx.
  1212. 2nd arg, SPEC is hostname or hostname:port or user@hostame:port.
  1213. hostname is domain name or dot notation.
  1214. If port is omitted, use 80 for METHOD_HTTP method,
  1215. use 1080 for METHOD_SOCKS method.
  1216. Username is also able to given by 3rd. format.
  1217. 2nd argument SPEC can be NULL. if NULL, use environment variable.
  1218. */
  1219. int
  1220. set_relay( int method, char *spec )
  1221. {
  1222. char *buf, *sep, *resolve;
  1223. relay_method = method;
  1224. read_parameter_file();
  1225. initialize_direct_addr();
  1226. if (n_direct_addr_list == 0) {
  1227. debug ("No direct address are specified.\n");
  1228. } else {
  1229. debug ("%d direct address entries.\n", n_direct_addr_list);
  1230. }
  1231. switch ( method ) {
  1232. case METHOD_DIRECT:
  1233. return -1; /* nothing to do */
  1234. case METHOD_SOCKS:
  1235. if ( spec == NULL ) {
  1236. switch ( socks_version ) {
  1237. case 5:
  1238. spec = getparam(ENV_SOCKS5_SERVER);
  1239. break;
  1240. case 4:
  1241. spec = getparam(ENV_SOCKS4_SERVER);
  1242. break;
  1243. }
  1244. }
  1245. if ( spec == NULL )
  1246. spec = getparam(ENV_SOCKS_SERVER);
  1247. if ( spec == NULL )
  1248. fatal("Failed to determine SOCKS server.\n");
  1249. relay_port = 1080; /* set default first */
  1250. /* determine resolve method */
  1251. if ( socks_resolve == RESOLVE_UNKNOWN ) {
  1252. if ( ((socks_version == 5) &&
  1253. ((resolve = getparam(ENV_SOCKS5_RESOLVE)) != NULL)) ||
  1254. ((socks_version == 4) &&
  1255. ((resolve = getparam(ENV_SOCKS4_RESOLVE)) != NULL)) ||
  1256. ((resolve = getparam(ENV_SOCKS_RESOLVE)) != NULL) ) {
  1257. socks_resolve = lookup_resolve( resolve );
  1258. if ( socks_resolve == RESOLVE_UNKNOWN )
  1259. fatal("Invalid resolve method: %s\n", resolve);
  1260. } else {
  1261. /* default */
  1262. if ( socks_version == 5 )
  1263. socks_resolve = RESOLVE_REMOTE;
  1264. else
  1265. socks_resolve = RESOLVE_LOCAL;
  1266. }
  1267. }
  1268. break;
  1269. case METHOD_HTTP:
  1270. if ( spec == NULL )
  1271. spec = getparam(ENV_HTTP_PROXY);
  1272. if ( spec == NULL )
  1273. fatal("You must specify http proxy server\n");
  1274. relay_port = 80; /* set default first */
  1275. break;
  1276. case METHOD_TELNET:
  1277. if ( spec == NULL )
  1278. spec = getparam(ENV_TELNET_PROXY);
  1279. if ( spec == NULL )
  1280. fatal("You must specify telnet proxy server\n");
  1281. relay_port = 23; /* set default first */
  1282. }
  1283. if (expect( spec, HTTP_PROXY_PREFIX)) {
  1284. /* URL format like: "http://server:port/" */
  1285. /* extract server:port part */
  1286. buf = strdup( spec + strlen(HTTP_PROXY_PREFIX));
  1287. buf[strcspn(buf, "/")] = '\0';
  1288. } else {
  1289. /* assume spec is aready "server:port" format */
  1290. buf = strdup( spec );
  1291. }
  1292. spec = buf;
  1293. /* check username in spec */
  1294. sep = strchr( spec, '@' );
  1295. if ( sep != NULL ) {
  1296. *sep = '\0';
  1297. relay_user = strdup( spec );
  1298. spec = sep +1;
  1299. }
  1300. if (relay_user == NULL)
  1301. relay_user = determine_relay_user();
  1302. /* split out hostname and port number from spec */
  1303. sep = strchr(spec,':');
  1304. if ( sep == NULL ) {
  1305. /* hostname only, port is already set as default */
  1306. relay_host = strdup( spec );
  1307. } else {
  1308. /* hostname and port */
  1309. relay_port = atoi(sep+1);
  1310. *sep = '\0';
  1311. relay_host = strdup( spec );
  1312. }
  1313. free(buf);
  1314. return 0;
  1315. }
  1316. u_short
  1317. resolve_port( const char *service )
  1318. {
  1319. int port;
  1320. if ( service[strspn (service, digits)] == '\0' ) {
  1321. /* all digits, port number */
  1322. port = atoi(service);
  1323. } else {
  1324. /* treat as service name */
  1325. struct servent *ent;
  1326. ent = getservbyname( service, NULL );
  1327. if ( ent == NULL ) {
  1328. debug("Unknown service, '%s'\n", service);
  1329. port = 0;
  1330. } else {
  1331. port = ntohs(ent->s_port);
  1332. debug("service: %s => %d\n", service, port);
  1333. }
  1334. }
  1335. return (u_short)port;
  1336. }
  1337. void
  1338. make_revstr(void)
  1339. {
  1340. char *ptr;
  1341. size_t len;
  1342. ptr = strstr(rcs_revstr, ": ");
  1343. if (!ptr) {
  1344. revstr = strdup("unknown");
  1345. return;
  1346. }
  1347. ptr += 2;
  1348. /* assume subversion's keyword expansion like "Revision: 96". */
  1349. minor_version = atoi(ptr);
  1350. revstr = xmalloc(20);
  1351. snprintf(revstr, 20, "%d.%d", major_version, minor_version);
  1352. }
  1353. int
  1354. getarg( int argc, char **argv )
  1355. {
  1356. int err = 0;
  1357. char *ptr, *server = (char*)NULL;
  1358. int method = METHOD_DIRECT;
  1359. progname = *argv;
  1360. argc--, argv++;
  1361. /* check optinos */
  1362. while ( (0 < argc) && (**argv == '-') ) {
  1363. ptr = *argv + 1;
  1364. while ( *ptr ) {
  1365. switch ( *ptr ) {
  1366. case 's': /* use SOCKS */
  1367. method = METHOD_SOCKS;
  1368. break;
  1369. case 'n': /* no proxy */
  1370. method = METHOD_DIRECT;
  1371. break;
  1372. case 'h': /* use http-proxy */
  1373. method = METHOD_HTTP;
  1374. break;
  1375. case 't':
  1376. method = METHOD_TELNET;
  1377. break;
  1378. case 'S': /* specify SOCKS server */
  1379. if ( 1 < argc ) {
  1380. argv++, argc--;
  1381. method = METHOD_SOCKS;
  1382. server = *argv;
  1383. } else {
  1384. error("option '-%c' needs argument.\n", *ptr);
  1385. err++;
  1386. }
  1387. break;
  1388. case 'H': /* specify http-proxy server */
  1389. if ( 1 < argc ) {
  1390. argv++, argc--;
  1391. method = METHOD_HTTP;
  1392. server = *argv;
  1393. } else {
  1394. error("option '-%c' needs argument.\n", *ptr);
  1395. err++;
  1396. }
  1397. break;
  1398. case 'T': /* specify telnet proxy server */
  1399. if ( 1 < argc ) {
  1400. argv++, argc--;
  1401. method = METHOD_TELNET;
  1402. server = *argv;
  1403. } else {
  1404. error("option '-%c' needs argument.\n", *ptr);
  1405. err++;
  1406. }
  1407. break;
  1408. case 'c':
  1409. if (1 < argc) {
  1410. argv++, argc--;
  1411. telnet_command = *argv;
  1412. } else {
  1413. error("option '%c' needs argument.\n", *ptr);
  1414. err++;
  1415. }
  1416. break;
  1417. case 'P':
  1418. f_hold_session = 1;
  1419. /* without break */
  1420. case 'p': /* specify port to forward */
  1421. if ( 1 < argc ) {
  1422. argv++, argc--;
  1423. local_type = LOCAL_SOCKET;
  1424. local_port = resolve_port(*argv);
  1425. } else {
  1426. error("option '-%c' needs argument.\n", *ptr);
  1427. err++;
  1428. }
  1429. break;
  1430. #ifndef _WIN32
  1431. case 'w':
  1432. if ( 1 < argc ) {
  1433. argv++, argc--;
  1434. connect_timeout = atoi(*argv);
  1435. } else {
  1436. error("option '-%c' needs argument.\n", *ptr);
  1437. err++;
  1438. }
  1439. break;
  1440. #endif /* not _WIN32 */
  1441. case '4':
  1442. socks_version = 4;
  1443. break;
  1444. case '5':
  1445. socks_version = 5;
  1446. break;
  1447. case 'a':
  1448. if ( 1 < argc ) {
  1449. argv++, argc--;
  1450. socks5_auth = *argv;
  1451. } else {
  1452. error("option '-%c' needs argument.\n", *ptr);
  1453. err++;
  1454. }
  1455. break;
  1456. case 'R': /* specify resolve method */
  1457. if ( 1 < argc ) {
  1458. argv++, argc--;
  1459. socks_resolve = lookup_resolve( *argv );
  1460. } else {
  1461. error("option '-%c' needs argument.\n", *ptr);
  1462. err++;
  1463. }
  1464. break;
  1465. case 'V': /* print version */
  1466. fprintf(stderr, "%s\nVersion %s\n", progdesc, revstr);
  1467. exit(0);
  1468. case 'd': /* debug mode */
  1469. f_debug++;
  1470. break;
  1471. default:
  1472. error("unknown option '-%c'\n", *ptr);
  1473. err++;
  1474. }
  1475. ptr++;
  1476. }
  1477. argc--, argv++;
  1478. }
  1479. /* check error */
  1480. if ( 0 < err )
  1481. goto quit;
  1482. set_relay( method, server );
  1483. /* check destination HOST (MUST) */
  1484. if ( argc == 0 ) {
  1485. fprintf(stderr, "%s\nVersion %s\n", progdesc, revstr);
  1486. fprintf(stderr, usage, progname);
  1487. exit(0);
  1488. }
  1489. dest_host = argv[0];
  1490. /* decide port or service name from programname or argument */
  1491. if ( ((ptr=strrchr( progname, '/' )) != NULL) ||
  1492. ((ptr=strchr( progname, '\\')) != NULL) )
  1493. ptr++;
  1494. else
  1495. ptr = progname;
  1496. if ( dest_port == 0 ) {
  1497. /* accept only if -P is not specified. */
  1498. if ( 1 < argc ) {
  1499. /* get port number from argument (prior to progname) */
  1500. /* NOTE: This way is for cvs ext method. */
  1501. dest_port = resolve_port(argv[1]);
  1502. } else if ( strncmp( ptr, "connect-", 8) == 0 ) {
  1503. /* decide port number from program name */
  1504. char *str = strdup( ptr+8 );
  1505. str[strcspn( str, "." )] = '\0';
  1506. dest_port = resolve_port(str);
  1507. free(str);
  1508. }
  1509. }
  1510. /* check port number */
  1511. if ( dest_port <= 0 ) {
  1512. error( "You must specify the destination port correctly.\n");
  1513. err++;
  1514. goto quit;
  1515. }
  1516. if ( (relay_method != METHOD_DIRECT) && (relay_port <= 0) ) {
  1517. error("Invalid relay port: %d\n", dest_port);
  1518. err++;
  1519. goto quit;
  1520. }
  1521. quit:
  1522. /* report for debugging */
  1523. debug("relay_method = %s (%d)\n",
  1524. method_names[relay_method], relay_method);
  1525. if ( relay_method != METHOD_DIRECT ) {
  1526. debug("relay_host=%s\n", relay_host);
  1527. debug("relay_port=%d\n", relay_port);
  1528. debug("relay_user=%s\n", relay_user);
  1529. }
  1530. if ( relay_method == METHOD_SOCKS ) {
  1531. debug("socks_version=%d\n", socks_version);
  1532. debug("socks_resolve=%s (%d)\n",
  1533. resolve_names[socks_resolve], socks_resolve);
  1534. }
  1535. debug("local_type=%s\n", local_type_names[local_type]);
  1536. if ( local_type == LOCAL_SOCKET ) {
  1537. debug("local_port=%d\n", local_port);
  1538. if (f_hold_session)
  1539. debug (" with holding remote session.\n");
  1540. }
  1541. debug("dest_host=%s\n", dest_host);
  1542. debug("dest_port=%d\n", dest_port);
  1543. if ( 0 < err ) {
  1544. fprintf(stderr, usage, progname);
  1545. exit(1);
  1546. }
  1547. return 0;
  1548. }
  1549. #ifndef _WIN32
  1550. /* Time-out feature is not allowed for Win32 native compilers. */
  1551. /* MSVC and Borland C cannot but Cygwin and UNIXes can. */
  1552. /* timeout signal hander */
  1553. void
  1554. sig_timeout(void)
  1555. {
  1556. signal( SIGALRM, SIG_IGN );
  1557. alarm( 0 );
  1558. error( "timed out\n" );
  1559. exit(1);
  1560. }
  1561. /* set timeout param = seconds, 0 clears */
  1562. void
  1563. set_timeout(int timeout)
  1564. {
  1565. /* This feature is allowed for UNIX or cygwin environments, currently */
  1566. if ( timeout == 0 ) {
  1567. debug( "clearing timeout\n" );
  1568. signal( SIGALRM, SIG_IGN );
  1569. alarm( 0 );
  1570. } else {
  1571. debug( "setting timeout: %d seconds\n", timeout );
  1572. signal(SIGALRM, (void *)sig_timeout);
  1573. alarm( timeout );
  1574. }
  1575. }
  1576. #endif
  1577. #if !defined(_WIN32) && !defined(__CYGWIN32__)
  1578. void
  1579. switch_ns (struct sockaddr_in *ns)
  1580. {
  1581. res_init();
  1582. memcpy (&_res.nsaddr_list[0], ns, sizeof(*ns));
  1583. _res.nscount = 1;
  1584. debug("Using nameserver at %s\n", inet_ntoa(ns->sin_addr));
  1585. }
  1586. #endif /* !_WIN32 && !__CYGWIN32__ */
  1587. /* TODO: IPv6
  1588. TODO: fallback if askpass execution failed.
  1589. */
  1590. int
  1591. local_resolve (const char *host, struct sockaddr_in *addr)
  1592. {
  1593. struct hostent *ent;
  1594. if ( strspn(host, dotdigits) == strlen(host) ) {
  1595. /* given by IPv4 address */
  1596. addr->sin_family = AF_INET;
  1597. addr->sin_addr.s_addr = inet_addr(host);
  1598. } else {
  1599. debug("resolving host by name: %s\n", host);
  1600. ent = gethostbyname (host);
  1601. if ( ent ) {
  1602. memcpy (&addr->sin_addr, ent->h_addr, ent->h_length);
  1603. addr->sin_family = ent->h_addrtype;
  1604. debug("resolved: %s (%s)\n",
  1605. host, inet_ntoa(addr->sin_addr));
  1606. } else {
  1607. debug("failed to resolve locally.\n");
  1608. return -1; /* failed */
  1609. }
  1610. }
  1611. return 0; /* good */
  1612. }
  1613. int
  1614. open_connection( const char *host, u_short port )
  1615. {
  1616. SOCKET s;
  1617. struct sockaddr_in saddr;
  1618. /* resolve address of proxy or direct target */
  1619. if (local_resolve (host, &saddr) < 0) {
  1620. error("can't resolve hostname: %s\n", host);
  1621. return SOCKET_ERROR;
  1622. }
  1623. saddr.sin_port = htons(port);
  1624. debug("connecting to %s:%u\n", inet_ntoa(saddr.sin_addr), port);
  1625. s = socket( AF_INET, SOCK_STREAM, 0 );
  1626. if ( connect( s, (struct sockaddr *)&saddr, sizeof(saddr))
  1627. == SOCKET_ERROR) {
  1628. debug( "connect() failed.\n");
  1629. return SOCKET_ERROR;
  1630. }
  1631. return s;
  1632. }
  1633. void
  1634. report_text( char *prefix, char *buf )
  1635. {
  1636. static char work[1024];
  1637. char *tmp;
  1638. if ( !f_debug )
  1639. return;
  1640. if ( !f_report )
  1641. return; /* don't report */
  1642. debug("%s \"", prefix);
  1643. while ( *buf ) {
  1644. memset( work, 0, sizeof(work));
  1645. tmp = work;
  1646. while ( *buf && ((tmp-work) < (int)sizeof(work)-5) ) {
  1647. switch ( *buf ) {
  1648. case '\t': *tmp++ = '\\'; *tmp++ = 't'; break;
  1649. case '\r': *tmp++ = '\\'; *tmp++ = 'r'; break;
  1650. case '\n': *tmp++ = '\\'; *tmp++ = 'n'; break;
  1651. case '\\': *tmp++ = '\\'; *tmp++ = '\\'; break;
  1652. default:
  1653. if ( isprint(*buf) ) {
  1654. *tmp++ = *buf;
  1655. } else {
  1656. int consumed = tmp - work;
  1657. snprintf( tmp, sizeof(work)-consumed,
  1658. "\\x%02X", (unsigned char)*buf);
  1659. tmp += strlen(tmp);
  1660. }
  1661. }
  1662. buf++;
  1663. *tmp = '\0';
  1664. }
  1665. debug_("%s", work);
  1666. }
  1667. debug_("\"\n");
  1668. }
  1669. void
  1670. report_bytes( char *prefix, char *buf, int len )
  1671. {
  1672. if ( ! f_debug )
  1673. return;
  1674. debug( "%s", prefix );
  1675. while ( 0 < len ) {
  1676. fprintf( stderr, " %02x", *(unsigned char *)buf);
  1677. buf++;
  1678. len--;
  1679. }
  1680. fprintf(stderr, "\n");
  1681. return;
  1682. }
  1683. int
  1684. atomic_out( SOCKET s, char *buf, int size )
  1685. {
  1686. int ret, len;
  1687. assert( buf != NULL );
  1688. assert( 0<=size );
  1689. /* do atomic out */
  1690. ret = 0;
  1691. while ( 0 < size ) {
  1692. len = send( s, buf+ret, size, 0 );
  1693. if ( len == -1 )
  1694. fatal("atomic_out() failed to send(), %d\n", socket_errno());
  1695. ret += len;
  1696. size -= len;
  1697. }
  1698. if (!f_report) {
  1699. debug("atomic_out() [some bytes]\n");
  1700. debug(">>> xx xx xx xx ...\n");
  1701. } else {
  1702. debug("atomic_out() [%d bytes]\n", ret);
  1703. report_bytes(">>>", buf, ret);
  1704. }
  1705. return ret;
  1706. }
  1707. int
  1708. atomic_in( SOCKET s, char *buf, int size )
  1709. {
  1710. int ret, len;
  1711. assert( buf != NULL );
  1712. assert( 0<=size );
  1713. /* do atomic in */
  1714. ret = 0;
  1715. while ( 0 < size ) {
  1716. len = recv( s, buf+ret, size, 0 );
  1717. if ( len == -1 ) {
  1718. fatal("atomic_in() failed to recv(), %d\n", socket_errno());
  1719. } else if ( len == 0 ) {
  1720. fatal( "Connection closed by peer.\n");
  1721. }
  1722. ret += len;
  1723. size -= len;
  1724. }
  1725. if (!f_report) {
  1726. debug("atomic_in() [some bytes]\n");
  1727. debug("<<< xx xx xx xx ...\n");
  1728. } else {
  1729. debug("atomic_in() [%d bytes]\n", ret);
  1730. report_bytes("<<<", buf, ret);
  1731. }
  1732. return ret;
  1733. }
  1734. int
  1735. line_input( SOCKET s, char *buf, int size )
  1736. {
  1737. char *dst = buf;
  1738. if ( size == 0 )
  1739. return 0; /* no error */
  1740. size--;
  1741. while ( 0 < size ) {
  1742. switch ( recv( s, dst, 1, 0) ) { /* recv one-by-one */
  1743. case SOCKET_ERROR:
  1744. error("recv() error\n");
  1745. return -1; /* error */
  1746. case 0:
  1747. size = 0; /* end of stream */
  1748. break;
  1749. default:
  1750. /* continue reading until last 1 char is EOL? */
  1751. if ( *dst == '\n' ) {
  1752. /* finished */
  1753. size = 0;
  1754. } else {
  1755. /* more... */
  1756. size--;
  1757. }
  1758. dst++;
  1759. }
  1760. }
  1761. *dst = '\0';
  1762. report_text( "<<<", buf);
  1763. return 0;
  1764. }
  1765. /* cut_token()
  1766. Span token in given string STR until char in DELIM is appeared.
  1767. Then replace contiguous DELIMS with '\0' for string termination
  1768. and returns next pointer.
  1769. If no next token, return NULL.
  1770. */
  1771. char *
  1772. cut_token( char *str, char *delim)
  1773. {
  1774. char *ptr = str + strcspn(str, delim);
  1775. char *end = ptr + strspn(ptr, delim);
  1776. if ( ptr == str )
  1777. return NULL;
  1778. while ( ptr < end )
  1779. *ptr++ = '\0';
  1780. return ptr;
  1781. }
  1782. const char *
  1783. lookup(int num, LOOKUP_ITEM *items)
  1784. {
  1785. int i = 0;
  1786. while (0 <= items[i].num) {
  1787. if (items[i].num == num)
  1788. return items[i].str;
  1789. i++;
  1790. }
  1791. return "(unknown)";
  1792. }
  1793. /* readpass()
  1794. password input routine
  1795. Use ssh-askpass (same mechanism to OpenSSH)
  1796. */
  1797. char *
  1798. readpass( const char* prompt, ...)
  1799. {
  1800. static char buf[1000]; /* XXX, don't be fix length */
  1801. va_list args;
  1802. va_start(args, prompt);
  1803. vsnprintf(buf, sizeof(buf), prompt, args);
  1804. va_end(args);
  1805. if ( getparam(ENV_SSH_ASKPASS)
  1806. #if !defined(_WIN32) && !defined(__CYGWIN32__)
  1807. && getenv("DISPLAY")
  1808. #endif /* not _WIN32 && not __CYGWIN32__ */
  1809. ) {
  1810. /* use ssh-askpass to get password */
  1811. FILE *fp;
  1812. char *askpass = getparam(ENV_SSH_ASKPASS), *cmd;
  1813. int cmd_size = strlen(askpass) +1 +1 +strlen(buf) +1 +1;
  1814. cmd = xmalloc(cmd_size);
  1815. snprintf(cmd, cmd_size, "%s \"%s\"", askpass, buf);
  1816. fp = popen(cmd, "r");
  1817. free(cmd);
  1818. if ( fp == NULL )
  1819. return NULL; /* fail */
  1820. buf[0] = '\0';
  1821. if (fgets(buf, sizeof(buf), fp) == NULL)
  1822. return NULL; /* fail */
  1823. fclose(fp);
  1824. } else {
  1825. tty_readpass( buf, buf, sizeof(buf));
  1826. }
  1827. buf[strcspn(buf, "\r\n")] = '\0';
  1828. return buf;
  1829. }
  1830. static int
  1831. socks5_do_auth_userpass( int s )
  1832. {
  1833. unsigned char buf[1024], *ptr;
  1834. char *pass = NULL;
  1835. int len;
  1836. /* do User/Password authentication. */
  1837. /* This feature requires username and password from
  1838. command line argument or environment variable,
  1839. or terminal. */
  1840. if (relay_user == NULL)
  1841. fatal("cannot determine user name.\n");
  1842. /* get password from environment variable if exists. */
  1843. if ((pass=determine_relay_password()) == NULL &&
  1844. (pass=readpass("Enter SOCKS5 password for %s@%s: ",
  1845. relay_user, relay_host)) == NULL)
  1846. fatal("Cannot get password for user: %s\n", relay_user);
  1847. /* make authentication packet */
  1848. ptr = buf;
  1849. PUT_BYTE( ptr++, 1 ); /* subnegotiation ver.: 1 */
  1850. len = strlen( relay_user ); /* ULEN and UNAME */
  1851. PUT_BYTE( ptr++, len );
  1852. strcpy( ptr, relay_user );
  1853. ptr += len;
  1854. len = strlen( pass ); /* PLEN and PASSWD */
  1855. PUT_BYTE( ptr++, strlen(pass));
  1856. strcpy( ptr, pass );
  1857. ptr += len;
  1858. memset (pass, 0, strlen(pass)); /* erase password */
  1859. /* send it and get answer */
  1860. f_report = 0;
  1861. atomic_out( s, buf, ptr-buf );
  1862. f_report = 1;
  1863. atomic_in( s, buf, 2 );
  1864. /* check status */
  1865. if ( buf[1] == 0 )
  1866. return 0; /* success */
  1867. else
  1868. return -1; /* fail */
  1869. }
  1870. static const char *
  1871. socks5_getauthname( int auth )
  1872. {
  1873. switch ( auth ) {
  1874. case SOCKS5_AUTH_REJECT: return "REJECTED";
  1875. case SOCKS5_AUTH_NOAUTH: return "NO-AUTH";
  1876. case SOCKS5_AUTH_GSSAPI: return "GSSAPI";
  1877. case SOCKS5_AUTH_USERPASS: return "USERPASS";
  1878. case SOCKS5_AUTH_CHAP: return "CHAP";
  1879. case SOCKS5_AUTH_EAP: return "EAP";
  1880. case SOCKS5_AUTH_MAF: return "MAF";
  1881. default: return "(unknown)";
  1882. }
  1883. }
  1884. typedef struct {
  1885. char* name;
  1886. unsigned char auth;
  1887. } AUTH_METHOD_ITEM;
  1888. AUTH_METHOD_ITEM socks5_auth_table[] = {
  1889. { "none", SOCKS5_AUTH_NOAUTH },
  1890. { "gssapi", SOCKS5_AUTH_GSSAPI },
  1891. { "userpass", SOCKS5_AUTH_USERPASS },
  1892. { "chap", SOCKS5_AUTH_CHAP },
  1893. { NULL, -1 },
  1894. };
  1895. int
  1896. socks5_auth_parse_1(char *start, char *end){
  1897. int i, len;
  1898. for ( ; *start; start++ )
  1899. if ( *start != ' ' && *start != '\t') break;
  1900. for ( end--; end >= start; end-- ) {
  1901. if ( *end != ' ' && *end != '\t'){
  1902. end++;
  1903. break;
  1904. }
  1905. }
  1906. len = end - start;
  1907. for ( i = 0; socks5_auth_table[i].name != NULL; i++ ){
  1908. if ( strncmp(start, socks5_auth_table[i].name, len) == 0) {
  1909. return socks5_auth_table[i].auth;
  1910. }
  1911. }
  1912. fatal("Unknown auth method: %s\n", start);
  1913. return -1;
  1914. }
  1915. int
  1916. socks5_auth_parse(char *start, unsigned char *auth_list, int max_auth){
  1917. char *end;
  1918. int i = 0;
  1919. while ( i < max_auth ) {
  1920. end = strchr(start, ',');
  1921. if (*start && end) {
  1922. auth_list[i++] = socks5_auth_parse_1(start, end);
  1923. start = ++end;
  1924. } else {
  1925. break;
  1926. }
  1927. }
  1928. if ( *start && ( i < max_auth ) ){
  1929. for( end = start; *end; end++ );
  1930. auth_list[i++] = socks5_auth_parse_1(start, end);
  1931. } else {
  1932. fatal("Too much auth method.\n");
  1933. }
  1934. return i;
  1935. }
  1936. /* begin SOCKS5 relaying
  1937. And no authentication is supported.
  1938. */
  1939. int
  1940. begin_socks5_relay( SOCKET s )
  1941. {
  1942. unsigned char buf[256], *ptr, *env = socks5_auth;
  1943. unsigned char n_auth = 0; unsigned char auth_list[10], auth_method;
  1944. int len, auth_result, i;
  1945. debug( "begin_socks_relay()\n");
  1946. /* request authentication */
  1947. ptr = buf;
  1948. PUT_BYTE( ptr++, 5); /* SOCKS version (5) */
  1949. if ( env == NULL )
  1950. env = getparam(ENV_SOCKS5_AUTH);
  1951. if ( env == NULL ) {
  1952. /* add no-auth authentication */
  1953. auth_list[n_auth++] = SOCKS5_AUTH_NOAUTH;
  1954. /* add user/pass authentication */
  1955. auth_list[n_auth++] = SOCKS5_AUTH_USERPASS;
  1956. } else {
  1957. n_auth = socks5_auth_parse(env, auth_list, 10);
  1958. }
  1959. PUT_BYTE( ptr++, n_auth); /* num auth */
  1960. for (i=0; i<n_auth; i++) {
  1961. debug("available auth method[%d] = %s (0x%02x)\n",
  1962. i, socks5_getauthname(auth_list[i]), auth_list[i]);
  1963. PUT_BYTE( ptr++, auth_list[i]); /* authentications */
  1964. }
  1965. atomic_out( s, buf, ptr-buf ); /* send requst */
  1966. atomic_in( s, buf, 2 ); /* recv response */
  1967. if ( (buf[0] != 5) || /* ver5 response */
  1968. (buf[1] == 0xFF) ) { /* check auth method */
  1969. error("No auth method accepted.\n");
  1970. return -1;
  1971. }
  1972. auth_method = buf[1];
  1973. debug("auth method: %s\n", socks5_getauthname(auth_method));
  1974. switch ( auth_method ) {
  1975. case SOCKS5_AUTH_REJECT:
  1976. error("No acceptable authentication method\n");
  1977. return -1; /* fail */
  1978. case SOCKS5_AUTH_NOAUTH:
  1979. /* nothing to do */
  1980. auth_result = 0;
  1981. break;
  1982. case SOCKS5_AUTH_USERPASS:
  1983. auth_result = socks5_do_auth_userpass(s);
  1984. break;
  1985. default:
  1986. error("Unsupported authentication method: %s\n",
  1987. socks5_getauthname( auth_method ));
  1988. return -1; /* fail */
  1989. }
  1990. if ( auth_result != 0 ) {
  1991. error("Authentication failed.\n");
  1992. return -1;
  1993. }
  1994. /* request to connect */
  1995. ptr = buf;
  1996. PUT_BYTE( ptr++, 5); /* SOCKS version (5) */
  1997. PUT_BYTE( ptr++, 1); /* CMD: CONNECT */
  1998. PUT_BYTE( ptr++, 0); /* FLG: 0 */
  1999. if ( dest_addr.sin_addr.s_addr == 0 ) {
  2000. /* resolved by SOCKS server */
  2001. PUT_BYTE( ptr++, 3); /* ATYP: DOMAINNAME */
  2002. len = strlen(dest_host);
  2003. PUT_BYTE( ptr++, len); /* DST.ADDR (len) */
  2004. memcpy( ptr, dest_host, len ); /* (hostname) */
  2005. ptr += len;
  2006. } else {
  2007. /* resolved localy */
  2008. PUT_BYTE( ptr++, 1 ); /* ATYP: IPv4 */
  2009. memcpy( ptr, &dest_addr.sin_addr.s_addr, sizeof(dest_addr.sin_addr));
  2010. ptr += sizeof(dest_addr.sin_addr);
  2011. }
  2012. PUT_BYTE( ptr++, dest_port>>8); /* DST.PORT */
  2013. PUT_BYTE( ptr++, dest_port&0xFF);
  2014. atomic_out( s, buf, ptr-buf); /* send request */
  2015. atomic_in( s, buf, 4 ); /* recv response */
  2016. if ( (buf[1] != SOCKS5_REP_SUCCEEDED) ) { /* check reply code */
  2017. error("Got error response from SOCKS server: %d (%s).\n",
  2018. buf[1], lookup(buf[1], socks5_rep_names));
  2019. return -1;
  2020. }
  2021. ptr = buf + 4;
  2022. switch ( buf[3] ) { /* case by ATYP */
  2023. case 1: /* IP v4 ADDR*/
  2024. atomic_in( s, ptr, 4+2 ); /* recv IPv4 addr and port */
  2025. break;
  2026. case 3: /* DOMAINNAME */
  2027. atomic_in( s, ptr, 1 ); /* recv name and port */
  2028. atomic_in( s, ptr+1, *(unsigned char*)ptr + 2);
  2029. break;
  2030. case 4: /* IP v6 ADDR */
  2031. atomic_in( s, ptr, 16+2 ); /* recv IPv6 addr and port */
  2032. break;
  2033. }
  2034. /* Conguraturation, connected via SOCKS5 server! */
  2035. return 0;
  2036. }
  2037. /* begin SOCKS protocol 4 relaying
  2038. And no authentication is supported.
  2039. There's SOCKS protocol version 4 and 4a. Protocol version
  2040. 4a has capability to resolve hostname by SOCKS server, so
  2041. we don't need resolving IP address of destination host on
  2042. local machine.
  2043. Environment variable SOCKS_RESOLVE directs how to resolve
  2044. IP addess. There's 3 keywords allowed; "local", "remote"
  2045. and "both" (case insensitive). Keyword "local" means taht
  2046. target host name is resolved by localhost resolver
  2047. (usualy with gethostbyname()), "remote" means by remote
  2048. SOCKS server, "both" means to try resolving by localhost
  2049. then remote.
  2050. SOCKS4 protocol and authentication of SOCKS5 protocol
  2051. requires user name on connect request.
  2052. User name is determined by following method.
  2053. 1. If server spec has user@hostname:port format then
  2054. user part is used for this SOCKS server.
  2055. 2. Get user name from environment variable LOGNAME, USER
  2056. (in this order).
  2057. */
  2058. int
  2059. begin_socks4_relay( SOCKET s )
  2060. {
  2061. unsigned char buf[256], *ptr;
  2062. debug( "begin_socks_relay()\n");
  2063. /* make connect request packet
  2064. protocol v4:
  2065. VN:1, CD:1, PORT:2, ADDR:4, USER:n, NULL:1
  2066. protocol v4a:
  2067. VN:1, CD:1, PORT:2, DUMMY:4, USER:n, NULL:1, HOSTNAME:n, NULL:1
  2068. */
  2069. ptr = buf;
  2070. PUT_BYTE( ptr++, 4); /* protocol version (4) */
  2071. PUT_BYTE( ptr++, 1); /* CONNECT command */
  2072. PUT_BYTE( ptr++, dest_port>>8); /* destination Port */
  2073. PUT_BYTE( ptr++, dest_port&0xFF);
  2074. /* destination IP */
  2075. memcpy(ptr, &dest_addr.sin_addr, sizeof(dest_addr.sin_addr));
  2076. ptr += sizeof(dest_addr.sin_addr);
  2077. if ( dest_addr.sin_addr.s_addr == 0 )
  2078. *(ptr-1) = 1; /* fake, protocol 4a */
  2079. /* username */
  2080. if (relay_user == NULL)
  2081. fatal( "Cannot determine user name.\n");
  2082. strcpy( ptr, relay_user );
  2083. ptr += strlen( relay_user ) +1;
  2084. /* destination host name (for protocol 4a) */
  2085. if ( (socks_version == 4) && (dest_addr.sin_addr.s_addr == 0)) {
  2086. strcpy( ptr, dest_host );
  2087. ptr += strlen( dest_host ) +1;
  2088. }
  2089. /* send command and get response
  2090. response is: VN:1, CD:1, PORT:2, ADDR:4 */
  2091. atomic_out( s, buf, ptr-buf); /* send request */
  2092. atomic_in( s, buf, 8 ); /* recv response */
  2093. if ( (buf[1] != SOCKS4_REP_SUCCEEDED) ) { /* check reply code */
  2094. error("Got error response: %d: '%s'.\n",
  2095. buf[1], lookup(buf[1], socks4_rep_names));
  2096. return -1; /* failed */
  2097. }
  2098. /* Conguraturation, connected via SOCKS4 server! */
  2099. return 0;
  2100. }
  2101. int
  2102. sendf(SOCKET s, const char *fmt,...)
  2103. {
  2104. static char buf[10240]; /* xxx, enough? */
  2105. va_list args;
  2106. va_start( args, fmt );
  2107. vsnprintf( buf, sizeof(buf), fmt, args );
  2108. va_end( args );
  2109. report_text(">>>", buf);
  2110. if ( send(s, buf, strlen(buf), 0) == SOCKET_ERROR ) {
  2111. debug("failed to send http request. errno=%d\n", socket_errno());
  2112. return -1;
  2113. }
  2114. return 0;
  2115. }
  2116. const char *base64_table =
  2117. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  2118. char *
  2119. make_base64_string(const char *str)
  2120. {
  2121. static char *buf;
  2122. unsigned char *src;
  2123. char *dst;
  2124. int bits, data, src_len, dst_len;
  2125. /* make base64 string */
  2126. src_len = strlen(str);
  2127. dst_len = (src_len+2)/3*4;
  2128. buf = xmalloc(dst_len+1);
  2129. bits = data = 0;
  2130. src = (unsigned char *)str;
  2131. dst = (unsigned char *)buf;
  2132. while ( dst_len-- ) {
  2133. if ( bits < 6 ) {
  2134. data = (data << 8) | *src;
  2135. bits += 8;
  2136. if ( *src != 0 )
  2137. src++;
  2138. }
  2139. *dst++ = base64_table[0x3F & (data >> (bits-6))];
  2140. bits -= 6;
  2141. }
  2142. *dst = '\0';
  2143. /* fix-up tail padding */
  2144. switch ( src_len%3 ) {
  2145. case 1:
  2146. *--dst = '=';
  2147. case 2:
  2148. *--dst = '=';
  2149. }
  2150. return buf;
  2151. }
  2152. int
  2153. basic_auth (SOCKET s)
  2154. {
  2155. char *userpass;
  2156. char *cred;
  2157. const char *user = relay_user;
  2158. char *pass = NULL;
  2159. int len, ret;
  2160. /* Get username/password for authentication */
  2161. if (user == NULL)
  2162. fatal("Cannot decide username for proxy authentication.");
  2163. if ((pass = determine_relay_password ()) == NULL &&
  2164. (pass = readpass("Enter proxy authentication password for %s@%s: ",
  2165. relay_user, relay_host)) == NULL)
  2166. fatal("Cannot decide password for proxy authentication.");
  2167. len = strlen(user)+strlen(pass)+1;
  2168. userpass = xmalloc(len+1);
  2169. snprintf(userpass, len+1, "%s:%s", user, pass);
  2170. memset (pass, 0, strlen(pass));
  2171. cred = make_base64_string(userpass);
  2172. memset (userpass, 0, len);
  2173. f_report = 0; /* don't report for security */
  2174. ret = sendf(s, "Proxy-Authorization: Basic %s\r\n", cred);
  2175. f_report = 1;
  2176. report_text(">>>", "Proxy-Authorization: Basic xxxxx\r\n");
  2177. memset(cred, 0, strlen(cred));
  2178. free(cred);
  2179. return ret;
  2180. }
  2181. /* begin relaying via HTTP proxy
  2182. Directs CONNECT method to proxy server to connect to
  2183. destination host (and port). It may not be allowed on your
  2184. proxy server.
  2185. */
  2186. int
  2187. begin_http_relay( SOCKET s )
  2188. {
  2189. char buf[1024];
  2190. int result;
  2191. char *auth_what;
  2192. debug("begin_http_relay()\n");
  2193. if (sendf(s,"CONNECT %s:%d HTTP/1.0\r\n", dest_host, dest_port) < 0)
  2194. return START_ERROR;
  2195. if (proxy_auth_type == PROXY_AUTH_BASIC && basic_auth (s) < 0)
  2196. return START_ERROR;
  2197. if (sendf(s,"\r\n") < 0)
  2198. return START_ERROR;
  2199. /* get response */
  2200. if ( line_input(s, buf, sizeof(buf)) < 0 ) {
  2201. debug("failed to read http response.\n");
  2202. return START_ERROR;
  2203. }
  2204. /* check status */
  2205. if (!strchr(buf, ' ')) {
  2206. error ("Unexpected http response: '%s'.\n", buf);
  2207. return START_ERROR;
  2208. }
  2209. result = atoi(strchr(buf,' '));
  2210. switch ( result ) {
  2211. case 200:
  2212. /* Conguraturation, connected via http proxy server! */
  2213. debug("connected, start user session.\n");
  2214. break;
  2215. case 302: /* redirect */
  2216. do {
  2217. if (line_input(s, buf, sizeof(buf)))
  2218. break;
  2219. downcase(buf);
  2220. if (expect(buf, "Location: ")) {
  2221. relay_host = cut_token(buf, "//");
  2222. cut_token(buf, "/");
  2223. relay_port = atoi(cut_token(buf, ":"));
  2224. }
  2225. } while (strcmp(buf,"\r\n") != 0);
  2226. return START_RETRY;
  2227. /* We handle both 401 and 407 codes here: 401 is WWW-Authenticate, which
  2228. * not strictly the correct response, but some proxies do send this (e.g.
  2229. * Symantec's Raptor firewall) */
  2230. case 401: /* WWW-Auth required */
  2231. case 407: /* Proxy-Auth required */
  2232. /** NOTE: As easy implementation, we support only BASIC scheme
  2233. and ignore realm. */
  2234. /* If proxy_auth_type is PROXY_AUTH_BASIC and get
  2235. this result code, authentication was failed. */
  2236. if (proxy_auth_type != PROXY_AUTH_NONE) {
  2237. error("Authentication failed.\n");
  2238. return START_ERROR;
  2239. }
  2240. auth_what = (result == 401) ? "WWW-Authenticate:" : "Proxy-Authenticate:";
  2241. do {
  2242. if ( line_input(s, buf, sizeof(buf)) ) {
  2243. break;
  2244. }
  2245. downcase(buf);
  2246. if (expect(buf, auth_what)) {
  2247. /* parse type and realm */
  2248. char *scheme, *realm;
  2249. scheme = cut_token(buf, " ");
  2250. realm = cut_token(scheme, " ");
  2251. if ( scheme == NULL || realm == NULL ) {
  2252. debug("Invalid format of %s field.", auth_what);
  2253. return START_ERROR; /* fail */
  2254. }
  2255. /* check supported auth type */
  2256. if (expect(scheme, "basic")) {
  2257. proxy_auth_type = PROXY_AUTH_BASIC;
  2258. } else {
  2259. debug("Unsupported authentication type: %s", scheme);
  2260. }
  2261. }
  2262. } while (strcmp(buf,"\r\n") != 0);
  2263. if ( proxy_auth_type == PROXY_AUTH_NONE ) {
  2264. debug("Can't find %s in response header.", auth_what);
  2265. return START_ERROR;
  2266. } else {
  2267. return START_RETRY;
  2268. }
  2269. default:
  2270. /* Not allowed */
  2271. debug("http proxy is not allowed.\n");
  2272. return START_ERROR;
  2273. }
  2274. /* skip to end of response header */
  2275. do {
  2276. if ( line_input(s, buf, sizeof(buf) ) ) {
  2277. debug("Can't skip response headers\n");
  2278. return START_ERROR;
  2279. }
  2280. } while ( strcmp(buf,"\r\n") != 0 );
  2281. return START_OK;
  2282. }
  2283. /* begin relaying via TELNET proxy.
  2284. Sends string specified by telnet_command (-c option) with
  2285. replacing host name and port number to the socket. */
  2286. int
  2287. begin_telnet_relay( SOCKET s )
  2288. {
  2289. char buf[1024];
  2290. char *cmd;
  2291. char *good_phrase = "connected to";
  2292. char *bad_phrase_list[] = {
  2293. " failed", " refused", " rejected", " closed"
  2294. };
  2295. char sep = ' ';
  2296. int i;
  2297. debug("begin_telnet_relay()\n");
  2298. /* report phrase */
  2299. debug("good phrase: '%s'\n", good_phrase);
  2300. debug("bad phrases");
  2301. sep = ':';
  2302. for (i=0; i< (sizeof(bad_phrase_list) / sizeof(char*)); i++) {
  2303. debug_("%c '%s'", sep, bad_phrase_list[i]);
  2304. sep = ',';
  2305. }
  2306. debug_("\n");
  2307. /* make request string with replacing %h by destination hostname
  2308. and %p by port number, etc. */
  2309. cmd = expand_host_and_port(telnet_command, dest_host, dest_port);
  2310. /* Sorry, we send request string now without waiting a prompt. */
  2311. if (sendf(s, "%s\r\n", cmd) < 0) {
  2312. free(cmd);
  2313. return START_ERROR;
  2314. }
  2315. free(cmd);
  2316. /* Process answer from proxy until good or bad phrase is detected. We
  2317. assume that the good phrase should be appeared only in the final
  2318. line of proxy responses. Bad keywods in the line causes operation
  2319. fail. First checks a good phrase, then checks bad phrases.
  2320. If no match, continue reading line from proxy. */
  2321. while (!line_input(s, buf, sizeof(buf)) && buf[0] != '\0') {
  2322. downcase(buf);
  2323. /* first, check good phrase */
  2324. if (strstr(buf, good_phrase)) {
  2325. debug("good phrase is detected: '%s'\n", good_phrase);
  2326. return START_OK;
  2327. }
  2328. /* then, check bad phrase */
  2329. for (i=0; i<(sizeof(bad_phrase_list)/sizeof(char*)); i++) {
  2330. if (strstr(buf, bad_phrase_list[i]) != NULL) {
  2331. debug("bad phrase is detected: '%s'\n", bad_phrase_list[i]);
  2332. return START_ERROR;
  2333. }
  2334. }
  2335. }
  2336. debug("error reading from telnet proxy\n");
  2337. return START_ERROR;
  2338. }
  2339. #ifdef _WIN32
  2340. /* ddatalen()
  2341. Returns 1 if data is available, otherwise return 0
  2342. */
  2343. int
  2344. stdindatalen (void)
  2345. {
  2346. DWORD len = 0;
  2347. struct stat st;
  2348. fstat( 0, &st );
  2349. if ( st.st_mode & _S_IFIFO ) {
  2350. /* in case of PIPE */
  2351. if ( !PeekNamedPipe( GetStdHandle(STD_INPUT_HANDLE),
  2352. NULL, 0, NULL, &len, NULL) ) {
  2353. if ( GetLastError() == ERROR_BROKEN_PIPE ) {
  2354. /* PIPE source is closed */
  2355. /* read() will detects EOF */
  2356. len = 1;
  2357. } else {
  2358. fatal("PeekNamedPipe() failed, errno=%d\n",
  2359. GetLastError());
  2360. }
  2361. }
  2362. } else if ( st.st_mode & _S_IFREG ) {
  2363. /* in case of regular file (redirected) */
  2364. len = 1; /* always data ready */
  2365. } else if ( _kbhit() ) {
  2366. /* in case of console */
  2367. len = 1;
  2368. }
  2369. return len;
  2370. }
  2371. #endif /* _WIN32 */
  2372. /* relay byte from stdin to socket and fro socket to stdout.
  2373. returns reason of termination */
  2374. int
  2375. do_repeater( SOCKET local_in, SOCKET local_out, SOCKET remote )
  2376. {
  2377. /** vars for local input data **/
  2378. char lbuf[1024]; /* local input buffer */
  2379. int lbuf_len; /* available data in lbuf */
  2380. int f_local; /* read local input more? */
  2381. /** vars for remote input data **/
  2382. char rbuf[1024]; /* remote input buffer */
  2383. int rbuf_len; /* available data in rbuf */
  2384. int f_remote; /* read remote input more? */
  2385. int close_reason = REASON_UNK; /* reason of end repeating */
  2386. /** other variables **/
  2387. int nfds, len;
  2388. fd_set ifds, ofds;
  2389. struct timeval *tmo;
  2390. #ifdef _WIN32
  2391. struct timeval win32_tmo;
  2392. #endif /* _WIN32 */
  2393. /* repeater between stdin/out and socket */
  2394. nfds = ((local_in<remote)? remote: local_in) +1;
  2395. f_local = 1; /* yes, read from local */
  2396. f_remote = 1; /* yes, read from remote */
  2397. lbuf_len = 0;
  2398. rbuf_len = 0;
  2399. while ( f_local || f_remote ) {
  2400. FD_ZERO(&ifds );
  2401. FD_ZERO(&ofds );
  2402. tmo = NULL;
  2403. /** prepare for reading local input **/
  2404. if ( f_local && (lbuf_len < (int)sizeof(lbuf)) ) {
  2405. #ifdef _WIN32
  2406. if ( local_type != LOCAL_SOCKET ) {
  2407. /* select() on Winsock is not accept standard handle.
  2408. So use select() with short timeout and checking data
  2409. in stdin by another method. */
  2410. win32_tmo.tv_sec = 0;
  2411. win32_tmo.tv_usec = 10*1000; /* 10 ms */
  2412. tmo = &win32_tmo;
  2413. } else
  2414. #endif /* !_WIN32 */
  2415. FD_SET( local_in, &ifds );
  2416. }
  2417. /** prepare for reading remote input **/
  2418. if ( f_remote && (rbuf_len < (int)sizeof(rbuf)) ) {
  2419. FD_SET( remote, &ifds );
  2420. }
  2421. /* FD_SET( local_out, ofds ); */
  2422. /* FD_SET( remote, ofds ); */
  2423. if ( select( nfds, &ifds, &ofds, (fd_set*)NULL, tmo ) == -1 ) {
  2424. /* some error */
  2425. error( "select() failed, %d\n", socket_errno());
  2426. return REASON_ERROR;
  2427. }
  2428. #ifdef _WIN32
  2429. /* fake ifds if local is stdio handle because
  2430. select() of Winsock does not accept stdio
  2431. handle. */
  2432. if (f_local && (local_type!=LOCAL_SOCKET) && (0<stdindatalen()))
  2433. FD_SET(0,&ifds); /* data ready */
  2434. #endif
  2435. /* remote => local */
  2436. if ( FD_ISSET(remote, &ifds) && (rbuf_len < (int)sizeof(rbuf)) ) {
  2437. len = recv( remote, rbuf + rbuf_len, sizeof(rbuf)-rbuf_len, 0);
  2438. if ( len == 0 || (len == -1 && socket_errno() == ECONNRESET)) {
  2439. debug("connection %s by peer\n",
  2440. (len==0)? "closed": "reset");
  2441. close_reason = REASON_CLOSED_BY_REMOTE;
  2442. f_remote = 0; /* no more read from socket */
  2443. f_local = 0;
  2444. } else if ( len == -1 ) {
  2445. /* error */
  2446. fatal("recv() failed, %d\n", socket_errno());
  2447. } else {
  2448. debug("recv %d bytes\n", len);
  2449. if ( 1 < f_debug ) /* more verbose */
  2450. report_bytes( "<<<", rbuf+rbuf_len, len);
  2451. rbuf_len += len;
  2452. }
  2453. }
  2454. /* local => remote */
  2455. if ( FD_ISSET(local_in, &ifds) && (lbuf_len < (int)sizeof(lbuf)) ) {
  2456. if (local_type == LOCAL_SOCKET)
  2457. len = recv(local_in, lbuf + lbuf_len,
  2458. sizeof(lbuf)-lbuf_len, 0);
  2459. else
  2460. len = read(local_in, lbuf + lbuf_len, sizeof(lbuf)-lbuf_len);
  2461. if ( len == 0 ) {
  2462. /* stdin is EOF */
  2463. debug("local input is EOF\n");
  2464. if (!f_hold_session)
  2465. shutdown(remote, 1); /* no-more writing */
  2466. f_local = 0;
  2467. close_reason = REASON_CLOSED_BY_LOCAL;
  2468. } else if ( len == -1 ) {
  2469. /* error on reading from stdin */
  2470. if (f_hold_session) {
  2471. debug ("failed to read from local\n");
  2472. f_local = 0;
  2473. close_reason = REASON_CLOSED_BY_LOCAL;
  2474. } else
  2475. fatal("recv() failed, errno = %d\n", errno);
  2476. } else {
  2477. /* repeat */
  2478. lbuf_len += len;
  2479. }
  2480. }
  2481. /* flush data in buffer to socket */
  2482. if ( 0 < lbuf_len ) {
  2483. len = send(remote, lbuf, lbuf_len, 0);
  2484. if ( len == -1 ) {
  2485. fatal("send() failed, %d\n", socket_errno());
  2486. } else if ( 0 < len ) {
  2487. if ( 1 < f_debug ) /* more verbose */
  2488. report_bytes( ">>>", lbuf, len);
  2489. /* move data on to top of buffer */
  2490. debug("sent %d bytes\n", len);
  2491. lbuf_len -= len;
  2492. if ( 0 < lbuf_len )
  2493. memcpy( lbuf, lbuf+len, lbuf_len );
  2494. assert( 0 <= lbuf_len );
  2495. }
  2496. }
  2497. /* flush data in buffer to local output */
  2498. if ( 0 < rbuf_len ) {
  2499. if (local_type == LOCAL_SOCKET)
  2500. len = send( local_out, rbuf, rbuf_len, 0);
  2501. else
  2502. len = write( local_out, rbuf, rbuf_len);
  2503. if ( len == -1 ) {
  2504. fatal("output (local) failed, errno=%d\n", errno);
  2505. }
  2506. rbuf_len -= len;
  2507. if ( len < rbuf_len )
  2508. memcpy( rbuf, rbuf+len, rbuf_len );
  2509. assert( 0 <= rbuf_len );
  2510. }
  2511. if (f_local == 0 && f_hold_session) {
  2512. debug ("closing local port without disconnecting from remote\n");
  2513. f_remote = 0;
  2514. shutdown (local_out, 2);
  2515. close (local_out);
  2516. break;
  2517. }
  2518. }
  2519. return close_reason;
  2520. }
  2521. int
  2522. accept_connection (u_short port)
  2523. {
  2524. static int sock = -1;
  2525. int connection;
  2526. struct sockaddr_in name;
  2527. struct sockaddr client;
  2528. int socklen;
  2529. fd_set ifds;
  2530. int nfds;
  2531. int sockopt;
  2532. /* Create the socket. */
  2533. debug("Creating source port to forward.\n");
  2534. sock = socket (PF_INET, SOCK_STREAM, 0);
  2535. if (sock < 0)
  2536. fatal("socket() failed, errno=%d\n", socket_errno());
  2537. sockopt = 1;
  2538. setsockopt (sock, SOL_SOCKET, SO_REUSEADDR,
  2539. (void*)&sockopt, sizeof(sockopt));
  2540. /* Give the socket a name. */
  2541. name.sin_family = AF_INET;
  2542. name.sin_port = htons (port);
  2543. name.sin_addr.s_addr = htonl (INADDR_ANY);
  2544. if (bind (sock, (struct sockaddr *) &name, sizeof (name)) < 0)
  2545. fatal ("bind() failed, errno=%d\n", socket_errno());
  2546. if (listen( sock, 1) < 0)
  2547. fatal ("listen() failed, errno=%d\n", socket_errno());
  2548. /* wait for new connection with watching EOF of stdin. */
  2549. debug ("waiting new connection at port %d (socket=%d)\n", port, sock);
  2550. nfds = sock + 1;
  2551. do {
  2552. int n;
  2553. struct timeval *ptmo = NULL;
  2554. #ifdef _WIN32
  2555. struct timeval tmo;
  2556. tmo.tv_sec = 0;
  2557. tmo.tv_usec = 100*1000; /* On Windows, 100ms timeout */
  2558. ptmo = &tmo;
  2559. #endif /* _WIN32 */
  2560. FD_ZERO (&ifds);
  2561. FD_SET ((SOCKET)sock, &ifds);
  2562. #ifndef _WIN32
  2563. FD_SET (0, &ifds); /* watch stdin */
  2564. #endif
  2565. n = select (nfds, &ifds, NULL, NULL, ptmo);
  2566. if (n == -1) {
  2567. fatal ("select() failed, %d\n", socket_errno());
  2568. exit (1);
  2569. }
  2570. #ifdef _WIN32
  2571. if (0 < stdindatalen()) {
  2572. FD_SET (0, &ifds); /* fake */
  2573. n++;
  2574. }
  2575. #endif
  2576. if (0 < n) {
  2577. if (FD_ISSET(0, &ifds) && (getchar() <= 0)) {
  2578. /* EOF */
  2579. debug ("Give-up waiting port because stdin is closed.");
  2580. exit(0);
  2581. }
  2582. if (FD_ISSET(sock, &ifds))
  2583. break; /* socket is stimulated */
  2584. }
  2585. } while (1);
  2586. socklen = sizeof(client);
  2587. connection = accept( sock, &client, &socklen);
  2588. if ( connection < 0 )
  2589. fatal ("accept() failed, errno=%d\n", socket_errno());
  2590. return connection;
  2591. }
  2592. /** Main of program **/
  2593. int
  2594. main( int argc, char **argv )
  2595. {
  2596. int ret;
  2597. int remote; /* socket */
  2598. int local_in; /* Local input */
  2599. int local_out; /* Local output */
  2600. int reason;
  2601. #ifdef _WIN32
  2602. WSADATA wsadata;
  2603. WSAStartup( 0x101, &wsadata);
  2604. #endif /* _WIN32 */
  2605. /* initialization */
  2606. make_revstr();
  2607. getarg( argc, argv );
  2608. debug("Program is $Revision: 100 $\n");
  2609. /* Open local_in and local_out if forwarding a port */
  2610. if ( local_type == LOCAL_SOCKET ) {
  2611. /* Relay between local port and destination */
  2612. local_in = local_out = accept_connection( local_port );
  2613. } else {
  2614. /* Relay between stdin/stdout and desteination */
  2615. local_in = 0;
  2616. local_out = 1;
  2617. #ifdef _WIN32
  2618. _setmode(local_in, O_BINARY);
  2619. _setmode(local_out, O_BINARY);
  2620. #endif
  2621. }
  2622. retry:
  2623. #ifndef _WIN32
  2624. if (0 < connect_timeout)
  2625. set_timeout (connect_timeout);
  2626. #endif /* not _WIN32 */
  2627. if (check_direct(dest_host))
  2628. relay_method = METHOD_DIRECT;
  2629. /* make connection */
  2630. if ( relay_method == METHOD_DIRECT ) {
  2631. remote = open_connection (dest_host, dest_port);
  2632. if ( remote == SOCKET_ERROR )
  2633. fatal( "Unable to connect to destination host, errno=%d\n",
  2634. socket_errno());
  2635. } else {
  2636. remote = open_connection (relay_host, relay_port);
  2637. if ( remote == SOCKET_ERROR )
  2638. fatal( "Unable to connect to relay host, errno=%d\n",
  2639. socket_errno());
  2640. }
  2641. /** resolve destination host (SOCKS) **/
  2642. #if !defined(_WIN32) && !defined(__CYGWIN32__)
  2643. if (socks_ns.sin_addr.s_addr != 0)
  2644. switch_ns (&socks_ns);
  2645. #endif /* not _WIN32 && not __CYGWIN32__ */
  2646. if (relay_method == METHOD_SOCKS &&
  2647. socks_resolve == RESOLVE_LOCAL &&
  2648. local_resolve (dest_host, &dest_addr) < 0) {
  2649. fatal("Unknown host: %s", dest_host);
  2650. }
  2651. /** relay negociation **/
  2652. switch ( relay_method ) {
  2653. case METHOD_SOCKS:
  2654. if ( ((socks_version == 5) && (begin_socks5_relay(remote) < 0)) ||
  2655. ((socks_version == 4) && (begin_socks4_relay(remote) < 0)) )
  2656. fatal( "failed to begin relaying via SOCKS.\n");
  2657. break;
  2658. case METHOD_HTTP:
  2659. ret = begin_http_relay(remote);
  2660. switch (ret) {
  2661. case START_ERROR:
  2662. close (remote);
  2663. fatal("failed to begin relaying via HTTP.\n");
  2664. case START_OK:
  2665. break;
  2666. case START_RETRY:
  2667. /* retry with authentication */
  2668. close (remote);
  2669. goto retry;
  2670. }
  2671. break;
  2672. case METHOD_TELNET:
  2673. if (begin_telnet_relay(remote) < 0)
  2674. fatal("failed to begin relaying via telnet.\n");
  2675. break;
  2676. }
  2677. debug("connected\n");
  2678. #ifndef _WIN32
  2679. if (0 < connect_timeout)
  2680. set_timeout (0);
  2681. #endif /* not _WIN32 */
  2682. /* main loop */
  2683. debug ("start relaying.\n");
  2684. do_repeater:
  2685. reason = do_repeater(local_in, local_out, remote);
  2686. debug ("relaying done.\n");
  2687. if (local_type == LOCAL_SOCKET &&
  2688. reason == REASON_CLOSED_BY_LOCAL &&
  2689. f_hold_session) {
  2690. /* re-wait at local port without closing remote session */
  2691. debug ("re-waiting at local port %d\n", local_port);
  2692. local_in = local_out = accept_connection( local_port );
  2693. debug ("re-start relaying\n");
  2694. goto do_repeater;
  2695. }
  2696. closesocket(remote);
  2697. if ( local_type == LOCAL_SOCKET)
  2698. closesocket(local_in);
  2699. #ifdef _WIN32
  2700. WSACleanup();
  2701. #endif /* _WIN32 */
  2702. debug ("that's all, bye.\n");
  2703. return 0;
  2704. }
  2705. /* ------------------------------------------------------------
  2706. Local Variables:
  2707. compile-command: "cc connect.c -o connect"
  2708. tab-width: 8
  2709. fill-column: 74
  2710. comment-column: 48
  2711. End:
  2712. ------------------------------------------------------------ */
  2713. /*** end of connect.c ***/