proxy.c 46 KB

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