proxy.c 46 KB

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