proxy.c 46 KB

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