proxy.c 46 KB

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