proxy.c 45 KB

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