proxy.c 45 KB

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