proxy.c 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514
  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, false);
  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, PlugLogType type, SockAddr *addr,
  144. int port, 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 SocketVtable ProxySocket_sockvt = {
  311. .plug = sk_proxy_plug,
  312. .close = sk_proxy_close,
  313. .write = sk_proxy_write,
  314. .write_oob = sk_proxy_write_oob,
  315. .write_eof = sk_proxy_write_eof,
  316. .set_frozen = sk_proxy_set_frozen,
  317. .socket_error = sk_proxy_socket_error,
  318. .peer_info = NULL,
  319. };
  320. static const PlugVtable ProxySocket_plugvt = {
  321. .log = plug_proxy_log,
  322. .closing = plug_proxy_closing,
  323. .receive = plug_proxy_receive,
  324. .sent = plug_proxy_sent,
  325. .accepting = 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)) != NULL)
  344. return sret;
  345. ret = snew(ProxySocket);
  346. ret->sock.vt = &ProxySocket_sockvt;
  347. ret->plugimpl.vt = &ProxySocket_plugvt;
  348. ret->conf = conf_copy(conf);
  349. ret->plug = plug;
  350. ret->remote_addr = addr; /* will need to be freed on close */
  351. ret->remote_port = port;
  352. ret->error = NULL;
  353. ret->pending_eof = false;
  354. ret->freeze = false;
  355. bufchain_init(&ret->pending_input_data);
  356. bufchain_init(&ret->pending_output_data);
  357. bufchain_init(&ret->pending_oob_output_data);
  358. ret->sub_socket = NULL;
  359. ret->state = PROXY_STATE_NEW;
  360. ret->negotiate = NULL;
  361. type = conf_get_int(conf, CONF_proxy_type);
  362. if (type == PROXY_HTTP) {
  363. ret->negotiate = proxy_http_negotiate;
  364. proxy_type = "HTTP";
  365. } else if (type == PROXY_SOCKS4) {
  366. ret->negotiate = proxy_socks4_negotiate;
  367. proxy_type = "SOCKS 4";
  368. } else if (type == PROXY_SOCKS5) {
  369. ret->negotiate = proxy_socks5_negotiate;
  370. proxy_type = "SOCKS 5";
  371. } else if (type == PROXY_TELNET) {
  372. ret->negotiate = proxy_telnet_negotiate;
  373. proxy_type = "Telnet";
  374. } else {
  375. ret->error = "Proxy error: Unknown proxy method";
  376. return &ret->sock;
  377. }
  378. {
  379. char *logmsg = dupprintf("Will use %s proxy at %s:%d to connect"
  380. " to %s:%d", proxy_type,
  381. conf_get_str(conf, CONF_proxy_host),
  382. conf_get_int(conf, CONF_proxy_port),
  383. hostname, port);
  384. plug_log(plug, PLUGLOG_PROXY_MSG, NULL, 0, logmsg, 0);
  385. sfree(logmsg);
  386. }
  387. {
  388. char *logmsg = dns_log_msg(conf_get_str(conf, CONF_proxy_host),
  389. conf_get_int(conf, CONF_addressfamily),
  390. "proxy");
  391. plug_log(plug, PLUGLOG_PROXY_MSG, NULL, 0, logmsg, 0);
  392. sfree(logmsg);
  393. }
  394. /* look-up proxy */
  395. proxy_addr = sk_namelookup(conf_get_str(conf, CONF_proxy_host),
  396. &proxy_canonical_name,
  397. conf_get_int(conf, CONF_addressfamily));
  398. if (sk_addr_error(proxy_addr) != NULL) {
  399. ret->error = "Proxy error: Unable to resolve proxy host name";
  400. sk_addr_free(proxy_addr);
  401. return &ret->sock;
  402. }
  403. sfree(proxy_canonical_name);
  404. {
  405. char addrbuf[256], *logmsg;
  406. sk_getaddr(proxy_addr, addrbuf, lenof(addrbuf));
  407. logmsg = dupprintf("Connecting to %s proxy at %s port %d",
  408. proxy_type, addrbuf,
  409. conf_get_int(conf, CONF_proxy_port));
  410. plug_log(plug, PLUGLOG_PROXY_MSG, NULL, 0, logmsg, 0);
  411. sfree(logmsg);
  412. }
  413. /* create the actual socket we will be using,
  414. * connected to our proxy server and port.
  415. */
  416. ret->sub_socket = sk_new(proxy_addr,
  417. conf_get_int(conf, CONF_proxy_port),
  418. privport, oobinline,
  419. nodelay, keepalive, &ret->plugimpl);
  420. if (sk_socket_error(ret->sub_socket) != NULL)
  421. return &ret->sock;
  422. /* start the proxy negotiation process... */
  423. sk_set_frozen(ret->sub_socket, false);
  424. ret->negotiate(ret, PROXY_CHANGE_NEW);
  425. return &ret->sock;
  426. }
  427. /* no proxy, so just return the direct socket */
  428. return sk_new(addr, port, privport, oobinline, nodelay, keepalive, plug);
  429. }
  430. Socket *new_listener(const char *srcaddr, int port, Plug *plug,
  431. bool local_host_only, Conf *conf, int addressfamily)
  432. {
  433. /* TODO: SOCKS (and potentially others) support inbound
  434. * TODO: connections via the proxy. support them.
  435. */
  436. return sk_newlistener(srcaddr, port, plug, local_host_only, addressfamily);
  437. }
  438. /* ----------------------------------------------------------------------
  439. * HTTP CONNECT proxy type.
  440. */
  441. static bool get_line_end(char *data, size_t len, size_t *out)
  442. {
  443. size_t off = 0;
  444. while (off < len)
  445. {
  446. if (data[off] == '\n') {
  447. /* we have a newline */
  448. off++;
  449. /* is that the only thing on this line? */
  450. if (off <= 2) {
  451. *out = off;
  452. return true;
  453. }
  454. /* if not, then there is the possibility that this header
  455. * continues onto the next line, if it starts with a space
  456. * or a tab.
  457. */
  458. if (off + 1 < len && data[off+1] != ' ' && data[off+1] != '\t') {
  459. *out = off;
  460. return true;
  461. }
  462. /* the line does continue, so we have to keep going
  463. * until we see an the header's "real" end of line.
  464. */
  465. off++;
  466. }
  467. off++;
  468. }
  469. return false;
  470. }
  471. int proxy_http_negotiate (ProxySocket *p, int change)
  472. {
  473. if (p->state == PROXY_STATE_NEW) {
  474. /* we are just beginning the proxy negotiate process,
  475. * so we'll send off the initial bits of the request.
  476. * for this proxy method, it's just a simple HTTP
  477. * request
  478. */
  479. char *buf, dest[512];
  480. char *username, *password;
  481. sk_getaddr(p->remote_addr, dest, lenof(dest));
  482. buf = dupprintf("CONNECT %s:%i HTTP/1.1\r\nHost: %s:%i\r\n",
  483. dest, p->remote_port, dest, p->remote_port);
  484. sk_write(p->sub_socket, buf, strlen(buf));
  485. sfree(buf);
  486. username = conf_get_str(p->conf, CONF_proxy_username);
  487. password = conf_get_str(p->conf, CONF_proxy_password);
  488. if (username[0] || password[0]) {
  489. char *buf, *buf2;
  490. int i, j, len;
  491. buf = dupprintf("%s:%s", username, password);
  492. len = strlen(buf);
  493. buf2 = snewn(len * 4 / 3 + 100, char);
  494. sprintf(buf2, "Proxy-Authorization: Basic ");
  495. for (i = 0, j = strlen(buf2); i < len; i += 3, j += 4)
  496. base64_encode_atom((unsigned char *)(buf+i),
  497. (len-i > 3 ? 3 : len-i), buf2+j);
  498. strcpy(buf2+j, "\r\n");
  499. sk_write(p->sub_socket, buf2, strlen(buf2));
  500. sfree(buf);
  501. sfree(buf2);
  502. }
  503. sk_write(p->sub_socket, "\r\n", 2);
  504. p->state = 1;
  505. return 0;
  506. }
  507. if (change == PROXY_CHANGE_CLOSING) {
  508. /* if our proxy negotiation process involves closing and opening
  509. * new sockets, then we would want to intercept this closing
  510. * callback when we were expecting it. if we aren't anticipating
  511. * a socket close, then some error must have occurred. we'll
  512. * just pass those errors up to the backend.
  513. */
  514. plug_closing(p->plug, p->closing_error_msg, p->closing_error_code,
  515. p->closing_calling_back);
  516. return 0; /* ignored */
  517. }
  518. if (change == PROXY_CHANGE_SENT) {
  519. /* some (or all) of what we wrote to the proxy was sent.
  520. * we don't do anything new, however, until we receive the
  521. * proxy's response. we might want to set a timer so we can
  522. * timeout the proxy negotiation after a while...
  523. */
  524. return 0;
  525. }
  526. if (change == PROXY_CHANGE_ACCEPTING) {
  527. /* we should _never_ see this, as we are using our socket to
  528. * connect to a proxy, not accepting inbound connections.
  529. * what should we do? close the socket with an appropriate
  530. * error message?
  531. */
  532. return plug_accepting(p->plug,
  533. p->accepting_constructor, p->accepting_ctx);
  534. }
  535. if (change == PROXY_CHANGE_RECEIVE) {
  536. /* we have received data from the underlying socket, which
  537. * we'll need to parse, process, and respond to appropriately.
  538. */
  539. char *data, *datap;
  540. size_t len, eol;
  541. if (p->state == 1) {
  542. int min_ver, maj_ver, status;
  543. /* get the status line */
  544. len = bufchain_size(&p->pending_input_data);
  545. assert(len > 0); /* or we wouldn't be here */
  546. data = snewn(len+1, char);
  547. bufchain_fetch(&p->pending_input_data, data, len);
  548. /*
  549. * We must NUL-terminate this data, because Windows
  550. * sscanf appears to require a NUL at the end of the
  551. * string because it strlens it _first_. Sigh.
  552. */
  553. data[len] = '\0';
  554. if (!get_line_end(data, len, &eol)) {
  555. sfree(data);
  556. return 1;
  557. }
  558. status = -1;
  559. /* We can't rely on whether the %n incremented the sscanf return */
  560. if (sscanf((char *)data, "HTTP/%i.%i %n",
  561. &maj_ver, &min_ver, &status) < 2 || status == -1) {
  562. plug_closing(p->plug, "Proxy error: HTTP response was absent",
  563. PROXY_ERROR_GENERAL, 0);
  564. sfree(data);
  565. return 1;
  566. }
  567. /* remove the status line from the input buffer. */
  568. bufchain_consume(&p->pending_input_data, eol);
  569. if (data[status] != '2') {
  570. /* error */
  571. char *buf;
  572. data[eol] = '\0';
  573. while (eol > status &&
  574. (data[eol-1] == '\r' || data[eol-1] == '\n'))
  575. data[--eol] = '\0';
  576. buf = dupprintf("Proxy error: %s", data+status);
  577. plug_closing(p->plug, buf, PROXY_ERROR_GENERAL, 0);
  578. sfree(buf);
  579. sfree(data);
  580. return 1;
  581. }
  582. sfree(data);
  583. p->state = 2;
  584. }
  585. if (p->state == 2) {
  586. /* get headers. we're done when we get a
  587. * header of length 2, (ie. just "\r\n")
  588. */
  589. len = bufchain_size(&p->pending_input_data);
  590. assert(len > 0); /* or we wouldn't be here */
  591. data = snewn(len, char);
  592. datap = data;
  593. bufchain_fetch(&p->pending_input_data, data, len);
  594. if (!get_line_end(datap, len, &eol)) {
  595. sfree(data);
  596. return 1;
  597. }
  598. while (eol > 2) {
  599. bufchain_consume(&p->pending_input_data, eol);
  600. datap += eol;
  601. len -= eol;
  602. if (!get_line_end(datap, len, &eol))
  603. eol = 0; /* terminate the loop */
  604. }
  605. if (eol == 2) {
  606. /* we're done */
  607. bufchain_consume(&p->pending_input_data, 2);
  608. proxy_activate(p);
  609. /* proxy activate will have dealt with
  610. * whatever is left of the buffer */
  611. sfree(data);
  612. return 1;
  613. }
  614. sfree(data);
  615. return 1;
  616. }
  617. }
  618. plug_closing(p->plug, "Proxy error: unexpected proxy error",
  619. PROXY_ERROR_UNEXPECTED, 0);
  620. return 1;
  621. }
  622. /* ----------------------------------------------------------------------
  623. * SOCKS proxy type.
  624. */
  625. /* SOCKS version 4 */
  626. int proxy_socks4_negotiate (ProxySocket *p, int change)
  627. {
  628. if (p->state == PROXY_CHANGE_NEW) {
  629. /* request format:
  630. * version number (1 byte) = 4
  631. * command code (1 byte)
  632. * 1 = CONNECT
  633. * 2 = BIND
  634. * dest. port (2 bytes) [network order]
  635. * dest. address (4 bytes)
  636. * user ID (variable length, null terminated string)
  637. */
  638. strbuf *command = strbuf_new();
  639. char hostname[512];
  640. bool write_hostname = false;
  641. put_byte(command, 4); /* SOCKS version 4 */
  642. put_byte(command, 1); /* CONNECT command */
  643. put_uint16(command, p->remote_port);
  644. switch (sk_addrtype(p->remote_addr)) {
  645. case ADDRTYPE_IPV4: {
  646. char addr[4];
  647. sk_addrcopy(p->remote_addr, addr);
  648. put_data(command, addr, 4);
  649. break;
  650. }
  651. case ADDRTYPE_NAME:
  652. sk_getaddr(p->remote_addr, hostname, lenof(hostname));
  653. put_uint32(command, 1);
  654. write_hostname = true;
  655. break;
  656. case ADDRTYPE_IPV6:
  657. p->error = "Proxy error: SOCKS version 4 does not support IPv6";
  658. strbuf_free(command);
  659. return 1;
  660. }
  661. put_asciz(command, conf_get_str(p->conf, CONF_proxy_username));
  662. if (write_hostname)
  663. put_asciz(command, hostname);
  664. sk_write(p->sub_socket, command->s, command->len);
  665. strbuf_free(command);
  666. p->state = 1;
  667. return 0;
  668. }
  669. if (change == PROXY_CHANGE_CLOSING) {
  670. /* if our proxy negotiation process involves closing and opening
  671. * new sockets, then we would want to intercept this closing
  672. * callback when we were expecting it. if we aren't anticipating
  673. * a socket close, then some error must have occurred. we'll
  674. * just pass those errors up to the backend.
  675. */
  676. plug_closing(p->plug, p->closing_error_msg, p->closing_error_code,
  677. p->closing_calling_back);
  678. return 0; /* ignored */
  679. }
  680. if (change == PROXY_CHANGE_SENT) {
  681. /* some (or all) of what we wrote to the proxy was sent.
  682. * we don't do anything new, however, until we receive the
  683. * proxy's response. we might want to set a timer so we can
  684. * timeout the proxy negotiation after a while...
  685. */
  686. return 0;
  687. }
  688. if (change == PROXY_CHANGE_ACCEPTING) {
  689. /* we should _never_ see this, as we are using our socket to
  690. * connect to a proxy, not accepting inbound connections.
  691. * what should we do? close the socket with an appropriate
  692. * error message?
  693. */
  694. return plug_accepting(p->plug,
  695. p->accepting_constructor, p->accepting_ctx);
  696. }
  697. if (change == PROXY_CHANGE_RECEIVE) {
  698. /* we have received data from the underlying socket, which
  699. * we'll need to parse, process, and respond to appropriately.
  700. */
  701. if (p->state == 1) {
  702. /* response format:
  703. * version number (1 byte) = 4
  704. * reply code (1 byte)
  705. * 90 = request granted
  706. * 91 = request rejected or failed
  707. * 92 = request rejected due to lack of IDENTD on client
  708. * 93 = request rejected due to difference in user ID
  709. * (what we sent vs. what IDENTD said)
  710. * dest. port (2 bytes)
  711. * dest. address (4 bytes)
  712. */
  713. char data[8];
  714. if (bufchain_size(&p->pending_input_data) < 8)
  715. return 1; /* not got anything yet */
  716. /* get the response */
  717. bufchain_fetch(&p->pending_input_data, data, 8);
  718. if (data[0] != 0) {
  719. plug_closing(p->plug, "Proxy error: SOCKS proxy responded with "
  720. "unexpected reply code version",
  721. PROXY_ERROR_GENERAL, 0);
  722. return 1;
  723. }
  724. if (data[1] != 90) {
  725. switch (data[1]) {
  726. case 92:
  727. plug_closing(p->plug, "Proxy error: SOCKS server wanted IDENTD on client",
  728. PROXY_ERROR_GENERAL, 0);
  729. break;
  730. case 93:
  731. plug_closing(p->plug, "Proxy error: Username and IDENTD on client don't agree",
  732. PROXY_ERROR_GENERAL, 0);
  733. break;
  734. case 91:
  735. default:
  736. plug_closing(p->plug, "Proxy error: Error while communicating with proxy",
  737. PROXY_ERROR_GENERAL, 0);
  738. break;
  739. }
  740. return 1;
  741. }
  742. bufchain_consume(&p->pending_input_data, 8);
  743. /* we're done */
  744. proxy_activate(p);
  745. /* proxy activate will have dealt with
  746. * whatever is left of the buffer */
  747. return 1;
  748. }
  749. }
  750. plug_closing(p->plug, "Proxy error: unexpected proxy error",
  751. PROXY_ERROR_UNEXPECTED, 0);
  752. return 1;
  753. }
  754. /* SOCKS version 5 */
  755. int proxy_socks5_negotiate (ProxySocket *p, int change)
  756. {
  757. if (p->state == PROXY_CHANGE_NEW) {
  758. /* initial command:
  759. * version number (1 byte) = 5
  760. * number of available authentication methods (1 byte)
  761. * available authentication methods (1 byte * previous value)
  762. * authentication methods:
  763. * 0x00 = no authentication
  764. * 0x01 = GSSAPI
  765. * 0x02 = username/password
  766. * 0x03 = CHAP
  767. */
  768. strbuf *command;
  769. char *username, *password;
  770. int method_count_offset, methods_start;
  771. command = strbuf_new();
  772. put_byte(command, 5); /* SOCKS version 5 */
  773. username = conf_get_str(p->conf, CONF_proxy_username);
  774. password = conf_get_str(p->conf, CONF_proxy_password);
  775. method_count_offset = command->len;
  776. put_byte(command, 0);
  777. methods_start = command->len;
  778. put_byte(command, 0x00); /* no authentication */
  779. if (username[0] || password[0]) {
  780. proxy_socks5_offerencryptedauth(BinarySink_UPCAST(command));
  781. put_byte(command, 0x02); /* username/password */
  782. }
  783. command->u[method_count_offset] = command->len - methods_start;
  784. sk_write(p->sub_socket, command->s, command->len);
  785. strbuf_free(command);
  786. p->state = 1;
  787. return 0;
  788. }
  789. if (change == PROXY_CHANGE_CLOSING) {
  790. /* if our proxy negotiation process involves closing and opening
  791. * new sockets, then we would want to intercept this closing
  792. * callback when we were expecting it. if we aren't anticipating
  793. * a socket close, then some error must have occurred. we'll
  794. * just pass those errors up to the backend.
  795. */
  796. plug_closing(p->plug, p->closing_error_msg, p->closing_error_code,
  797. p->closing_calling_back);
  798. return 0; /* ignored */
  799. }
  800. if (change == PROXY_CHANGE_SENT) {
  801. /* some (or all) of what we wrote to the proxy was sent.
  802. * we don't do anything new, however, until we receive the
  803. * proxy's response. we might want to set a timer so we can
  804. * timeout the proxy negotiation after a while...
  805. */
  806. return 0;
  807. }
  808. if (change == PROXY_CHANGE_ACCEPTING) {
  809. /* we should _never_ see this, as we are using our socket to
  810. * connect to a proxy, not accepting inbound connections.
  811. * what should we do? close the socket with an appropriate
  812. * error message?
  813. */
  814. return plug_accepting(p->plug,
  815. p->accepting_constructor, p->accepting_ctx);
  816. }
  817. if (change == PROXY_CHANGE_RECEIVE) {
  818. /* we have received data from the underlying socket, which
  819. * we'll need to parse, process, and respond to appropriately.
  820. */
  821. if (p->state == 1) {
  822. /* initial response:
  823. * version number (1 byte) = 5
  824. * authentication method (1 byte)
  825. * authentication methods:
  826. * 0x00 = no authentication
  827. * 0x01 = GSSAPI
  828. * 0x02 = username/password
  829. * 0x03 = CHAP
  830. * 0xff = no acceptable methods
  831. */
  832. char data[2];
  833. if (bufchain_size(&p->pending_input_data) < 2)
  834. return 1; /* not got anything yet */
  835. /* get the response */
  836. bufchain_fetch(&p->pending_input_data, data, 2);
  837. if (data[0] != 5) {
  838. plug_closing(p->plug, "Proxy error: SOCKS proxy returned unexpected version",
  839. PROXY_ERROR_GENERAL, 0);
  840. return 1;
  841. }
  842. if (data[1] == 0x00) p->state = 2; /* no authentication needed */
  843. else if (data[1] == 0x01) p->state = 4; /* GSSAPI authentication */
  844. else if (data[1] == 0x02) p->state = 5; /* username/password authentication */
  845. else if (data[1] == 0x03) p->state = 6; /* CHAP authentication */
  846. else {
  847. plug_closing(p->plug, "Proxy error: SOCKS proxy did not accept our authentication",
  848. PROXY_ERROR_GENERAL, 0);
  849. return 1;
  850. }
  851. bufchain_consume(&p->pending_input_data, 2);
  852. }
  853. if (p->state == 7) {
  854. /* password authentication reply format:
  855. * version number (1 bytes) = 1
  856. * reply code (1 byte)
  857. * 0 = succeeded
  858. * >0 = failed
  859. */
  860. char data[2];
  861. if (bufchain_size(&p->pending_input_data) < 2)
  862. return 1; /* not got anything yet */
  863. /* get the response */
  864. bufchain_fetch(&p->pending_input_data, data, 2);
  865. if (data[0] != 1) {
  866. plug_closing(p->plug, "Proxy error: SOCKS password "
  867. "subnegotiation contained wrong version number",
  868. PROXY_ERROR_GENERAL, 0);
  869. return 1;
  870. }
  871. if (data[1] != 0) {
  872. plug_closing(p->plug, "Proxy error: SOCKS proxy refused"
  873. " password authentication",
  874. PROXY_ERROR_GENERAL, 0);
  875. return 1;
  876. }
  877. bufchain_consume(&p->pending_input_data, 2);
  878. p->state = 2; /* now proceed as authenticated */
  879. }
  880. if (p->state == 8) {
  881. int ret;
  882. ret = proxy_socks5_handlechap(p);
  883. if (ret) return ret;
  884. }
  885. if (p->state == 2) {
  886. /* request format:
  887. * version number (1 byte) = 5
  888. * command code (1 byte)
  889. * 1 = CONNECT
  890. * 2 = BIND
  891. * 3 = UDP ASSOCIATE
  892. * reserved (1 byte) = 0x00
  893. * address type (1 byte)
  894. * 1 = IPv4
  895. * 3 = domainname (first byte has length, no terminating null)
  896. * 4 = IPv6
  897. * dest. address (variable)
  898. * dest. port (2 bytes) [network order]
  899. */
  900. strbuf *command = strbuf_new();
  901. put_byte(command, 5); /* SOCKS version 5 */
  902. put_byte(command, 1); /* CONNECT command */
  903. put_byte(command, 0x00); /* reserved byte */
  904. switch (sk_addrtype(p->remote_addr)) {
  905. case ADDRTYPE_IPV4:
  906. put_byte(command, 1); /* IPv4 */
  907. sk_addrcopy(p->remote_addr, strbuf_append(command, 4));
  908. break;
  909. case ADDRTYPE_IPV6:
  910. put_byte(command, 4); /* IPv6 */
  911. sk_addrcopy(p->remote_addr, strbuf_append(command, 16));
  912. break;
  913. case ADDRTYPE_NAME: {
  914. char hostname[512];
  915. put_byte(command, 3); /* domain name */
  916. sk_getaddr(p->remote_addr, hostname, lenof(hostname));
  917. if (!put_pstring(command, hostname)) {
  918. p->error = "Proxy error: SOCKS 5 cannot "
  919. "support host names longer than 255 chars";
  920. strbuf_free(command);
  921. return 1;
  922. }
  923. break;
  924. }
  925. }
  926. put_uint16(command, p->remote_port);
  927. sk_write(p->sub_socket, command->s, command->len);
  928. strbuf_free(command);
  929. p->state = 3;
  930. return 1;
  931. }
  932. if (p->state == 3) {
  933. /* reply format:
  934. * version number (1 bytes) = 5
  935. * reply code (1 byte)
  936. * 0 = succeeded
  937. * 1 = general SOCKS server failure
  938. * 2 = connection not allowed by ruleset
  939. * 3 = network unreachable
  940. * 4 = host unreachable
  941. * 5 = connection refused
  942. * 6 = TTL expired
  943. * 7 = command not supported
  944. * 8 = address type not supported
  945. * reserved (1 byte) = x00
  946. * address type (1 byte)
  947. * 1 = IPv4
  948. * 3 = domainname (first byte has length, no terminating null)
  949. * 4 = IPv6
  950. * server bound address (variable)
  951. * server bound port (2 bytes) [network order]
  952. */
  953. char data[5];
  954. int len;
  955. /* First 5 bytes of packet are enough to tell its length. */
  956. if (bufchain_size(&p->pending_input_data) < 5)
  957. return 1; /* not got anything yet */
  958. /* get the response */
  959. bufchain_fetch(&p->pending_input_data, data, 5);
  960. if (data[0] != 5) {
  961. plug_closing(p->plug, "Proxy error: SOCKS proxy returned wrong version number",
  962. PROXY_ERROR_GENERAL, 0);
  963. return 1;
  964. }
  965. if (data[1] != 0) {
  966. char buf[256];
  967. strcpy(buf, "Proxy error: ");
  968. switch (data[1]) {
  969. case 1: strcat(buf, "General SOCKS server failure"); break;
  970. case 2: strcat(buf, "Connection not allowed by ruleset"); break;
  971. case 3: strcat(buf, "Network unreachable"); break;
  972. case 4: strcat(buf, "Host unreachable"); break;
  973. case 5: strcat(buf, "Connection refused"); break;
  974. case 6: strcat(buf, "TTL expired"); break;
  975. case 7: strcat(buf, "Command not supported"); break;
  976. case 8: strcat(buf, "Address type not supported"); break;
  977. default: sprintf(buf+strlen(buf),
  978. "Unrecognised SOCKS error code %d",
  979. data[1]);
  980. break;
  981. }
  982. plug_closing(p->plug, buf, PROXY_ERROR_GENERAL, 0);
  983. return 1;
  984. }
  985. /*
  986. * Eat the rest of the reply packet.
  987. */
  988. len = 6; /* first 4 bytes, last 2 */
  989. switch (data[3]) {
  990. case 1: len += 4; break; /* IPv4 address */
  991. case 4: len += 16; break;/* IPv6 address */
  992. case 3: len += 1+(unsigned char)data[4]; break; /* domain name */
  993. default:
  994. plug_closing(p->plug, "Proxy error: SOCKS proxy returned "
  995. "unrecognised address format",
  996. PROXY_ERROR_GENERAL, 0);
  997. return 1;
  998. }
  999. if (bufchain_size(&p->pending_input_data) < len)
  1000. return 1; /* not got whole reply yet */
  1001. bufchain_consume(&p->pending_input_data, len);
  1002. /* we're done */
  1003. proxy_activate(p);
  1004. return 1;
  1005. }
  1006. if (p->state == 4) {
  1007. /* TODO: Handle GSSAPI authentication */
  1008. plug_closing(p->plug, "Proxy error: We don't support GSSAPI authentication",
  1009. PROXY_ERROR_GENERAL, 0);
  1010. return 1;
  1011. }
  1012. if (p->state == 5) {
  1013. const char *username = conf_get_str(p->conf, CONF_proxy_username);
  1014. const char *password = conf_get_str(p->conf, CONF_proxy_password);
  1015. if (username[0] || password[0]) {
  1016. strbuf *auth = strbuf_new_nm();
  1017. put_byte(auth, 1); /* version number of subnegotiation */
  1018. if (!put_pstring(auth, username)) {
  1019. p->error = "Proxy error: SOCKS 5 authentication cannot "
  1020. "support usernames longer than 255 chars";
  1021. strbuf_free(auth);
  1022. return 1;
  1023. }
  1024. if (!put_pstring(auth, password)) {
  1025. p->error = "Proxy error: SOCKS 5 authentication cannot "
  1026. "support passwords longer than 255 chars";
  1027. strbuf_free(auth);
  1028. return 1;
  1029. }
  1030. sk_write(p->sub_socket, auth->s, auth->len);
  1031. strbuf_free(auth);
  1032. p->state = 7;
  1033. } else
  1034. plug_closing(p->plug, "Proxy error: Server chose "
  1035. "username/password authentication but we "
  1036. "didn't offer it!",
  1037. PROXY_ERROR_GENERAL, 0);
  1038. return 1;
  1039. }
  1040. if (p->state == 6) {
  1041. int ret;
  1042. ret = proxy_socks5_selectchap(p);
  1043. if (ret) return ret;
  1044. }
  1045. }
  1046. plug_closing(p->plug, "Proxy error: Unexpected proxy error",
  1047. PROXY_ERROR_UNEXPECTED, 0);
  1048. return 1;
  1049. }
  1050. /* ----------------------------------------------------------------------
  1051. * `Telnet' proxy type.
  1052. *
  1053. * (This is for ad-hoc proxies where you connect to the proxy's
  1054. * telnet port and send a command such as `connect host port'. The
  1055. * command is configurable, since this proxy type is typically not
  1056. * standardised or at all well-defined.)
  1057. */
  1058. char *format_telnet_command(SockAddr *addr, int port, Conf *conf)
  1059. {
  1060. char *fmt = conf_get_str(conf, CONF_proxy_telnet_command);
  1061. int so = 0, eo = 0;
  1062. strbuf *buf = strbuf_new();
  1063. /* we need to escape \\, \%, \r, \n, \t, \x??, \0???,
  1064. * %%, %host, %port, %user, and %pass
  1065. */
  1066. while (fmt[eo] != 0) {
  1067. /* scan forward until we hit end-of-line,
  1068. * or an escape character (\ or %) */
  1069. while (fmt[eo] != 0 && fmt[eo] != '%' && fmt[eo] != '\\')
  1070. eo++;
  1071. /* if we hit eol, break out of our escaping loop */
  1072. if (fmt[eo] == 0) break;
  1073. /* if there was any unescaped text before the escape
  1074. * character, send that now */
  1075. if (eo != so)
  1076. put_data(buf, fmt + so, eo - so);
  1077. so = eo++;
  1078. /* if the escape character was the last character of
  1079. * the line, we'll just stop and send it. */
  1080. if (fmt[eo] == 0) break;
  1081. if (fmt[so] == '\\') {
  1082. /* we recognize \\, \%, \r, \n, \t, \x??.
  1083. * anything else, we just send unescaped (including the \).
  1084. */
  1085. switch (fmt[eo]) {
  1086. case '\\':
  1087. put_byte(buf, '\\');
  1088. eo++;
  1089. break;
  1090. case '%':
  1091. put_byte(buf, '%');
  1092. eo++;
  1093. break;
  1094. case 'r':
  1095. put_byte(buf, '\r');
  1096. eo++;
  1097. break;
  1098. case 'n':
  1099. put_byte(buf, '\n');
  1100. eo++;
  1101. break;
  1102. case 't':
  1103. put_byte(buf, '\t');
  1104. eo++;
  1105. break;
  1106. case 'x':
  1107. case 'X': {
  1108. /* escaped hexadecimal value (ie. \xff) */
  1109. unsigned char v = 0;
  1110. int i = 0;
  1111. for (;;) {
  1112. eo++;
  1113. if (fmt[eo] >= '0' && fmt[eo] <= '9')
  1114. v += fmt[eo] - '0';
  1115. else if (fmt[eo] >= 'a' && fmt[eo] <= 'f')
  1116. v += fmt[eo] - 'a' + 10;
  1117. else if (fmt[eo] >= 'A' && fmt[eo] <= 'F')
  1118. v += fmt[eo] - 'A' + 10;
  1119. else {
  1120. /* non hex character, so we abort and just
  1121. * send the whole thing unescaped (including \x)
  1122. */
  1123. put_byte(buf, '\\');
  1124. eo = so + 1;
  1125. break;
  1126. }
  1127. /* we only extract two hex characters */
  1128. if (i == 1) {
  1129. put_byte(buf, v);
  1130. eo++;
  1131. break;
  1132. }
  1133. i++;
  1134. v <<= 4;
  1135. }
  1136. break;
  1137. }
  1138. default:
  1139. put_data(buf, fmt + so, 2);
  1140. eo++;
  1141. break;
  1142. }
  1143. } else {
  1144. /* % escape. we recognize %%, %host, %port, %user, %pass.
  1145. * %proxyhost, %proxyport. Anything else we just send
  1146. * unescaped (including the %).
  1147. */
  1148. if (fmt[eo] == '%') {
  1149. put_byte(buf, '%');
  1150. eo++;
  1151. }
  1152. else if (strnicmp(fmt + eo, "host", 4) == 0) {
  1153. char dest[512];
  1154. sk_getaddr(addr, dest, lenof(dest));
  1155. put_data(buf, dest, strlen(dest));
  1156. eo += 4;
  1157. }
  1158. else if (strnicmp(fmt + eo, "port", 4) == 0) {
  1159. strbuf_catf(buf, "%d", port);
  1160. eo += 4;
  1161. }
  1162. else if (strnicmp(fmt + eo, "user", 4) == 0) {
  1163. const char *username = conf_get_str(conf, CONF_proxy_username);
  1164. put_data(buf, username, strlen(username));
  1165. eo += 4;
  1166. }
  1167. else if (strnicmp(fmt + eo, "pass", 4) == 0) {
  1168. const char *password = conf_get_str(conf, CONF_proxy_password);
  1169. put_data(buf, password, strlen(password));
  1170. eo += 4;
  1171. }
  1172. else if (strnicmp(fmt + eo, "proxyhost", 9) == 0) {
  1173. const char *host = conf_get_str(conf, CONF_proxy_host);
  1174. put_data(buf, host, strlen(host));
  1175. eo += 9;
  1176. }
  1177. else if (strnicmp(fmt + eo, "proxyport", 9) == 0) {
  1178. int port = conf_get_int(conf, CONF_proxy_port);
  1179. strbuf_catf(buf, "%d", port);
  1180. eo += 9;
  1181. }
  1182. else {
  1183. /* we don't escape this, so send the % now, and
  1184. * don't advance eo, so that we'll consider the
  1185. * text immediately following the % as unescaped.
  1186. */
  1187. put_byte(buf, '%');
  1188. }
  1189. }
  1190. /* resume scanning for additional escapes after this one. */
  1191. so = eo;
  1192. }
  1193. /* if there is any unescaped text at the end of the line, send it */
  1194. if (eo != so) {
  1195. put_data(buf, fmt + so, eo - so);
  1196. }
  1197. return strbuf_to_str(buf);
  1198. }
  1199. int proxy_telnet_negotiate (ProxySocket *p, int change)
  1200. {
  1201. if (p->state == PROXY_CHANGE_NEW) {
  1202. char *formatted_cmd;
  1203. formatted_cmd = format_telnet_command(p->remote_addr, p->remote_port,
  1204. p->conf);
  1205. {
  1206. /*
  1207. * Re-escape control chars in the command, for logging.
  1208. */
  1209. char *reescaped = snewn(4*strlen(formatted_cmd) + 1, char);
  1210. const char *in;
  1211. char *out;
  1212. char *logmsg;
  1213. for (in = formatted_cmd, out = reescaped; *in; in++) {
  1214. if (*in == '\n') {
  1215. *out++ = '\\'; *out++ = 'n';
  1216. } else if (*in == '\r') {
  1217. *out++ = '\\'; *out++ = 'r';
  1218. } else if (*in == '\t') {
  1219. *out++ = '\\'; *out++ = 't';
  1220. } else if (*in == '\\') {
  1221. *out++ = '\\'; *out++ = '\\';
  1222. } else if ((unsigned)(((unsigned char)*in) - 0x20) <
  1223. (0x7F-0x20)) {
  1224. *out++ = *in;
  1225. } else {
  1226. out += sprintf(out, "\\x%02X", (unsigned)*in & 0xFF);
  1227. }
  1228. }
  1229. *out = '\0';
  1230. logmsg = dupprintf("Sending Telnet proxy command: %s", reescaped);
  1231. plug_log(p->plug, PLUGLOG_PROXY_MSG, NULL, 0, logmsg, 0);
  1232. sfree(logmsg);
  1233. sfree(reescaped);
  1234. }
  1235. sk_write(p->sub_socket, formatted_cmd, strlen(formatted_cmd));
  1236. sfree(formatted_cmd);
  1237. p->state = 1;
  1238. return 0;
  1239. }
  1240. if (change == PROXY_CHANGE_CLOSING) {
  1241. /* if our proxy negotiation process involves closing and opening
  1242. * new sockets, then we would want to intercept this closing
  1243. * callback when we were expecting it. if we aren't anticipating
  1244. * a socket close, then some error must have occurred. we'll
  1245. * just pass those errors up to the backend.
  1246. */
  1247. plug_closing(p->plug, p->closing_error_msg, p->closing_error_code,
  1248. p->closing_calling_back);
  1249. return 0; /* ignored */
  1250. }
  1251. if (change == PROXY_CHANGE_SENT) {
  1252. /* some (or all) of what we wrote to the proxy was sent.
  1253. * we don't do anything new, however, until we receive the
  1254. * proxy's response. we might want to set a timer so we can
  1255. * timeout the proxy negotiation after a while...
  1256. */
  1257. return 0;
  1258. }
  1259. if (change == PROXY_CHANGE_ACCEPTING) {
  1260. /* we should _never_ see this, as we are using our socket to
  1261. * connect to a proxy, not accepting inbound connections.
  1262. * what should we do? close the socket with an appropriate
  1263. * error message?
  1264. */
  1265. return plug_accepting(p->plug,
  1266. p->accepting_constructor, p->accepting_ctx);
  1267. }
  1268. if (change == PROXY_CHANGE_RECEIVE) {
  1269. /* we have received data from the underlying socket, which
  1270. * we'll need to parse, process, and respond to appropriately.
  1271. */
  1272. /* we're done */
  1273. proxy_activate(p);
  1274. /* proxy activate will have dealt with
  1275. * whatever is left of the buffer */
  1276. return 1;
  1277. }
  1278. plug_closing(p->plug, "Proxy error: Unexpected proxy error",
  1279. PROXY_ERROR_UNEXPECTED, 0);
  1280. return 1;
  1281. }