proxy.c 46 KB

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