proxy.c 53 KB

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