proxy.c 52 KB

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