proxy.c 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604
  1. /*
  2. * Network proxy abstraction in PuTTY
  3. *
  4. * A proxy layer, if necessary, wedges itself between the network
  5. * code and the higher level backend.
  6. */
  7. #include <assert.h>
  8. #include <ctype.h>
  9. #include <string.h>
  10. #define DEFINE_PLUG_METHOD_MACROS
  11. #include "putty.h"
  12. #include "network.h"
  13. #include "proxy.h"
  14. #define do_proxy_dns(conf) \
  15. (conf_get_int(conf, CONF_proxy_dns) == FORCE_ON || \
  16. (conf_get_int(conf, CONF_proxy_dns) == AUTO && \
  17. conf_get_int(conf, CONF_proxy_type) != PROXY_SOCKS4))
  18. /*
  19. * Call this when proxy negotiation is complete, so that this
  20. * socket can begin working normally.
  21. */
  22. void proxy_activate (Proxy_Socket p)
  23. {
  24. void *data;
  25. int len;
  26. long output_before, output_after;
  27. p->state = PROXY_STATE_ACTIVE;
  28. /* we want to ignore new receive events until we have sent
  29. * all of our buffered receive data.
  30. */
  31. sk_set_frozen(p->sub_socket, 1);
  32. /* how many bytes of output have we buffered? */
  33. output_before = bufchain_size(&p->pending_oob_output_data) +
  34. bufchain_size(&p->pending_output_data);
  35. /* and keep track of how many bytes do not get sent. */
  36. output_after = 0;
  37. /* send buffered OOB writes */
  38. while (bufchain_size(&p->pending_oob_output_data) > 0) {
  39. bufchain_prefix(&p->pending_oob_output_data, &data, &len);
  40. output_after += sk_write_oob(p->sub_socket, data, len);
  41. bufchain_consume(&p->pending_oob_output_data, len);
  42. }
  43. /* send buffered normal writes */
  44. while (bufchain_size(&p->pending_output_data) > 0) {
  45. bufchain_prefix(&p->pending_output_data, &data, &len);
  46. output_after += sk_write(p->sub_socket, data, len);
  47. bufchain_consume(&p->pending_output_data, len);
  48. }
  49. /* if we managed to send any data, let the higher levels know. */
  50. if (output_after < output_before)
  51. plug_sent(p->plug, output_after);
  52. /* if we were asked to flush the output during
  53. * the proxy negotiation process, do so now.
  54. */
  55. if (p->pending_flush) sk_flush(p->sub_socket);
  56. /* if we have a pending EOF to send, send it */
  57. if (p->pending_eof) sk_write_eof(p->sub_socket);
  58. /* if the backend wanted the socket unfrozen, try to unfreeze.
  59. * our set_frozen handler will flush buffered receive data before
  60. * unfreezing the actual underlying socket.
  61. */
  62. if (!p->freeze)
  63. sk_set_frozen((Socket)p, 0);
  64. }
  65. /* basic proxy socket functions */
  66. static Plug sk_proxy_plug (Socket s, Plug p)
  67. {
  68. Proxy_Socket ps = (Proxy_Socket) s;
  69. Plug ret = ps->plug;
  70. if (p)
  71. ps->plug = p;
  72. return ret;
  73. }
  74. static void sk_proxy_close (Socket s)
  75. {
  76. Proxy_Socket ps = (Proxy_Socket) s;
  77. sk_close(ps->sub_socket);
  78. sk_addr_free(ps->remote_addr);
  79. sfree(ps);
  80. }
  81. static int sk_proxy_write (Socket s, const char *data, int len)
  82. {
  83. Proxy_Socket ps = (Proxy_Socket) s;
  84. if (ps->state != PROXY_STATE_ACTIVE) {
  85. bufchain_add(&ps->pending_output_data, data, len);
  86. return bufchain_size(&ps->pending_output_data);
  87. }
  88. return sk_write(ps->sub_socket, data, len);
  89. }
  90. static int sk_proxy_write_oob (Socket s, const char *data, int len)
  91. {
  92. Proxy_Socket ps = (Proxy_Socket) s;
  93. if (ps->state != PROXY_STATE_ACTIVE) {
  94. bufchain_clear(&ps->pending_output_data);
  95. bufchain_clear(&ps->pending_oob_output_data);
  96. bufchain_add(&ps->pending_oob_output_data, data, len);
  97. return len;
  98. }
  99. return sk_write_oob(ps->sub_socket, data, len);
  100. }
  101. static void sk_proxy_write_eof (Socket s)
  102. {
  103. Proxy_Socket ps = (Proxy_Socket) s;
  104. if (ps->state != PROXY_STATE_ACTIVE) {
  105. ps->pending_eof = 1;
  106. return;
  107. }
  108. sk_write_eof(ps->sub_socket);
  109. }
  110. static void sk_proxy_flush (Socket s)
  111. {
  112. Proxy_Socket ps = (Proxy_Socket) s;
  113. if (ps->state != PROXY_STATE_ACTIVE) {
  114. ps->pending_flush = 1;
  115. return;
  116. }
  117. sk_flush(ps->sub_socket);
  118. }
  119. static void sk_proxy_set_frozen (Socket s, int is_frozen)
  120. {
  121. Proxy_Socket ps = (Proxy_Socket) s;
  122. if (ps->state != PROXY_STATE_ACTIVE) {
  123. ps->freeze = is_frozen;
  124. return;
  125. }
  126. /* handle any remaining buffered recv data first */
  127. if (bufchain_size(&ps->pending_input_data) > 0) {
  128. ps->freeze = is_frozen;
  129. /* loop while we still have buffered data, and while we are
  130. * unfrozen. the plug_receive call in the loop could result
  131. * in a call back into this function refreezing the socket,
  132. * so we have to check each time.
  133. */
  134. while (!ps->freeze && bufchain_size(&ps->pending_input_data) > 0) {
  135. void *data;
  136. char databuf[512];
  137. int len;
  138. bufchain_prefix(&ps->pending_input_data, &data, &len);
  139. if (len > lenof(databuf))
  140. len = lenof(databuf);
  141. memcpy(databuf, data, len);
  142. bufchain_consume(&ps->pending_input_data, len);
  143. plug_receive(ps->plug, 0, databuf, len);
  144. }
  145. /* if we're still frozen, we'll have to wait for another
  146. * call from the backend to finish unbuffering the data.
  147. */
  148. if (ps->freeze) return;
  149. }
  150. sk_set_frozen(ps->sub_socket, is_frozen);
  151. }
  152. static const char * sk_proxy_socket_error (Socket s)
  153. {
  154. Proxy_Socket ps = (Proxy_Socket) s;
  155. if (ps->error != NULL || ps->sub_socket == NULL) {
  156. return ps->error;
  157. }
  158. return sk_socket_error(ps->sub_socket);
  159. }
  160. /* basic proxy plug functions */
  161. static void plug_proxy_log(Plug plug, int type, SockAddr addr, int port,
  162. const char *error_msg, int error_code)
  163. {
  164. Proxy_Plug pp = (Proxy_Plug) plug;
  165. Proxy_Socket ps = pp->proxy_socket;
  166. plug_log(ps->plug, type, addr, port, error_msg, error_code);
  167. }
  168. static void plug_proxy_closing (Plug p, const char *error_msg,
  169. int error_code, int calling_back)
  170. {
  171. Proxy_Plug pp = (Proxy_Plug) p;
  172. Proxy_Socket ps = pp->proxy_socket;
  173. if (ps->state != PROXY_STATE_ACTIVE) {
  174. ps->closing_error_msg = error_msg;
  175. ps->closing_error_code = error_code;
  176. ps->closing_calling_back = calling_back;
  177. ps->negotiate(ps, PROXY_CHANGE_CLOSING);
  178. } else {
  179. plug_closing(ps->plug, error_msg, error_code, calling_back);
  180. }
  181. }
  182. static void plug_proxy_receive (Plug p, int urgent, char *data, int len)
  183. {
  184. Proxy_Plug pp = (Proxy_Plug) p;
  185. Proxy_Socket ps = pp->proxy_socket;
  186. if (ps->state != PROXY_STATE_ACTIVE) {
  187. /* we will lose the urgentness of this data, but since most,
  188. * if not all, of this data will be consumed by the negotiation
  189. * process, hopefully it won't affect the protocol above us
  190. */
  191. bufchain_add(&ps->pending_input_data, data, len);
  192. ps->receive_urgent = urgent;
  193. ps->receive_data = data;
  194. ps->receive_len = len;
  195. ps->negotiate(ps, PROXY_CHANGE_RECEIVE);
  196. } else {
  197. plug_receive(ps->plug, urgent, data, len);
  198. }
  199. }
  200. static void plug_proxy_sent (Plug p, int bufsize)
  201. {
  202. Proxy_Plug pp = (Proxy_Plug) p;
  203. Proxy_Socket ps = pp->proxy_socket;
  204. if (ps->state != PROXY_STATE_ACTIVE) {
  205. ps->sent_bufsize = bufsize;
  206. ps->negotiate(ps, PROXY_CHANGE_SENT);
  207. return;
  208. }
  209. plug_sent(ps->plug, bufsize);
  210. }
  211. static int plug_proxy_accepting(Plug p,
  212. accept_fn_t constructor, accept_ctx_t ctx)
  213. {
  214. Proxy_Plug pp = (Proxy_Plug) p;
  215. Proxy_Socket ps = pp->proxy_socket;
  216. if (ps->state != PROXY_STATE_ACTIVE) {
  217. ps->accepting_constructor = constructor;
  218. ps->accepting_ctx = ctx;
  219. return ps->negotiate(ps, PROXY_CHANGE_ACCEPTING);
  220. }
  221. return plug_accepting(ps->plug, constructor, ctx);
  222. }
  223. /*
  224. * This function can accept a NULL pointer as `addr', in which case
  225. * it will only check the host name.
  226. */
  227. int proxy_for_destination (SockAddr addr, const char *hostname,
  228. int port, Conf *conf)
  229. {
  230. int s = 0, e = 0;
  231. char hostip[64];
  232. int hostip_len, hostname_len;
  233. const char *exclude_list;
  234. /*
  235. * Special local connections such as Unix-domain sockets
  236. * unconditionally cannot be proxied, even in proxy-localhost
  237. * mode. There just isn't any way to ask any known proxy type for
  238. * them.
  239. */
  240. if (addr && sk_address_is_special_local(addr))
  241. return 0; /* do not proxy */
  242. /*
  243. * Check the host name and IP against the hard-coded
  244. * representations of `localhost'.
  245. */
  246. if (!conf_get_int(conf, CONF_even_proxy_localhost) &&
  247. (sk_hostname_is_local(hostname) ||
  248. (addr && sk_address_is_local(addr))))
  249. return 0; /* do not proxy */
  250. /* we want a string representation of the IP address for comparisons */
  251. if (addr) {
  252. sk_getaddr(addr, hostip, 64);
  253. hostip_len = strlen(hostip);
  254. } else
  255. hostip_len = 0; /* placate gcc; shouldn't be required */
  256. hostname_len = strlen(hostname);
  257. exclude_list = conf_get_str(conf, CONF_proxy_exclude_list);
  258. /* now parse the exclude list, and see if either our IP
  259. * or hostname matches anything in it.
  260. */
  261. while (exclude_list[s]) {
  262. while (exclude_list[s] &&
  263. (isspace((unsigned char)exclude_list[s]) ||
  264. exclude_list[s] == ',')) s++;
  265. if (!exclude_list[s]) break;
  266. e = s;
  267. while (exclude_list[e] &&
  268. (isalnum((unsigned char)exclude_list[e]) ||
  269. exclude_list[e] == '-' ||
  270. exclude_list[e] == '.' ||
  271. exclude_list[e] == '*')) e++;
  272. if (exclude_list[s] == '*') {
  273. /* wildcard at beginning of entry */
  274. if ((addr && strnicmp(hostip + hostip_len - (e - s - 1),
  275. exclude_list + s + 1, e - s - 1) == 0) ||
  276. strnicmp(hostname + hostname_len - (e - s - 1),
  277. exclude_list + s + 1, e - s - 1) == 0)
  278. return 0; /* IP/hostname range excluded. do not use proxy. */
  279. } else if (exclude_list[e-1] == '*') {
  280. /* wildcard at end of entry */
  281. if ((addr && strnicmp(hostip, exclude_list + s, e - s - 1) == 0) ||
  282. strnicmp(hostname, exclude_list + s, e - s - 1) == 0)
  283. return 0; /* IP/hostname range excluded. do not use proxy. */
  284. } else {
  285. /* no wildcard at either end, so let's try an absolute
  286. * match (ie. a specific IP)
  287. */
  288. if (addr && strnicmp(hostip, exclude_list + s, e - s) == 0)
  289. return 0; /* IP/hostname excluded. do not use proxy. */
  290. if (strnicmp(hostname, exclude_list + s, e - s) == 0)
  291. return 0; /* IP/hostname excluded. do not use proxy. */
  292. }
  293. s = e;
  294. /* Make sure we really have reached the next comma or end-of-string */
  295. while (exclude_list[s] &&
  296. !isspace((unsigned char)exclude_list[s]) &&
  297. exclude_list[s] != ',') s++;
  298. }
  299. /* no matches in the exclude list, so use the proxy */
  300. return 1;
  301. }
  302. static char *dns_log_msg(const char *host, int addressfamily,
  303. const char *reason)
  304. {
  305. return dupprintf("Looking up host \"%s\"%s for %s", host,
  306. (addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
  307. addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" :
  308. ""), reason);
  309. }
  310. SockAddr name_lookup(const char *host, int port, char **canonicalname,
  311. Conf *conf, int addressfamily, void *frontend,
  312. const char *reason)
  313. {
  314. char *logmsg;
  315. if (conf_get_int(conf, CONF_proxy_type) != PROXY_NONE &&
  316. do_proxy_dns(conf) &&
  317. proxy_for_destination(NULL, host, port, conf)) {
  318. if (frontend) {
  319. logmsg = dupprintf("Leaving host lookup to proxy of \"%s\""
  320. " (for %s)", host, reason);
  321. logevent(frontend, logmsg);
  322. sfree(logmsg);
  323. }
  324. *canonicalname = dupstr(host);
  325. return sk_nonamelookup(host);
  326. } else {
  327. if (frontend) {
  328. logmsg = dns_log_msg(host, addressfamily, reason);
  329. logevent(frontend, logmsg);
  330. sfree(logmsg);
  331. }
  332. return sk_namelookup(host, canonicalname, addressfamily);
  333. }
  334. }
  335. Socket new_connection(SockAddr addr, const char *hostname,
  336. int port, int privport,
  337. int oobinline, int nodelay, int keepalive,
  338. Plug plug, Conf *conf)
  339. {
  340. static const struct socket_function_table socket_fn_table = {
  341. sk_proxy_plug,
  342. sk_proxy_close,
  343. sk_proxy_write,
  344. sk_proxy_write_oob,
  345. sk_proxy_write_eof,
  346. sk_proxy_flush,
  347. sk_proxy_set_frozen,
  348. sk_proxy_socket_error,
  349. NULL, /* peer_info */
  350. };
  351. static const struct plug_function_table plug_fn_table = {
  352. plug_proxy_log,
  353. plug_proxy_closing,
  354. plug_proxy_receive,
  355. plug_proxy_sent,
  356. plug_proxy_accepting
  357. };
  358. if (conf_get_int(conf, CONF_proxy_type) != PROXY_NONE &&
  359. proxy_for_destination(addr, hostname, port, conf))
  360. {
  361. Proxy_Socket ret;
  362. Proxy_Plug pplug;
  363. SockAddr proxy_addr;
  364. char *proxy_canonical_name;
  365. const char *proxy_type;
  366. Socket sret;
  367. int type;
  368. if ((sret = platform_new_connection(addr, hostname, port, privport,
  369. oobinline, nodelay, keepalive,
  370. plug, conf)) !=
  371. NULL)
  372. return sret;
  373. ret = snew(struct Socket_proxy_tag);
  374. ret->fn = &socket_fn_table;
  375. ret->conf = conf_copy(conf);
  376. ret->plug = plug;
  377. ret->remote_addr = addr; /* will need to be freed on close */
  378. ret->remote_port = port;
  379. ret->error = NULL;
  380. ret->pending_flush = 0;
  381. ret->pending_eof = 0;
  382. ret->freeze = 0;
  383. bufchain_init(&ret->pending_input_data);
  384. bufchain_init(&ret->pending_output_data);
  385. bufchain_init(&ret->pending_oob_output_data);
  386. ret->sub_socket = NULL;
  387. ret->state = PROXY_STATE_NEW;
  388. ret->negotiate = NULL;
  389. type = conf_get_int(conf, CONF_proxy_type);
  390. if (type == PROXY_HTTP) {
  391. ret->negotiate = proxy_http_negotiate;
  392. proxy_type = "HTTP";
  393. } else if (type == PROXY_SOCKS4) {
  394. ret->negotiate = proxy_socks4_negotiate;
  395. proxy_type = "SOCKS 4";
  396. } else if (type == PROXY_SOCKS5) {
  397. ret->negotiate = proxy_socks5_negotiate;
  398. proxy_type = "SOCKS 5";
  399. } else if (type == PROXY_TELNET) {
  400. ret->negotiate = proxy_telnet_negotiate;
  401. proxy_type = "Telnet";
  402. } else {
  403. ret->error = "Proxy error: Unknown proxy method";
  404. return (Socket) ret;
  405. }
  406. {
  407. char *logmsg = dupprintf("Will use %s proxy at %s:%d to connect"
  408. " to %s:%d", proxy_type,
  409. conf_get_str(conf, CONF_proxy_host),
  410. conf_get_int(conf, CONF_proxy_port),
  411. hostname, port);
  412. plug_log(plug, 2, NULL, 0, logmsg, 0);
  413. sfree(logmsg);
  414. }
  415. /* create the proxy plug to map calls from the actual
  416. * socket into our proxy socket layer */
  417. pplug = snew(struct Plug_proxy_tag);
  418. pplug->fn = &plug_fn_table;
  419. pplug->proxy_socket = ret;
  420. {
  421. char *logmsg = dns_log_msg(conf_get_str(conf, CONF_proxy_host),
  422. conf_get_int(conf, CONF_addressfamily),
  423. "proxy");
  424. plug_log(plug, 2, NULL, 0, logmsg, 0);
  425. sfree(logmsg);
  426. }
  427. /* look-up proxy */
  428. proxy_addr = sk_namelookup(conf_get_str(conf, CONF_proxy_host),
  429. &proxy_canonical_name,
  430. conf_get_int(conf, CONF_addressfamily));
  431. if (sk_addr_error(proxy_addr) != NULL) {
  432. ret->error = "Proxy error: Unable to resolve proxy host name";
  433. sfree(pplug);
  434. sk_addr_free(proxy_addr);
  435. return (Socket)ret;
  436. }
  437. sfree(proxy_canonical_name);
  438. {
  439. char addrbuf[256], *logmsg;
  440. sk_getaddr(proxy_addr, addrbuf, lenof(addrbuf));
  441. logmsg = dupprintf("Connecting to %s proxy at %s port %d",
  442. proxy_type, addrbuf,
  443. conf_get_int(conf, CONF_proxy_port));
  444. plug_log(plug, 2, NULL, 0, logmsg, 0);
  445. sfree(logmsg);
  446. }
  447. /* create the actual socket we will be using,
  448. * connected to our proxy server and port.
  449. */
  450. ret->sub_socket = sk_new(proxy_addr,
  451. conf_get_int(conf, CONF_proxy_port),
  452. privport, oobinline,
  453. nodelay, keepalive, (Plug) pplug);
  454. if (sk_socket_error(ret->sub_socket) != NULL)
  455. return (Socket) ret;
  456. /* start the proxy negotiation process... */
  457. sk_set_frozen(ret->sub_socket, 0);
  458. ret->negotiate(ret, PROXY_CHANGE_NEW);
  459. return (Socket) ret;
  460. }
  461. /* no proxy, so just return the direct socket */
  462. return sk_new(addr, port, privport, oobinline, nodelay, keepalive, plug);
  463. }
  464. Socket new_listener(const char *srcaddr, int port, Plug plug,
  465. int local_host_only, Conf *conf, int addressfamily)
  466. {
  467. /* TODO: SOCKS (and potentially others) support inbound
  468. * TODO: connections via the proxy. support them.
  469. */
  470. return sk_newlistener(srcaddr, port, plug, local_host_only, addressfamily);
  471. }
  472. /* ----------------------------------------------------------------------
  473. * HTTP CONNECT proxy type.
  474. */
  475. static int get_line_end (char * data, int len)
  476. {
  477. int off = 0;
  478. while (off < len)
  479. {
  480. if (data[off] == '\n') {
  481. /* we have a newline */
  482. off++;
  483. /* is that the only thing on this line? */
  484. if (off <= 2) return off;
  485. /* if not, then there is the possibility that this header
  486. * continues onto the next line, if it starts with a space
  487. * or a tab.
  488. */
  489. if (off + 1 < len &&
  490. data[off+1] != ' ' &&
  491. data[off+1] != '\t') return off;
  492. /* the line does continue, so we have to keep going
  493. * until we see an the header's "real" end of line.
  494. */
  495. off++;
  496. }
  497. off++;
  498. }
  499. return -1;
  500. }
  501. int proxy_http_negotiate (Proxy_Socket p, int change)
  502. {
  503. if (p->state == PROXY_STATE_NEW) {
  504. /* we are just beginning the proxy negotiate process,
  505. * so we'll send off the initial bits of the request.
  506. * for this proxy method, it's just a simple HTTP
  507. * request
  508. */
  509. char *buf, dest[512];
  510. char *username, *password;
  511. sk_getaddr(p->remote_addr, dest, lenof(dest));
  512. buf = dupprintf("CONNECT %s:%i HTTP/1.1\r\nHost: %s:%i\r\n",
  513. dest, p->remote_port, dest, p->remote_port);
  514. sk_write(p->sub_socket, buf, strlen(buf));
  515. sfree(buf);
  516. username = conf_get_str(p->conf, CONF_proxy_username);
  517. password = conf_get_str(p->conf, CONF_proxy_password);
  518. if (username[0] || password[0]) {
  519. char *buf, *buf2;
  520. int i, j, len;
  521. buf = dupprintf("%s:%s", username, password);
  522. len = strlen(buf);
  523. buf2 = snewn(len * 4 / 3 + 100, char);
  524. sprintf(buf2, "Proxy-Authorization: Basic ");
  525. for (i = 0, j = strlen(buf2); i < len; i += 3, j += 4)
  526. base64_encode_atom((unsigned char *)(buf+i),
  527. (len-i > 3 ? 3 : len-i), buf2+j);
  528. strcpy(buf2+j, "\r\n");
  529. sk_write(p->sub_socket, buf2, strlen(buf2));
  530. sfree(buf);
  531. sfree(buf2);
  532. }
  533. sk_write(p->sub_socket, "\r\n", 2);
  534. p->state = 1;
  535. return 0;
  536. }
  537. if (change == PROXY_CHANGE_CLOSING) {
  538. /* if our proxy negotiation process involves closing and opening
  539. * new sockets, then we would want to intercept this closing
  540. * callback when we were expecting it. if we aren't anticipating
  541. * a socket close, then some error must have occurred. we'll
  542. * just pass those errors up to the backend.
  543. */
  544. plug_closing(p->plug, p->closing_error_msg, p->closing_error_code,
  545. p->closing_calling_back);
  546. return 0; /* ignored */
  547. }
  548. if (change == PROXY_CHANGE_SENT) {
  549. /* some (or all) of what we wrote to the proxy was sent.
  550. * we don't do anything new, however, until we receive the
  551. * proxy's response. we might want to set a timer so we can
  552. * timeout the proxy negotiation after a while...
  553. */
  554. return 0;
  555. }
  556. if (change == PROXY_CHANGE_ACCEPTING) {
  557. /* we should _never_ see this, as we are using our socket to
  558. * connect to a proxy, not accepting inbound connections.
  559. * what should we do? close the socket with an appropriate
  560. * error message?
  561. */
  562. return plug_accepting(p->plug,
  563. p->accepting_constructor, p->accepting_ctx);
  564. }
  565. if (change == PROXY_CHANGE_RECEIVE) {
  566. /* we have received data from the underlying socket, which
  567. * we'll need to parse, process, and respond to appropriately.
  568. */
  569. char *data, *datap;
  570. int len;
  571. int eol;
  572. if (p->state == 1) {
  573. int min_ver, maj_ver, status;
  574. /* get the status line */
  575. len = bufchain_size(&p->pending_input_data);
  576. assert(len > 0); /* or we wouldn't be here */
  577. data = snewn(len+1, char);
  578. bufchain_fetch(&p->pending_input_data, data, len);
  579. /*
  580. * We must NUL-terminate this data, because Windows
  581. * sscanf appears to require a NUL at the end of the
  582. * string because it strlens it _first_. Sigh.
  583. */
  584. data[len] = '\0';
  585. eol = get_line_end(data, len);
  586. if (eol < 0) {
  587. sfree(data);
  588. return 1;
  589. }
  590. status = -1;
  591. /* We can't rely on whether the %n incremented the sscanf return */
  592. if (sscanf((char *)data, "HTTP/%i.%i %n",
  593. &maj_ver, &min_ver, &status) < 2 || status == -1) {
  594. plug_closing(p->plug, "Proxy error: HTTP response was absent",
  595. PROXY_ERROR_GENERAL, 0);
  596. sfree(data);
  597. return 1;
  598. }
  599. /* remove the status line from the input buffer. */
  600. bufchain_consume(&p->pending_input_data, eol);
  601. if (data[status] != '2') {
  602. /* error */
  603. char *buf;
  604. data[eol] = '\0';
  605. while (eol > status &&
  606. (data[eol-1] == '\r' || data[eol-1] == '\n'))
  607. data[--eol] = '\0';
  608. buf = dupprintf("Proxy error: %s", data+status);
  609. plug_closing(p->plug, buf, PROXY_ERROR_GENERAL, 0);
  610. sfree(buf);
  611. sfree(data);
  612. return 1;
  613. }
  614. sfree(data);
  615. p->state = 2;
  616. }
  617. if (p->state == 2) {
  618. /* get headers. we're done when we get a
  619. * header of length 2, (ie. just "\r\n")
  620. */
  621. len = bufchain_size(&p->pending_input_data);
  622. assert(len > 0); /* or we wouldn't be here */
  623. data = snewn(len, char);
  624. datap = data;
  625. bufchain_fetch(&p->pending_input_data, data, len);
  626. eol = get_line_end(datap, len);
  627. if (eol < 0) {
  628. sfree(data);
  629. return 1;
  630. }
  631. while (eol > 2)
  632. {
  633. bufchain_consume(&p->pending_input_data, eol);
  634. datap += eol;
  635. len -= eol;
  636. eol = get_line_end(datap, len);
  637. }
  638. if (eol == 2) {
  639. /* we're done */
  640. bufchain_consume(&p->pending_input_data, 2);
  641. proxy_activate(p);
  642. /* proxy activate will have dealt with
  643. * whatever is left of the buffer */
  644. sfree(data);
  645. return 1;
  646. }
  647. sfree(data);
  648. return 1;
  649. }
  650. }
  651. plug_closing(p->plug, "Proxy error: unexpected proxy error",
  652. PROXY_ERROR_UNEXPECTED, 0);
  653. return 1;
  654. }
  655. /* ----------------------------------------------------------------------
  656. * SOCKS proxy type.
  657. */
  658. /* SOCKS version 4 */
  659. int proxy_socks4_negotiate (Proxy_Socket p, int change)
  660. {
  661. if (p->state == PROXY_CHANGE_NEW) {
  662. /* request format:
  663. * version number (1 byte) = 4
  664. * command code (1 byte)
  665. * 1 = CONNECT
  666. * 2 = BIND
  667. * dest. port (2 bytes) [network order]
  668. * dest. address (4 bytes)
  669. * user ID (variable length, null terminated string)
  670. */
  671. int length, type, namelen;
  672. char *command, addr[4], hostname[512];
  673. char *username;
  674. type = sk_addrtype(p->remote_addr);
  675. if (type == ADDRTYPE_IPV6) {
  676. p->error = "Proxy error: SOCKS version 4 does not support IPv6";
  677. return 1;
  678. } else if (type == ADDRTYPE_IPV4) {
  679. namelen = 0;
  680. sk_addrcopy(p->remote_addr, addr);
  681. } else { /* type == ADDRTYPE_NAME */
  682. assert(type == ADDRTYPE_NAME);
  683. sk_getaddr(p->remote_addr, hostname, lenof(hostname));
  684. namelen = strlen(hostname) + 1; /* include the NUL */
  685. addr[0] = addr[1] = addr[2] = 0;
  686. addr[3] = 1;
  687. }
  688. username = conf_get_str(p->conf, CONF_proxy_username);
  689. length = strlen(username) + namelen + 9;
  690. command = snewn(length, char);
  691. strcpy(command + 8, username);
  692. command[0] = 4; /* version 4 */
  693. command[1] = 1; /* CONNECT command */
  694. /* port */
  695. command[2] = (char) (p->remote_port >> 8) & 0xff;
  696. command[3] = (char) p->remote_port & 0xff;
  697. /* address */
  698. memcpy(command + 4, addr, 4);
  699. /* hostname */
  700. memcpy(command + 8 + strlen(username) + 1,
  701. hostname, namelen);
  702. sk_write(p->sub_socket, command, length);
  703. sfree(username);
  704. sfree(command);
  705. p->state = 1;
  706. return 0;
  707. }
  708. if (change == PROXY_CHANGE_CLOSING) {
  709. /* if our proxy negotiation process involves closing and opening
  710. * new sockets, then we would want to intercept this closing
  711. * callback when we were expecting it. if we aren't anticipating
  712. * a socket close, then some error must have occurred. we'll
  713. * just pass those errors up to the backend.
  714. */
  715. plug_closing(p->plug, p->closing_error_msg, p->closing_error_code,
  716. p->closing_calling_back);
  717. return 0; /* ignored */
  718. }
  719. if (change == PROXY_CHANGE_SENT) {
  720. /* some (or all) of what we wrote to the proxy was sent.
  721. * we don't do anything new, however, until we receive the
  722. * proxy's response. we might want to set a timer so we can
  723. * timeout the proxy negotiation after a while...
  724. */
  725. return 0;
  726. }
  727. if (change == PROXY_CHANGE_ACCEPTING) {
  728. /* we should _never_ see this, as we are using our socket to
  729. * connect to a proxy, not accepting inbound connections.
  730. * what should we do? close the socket with an appropriate
  731. * error message?
  732. */
  733. return plug_accepting(p->plug,
  734. p->accepting_constructor, p->accepting_ctx);
  735. }
  736. if (change == PROXY_CHANGE_RECEIVE) {
  737. /* we have received data from the underlying socket, which
  738. * we'll need to parse, process, and respond to appropriately.
  739. */
  740. if (p->state == 1) {
  741. /* response format:
  742. * version number (1 byte) = 4
  743. * reply code (1 byte)
  744. * 90 = request granted
  745. * 91 = request rejected or failed
  746. * 92 = request rejected due to lack of IDENTD on client
  747. * 93 = request rejected due to difference in user ID
  748. * (what we sent vs. what IDENTD said)
  749. * dest. port (2 bytes)
  750. * dest. address (4 bytes)
  751. */
  752. char data[8];
  753. if (bufchain_size(&p->pending_input_data) < 8)
  754. return 1; /* not got anything yet */
  755. /* get the response */
  756. bufchain_fetch(&p->pending_input_data, data, 8);
  757. if (data[0] != 0) {
  758. plug_closing(p->plug, "Proxy error: SOCKS proxy responded with "
  759. "unexpected reply code version",
  760. PROXY_ERROR_GENERAL, 0);
  761. return 1;
  762. }
  763. if (data[1] != 90) {
  764. switch (data[1]) {
  765. case 92:
  766. plug_closing(p->plug, "Proxy error: SOCKS server wanted IDENTD on client",
  767. PROXY_ERROR_GENERAL, 0);
  768. break;
  769. case 93:
  770. plug_closing(p->plug, "Proxy error: Username and IDENTD on client don't agree",
  771. PROXY_ERROR_GENERAL, 0);
  772. break;
  773. case 91:
  774. default:
  775. plug_closing(p->plug, "Proxy error: Error while communicating with proxy",
  776. PROXY_ERROR_GENERAL, 0);
  777. break;
  778. }
  779. return 1;
  780. }
  781. bufchain_consume(&p->pending_input_data, 8);
  782. /* we're done */
  783. proxy_activate(p);
  784. /* proxy activate will have dealt with
  785. * whatever is left of the buffer */
  786. return 1;
  787. }
  788. }
  789. plug_closing(p->plug, "Proxy error: unexpected proxy error",
  790. PROXY_ERROR_UNEXPECTED, 0);
  791. return 1;
  792. }
  793. /* SOCKS version 5 */
  794. int proxy_socks5_negotiate (Proxy_Socket p, int change)
  795. {
  796. if (p->state == PROXY_CHANGE_NEW) {
  797. /* initial command:
  798. * version number (1 byte) = 5
  799. * number of available authentication methods (1 byte)
  800. * available authentication methods (1 byte * previous value)
  801. * authentication methods:
  802. * 0x00 = no authentication
  803. * 0x01 = GSSAPI
  804. * 0x02 = username/password
  805. * 0x03 = CHAP
  806. */
  807. char command[5];
  808. char *username, *password;
  809. int len;
  810. command[0] = 5; /* version 5 */
  811. username = conf_get_str(p->conf, CONF_proxy_username);
  812. password = conf_get_str(p->conf, CONF_proxy_password);
  813. if (username[0] || password[0]) {
  814. command[2] = 0x00; /* no authentication */
  815. len = 3;
  816. proxy_socks5_offerencryptedauth (command, &len);
  817. command[len++] = 0x02; /* username/password */
  818. command[1] = len - 2; /* Number of methods supported */
  819. } else {
  820. command[1] = 1; /* one methods supported: */
  821. command[2] = 0x00; /* no authentication */
  822. len = 3;
  823. }
  824. sk_write(p->sub_socket, command, len);
  825. p->state = 1;
  826. return 0;
  827. }
  828. if (change == PROXY_CHANGE_CLOSING) {
  829. /* if our proxy negotiation process involves closing and opening
  830. * new sockets, then we would want to intercept this closing
  831. * callback when we were expecting it. if we aren't anticipating
  832. * a socket close, then some error must have occurred. we'll
  833. * just pass those errors up to the backend.
  834. */
  835. plug_closing(p->plug, p->closing_error_msg, p->closing_error_code,
  836. p->closing_calling_back);
  837. return 0; /* ignored */
  838. }
  839. if (change == PROXY_CHANGE_SENT) {
  840. /* some (or all) of what we wrote to the proxy was sent.
  841. * we don't do anything new, however, until we receive the
  842. * proxy's response. we might want to set a timer so we can
  843. * timeout the proxy negotiation after a while...
  844. */
  845. return 0;
  846. }
  847. if (change == PROXY_CHANGE_ACCEPTING) {
  848. /* we should _never_ see this, as we are using our socket to
  849. * connect to a proxy, not accepting inbound connections.
  850. * what should we do? close the socket with an appropriate
  851. * error message?
  852. */
  853. return plug_accepting(p->plug,
  854. p->accepting_constructor, p->accepting_ctx);
  855. }
  856. if (change == PROXY_CHANGE_RECEIVE) {
  857. /* we have received data from the underlying socket, which
  858. * we'll need to parse, process, and respond to appropriately.
  859. */
  860. if (p->state == 1) {
  861. /* initial response:
  862. * version number (1 byte) = 5
  863. * authentication method (1 byte)
  864. * authentication methods:
  865. * 0x00 = no authentication
  866. * 0x01 = GSSAPI
  867. * 0x02 = username/password
  868. * 0x03 = CHAP
  869. * 0xff = no acceptable methods
  870. */
  871. char data[2];
  872. if (bufchain_size(&p->pending_input_data) < 2)
  873. return 1; /* not got anything yet */
  874. /* get the response */
  875. bufchain_fetch(&p->pending_input_data, data, 2);
  876. if (data[0] != 5) {
  877. plug_closing(p->plug, "Proxy error: SOCKS proxy returned unexpected version",
  878. PROXY_ERROR_GENERAL, 0);
  879. return 1;
  880. }
  881. if (data[1] == 0x00) p->state = 2; /* no authentication needed */
  882. else if (data[1] == 0x01) p->state = 4; /* GSSAPI authentication */
  883. else if (data[1] == 0x02) p->state = 5; /* username/password authentication */
  884. else if (data[1] == 0x03) p->state = 6; /* CHAP authentication */
  885. else {
  886. plug_closing(p->plug, "Proxy error: SOCKS proxy did not accept our authentication",
  887. PROXY_ERROR_GENERAL, 0);
  888. return 1;
  889. }
  890. bufchain_consume(&p->pending_input_data, 2);
  891. }
  892. if (p->state == 7) {
  893. /* password authentication reply format:
  894. * version number (1 bytes) = 1
  895. * reply code (1 byte)
  896. * 0 = succeeded
  897. * >0 = failed
  898. */
  899. char data[2];
  900. if (bufchain_size(&p->pending_input_data) < 2)
  901. return 1; /* not got anything yet */
  902. /* get the response */
  903. bufchain_fetch(&p->pending_input_data, data, 2);
  904. if (data[0] != 1) {
  905. plug_closing(p->plug, "Proxy error: SOCKS password "
  906. "subnegotiation contained wrong version number",
  907. PROXY_ERROR_GENERAL, 0);
  908. return 1;
  909. }
  910. if (data[1] != 0) {
  911. plug_closing(p->plug, "Proxy error: SOCKS proxy refused"
  912. " password authentication",
  913. PROXY_ERROR_GENERAL, 0);
  914. return 1;
  915. }
  916. bufchain_consume(&p->pending_input_data, 2);
  917. p->state = 2; /* now proceed as authenticated */
  918. }
  919. if (p->state == 8) {
  920. int ret;
  921. ret = proxy_socks5_handlechap(p);
  922. if (ret) return ret;
  923. }
  924. if (p->state == 2) {
  925. /* request format:
  926. * version number (1 byte) = 5
  927. * command code (1 byte)
  928. * 1 = CONNECT
  929. * 2 = BIND
  930. * 3 = UDP ASSOCIATE
  931. * reserved (1 byte) = 0x00
  932. * address type (1 byte)
  933. * 1 = IPv4
  934. * 3 = domainname (first byte has length, no terminating null)
  935. * 4 = IPv6
  936. * dest. address (variable)
  937. * dest. port (2 bytes) [network order]
  938. */
  939. char command[512];
  940. int len;
  941. int type;
  942. type = sk_addrtype(p->remote_addr);
  943. if (type == ADDRTYPE_IPV4) {
  944. len = 10; /* 4 hdr + 4 addr + 2 trailer */
  945. command[3] = 1; /* IPv4 */
  946. sk_addrcopy(p->remote_addr, command+4);
  947. } else if (type == ADDRTYPE_IPV6) {
  948. len = 22; /* 4 hdr + 16 addr + 2 trailer */
  949. command[3] = 4; /* IPv6 */
  950. sk_addrcopy(p->remote_addr, command+4);
  951. } else {
  952. assert(type == ADDRTYPE_NAME);
  953. command[3] = 3;
  954. sk_getaddr(p->remote_addr, command+5, 256);
  955. command[4] = strlen(command+5);
  956. len = 7 + command[4]; /* 4 hdr, 1 len, N addr, 2 trailer */
  957. }
  958. command[0] = 5; /* version 5 */
  959. command[1] = 1; /* CONNECT command */
  960. command[2] = 0x00;
  961. /* port */
  962. command[len-2] = (char) (p->remote_port >> 8) & 0xff;
  963. command[len-1] = (char) p->remote_port & 0xff;
  964. sk_write(p->sub_socket, command, len);
  965. p->state = 3;
  966. return 1;
  967. }
  968. if (p->state == 3) {
  969. /* reply format:
  970. * version number (1 bytes) = 5
  971. * reply code (1 byte)
  972. * 0 = succeeded
  973. * 1 = general SOCKS server failure
  974. * 2 = connection not allowed by ruleset
  975. * 3 = network unreachable
  976. * 4 = host unreachable
  977. * 5 = connection refused
  978. * 6 = TTL expired
  979. * 7 = command not supported
  980. * 8 = address type not supported
  981. * reserved (1 byte) = x00
  982. * address type (1 byte)
  983. * 1 = IPv4
  984. * 3 = domainname (first byte has length, no terminating null)
  985. * 4 = IPv6
  986. * server bound address (variable)
  987. * server bound port (2 bytes) [network order]
  988. */
  989. char data[5];
  990. int len;
  991. /* First 5 bytes of packet are enough to tell its length. */
  992. if (bufchain_size(&p->pending_input_data) < 5)
  993. return 1; /* not got anything yet */
  994. /* get the response */
  995. bufchain_fetch(&p->pending_input_data, data, 5);
  996. if (data[0] != 5) {
  997. plug_closing(p->plug, "Proxy error: SOCKS proxy returned wrong version number",
  998. PROXY_ERROR_GENERAL, 0);
  999. return 1;
  1000. }
  1001. if (data[1] != 0) {
  1002. char buf[256];
  1003. strcpy(buf, "Proxy error: ");
  1004. switch (data[1]) {
  1005. case 1: strcat(buf, "General SOCKS server failure"); break;
  1006. case 2: strcat(buf, "Connection not allowed by ruleset"); break;
  1007. case 3: strcat(buf, "Network unreachable"); break;
  1008. case 4: strcat(buf, "Host unreachable"); break;
  1009. case 5: strcat(buf, "Connection refused"); break;
  1010. case 6: strcat(buf, "TTL expired"); break;
  1011. case 7: strcat(buf, "Command not supported"); break;
  1012. case 8: strcat(buf, "Address type not supported"); break;
  1013. default: sprintf(buf+strlen(buf),
  1014. "Unrecognised SOCKS error code %d",
  1015. data[1]);
  1016. break;
  1017. }
  1018. plug_closing(p->plug, buf, PROXY_ERROR_GENERAL, 0);
  1019. return 1;
  1020. }
  1021. /*
  1022. * Eat the rest of the reply packet.
  1023. */
  1024. len = 6; /* first 4 bytes, last 2 */
  1025. switch (data[3]) {
  1026. case 1: len += 4; break; /* IPv4 address */
  1027. case 4: len += 16; break;/* IPv6 address */
  1028. case 3: len += (unsigned char)data[4]; break; /* domain name */
  1029. default:
  1030. plug_closing(p->plug, "Proxy error: SOCKS proxy returned "
  1031. "unrecognised address format",
  1032. PROXY_ERROR_GENERAL, 0);
  1033. return 1;
  1034. }
  1035. if (bufchain_size(&p->pending_input_data) < len)
  1036. return 1; /* not got whole reply yet */
  1037. bufchain_consume(&p->pending_input_data, len);
  1038. /* we're done */
  1039. proxy_activate(p);
  1040. return 1;
  1041. }
  1042. if (p->state == 4) {
  1043. /* TODO: Handle GSSAPI authentication */
  1044. plug_closing(p->plug, "Proxy error: We don't support GSSAPI authentication",
  1045. PROXY_ERROR_GENERAL, 0);
  1046. return 1;
  1047. }
  1048. if (p->state == 5) {
  1049. char *username = conf_get_str(p->conf, CONF_proxy_username);
  1050. char *password = conf_get_str(p->conf, CONF_proxy_password);
  1051. if (username[0] || password[0]) {
  1052. char userpwbuf[255 + 255 + 3];
  1053. int ulen, plen;
  1054. ulen = strlen(username);
  1055. if (ulen > 255) ulen = 255;
  1056. if (ulen < 1) ulen = 1;
  1057. plen = strlen(password);
  1058. if (plen > 255) plen = 255;
  1059. if (plen < 1) plen = 1;
  1060. userpwbuf[0] = 1; /* version number of subnegotiation */
  1061. userpwbuf[1] = ulen;
  1062. memcpy(userpwbuf+2, username, ulen);
  1063. userpwbuf[ulen+2] = plen;
  1064. memcpy(userpwbuf+ulen+3, password, plen);
  1065. sk_write(p->sub_socket, userpwbuf, ulen + plen + 3);
  1066. p->state = 7;
  1067. } else
  1068. plug_closing(p->plug, "Proxy error: Server chose "
  1069. "username/password authentication but we "
  1070. "didn't offer it!",
  1071. PROXY_ERROR_GENERAL, 0);
  1072. return 1;
  1073. }
  1074. if (p->state == 6) {
  1075. int ret;
  1076. ret = proxy_socks5_selectchap(p);
  1077. if (ret) return ret;
  1078. }
  1079. }
  1080. plug_closing(p->plug, "Proxy error: Unexpected proxy error",
  1081. PROXY_ERROR_UNEXPECTED, 0);
  1082. return 1;
  1083. }
  1084. /* ----------------------------------------------------------------------
  1085. * `Telnet' proxy type.
  1086. *
  1087. * (This is for ad-hoc proxies where you connect to the proxy's
  1088. * telnet port and send a command such as `connect host port'. The
  1089. * command is configurable, since this proxy type is typically not
  1090. * standardised or at all well-defined.)
  1091. */
  1092. char *format_telnet_command(SockAddr addr, int port, Conf *conf)
  1093. {
  1094. char *fmt = conf_get_str(conf, CONF_proxy_telnet_command);
  1095. char *ret = NULL;
  1096. int retlen = 0, retsize = 0;
  1097. int so = 0, eo = 0;
  1098. #define ENSURE(n) do { \
  1099. if (retsize < retlen + n) { \
  1100. retsize = retlen + n + 512; \
  1101. ret = sresize(ret, retsize, char); \
  1102. } \
  1103. } while (0)
  1104. /* we need to escape \\, \%, \r, \n, \t, \x??, \0???,
  1105. * %%, %host, %port, %user, and %pass
  1106. */
  1107. while (fmt[eo] != 0) {
  1108. /* scan forward until we hit end-of-line,
  1109. * or an escape character (\ or %) */
  1110. while (fmt[eo] != 0 && fmt[eo] != '%' && fmt[eo] != '\\')
  1111. eo++;
  1112. /* if we hit eol, break out of our escaping loop */
  1113. if (fmt[eo] == 0) break;
  1114. /* if there was any unescaped text before the escape
  1115. * character, send that now */
  1116. if (eo != so) {
  1117. ENSURE(eo - so);
  1118. memcpy(ret + retlen, fmt + so, eo - so);
  1119. retlen += eo - so;
  1120. }
  1121. so = eo++;
  1122. /* if the escape character was the last character of
  1123. * the line, we'll just stop and send it. */
  1124. if (fmt[eo] == 0) break;
  1125. if (fmt[so] == '\\') {
  1126. /* we recognize \\, \%, \r, \n, \t, \x??.
  1127. * anything else, we just send unescaped (including the \).
  1128. */
  1129. switch (fmt[eo]) {
  1130. case '\\':
  1131. ENSURE(1);
  1132. ret[retlen++] = '\\';
  1133. eo++;
  1134. break;
  1135. case '%':
  1136. ENSURE(1);
  1137. ret[retlen++] = '%';
  1138. eo++;
  1139. break;
  1140. case 'r':
  1141. ENSURE(1);
  1142. ret[retlen++] = '\r';
  1143. eo++;
  1144. break;
  1145. case 'n':
  1146. ENSURE(1);
  1147. ret[retlen++] = '\n';
  1148. eo++;
  1149. break;
  1150. case 't':
  1151. ENSURE(1);
  1152. ret[retlen++] = '\t';
  1153. eo++;
  1154. break;
  1155. case 'x':
  1156. case 'X':
  1157. {
  1158. /* escaped hexadecimal value (ie. \xff) */
  1159. unsigned char v = 0;
  1160. int i = 0;
  1161. for (;;) {
  1162. eo++;
  1163. if (fmt[eo] >= '0' && fmt[eo] <= '9')
  1164. v += fmt[eo] - '0';
  1165. else if (fmt[eo] >= 'a' && fmt[eo] <= 'f')
  1166. v += fmt[eo] - 'a' + 10;
  1167. else if (fmt[eo] >= 'A' && fmt[eo] <= 'F')
  1168. v += fmt[eo] - 'A' + 10;
  1169. else {
  1170. /* non hex character, so we abort and just
  1171. * send the whole thing unescaped (including \x)
  1172. */
  1173. ENSURE(1);
  1174. ret[retlen++] = '\\';
  1175. eo = so + 1;
  1176. break;
  1177. }
  1178. /* we only extract two hex characters */
  1179. if (i == 1) {
  1180. ENSURE(1);
  1181. ret[retlen++] = v;
  1182. eo++;
  1183. break;
  1184. }
  1185. i++;
  1186. v <<= 4;
  1187. }
  1188. }
  1189. break;
  1190. default:
  1191. ENSURE(2);
  1192. memcpy(ret+retlen, fmt + so, 2);
  1193. retlen += 2;
  1194. eo++;
  1195. break;
  1196. }
  1197. } else {
  1198. /* % escape. we recognize %%, %host, %port, %user, %pass.
  1199. * %proxyhost, %proxyport. Anything else we just send
  1200. * unescaped (including the %).
  1201. */
  1202. if (fmt[eo] == '%') {
  1203. ENSURE(1);
  1204. ret[retlen++] = '%';
  1205. eo++;
  1206. }
  1207. else if (strnicmp(fmt + eo, "host", 4) == 0) {
  1208. char dest[512];
  1209. int destlen;
  1210. sk_getaddr(addr, dest, lenof(dest));
  1211. destlen = strlen(dest);
  1212. ENSURE(destlen);
  1213. memcpy(ret+retlen, dest, destlen);
  1214. retlen += destlen;
  1215. eo += 4;
  1216. }
  1217. else if (strnicmp(fmt + eo, "port", 4) == 0) {
  1218. char portstr[8], portlen;
  1219. portlen = sprintf(portstr, "%i", port);
  1220. ENSURE(portlen);
  1221. memcpy(ret + retlen, portstr, portlen);
  1222. retlen += portlen;
  1223. eo += 4;
  1224. }
  1225. else if (strnicmp(fmt + eo, "user", 4) == 0) {
  1226. char *username = conf_get_str(conf, CONF_proxy_username);
  1227. int userlen = strlen(username);
  1228. ENSURE(userlen);
  1229. memcpy(ret+retlen, username, userlen);
  1230. retlen += userlen;
  1231. eo += 4;
  1232. }
  1233. else if (strnicmp(fmt + eo, "pass", 4) == 0) {
  1234. char *password = conf_get_str(conf, CONF_proxy_password);
  1235. int passlen = strlen(password);
  1236. ENSURE(passlen);
  1237. memcpy(ret+retlen, password, passlen);
  1238. retlen += passlen;
  1239. eo += 4;
  1240. }
  1241. else if (strnicmp(fmt + eo, "proxyhost", 9) == 0) {
  1242. char *host = conf_get_str(conf, CONF_proxy_host);
  1243. int phlen = strlen(host);
  1244. ENSURE(phlen);
  1245. memcpy(ret+retlen, host, phlen);
  1246. retlen += phlen;
  1247. eo += 9;
  1248. }
  1249. else if (strnicmp(fmt + eo, "proxyport", 9) == 0) {
  1250. int port = conf_get_int(conf, CONF_proxy_port);
  1251. char pport[50];
  1252. int pplen;
  1253. sprintf(pport, "%d", port);
  1254. pplen = strlen(pport);
  1255. ENSURE(pplen);
  1256. memcpy(ret+retlen, pport, pplen);
  1257. retlen += pplen;
  1258. eo += 9;
  1259. }
  1260. else {
  1261. /* we don't escape this, so send the % now, and
  1262. * don't advance eo, so that we'll consider the
  1263. * text immediately following the % as unescaped.
  1264. */
  1265. ENSURE(1);
  1266. ret[retlen++] = '%';
  1267. }
  1268. }
  1269. /* resume scanning for additional escapes after this one. */
  1270. so = eo;
  1271. }
  1272. /* if there is any unescaped text at the end of the line, send it */
  1273. if (eo != so) {
  1274. ENSURE(eo - so);
  1275. memcpy(ret + retlen, fmt + so, eo - so);
  1276. retlen += eo - so;
  1277. }
  1278. ENSURE(1);
  1279. ret[retlen] = '\0';
  1280. return ret;
  1281. #undef ENSURE
  1282. }
  1283. int proxy_telnet_negotiate (Proxy_Socket p, int change)
  1284. {
  1285. if (p->state == PROXY_CHANGE_NEW) {
  1286. char *formatted_cmd;
  1287. formatted_cmd = format_telnet_command(p->remote_addr, p->remote_port,
  1288. p->conf);
  1289. {
  1290. /*
  1291. * Re-escape control chars in the command, for logging.
  1292. */
  1293. char *reescaped = snewn(4*strlen(formatted_cmd) + 1, char);
  1294. const char *in;
  1295. char *out;
  1296. char *logmsg;
  1297. for (in = formatted_cmd, out = reescaped; *in; in++) {
  1298. if (*in == '\n') {
  1299. *out++ = '\\'; *out++ = 'n';
  1300. } else if (*in == '\r') {
  1301. *out++ = '\\'; *out++ = 'r';
  1302. } else if (*in == '\t') {
  1303. *out++ = '\\'; *out++ = 't';
  1304. } else if (*in == '\\') {
  1305. *out++ = '\\'; *out++ = '\\';
  1306. } else if ((unsigned)(((unsigned char)*in) - 0x20) <
  1307. (0x7F-0x20)) {
  1308. *out++ = *in;
  1309. } else {
  1310. out += sprintf(out, "\\x%02X", (unsigned)*in & 0xFF);
  1311. }
  1312. }
  1313. *out = '\0';
  1314. logmsg = dupprintf("Sending Telnet proxy command: %s", reescaped);
  1315. plug_log(p->plug, 2, NULL, 0, logmsg, 0);
  1316. sfree(logmsg);
  1317. sfree(reescaped);
  1318. }
  1319. sk_write(p->sub_socket, formatted_cmd, strlen(formatted_cmd));
  1320. sfree(formatted_cmd);
  1321. p->state = 1;
  1322. return 0;
  1323. }
  1324. if (change == PROXY_CHANGE_CLOSING) {
  1325. /* if our proxy negotiation process involves closing and opening
  1326. * new sockets, then we would want to intercept this closing
  1327. * callback when we were expecting it. if we aren't anticipating
  1328. * a socket close, then some error must have occurred. we'll
  1329. * just pass those errors up to the backend.
  1330. */
  1331. plug_closing(p->plug, p->closing_error_msg, p->closing_error_code,
  1332. p->closing_calling_back);
  1333. return 0; /* ignored */
  1334. }
  1335. if (change == PROXY_CHANGE_SENT) {
  1336. /* some (or all) of what we wrote to the proxy was sent.
  1337. * we don't do anything new, however, until we receive the
  1338. * proxy's response. we might want to set a timer so we can
  1339. * timeout the proxy negotiation after a while...
  1340. */
  1341. return 0;
  1342. }
  1343. if (change == PROXY_CHANGE_ACCEPTING) {
  1344. /* we should _never_ see this, as we are using our socket to
  1345. * connect to a proxy, not accepting inbound connections.
  1346. * what should we do? close the socket with an appropriate
  1347. * error message?
  1348. */
  1349. return plug_accepting(p->plug,
  1350. p->accepting_constructor, p->accepting_ctx);
  1351. }
  1352. if (change == PROXY_CHANGE_RECEIVE) {
  1353. /* we have received data from the underlying socket, which
  1354. * we'll need to parse, process, and respond to appropriately.
  1355. */
  1356. /* we're done */
  1357. proxy_activate(p);
  1358. /* proxy activate will have dealt with
  1359. * whatever is left of the buffer */
  1360. return 1;
  1361. }
  1362. plug_closing(p->plug, "Proxy error: Unexpected proxy error",
  1363. PROXY_ERROR_UNEXPECTED, 0);
  1364. return 1;
  1365. }