proxy.c 46 KB

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