proxy.c 46 KB

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