proxy.c 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612
  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. #ifdef MPEXT
  455. conf_get_int(conf, CONF_connect_timeout), conf_get_int(conf, CONF_sndbuf)
  456. #endif
  457. );
  458. if (sk_socket_error(ret->sub_socket) != NULL)
  459. return (Socket) ret;
  460. /* start the proxy negotiation process... */
  461. sk_set_frozen(ret->sub_socket, 0);
  462. ret->negotiate(ret, PROXY_CHANGE_NEW);
  463. return (Socket) ret;
  464. }
  465. /* no proxy, so just return the direct socket */
  466. return sk_new(addr, port, privport, oobinline, nodelay, keepalive, plug,
  467. #ifdef MPEXT
  468. conf_get_int(conf, CONF_connect_timeout), conf_get_int(conf, CONF_sndbuf)
  469. #endif
  470. );
  471. }
  472. Socket new_listener(const char *srcaddr, int port, Plug plug,
  473. int local_host_only, Conf *conf, int addressfamily)
  474. {
  475. /* TODO: SOCKS (and potentially others) support inbound
  476. * TODO: connections via the proxy. support them.
  477. */
  478. return sk_newlistener(srcaddr, port, plug, local_host_only, addressfamily);
  479. }
  480. /* ----------------------------------------------------------------------
  481. * HTTP CONNECT proxy type.
  482. */
  483. static int get_line_end (char * data, int len)
  484. {
  485. int off = 0;
  486. while (off < len)
  487. {
  488. if (data[off] == '\n') {
  489. /* we have a newline */
  490. off++;
  491. /* is that the only thing on this line? */
  492. if (off <= 2) return off;
  493. /* if not, then there is the possibility that this header
  494. * continues onto the next line, if it starts with a space
  495. * or a tab.
  496. */
  497. if (off + 1 < len &&
  498. data[off+1] != ' ' &&
  499. data[off+1] != '\t') return off;
  500. /* the line does continue, so we have to keep going
  501. * until we see an the header's "real" end of line.
  502. */
  503. off++;
  504. }
  505. off++;
  506. }
  507. return -1;
  508. }
  509. int proxy_http_negotiate (Proxy_Socket p, int change)
  510. {
  511. if (p->state == PROXY_STATE_NEW) {
  512. /* we are just beginning the proxy negotiate process,
  513. * so we'll send off the initial bits of the request.
  514. * for this proxy method, it's just a simple HTTP
  515. * request
  516. */
  517. char *buf, dest[512];
  518. char *username, *password;
  519. sk_getaddr(p->remote_addr, dest, lenof(dest));
  520. buf = dupprintf("CONNECT %s:%i HTTP/1.1\r\nHost: %s:%i\r\n",
  521. dest, p->remote_port, dest, p->remote_port);
  522. sk_write(p->sub_socket, buf, strlen(buf));
  523. sfree(buf);
  524. username = conf_get_str(p->conf, CONF_proxy_username);
  525. password = conf_get_str(p->conf, CONF_proxy_password);
  526. if (username[0] || password[0]) {
  527. char *buf, *buf2;
  528. int i, j, len;
  529. buf = dupprintf("%s:%s", username, password);
  530. len = strlen(buf);
  531. buf2 = snewn(len * 4 / 3 + 100, char);
  532. sprintf(buf2, "Proxy-Authorization: Basic ");
  533. for (i = 0, j = strlen(buf2); i < len; i += 3, j += 4)
  534. base64_encode_atom((unsigned char *)(buf+i),
  535. (len-i > 3 ? 3 : len-i), buf2+j);
  536. strcpy(buf2+j, "\r\n");
  537. sk_write(p->sub_socket, buf2, strlen(buf2));
  538. sfree(buf);
  539. sfree(buf2);
  540. }
  541. sk_write(p->sub_socket, "\r\n", 2);
  542. p->state = 1;
  543. return 0;
  544. }
  545. if (change == PROXY_CHANGE_CLOSING) {
  546. /* if our proxy negotiation process involves closing and opening
  547. * new sockets, then we would want to intercept this closing
  548. * callback when we were expecting it. if we aren't anticipating
  549. * a socket close, then some error must have occurred. we'll
  550. * just pass those errors up to the backend.
  551. */
  552. plug_closing(p->plug, p->closing_error_msg, p->closing_error_code,
  553. p->closing_calling_back);
  554. return 0; /* ignored */
  555. }
  556. if (change == PROXY_CHANGE_SENT) {
  557. /* some (or all) of what we wrote to the proxy was sent.
  558. * we don't do anything new, however, until we receive the
  559. * proxy's response. we might want to set a timer so we can
  560. * timeout the proxy negotiation after a while...
  561. */
  562. return 0;
  563. }
  564. if (change == PROXY_CHANGE_ACCEPTING) {
  565. /* we should _never_ see this, as we are using our socket to
  566. * connect to a proxy, not accepting inbound connections.
  567. * what should we do? close the socket with an appropriate
  568. * error message?
  569. */
  570. return plug_accepting(p->plug,
  571. p->accepting_constructor, p->accepting_ctx);
  572. }
  573. if (change == PROXY_CHANGE_RECEIVE) {
  574. /* we have received data from the underlying socket, which
  575. * we'll need to parse, process, and respond to appropriately.
  576. */
  577. char *data, *datap;
  578. int len;
  579. int eol;
  580. if (p->state == 1) {
  581. int min_ver, maj_ver, status;
  582. /* get the status line */
  583. len = bufchain_size(&p->pending_input_data);
  584. assert(len > 0); /* or we wouldn't be here */
  585. data = snewn(len+1, char);
  586. bufchain_fetch(&p->pending_input_data, data, len);
  587. /*
  588. * We must NUL-terminate this data, because Windows
  589. * sscanf appears to require a NUL at the end of the
  590. * string because it strlens it _first_. Sigh.
  591. */
  592. data[len] = '\0';
  593. eol = get_line_end(data, len);
  594. if (eol < 0) {
  595. sfree(data);
  596. return 1;
  597. }
  598. status = -1;
  599. /* We can't rely on whether the %n incremented the sscanf return */
  600. if (sscanf((char *)data, "HTTP/%i.%i %n",
  601. &maj_ver, &min_ver, &status) < 2 || status == -1) {
  602. plug_closing(p->plug, "Proxy error: HTTP response was absent",
  603. PROXY_ERROR_GENERAL, 0);
  604. sfree(data);
  605. return 1;
  606. }
  607. /* remove the status line from the input buffer. */
  608. bufchain_consume(&p->pending_input_data, eol);
  609. if (data[status] != '2') {
  610. /* error */
  611. char *buf;
  612. data[eol] = '\0';
  613. while (eol > status &&
  614. (data[eol-1] == '\r' || data[eol-1] == '\n'))
  615. data[--eol] = '\0';
  616. buf = dupprintf("Proxy error: %s", data+status);
  617. plug_closing(p->plug, buf, PROXY_ERROR_GENERAL, 0);
  618. sfree(buf);
  619. sfree(data);
  620. return 1;
  621. }
  622. sfree(data);
  623. p->state = 2;
  624. }
  625. if (p->state == 2) {
  626. /* get headers. we're done when we get a
  627. * header of length 2, (ie. just "\r\n")
  628. */
  629. len = bufchain_size(&p->pending_input_data);
  630. assert(len > 0); /* or we wouldn't be here */
  631. data = snewn(len, char);
  632. datap = data;
  633. bufchain_fetch(&p->pending_input_data, data, len);
  634. eol = get_line_end(datap, len);
  635. if (eol < 0) {
  636. sfree(data);
  637. return 1;
  638. }
  639. while (eol > 2)
  640. {
  641. bufchain_consume(&p->pending_input_data, eol);
  642. datap += eol;
  643. len -= eol;
  644. eol = get_line_end(datap, len);
  645. }
  646. if (eol == 2) {
  647. /* we're done */
  648. bufchain_consume(&p->pending_input_data, 2);
  649. proxy_activate(p);
  650. /* proxy activate will have dealt with
  651. * whatever is left of the buffer */
  652. sfree(data);
  653. return 1;
  654. }
  655. sfree(data);
  656. return 1;
  657. }
  658. }
  659. plug_closing(p->plug, "Proxy error: unexpected proxy error",
  660. PROXY_ERROR_UNEXPECTED, 0);
  661. return 1;
  662. }
  663. /* ----------------------------------------------------------------------
  664. * SOCKS proxy type.
  665. */
  666. /* SOCKS version 4 */
  667. int proxy_socks4_negotiate (Proxy_Socket p, int change)
  668. {
  669. if (p->state == PROXY_CHANGE_NEW) {
  670. /* request format:
  671. * version number (1 byte) = 4
  672. * command code (1 byte)
  673. * 1 = CONNECT
  674. * 2 = BIND
  675. * dest. port (2 bytes) [network order]
  676. * dest. address (4 bytes)
  677. * user ID (variable length, null terminated string)
  678. */
  679. int length, type, namelen;
  680. char *command, addr[4], hostname[512];
  681. char *username;
  682. type = sk_addrtype(p->remote_addr);
  683. if (type == ADDRTYPE_IPV6) {
  684. p->error = "Proxy error: SOCKS version 4 does not support IPv6";
  685. return 1;
  686. } else if (type == ADDRTYPE_IPV4) {
  687. namelen = 0;
  688. sk_addrcopy(p->remote_addr, addr);
  689. } else { /* type == ADDRTYPE_NAME */
  690. assert(type == ADDRTYPE_NAME);
  691. sk_getaddr(p->remote_addr, hostname, lenof(hostname));
  692. namelen = strlen(hostname) + 1; /* include the NUL */
  693. addr[0] = addr[1] = addr[2] = 0;
  694. addr[3] = 1;
  695. }
  696. username = conf_get_str(p->conf, CONF_proxy_username);
  697. length = strlen(username) + namelen + 9;
  698. command = snewn(length, char);
  699. strcpy(command + 8, username);
  700. command[0] = 4; /* version 4 */
  701. command[1] = 1; /* CONNECT command */
  702. /* port */
  703. command[2] = (char) (p->remote_port >> 8) & 0xff;
  704. command[3] = (char) p->remote_port & 0xff;
  705. /* address */
  706. memcpy(command + 4, addr, 4);
  707. /* hostname */
  708. memcpy(command + 8 + strlen(username) + 1,
  709. hostname, namelen);
  710. sk_write(p->sub_socket, command, length);
  711. sfree(username);
  712. sfree(command);
  713. p->state = 1;
  714. return 0;
  715. }
  716. if (change == PROXY_CHANGE_CLOSING) {
  717. /* if our proxy negotiation process involves closing and opening
  718. * new sockets, then we would want to intercept this closing
  719. * callback when we were expecting it. if we aren't anticipating
  720. * a socket close, then some error must have occurred. we'll
  721. * just pass those errors up to the backend.
  722. */
  723. plug_closing(p->plug, p->closing_error_msg, p->closing_error_code,
  724. p->closing_calling_back);
  725. return 0; /* ignored */
  726. }
  727. if (change == PROXY_CHANGE_SENT) {
  728. /* some (or all) of what we wrote to the proxy was sent.
  729. * we don't do anything new, however, until we receive the
  730. * proxy's response. we might want to set a timer so we can
  731. * timeout the proxy negotiation after a while...
  732. */
  733. return 0;
  734. }
  735. if (change == PROXY_CHANGE_ACCEPTING) {
  736. /* we should _never_ see this, as we are using our socket to
  737. * connect to a proxy, not accepting inbound connections.
  738. * what should we do? close the socket with an appropriate
  739. * error message?
  740. */
  741. return plug_accepting(p->plug,
  742. p->accepting_constructor, p->accepting_ctx);
  743. }
  744. if (change == PROXY_CHANGE_RECEIVE) {
  745. /* we have received data from the underlying socket, which
  746. * we'll need to parse, process, and respond to appropriately.
  747. */
  748. if (p->state == 1) {
  749. /* response format:
  750. * version number (1 byte) = 4
  751. * reply code (1 byte)
  752. * 90 = request granted
  753. * 91 = request rejected or failed
  754. * 92 = request rejected due to lack of IDENTD on client
  755. * 93 = request rejected due to difference in user ID
  756. * (what we sent vs. what IDENTD said)
  757. * dest. port (2 bytes)
  758. * dest. address (4 bytes)
  759. */
  760. char data[8];
  761. if (bufchain_size(&p->pending_input_data) < 8)
  762. return 1; /* not got anything yet */
  763. /* get the response */
  764. bufchain_fetch(&p->pending_input_data, data, 8);
  765. if (data[0] != 0) {
  766. plug_closing(p->plug, "Proxy error: SOCKS proxy responded with "
  767. "unexpected reply code version",
  768. PROXY_ERROR_GENERAL, 0);
  769. return 1;
  770. }
  771. if (data[1] != 90) {
  772. switch (data[1]) {
  773. case 92:
  774. plug_closing(p->plug, "Proxy error: SOCKS server wanted IDENTD on client",
  775. PROXY_ERROR_GENERAL, 0);
  776. break;
  777. case 93:
  778. plug_closing(p->plug, "Proxy error: Username and IDENTD on client don't agree",
  779. PROXY_ERROR_GENERAL, 0);
  780. break;
  781. case 91:
  782. default:
  783. plug_closing(p->plug, "Proxy error: Error while communicating with proxy",
  784. PROXY_ERROR_GENERAL, 0);
  785. break;
  786. }
  787. return 1;
  788. }
  789. bufchain_consume(&p->pending_input_data, 8);
  790. /* we're done */
  791. proxy_activate(p);
  792. /* proxy activate will have dealt with
  793. * whatever is left of the buffer */
  794. return 1;
  795. }
  796. }
  797. plug_closing(p->plug, "Proxy error: unexpected proxy error",
  798. PROXY_ERROR_UNEXPECTED, 0);
  799. return 1;
  800. }
  801. /* SOCKS version 5 */
  802. int proxy_socks5_negotiate (Proxy_Socket p, int change)
  803. {
  804. if (p->state == PROXY_CHANGE_NEW) {
  805. /* initial command:
  806. * version number (1 byte) = 5
  807. * number of available authentication methods (1 byte)
  808. * available authentication methods (1 byte * previous value)
  809. * authentication methods:
  810. * 0x00 = no authentication
  811. * 0x01 = GSSAPI
  812. * 0x02 = username/password
  813. * 0x03 = CHAP
  814. */
  815. char command[5];
  816. char *username, *password;
  817. int len;
  818. command[0] = 5; /* version 5 */
  819. username = conf_get_str(p->conf, CONF_proxy_username);
  820. password = conf_get_str(p->conf, CONF_proxy_password);
  821. if (username[0] || password[0]) {
  822. command[2] = 0x00; /* no authentication */
  823. len = 3;
  824. proxy_socks5_offerencryptedauth (command, &len);
  825. command[len++] = 0x02; /* username/password */
  826. command[1] = len - 2; /* Number of methods supported */
  827. } else {
  828. command[1] = 1; /* one methods supported: */
  829. command[2] = 0x00; /* no authentication */
  830. len = 3;
  831. }
  832. sk_write(p->sub_socket, command, len);
  833. p->state = 1;
  834. return 0;
  835. }
  836. if (change == PROXY_CHANGE_CLOSING) {
  837. /* if our proxy negotiation process involves closing and opening
  838. * new sockets, then we would want to intercept this closing
  839. * callback when we were expecting it. if we aren't anticipating
  840. * a socket close, then some error must have occurred. we'll
  841. * just pass those errors up to the backend.
  842. */
  843. plug_closing(p->plug, p->closing_error_msg, p->closing_error_code,
  844. p->closing_calling_back);
  845. return 0; /* ignored */
  846. }
  847. if (change == PROXY_CHANGE_SENT) {
  848. /* some (or all) of what we wrote to the proxy was sent.
  849. * we don't do anything new, however, until we receive the
  850. * proxy's response. we might want to set a timer so we can
  851. * timeout the proxy negotiation after a while...
  852. */
  853. return 0;
  854. }
  855. if (change == PROXY_CHANGE_ACCEPTING) {
  856. /* we should _never_ see this, as we are using our socket to
  857. * connect to a proxy, not accepting inbound connections.
  858. * what should we do? close the socket with an appropriate
  859. * error message?
  860. */
  861. return plug_accepting(p->plug,
  862. p->accepting_constructor, p->accepting_ctx);
  863. }
  864. if (change == PROXY_CHANGE_RECEIVE) {
  865. /* we have received data from the underlying socket, which
  866. * we'll need to parse, process, and respond to appropriately.
  867. */
  868. if (p->state == 1) {
  869. /* initial response:
  870. * version number (1 byte) = 5
  871. * authentication method (1 byte)
  872. * authentication methods:
  873. * 0x00 = no authentication
  874. * 0x01 = GSSAPI
  875. * 0x02 = username/password
  876. * 0x03 = CHAP
  877. * 0xff = no acceptable methods
  878. */
  879. char data[2];
  880. if (bufchain_size(&p->pending_input_data) < 2)
  881. return 1; /* not got anything yet */
  882. /* get the response */
  883. bufchain_fetch(&p->pending_input_data, data, 2);
  884. if (data[0] != 5) {
  885. plug_closing(p->plug, "Proxy error: SOCKS proxy returned unexpected version",
  886. PROXY_ERROR_GENERAL, 0);
  887. return 1;
  888. }
  889. if (data[1] == 0x00) p->state = 2; /* no authentication needed */
  890. else if (data[1] == 0x01) p->state = 4; /* GSSAPI authentication */
  891. else if (data[1] == 0x02) p->state = 5; /* username/password authentication */
  892. else if (data[1] == 0x03) p->state = 6; /* CHAP authentication */
  893. else {
  894. plug_closing(p->plug, "Proxy error: SOCKS proxy did not accept our authentication",
  895. PROXY_ERROR_GENERAL, 0);
  896. return 1;
  897. }
  898. bufchain_consume(&p->pending_input_data, 2);
  899. }
  900. if (p->state == 7) {
  901. /* password authentication reply format:
  902. * version number (1 bytes) = 1
  903. * reply code (1 byte)
  904. * 0 = succeeded
  905. * >0 = failed
  906. */
  907. char data[2];
  908. if (bufchain_size(&p->pending_input_data) < 2)
  909. return 1; /* not got anything yet */
  910. /* get the response */
  911. bufchain_fetch(&p->pending_input_data, data, 2);
  912. if (data[0] != 1) {
  913. plug_closing(p->plug, "Proxy error: SOCKS password "
  914. "subnegotiation contained wrong version number",
  915. PROXY_ERROR_GENERAL, 0);
  916. return 1;
  917. }
  918. if (data[1] != 0) {
  919. plug_closing(p->plug, "Proxy error: SOCKS proxy refused"
  920. " password authentication",
  921. PROXY_ERROR_GENERAL, 0);
  922. return 1;
  923. }
  924. bufchain_consume(&p->pending_input_data, 2);
  925. p->state = 2; /* now proceed as authenticated */
  926. }
  927. if (p->state == 8) {
  928. int ret;
  929. ret = proxy_socks5_handlechap(p);
  930. if (ret) return ret;
  931. }
  932. if (p->state == 2) {
  933. /* request format:
  934. * version number (1 byte) = 5
  935. * command code (1 byte)
  936. * 1 = CONNECT
  937. * 2 = BIND
  938. * 3 = UDP ASSOCIATE
  939. * reserved (1 byte) = 0x00
  940. * address type (1 byte)
  941. * 1 = IPv4
  942. * 3 = domainname (first byte has length, no terminating null)
  943. * 4 = IPv6
  944. * dest. address (variable)
  945. * dest. port (2 bytes) [network order]
  946. */
  947. char command[512];
  948. int len;
  949. int type;
  950. type = sk_addrtype(p->remote_addr);
  951. if (type == ADDRTYPE_IPV4) {
  952. len = 10; /* 4 hdr + 4 addr + 2 trailer */
  953. command[3] = 1; /* IPv4 */
  954. sk_addrcopy(p->remote_addr, command+4);
  955. } else if (type == ADDRTYPE_IPV6) {
  956. len = 22; /* 4 hdr + 16 addr + 2 trailer */
  957. command[3] = 4; /* IPv6 */
  958. sk_addrcopy(p->remote_addr, command+4);
  959. } else {
  960. assert(type == ADDRTYPE_NAME);
  961. command[3] = 3;
  962. sk_getaddr(p->remote_addr, command+5, 256);
  963. command[4] = strlen(command+5);
  964. len = 7 + command[4]; /* 4 hdr, 1 len, N addr, 2 trailer */
  965. }
  966. command[0] = 5; /* version 5 */
  967. command[1] = 1; /* CONNECT command */
  968. command[2] = 0x00;
  969. /* port */
  970. command[len-2] = (char) (p->remote_port >> 8) & 0xff;
  971. command[len-1] = (char) p->remote_port & 0xff;
  972. sk_write(p->sub_socket, command, len);
  973. p->state = 3;
  974. return 1;
  975. }
  976. if (p->state == 3) {
  977. /* reply format:
  978. * version number (1 bytes) = 5
  979. * reply code (1 byte)
  980. * 0 = succeeded
  981. * 1 = general SOCKS server failure
  982. * 2 = connection not allowed by ruleset
  983. * 3 = network unreachable
  984. * 4 = host unreachable
  985. * 5 = connection refused
  986. * 6 = TTL expired
  987. * 7 = command not supported
  988. * 8 = address type not supported
  989. * reserved (1 byte) = x00
  990. * address type (1 byte)
  991. * 1 = IPv4
  992. * 3 = domainname (first byte has length, no terminating null)
  993. * 4 = IPv6
  994. * server bound address (variable)
  995. * server bound port (2 bytes) [network order]
  996. */
  997. char data[5];
  998. int len;
  999. /* First 5 bytes of packet are enough to tell its length. */
  1000. if (bufchain_size(&p->pending_input_data) < 5)
  1001. return 1; /* not got anything yet */
  1002. /* get the response */
  1003. bufchain_fetch(&p->pending_input_data, data, 5);
  1004. if (data[0] != 5) {
  1005. plug_closing(p->plug, "Proxy error: SOCKS proxy returned wrong version number",
  1006. PROXY_ERROR_GENERAL, 0);
  1007. return 1;
  1008. }
  1009. if (data[1] != 0) {
  1010. char buf[256];
  1011. strcpy(buf, "Proxy error: ");
  1012. switch (data[1]) {
  1013. case 1: strcat(buf, "General SOCKS server failure"); break;
  1014. case 2: strcat(buf, "Connection not allowed by ruleset"); break;
  1015. case 3: strcat(buf, "Network unreachable"); break;
  1016. case 4: strcat(buf, "Host unreachable"); break;
  1017. case 5: strcat(buf, "Connection refused"); break;
  1018. case 6: strcat(buf, "TTL expired"); break;
  1019. case 7: strcat(buf, "Command not supported"); break;
  1020. case 8: strcat(buf, "Address type not supported"); break;
  1021. default: sprintf(buf+strlen(buf),
  1022. "Unrecognised SOCKS error code %d",
  1023. data[1]);
  1024. break;
  1025. }
  1026. plug_closing(p->plug, buf, PROXY_ERROR_GENERAL, 0);
  1027. return 1;
  1028. }
  1029. /*
  1030. * Eat the rest of the reply packet.
  1031. */
  1032. len = 6; /* first 4 bytes, last 2 */
  1033. switch (data[3]) {
  1034. case 1: len += 4; break; /* IPv4 address */
  1035. case 4: len += 16; break;/* IPv6 address */
  1036. case 3: len += (unsigned char)data[4]; break; /* domain name */
  1037. default:
  1038. plug_closing(p->plug, "Proxy error: SOCKS proxy returned "
  1039. "unrecognised address format",
  1040. PROXY_ERROR_GENERAL, 0);
  1041. return 1;
  1042. }
  1043. if (bufchain_size(&p->pending_input_data) < len)
  1044. return 1; /* not got whole reply yet */
  1045. bufchain_consume(&p->pending_input_data, len);
  1046. /* we're done */
  1047. proxy_activate(p);
  1048. return 1;
  1049. }
  1050. if (p->state == 4) {
  1051. /* TODO: Handle GSSAPI authentication */
  1052. plug_closing(p->plug, "Proxy error: We don't support GSSAPI authentication",
  1053. PROXY_ERROR_GENERAL, 0);
  1054. return 1;
  1055. }
  1056. if (p->state == 5) {
  1057. char *username = conf_get_str(p->conf, CONF_proxy_username);
  1058. char *password = conf_get_str(p->conf, CONF_proxy_password);
  1059. if (username[0] || password[0]) {
  1060. char userpwbuf[255 + 255 + 3];
  1061. int ulen, plen;
  1062. ulen = strlen(username);
  1063. if (ulen > 255) ulen = 255;
  1064. if (ulen < 1) ulen = 1;
  1065. plen = strlen(password);
  1066. if (plen > 255) plen = 255;
  1067. if (plen < 1) plen = 1;
  1068. userpwbuf[0] = 1; /* version number of subnegotiation */
  1069. userpwbuf[1] = ulen;
  1070. memcpy(userpwbuf+2, username, ulen);
  1071. userpwbuf[ulen+2] = plen;
  1072. memcpy(userpwbuf+ulen+3, password, plen);
  1073. sk_write(p->sub_socket, userpwbuf, ulen + plen + 3);
  1074. p->state = 7;
  1075. } else
  1076. plug_closing(p->plug, "Proxy error: Server chose "
  1077. "username/password authentication but we "
  1078. "didn't offer it!",
  1079. PROXY_ERROR_GENERAL, 0);
  1080. return 1;
  1081. }
  1082. if (p->state == 6) {
  1083. int ret;
  1084. ret = proxy_socks5_selectchap(p);
  1085. if (ret) return ret;
  1086. }
  1087. }
  1088. plug_closing(p->plug, "Proxy error: Unexpected proxy error",
  1089. PROXY_ERROR_UNEXPECTED, 0);
  1090. return 1;
  1091. }
  1092. /* ----------------------------------------------------------------------
  1093. * `Telnet' proxy type.
  1094. *
  1095. * (This is for ad-hoc proxies where you connect to the proxy's
  1096. * telnet port and send a command such as `connect host port'. The
  1097. * command is configurable, since this proxy type is typically not
  1098. * standardised or at all well-defined.)
  1099. */
  1100. char *format_telnet_command(SockAddr addr, int port, Conf *conf)
  1101. {
  1102. char *fmt = conf_get_str(conf, CONF_proxy_telnet_command);
  1103. char *ret = NULL;
  1104. int retlen = 0, retsize = 0;
  1105. int so = 0, eo = 0;
  1106. #define ENSURE(n) do { \
  1107. if (retsize < retlen + n) { \
  1108. retsize = retlen + n + 512; \
  1109. ret = sresize(ret, retsize, char); \
  1110. } \
  1111. } while (0)
  1112. /* we need to escape \\, \%, \r, \n, \t, \x??, \0???,
  1113. * %%, %host, %port, %user, and %pass
  1114. */
  1115. while (fmt[eo] != 0) {
  1116. /* scan forward until we hit end-of-line,
  1117. * or an escape character (\ or %) */
  1118. while (fmt[eo] != 0 && fmt[eo] != '%' && fmt[eo] != '\\')
  1119. eo++;
  1120. /* if we hit eol, break out of our escaping loop */
  1121. if (fmt[eo] == 0) break;
  1122. /* if there was any unescaped text before the escape
  1123. * character, send that now */
  1124. if (eo != so) {
  1125. ENSURE(eo - so);
  1126. memcpy(ret + retlen, fmt + so, eo - so);
  1127. retlen += eo - so;
  1128. }
  1129. so = eo++;
  1130. /* if the escape character was the last character of
  1131. * the line, we'll just stop and send it. */
  1132. if (fmt[eo] == 0) break;
  1133. if (fmt[so] == '\\') {
  1134. /* we recognize \\, \%, \r, \n, \t, \x??.
  1135. * anything else, we just send unescaped (including the \).
  1136. */
  1137. switch (fmt[eo]) {
  1138. case '\\':
  1139. ENSURE(1);
  1140. ret[retlen++] = '\\';
  1141. eo++;
  1142. break;
  1143. case '%':
  1144. ENSURE(1);
  1145. ret[retlen++] = '%';
  1146. eo++;
  1147. break;
  1148. case 'r':
  1149. ENSURE(1);
  1150. ret[retlen++] = '\r';
  1151. eo++;
  1152. break;
  1153. case 'n':
  1154. ENSURE(1);
  1155. ret[retlen++] = '\n';
  1156. eo++;
  1157. break;
  1158. case 't':
  1159. ENSURE(1);
  1160. ret[retlen++] = '\t';
  1161. eo++;
  1162. break;
  1163. case 'x':
  1164. case 'X':
  1165. {
  1166. /* escaped hexadecimal value (ie. \xff) */
  1167. unsigned char v = 0;
  1168. int i = 0;
  1169. for (;;) {
  1170. eo++;
  1171. if (fmt[eo] >= '0' && fmt[eo] <= '9')
  1172. v += fmt[eo] - '0';
  1173. else if (fmt[eo] >= 'a' && fmt[eo] <= 'f')
  1174. v += fmt[eo] - 'a' + 10;
  1175. else if (fmt[eo] >= 'A' && fmt[eo] <= 'F')
  1176. v += fmt[eo] - 'A' + 10;
  1177. else {
  1178. /* non hex character, so we abort and just
  1179. * send the whole thing unescaped (including \x)
  1180. */
  1181. ENSURE(1);
  1182. ret[retlen++] = '\\';
  1183. eo = so + 1;
  1184. break;
  1185. }
  1186. /* we only extract two hex characters */
  1187. if (i == 1) {
  1188. ENSURE(1);
  1189. ret[retlen++] = v;
  1190. eo++;
  1191. break;
  1192. }
  1193. i++;
  1194. v <<= 4;
  1195. }
  1196. }
  1197. break;
  1198. default:
  1199. ENSURE(2);
  1200. memcpy(ret+retlen, fmt + so, 2);
  1201. retlen += 2;
  1202. eo++;
  1203. break;
  1204. }
  1205. } else {
  1206. /* % escape. we recognize %%, %host, %port, %user, %pass.
  1207. * %proxyhost, %proxyport. Anything else we just send
  1208. * unescaped (including the %).
  1209. */
  1210. if (fmt[eo] == '%') {
  1211. ENSURE(1);
  1212. ret[retlen++] = '%';
  1213. eo++;
  1214. }
  1215. else if (strnicmp(fmt + eo, "host", 4) == 0) {
  1216. char dest[512];
  1217. int destlen;
  1218. sk_getaddr(addr, dest, lenof(dest));
  1219. destlen = strlen(dest);
  1220. ENSURE(destlen);
  1221. memcpy(ret+retlen, dest, destlen);
  1222. retlen += destlen;
  1223. eo += 4;
  1224. }
  1225. else if (strnicmp(fmt + eo, "port", 4) == 0) {
  1226. char portstr[8], portlen;
  1227. portlen = sprintf(portstr, "%i", port);
  1228. ENSURE(portlen);
  1229. memcpy(ret + retlen, portstr, portlen);
  1230. retlen += portlen;
  1231. eo += 4;
  1232. }
  1233. else if (strnicmp(fmt + eo, "user", 4) == 0) {
  1234. char *username = conf_get_str(conf, CONF_proxy_username);
  1235. int userlen = strlen(username);
  1236. ENSURE(userlen);
  1237. memcpy(ret+retlen, username, userlen);
  1238. retlen += userlen;
  1239. eo += 4;
  1240. }
  1241. else if (strnicmp(fmt + eo, "pass", 4) == 0) {
  1242. char *password = conf_get_str(conf, CONF_proxy_password);
  1243. int passlen = strlen(password);
  1244. ENSURE(passlen);
  1245. memcpy(ret+retlen, password, passlen);
  1246. retlen += passlen;
  1247. eo += 4;
  1248. }
  1249. else if (strnicmp(fmt + eo, "proxyhost", 9) == 0) {
  1250. char *host = conf_get_str(conf, CONF_proxy_host);
  1251. int phlen = strlen(host);
  1252. ENSURE(phlen);
  1253. memcpy(ret+retlen, host, phlen);
  1254. retlen += phlen;
  1255. eo += 9;
  1256. }
  1257. else if (strnicmp(fmt + eo, "proxyport", 9) == 0) {
  1258. int port = conf_get_int(conf, CONF_proxy_port);
  1259. char pport[50];
  1260. int pplen;
  1261. sprintf(pport, "%d", port);
  1262. pplen = strlen(pport);
  1263. ENSURE(pplen);
  1264. memcpy(ret+retlen, pport, pplen);
  1265. retlen += pplen;
  1266. eo += 9;
  1267. }
  1268. else {
  1269. /* we don't escape this, so send the % now, and
  1270. * don't advance eo, so that we'll consider the
  1271. * text immediately following the % as unescaped.
  1272. */
  1273. ENSURE(1);
  1274. ret[retlen++] = '%';
  1275. }
  1276. }
  1277. /* resume scanning for additional escapes after this one. */
  1278. so = eo;
  1279. }
  1280. /* if there is any unescaped text at the end of the line, send it */
  1281. if (eo != so) {
  1282. ENSURE(eo - so);
  1283. memcpy(ret + retlen, fmt + so, eo - so);
  1284. retlen += eo - so;
  1285. }
  1286. ENSURE(1);
  1287. ret[retlen] = '\0';
  1288. return ret;
  1289. #undef ENSURE
  1290. }
  1291. int proxy_telnet_negotiate (Proxy_Socket p, int change)
  1292. {
  1293. if (p->state == PROXY_CHANGE_NEW) {
  1294. char *formatted_cmd;
  1295. formatted_cmd = format_telnet_command(p->remote_addr, p->remote_port,
  1296. p->conf);
  1297. {
  1298. /*
  1299. * Re-escape control chars in the command, for logging.
  1300. */
  1301. char *reescaped = snewn(4*strlen(formatted_cmd) + 1, char);
  1302. const char *in;
  1303. char *out;
  1304. char *logmsg;
  1305. for (in = formatted_cmd, out = reescaped; *in; in++) {
  1306. if (*in == '\n') {
  1307. *out++ = '\\'; *out++ = 'n';
  1308. } else if (*in == '\r') {
  1309. *out++ = '\\'; *out++ = 'r';
  1310. } else if (*in == '\t') {
  1311. *out++ = '\\'; *out++ = 't';
  1312. } else if (*in == '\\') {
  1313. *out++ = '\\'; *out++ = '\\';
  1314. } else if ((unsigned)(((unsigned char)*in) - 0x20) <
  1315. (0x7F-0x20)) {
  1316. *out++ = *in;
  1317. } else {
  1318. out += sprintf(out, "\\x%02X", (unsigned)*in & 0xFF);
  1319. }
  1320. }
  1321. *out = '\0';
  1322. logmsg = dupprintf("Sending Telnet proxy command: %s", reescaped);
  1323. plug_log(p->plug, 2, NULL, 0, logmsg, 0);
  1324. sfree(logmsg);
  1325. sfree(reescaped);
  1326. }
  1327. sk_write(p->sub_socket, formatted_cmd, strlen(formatted_cmd));
  1328. sfree(formatted_cmd);
  1329. p->state = 1;
  1330. return 0;
  1331. }
  1332. if (change == PROXY_CHANGE_CLOSING) {
  1333. /* if our proxy negotiation process involves closing and opening
  1334. * new sockets, then we would want to intercept this closing
  1335. * callback when we were expecting it. if we aren't anticipating
  1336. * a socket close, then some error must have occurred. we'll
  1337. * just pass those errors up to the backend.
  1338. */
  1339. plug_closing(p->plug, p->closing_error_msg, p->closing_error_code,
  1340. p->closing_calling_back);
  1341. return 0; /* ignored */
  1342. }
  1343. if (change == PROXY_CHANGE_SENT) {
  1344. /* some (or all) of what we wrote to the proxy was sent.
  1345. * we don't do anything new, however, until we receive the
  1346. * proxy's response. we might want to set a timer so we can
  1347. * timeout the proxy negotiation after a while...
  1348. */
  1349. return 0;
  1350. }
  1351. if (change == PROXY_CHANGE_ACCEPTING) {
  1352. /* we should _never_ see this, as we are using our socket to
  1353. * connect to a proxy, not accepting inbound connections.
  1354. * what should we do? close the socket with an appropriate
  1355. * error message?
  1356. */
  1357. return plug_accepting(p->plug,
  1358. p->accepting_constructor, p->accepting_ctx);
  1359. }
  1360. if (change == PROXY_CHANGE_RECEIVE) {
  1361. /* we have received data from the underlying socket, which
  1362. * we'll need to parse, process, and respond to appropriately.
  1363. */
  1364. /* we're done */
  1365. proxy_activate(p);
  1366. /* proxy activate will have dealt with
  1367. * whatever is left of the buffer */
  1368. return 1;
  1369. }
  1370. plug_closing(p->plug, "Proxy error: Unexpected proxy error",
  1371. PROXY_ERROR_UNEXPECTED, 0);
  1372. return 1;
  1373. }