transports.c 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738
  1. /* Copyright (c) 2011-2018, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. /**
  4. * \file transports.c
  5. * \brief Pluggable Transports related code.
  6. *
  7. * \details
  8. * Each managed proxy is represented by a <b>managed_proxy_t</b>.
  9. * Each managed proxy can support multiple transports.
  10. * Each managed proxy gets configured through a multistep process.
  11. *
  12. * ::managed_proxy_list contains all the managed proxies this tor
  13. * instance is supporting.
  14. * In the ::managed_proxy_list there are ::unconfigured_proxies_n
  15. * managed proxies that are still unconfigured.
  16. *
  17. * In every run_scheduled_event() tick, we attempt to launch and then
  18. * configure the unconfiged managed proxies, using the configuration
  19. * protocol defined in the 180_pluggable_transport.txt proposal. A
  20. * managed proxy might need several ticks to get fully configured.
  21. *
  22. * When a managed proxy is fully configured, we register all its
  23. * transports to the circuitbuild.c subsystem. At that point the
  24. * transports are owned by the circuitbuild.c subsystem.
  25. *
  26. * When a managed proxy fails to follow the 180 configuration
  27. * protocol, it gets marked as broken and gets destroyed.
  28. *
  29. * <b>In a little more detail:</b>
  30. *
  31. * While we are serially parsing torrc, we store all the transports
  32. * that a proxy should spawn in its <em>transports_to_launch</em>
  33. * element.
  34. *
  35. * When we finish reading the torrc, we spawn the managed proxy and
  36. * expect {S,C}METHOD lines from its output. We add transports
  37. * described by METHOD lines to its <em>transports</em> element, as
  38. * transport_t structs.
  39. *
  40. * When the managed proxy stops spitting METHOD lines (signified by a
  41. * '{S,C}METHODS DONE' message) we pass copies of its transports to
  42. * the bridge subsystem. We keep copies of the 'transport_t's on the
  43. * managed proxy to be able to associate the proxy with its
  44. * transports, and we pass copies to the bridge subsystem so that
  45. * transports can be associated with bridges.
  46. * [ XXX We should try see whether the two copies are really needed
  47. * and maybe cut it into a single copy of the 'transport_t' shared
  48. * between the managed proxy and the bridge subsystem. Preliminary
  49. * analysis shows that both copies are needed with the current code
  50. * logic, because of race conditions that can cause dangling
  51. * pointers. ]
  52. *
  53. * <b>In even more detail, this is what happens when a config read
  54. * (like a SIGHUP or a SETCONF) occurs:</b>
  55. *
  56. * We immediately destroy all unconfigured proxies (We shouldn't have
  57. * unconfigured proxies in the first place, except when the config
  58. * read happens immediately after tor is launched.).
  59. *
  60. * We mark all managed proxies and transports to signify that they
  61. * must be removed if they don't contribute by the new torrc
  62. * (we mark using the <b>marked_for_removal</b> element).
  63. * We also mark all managed proxies to signify that they might need to
  64. * be restarted so that they end up supporting all the transports the
  65. * new torrc wants them to support
  66. * (we mark using the <b>was_around_before_config_read</b> element).
  67. * We also clear their <b>transports_to_launch</b> list so that we can
  68. * put there the transports we need to launch according to the new
  69. * torrc.
  70. *
  71. * We then start parsing torrc again.
  72. *
  73. * Everytime we encounter a transport line using a managed proxy that
  74. * was around before the config read, we cleanse that proxy from the
  75. * removal mark. We also toggle the <b>check_if_restarts_needed</b>
  76. * flag, so that on the next <b>pt_configure_remaining_proxies</b>
  77. * tick, we investigate whether we need to restart the proxy so that
  78. * it also spawns the new transports. If the post-config-read
  79. * <b>transports_to_launch</b> list is identical to the pre-config-read
  80. * one, it means that no changes were introduced to this proxy during
  81. * the config read and no restart has to take place.
  82. *
  83. * During the post-config-read torrc parsing, we unmark all transports
  84. * spawned by managed proxies that we find in our torrc.
  85. * We do that so that if we don't need to restart a managed proxy, we
  86. * can continue using its old transports normally.
  87. * If we end up restarting the proxy, we destroy and unregister all
  88. * old transports from the circuitbuild.c subsystem.
  89. **/
  90. #define PT_PRIVATE
  91. #include "core/or/or.h"
  92. #include "feature/client/bridges.h"
  93. #include "app/config/config.h"
  94. #include "core/mainloop/connection.h"
  95. #include "core/or/circuitbuild.h"
  96. #include "feature/client/transports.h"
  97. #include "feature/relay/router.h"
  98. #include "app/config/statefile.h"
  99. #include "core/or/connection_or.h"
  100. #include "feature/relay/ext_orport.h"
  101. #include "feature/control/control.h"
  102. #include "lib/process/env.h"
  103. #include "lib/process/subprocess.h"
  104. static process_environment_t *
  105. create_managed_proxy_environment(const managed_proxy_t *mp);
  106. static inline int proxy_configuration_finished(const managed_proxy_t *mp);
  107. static void handle_finished_proxy(managed_proxy_t *mp);
  108. static void parse_method_error(const char *line, int is_server_method);
  109. #define parse_server_method_error(l) parse_method_error(l, 1)
  110. #define parse_client_method_error(l) parse_method_error(l, 0)
  111. /** Managed proxy protocol strings */
  112. #define PROTO_ENV_ERROR "ENV-ERROR"
  113. #define PROTO_NEG_SUCCESS "VERSION"
  114. #define PROTO_NEG_FAIL "VERSION-ERROR no-version"
  115. #define PROTO_CMETHOD "CMETHOD"
  116. #define PROTO_SMETHOD "SMETHOD"
  117. #define PROTO_CMETHOD_ERROR "CMETHOD-ERROR"
  118. #define PROTO_SMETHOD_ERROR "SMETHOD-ERROR"
  119. #define PROTO_CMETHODS_DONE "CMETHODS DONE"
  120. #define PROTO_SMETHODS_DONE "SMETHODS DONE"
  121. #define PROTO_PROXY_DONE "PROXY DONE"
  122. #define PROTO_PROXY_ERROR "PROXY-ERROR"
  123. /** The first and only supported - at the moment - configuration
  124. protocol version. */
  125. #define PROTO_VERSION_ONE 1
  126. /** A list of pluggable transports found in torrc. */
  127. static smartlist_t *transport_list = NULL;
  128. /** Returns a transport_t struct for a transport proxy supporting the
  129. protocol <b>name</b> listening at <b>addr</b>:<b>port</b> using
  130. SOCKS version <b>socks_ver</b>. */
  131. STATIC transport_t *
  132. transport_new(const tor_addr_t *addr, uint16_t port,
  133. const char *name, int socks_ver,
  134. const char *extra_info_args)
  135. {
  136. transport_t *t = tor_malloc_zero(sizeof(transport_t));
  137. tor_addr_copy(&t->addr, addr);
  138. t->port = port;
  139. t->name = tor_strdup(name);
  140. t->socks_version = socks_ver;
  141. if (extra_info_args)
  142. t->extra_info_args = tor_strdup(extra_info_args);
  143. return t;
  144. }
  145. /** Free the pluggable transport struct <b>transport</b>. */
  146. void
  147. transport_free_(transport_t *transport)
  148. {
  149. if (!transport)
  150. return;
  151. tor_free(transport->name);
  152. tor_free(transport->extra_info_args);
  153. tor_free(transport);
  154. }
  155. /** Mark every entry of the transport list to be removed on our next call to
  156. * sweep_transport_list unless it has first been un-marked. */
  157. void
  158. mark_transport_list(void)
  159. {
  160. if (!transport_list)
  161. transport_list = smartlist_new();
  162. SMARTLIST_FOREACH(transport_list, transport_t *, t,
  163. t->marked_for_removal = 1);
  164. }
  165. /** Remove every entry of the transport list that was marked with
  166. * mark_transport_list if it has not subsequently been un-marked. */
  167. void
  168. sweep_transport_list(void)
  169. {
  170. if (!transport_list)
  171. transport_list = smartlist_new();
  172. SMARTLIST_FOREACH_BEGIN(transport_list, transport_t *, t) {
  173. if (t->marked_for_removal) {
  174. SMARTLIST_DEL_CURRENT(transport_list, t);
  175. transport_free(t);
  176. }
  177. } SMARTLIST_FOREACH_END(t);
  178. }
  179. /** Initialize the pluggable transports list to empty, creating it if
  180. * needed. */
  181. static void
  182. clear_transport_list(void)
  183. {
  184. if (!transport_list)
  185. transport_list = smartlist_new();
  186. SMARTLIST_FOREACH(transport_list, transport_t *, t, transport_free(t));
  187. smartlist_clear(transport_list);
  188. }
  189. /** Return a deep copy of <b>transport</b>. */
  190. static transport_t *
  191. transport_copy(const transport_t *transport)
  192. {
  193. transport_t *new_transport = NULL;
  194. tor_assert(transport);
  195. new_transport = tor_malloc_zero(sizeof(transport_t));
  196. new_transport->socks_version = transport->socks_version;
  197. new_transport->name = tor_strdup(transport->name);
  198. tor_addr_copy(&new_transport->addr, &transport->addr);
  199. new_transport->port = transport->port;
  200. new_transport->marked_for_removal = transport->marked_for_removal;
  201. return new_transport;
  202. }
  203. /** Returns the transport in our transport list that has the name <b>name</b>.
  204. * Else returns NULL. */
  205. MOCK_IMPL(transport_t *,
  206. transport_get_by_name,(const char *name))
  207. {
  208. tor_assert(name);
  209. if (!transport_list)
  210. return NULL;
  211. SMARTLIST_FOREACH_BEGIN(transport_list, transport_t *, transport) {
  212. if (!strcmp(transport->name, name))
  213. return transport;
  214. } SMARTLIST_FOREACH_END(transport);
  215. return NULL;
  216. }
  217. /** Resolve any conflicts that the insertion of transport <b>t</b>
  218. * might cause.
  219. * Return 0 if <b>t</b> is OK and should be registered, 1 if there is
  220. * a transport identical to <b>t</b> already registered and -1 if
  221. * <b>t</b> cannot be added due to conflicts. */
  222. static int
  223. transport_resolve_conflicts(const transport_t *t)
  224. {
  225. /* This is how we resolve transport conflicts:
  226. If there is already a transport with the same name and addrport,
  227. we either have duplicate torrc lines OR we are here post-HUP and
  228. this transport was here pre-HUP as well. In any case, mark the
  229. old transport so that it doesn't get removed and ignore the new
  230. one. Our caller has to free the new transport so we return '1' to
  231. signify this.
  232. If there is already a transport with the same name but different
  233. addrport:
  234. * if it's marked for removal, it means that it either has a lower
  235. priority than 't' in torrc (otherwise the mark would have been
  236. cleared by the paragraph above), or it doesn't exist at all in
  237. the post-HUP torrc. We destroy the old transport and register 't'.
  238. * if it's *not* marked for removal, it means that it was newly
  239. added in the post-HUP torrc or that it's of higher priority, in
  240. this case we ignore 't'. */
  241. transport_t *t_tmp = transport_get_by_name(t->name);
  242. if (t_tmp) { /* same name */
  243. if (tor_addr_eq(&t->addr, &t_tmp->addr) && (t->port == t_tmp->port)) {
  244. /* same name *and* addrport */
  245. t_tmp->marked_for_removal = 0;
  246. return 1;
  247. } else { /* same name but different addrport */
  248. char *new_transport_addrport =
  249. tor_strdup(fmt_addrport(&t->addr, t->port));
  250. if (t_tmp->marked_for_removal) { /* marked for removal */
  251. log_notice(LD_GENERAL, "You tried to add transport '%s' at '%s' "
  252. "but there was already a transport marked for deletion at "
  253. "'%s'. We deleted the old transport and registered the "
  254. "new one.", t->name, new_transport_addrport,
  255. fmt_addrport(&t_tmp->addr, t_tmp->port));
  256. smartlist_remove(transport_list, t_tmp);
  257. transport_free(t_tmp);
  258. tor_free(new_transport_addrport);
  259. } else { /* *not* marked for removal */
  260. log_notice(LD_GENERAL, "You tried to add transport '%s' at '%s' "
  261. "but the same transport already exists at '%s'. "
  262. "Skipping.", t->name, new_transport_addrport,
  263. fmt_addrport(&t_tmp->addr, t_tmp->port));
  264. tor_free(new_transport_addrport);
  265. return -1;
  266. }
  267. tor_free(new_transport_addrport);
  268. }
  269. }
  270. return 0;
  271. }
  272. /** Add transport <b>t</b> to the internal list of pluggable
  273. * transports.
  274. * Returns 0 if the transport was added correctly, 1 if the same
  275. * transport was already registered (in this case the caller must
  276. * free the transport) and -1 if there was an error. */
  277. static int
  278. transport_add(transport_t *t)
  279. {
  280. int r;
  281. tor_assert(t);
  282. r = transport_resolve_conflicts(t);
  283. switch (r) {
  284. case 0: /* should register transport */
  285. if (!transport_list)
  286. transport_list = smartlist_new();
  287. smartlist_add(transport_list, t);
  288. return 0;
  289. default: /* let our caller know the return code */
  290. return r;
  291. }
  292. }
  293. /** Remember a new pluggable transport proxy at <b>addr</b>:<b>port</b>.
  294. * <b>name</b> is set to the name of the protocol this proxy uses.
  295. * <b>socks_ver</b> is set to the SOCKS version of the proxy. */
  296. MOCK_IMPL(int,
  297. transport_add_from_config, (const tor_addr_t *addr, uint16_t port,
  298. const char *name, int socks_ver))
  299. {
  300. transport_t *t = transport_new(addr, port, name, socks_ver, NULL);
  301. int r = transport_add(t);
  302. switch (r) {
  303. case -1:
  304. default:
  305. log_notice(LD_GENERAL, "Could not add transport %s at %s. Skipping.",
  306. t->name, fmt_addrport(&t->addr, t->port));
  307. transport_free(t);
  308. return -1;
  309. case 1:
  310. log_info(LD_GENERAL, "Successfully registered transport %s at %s.",
  311. t->name, fmt_addrport(&t->addr, t->port));
  312. transport_free(t); /* falling */
  313. return 0;
  314. case 0:
  315. log_info(LD_GENERAL, "Successfully registered transport %s at %s.",
  316. t->name, fmt_addrport(&t->addr, t->port));
  317. return 0;
  318. }
  319. }
  320. /** List of unconfigured managed proxies. */
  321. static smartlist_t *managed_proxy_list = NULL;
  322. /** Number of still unconfigured proxies. */
  323. static int unconfigured_proxies_n = 0;
  324. /** Boolean: True iff we might need to restart some proxies. */
  325. static int check_if_restarts_needed = 0;
  326. /** Return true if there are still unconfigured managed proxies, or proxies
  327. * that need restarting. */
  328. int
  329. pt_proxies_configuration_pending(void)
  330. {
  331. return unconfigured_proxies_n || check_if_restarts_needed;
  332. }
  333. /** Assert that the unconfigured_proxies_n value correctly matches the number
  334. * of proxies in a state other than PT_PROTO_COMPLETE. */
  335. static void
  336. assert_unconfigured_count_ok(void)
  337. {
  338. int n_completed = 0;
  339. if (!managed_proxy_list) {
  340. tor_assert(unconfigured_proxies_n == 0);
  341. return;
  342. }
  343. SMARTLIST_FOREACH(managed_proxy_list, managed_proxy_t *, mp, {
  344. if (mp->conf_state == PT_PROTO_COMPLETED)
  345. ++n_completed;
  346. });
  347. tor_assert(n_completed + unconfigured_proxies_n ==
  348. smartlist_len(managed_proxy_list));
  349. }
  350. /** Return true if <b>mp</b> has the same argv as <b>proxy_argv</b> */
  351. static int
  352. managed_proxy_has_argv(const managed_proxy_t *mp, char **proxy_argv)
  353. {
  354. char **tmp1=proxy_argv;
  355. char **tmp2=mp->argv;
  356. tor_assert(tmp1);
  357. tor_assert(tmp2);
  358. while (*tmp1 && *tmp2) {
  359. if (strcmp(*tmp1++, *tmp2++))
  360. return 0;
  361. }
  362. if (!*tmp1 && !*tmp2)
  363. return 1;
  364. return 0;
  365. }
  366. /** Return a managed proxy with the same argv as <b>proxy_argv</b>.
  367. * If no such managed proxy exists, return NULL. */
  368. static managed_proxy_t *
  369. get_managed_proxy_by_argv_and_type(char **proxy_argv, int is_server)
  370. {
  371. if (!managed_proxy_list)
  372. return NULL;
  373. SMARTLIST_FOREACH_BEGIN(managed_proxy_list, managed_proxy_t *, mp) {
  374. if (managed_proxy_has_argv(mp, proxy_argv) &&
  375. mp->is_server == is_server)
  376. return mp;
  377. } SMARTLIST_FOREACH_END(mp);
  378. return NULL;
  379. }
  380. /** Add <b>transport</b> to managed proxy <b>mp</b>. */
  381. static void
  382. add_transport_to_proxy(const char *transport, managed_proxy_t *mp)
  383. {
  384. tor_assert(mp->transports_to_launch);
  385. if (!smartlist_contains_string(mp->transports_to_launch, transport))
  386. smartlist_add_strdup(mp->transports_to_launch, transport);
  387. }
  388. /** Called when a SIGHUP occurs. Returns true if managed proxy
  389. * <b>mp</b> needs to be restarted after the SIGHUP, based on the new
  390. * torrc. */
  391. static int
  392. proxy_needs_restart(const managed_proxy_t *mp)
  393. {
  394. int ret = 1;
  395. char* proxy_uri;
  396. /* If the PT proxy config has changed, then all existing pluggable transports
  397. * should be restarted.
  398. */
  399. proxy_uri = get_pt_proxy_uri();
  400. if (strcmp_opt(proxy_uri, mp->proxy_uri) != 0)
  401. goto needs_restart;
  402. /* mp->transport_to_launch is populated with the names of the
  403. transports that must be launched *after* the SIGHUP.
  404. mp->transports is populated with the transports that were
  405. launched *before* the SIGHUP.
  406. Check if all the transports that need to be launched are already
  407. launched: */
  408. tor_assert(smartlist_len(mp->transports_to_launch) > 0);
  409. tor_assert(mp->conf_state == PT_PROTO_COMPLETED);
  410. if (smartlist_len(mp->transports_to_launch) != smartlist_len(mp->transports))
  411. goto needs_restart;
  412. SMARTLIST_FOREACH_BEGIN(mp->transports, const transport_t *, t) {
  413. if (!smartlist_contains_string(mp->transports_to_launch, t->name))
  414. goto needs_restart;
  415. } SMARTLIST_FOREACH_END(t);
  416. ret = 0;
  417. needs_restart:
  418. tor_free(proxy_uri);
  419. return ret;
  420. }
  421. /** Managed proxy <b>mp</b> must be restarted. Do all the necessary
  422. * preparations and then flag its state so that it will be relaunched
  423. * in the next tick. */
  424. static void
  425. proxy_prepare_for_restart(managed_proxy_t *mp)
  426. {
  427. transport_t *t_tmp = NULL;
  428. tor_assert(mp->conf_state == PT_PROTO_COMPLETED);
  429. /* destroy the process handle and terminate the process. */
  430. tor_process_handle_destroy(mp->process_handle, 1);
  431. mp->process_handle = NULL;
  432. /* destroy all its registered transports, since we will no longer
  433. use them. */
  434. SMARTLIST_FOREACH_BEGIN(mp->transports, const transport_t *, t) {
  435. t_tmp = transport_get_by_name(t->name);
  436. if (t_tmp)
  437. t_tmp->marked_for_removal = 1;
  438. } SMARTLIST_FOREACH_END(t);
  439. sweep_transport_list();
  440. /* free the transport in mp->transports */
  441. SMARTLIST_FOREACH(mp->transports, transport_t *, t, transport_free(t));
  442. smartlist_clear(mp->transports);
  443. /* Reset the proxy's HTTPS/SOCKS proxy */
  444. tor_free(mp->proxy_uri);
  445. mp->proxy_uri = get_pt_proxy_uri();
  446. mp->proxy_supported = 0;
  447. /* flag it as an infant proxy so that it gets launched on next tick */
  448. mp->conf_state = PT_PROTO_INFANT;
  449. unconfigured_proxies_n++;
  450. }
  451. /** Launch managed proxy <b>mp</b>. */
  452. static int
  453. launch_managed_proxy(managed_proxy_t *mp)
  454. {
  455. int retval;
  456. process_environment_t *env = create_managed_proxy_environment(mp);
  457. #ifdef _WIN32
  458. /* Passing NULL as lpApplicationName makes Windows search for the .exe */
  459. retval = tor_spawn_background(NULL,
  460. (const char **)mp->argv,
  461. env,
  462. &mp->process_handle);
  463. #else /* !(defined(_WIN32)) */
  464. retval = tor_spawn_background(mp->argv[0],
  465. (const char **)mp->argv,
  466. env,
  467. &mp->process_handle);
  468. #endif /* defined(_WIN32) */
  469. process_environment_free(env);
  470. if (retval == PROCESS_STATUS_ERROR) {
  471. log_warn(LD_GENERAL, "Managed proxy at '%s' failed at launch.",
  472. mp->argv[0]);
  473. return -1;
  474. }
  475. log_info(LD_CONFIG, "Managed proxy at '%s' has spawned with PID '%d'.",
  476. mp->argv[0], tor_process_get_pid(mp->process_handle));
  477. mp->conf_state = PT_PROTO_LAUNCHED;
  478. return 0;
  479. }
  480. /** Check if any of the managed proxies we are currently trying to
  481. * configure has anything new to say. */
  482. void
  483. pt_configure_remaining_proxies(void)
  484. {
  485. int at_least_a_proxy_config_finished = 0;
  486. smartlist_t *tmp = smartlist_new();
  487. log_debug(LD_CONFIG, "Configuring remaining managed proxies (%d)!",
  488. unconfigured_proxies_n);
  489. /* Iterate over tmp, not managed_proxy_list, since configure_proxy can
  490. * remove elements from managed_proxy_list. */
  491. smartlist_add_all(tmp, managed_proxy_list);
  492. assert_unconfigured_count_ok();
  493. SMARTLIST_FOREACH_BEGIN(tmp, managed_proxy_t *, mp) {
  494. tor_assert(mp->conf_state != PT_PROTO_BROKEN &&
  495. mp->conf_state != PT_PROTO_FAILED_LAUNCH);
  496. if (mp->was_around_before_config_read) {
  497. /* This proxy is marked by a config read. Check whether we need
  498. to restart it. */
  499. mp->was_around_before_config_read = 0;
  500. if (proxy_needs_restart(mp)) {
  501. log_info(LD_GENERAL, "Preparing managed proxy '%s' for restart.",
  502. mp->argv[0]);
  503. proxy_prepare_for_restart(mp);
  504. } else { /* it doesn't need to be restarted. */
  505. log_info(LD_GENERAL, "Nothing changed for managed proxy '%s' after "
  506. "HUP: not restarting.", mp->argv[0]);
  507. }
  508. continue;
  509. }
  510. /* If the proxy is not fully configured, try to configure it
  511. further. */
  512. if (!proxy_configuration_finished(mp))
  513. if (configure_proxy(mp) == 1)
  514. at_least_a_proxy_config_finished = 1;
  515. } SMARTLIST_FOREACH_END(mp);
  516. smartlist_free(tmp);
  517. check_if_restarts_needed = 0;
  518. assert_unconfigured_count_ok();
  519. if (at_least_a_proxy_config_finished)
  520. mark_my_descriptor_dirty("configured managed proxies");
  521. }
  522. /** Attempt to continue configuring managed proxy <b>mp</b>.
  523. * Return 1 if the transport configuration finished, and return 0
  524. * otherwise (if we still have more configuring to do for this
  525. * proxy). */
  526. STATIC int
  527. configure_proxy(managed_proxy_t *mp)
  528. {
  529. int configuration_finished = 0;
  530. smartlist_t *proxy_output = NULL;
  531. enum stream_status stream_status = 0;
  532. /* if we haven't launched the proxy yet, do it now */
  533. if (mp->conf_state == PT_PROTO_INFANT) {
  534. if (launch_managed_proxy(mp) < 0) { /* launch fail */
  535. mp->conf_state = PT_PROTO_FAILED_LAUNCH;
  536. handle_finished_proxy(mp);
  537. }
  538. return 0;
  539. }
  540. tor_assert(mp->conf_state != PT_PROTO_INFANT);
  541. tor_assert(mp->process_handle);
  542. proxy_output =
  543. tor_get_lines_from_handle(tor_process_get_stdout_pipe(mp->process_handle),
  544. &stream_status);
  545. if (!proxy_output) { /* failed to get input from proxy */
  546. if (stream_status != IO_STREAM_EAGAIN) { /* bad stream status! */
  547. mp->conf_state = PT_PROTO_BROKEN;
  548. log_warn(LD_GENERAL, "The communication stream of managed proxy '%s' "
  549. "is '%s'. Most probably the managed proxy stopped running. "
  550. "This might be a bug of the managed proxy, a bug of Tor, or "
  551. "a misconfiguration. Please enable logging on your managed "
  552. "proxy and check the logs for errors.",
  553. mp->argv[0], stream_status_to_string(stream_status));
  554. }
  555. goto done;
  556. }
  557. /* Handle lines. */
  558. SMARTLIST_FOREACH_BEGIN(proxy_output, const char *, line) {
  559. handle_proxy_line(line, mp);
  560. if (proxy_configuration_finished(mp))
  561. goto done;
  562. } SMARTLIST_FOREACH_END(line);
  563. done:
  564. /* if the proxy finished configuring, exit the loop. */
  565. if (proxy_configuration_finished(mp)) {
  566. handle_finished_proxy(mp);
  567. configuration_finished = 1;
  568. }
  569. if (proxy_output) {
  570. SMARTLIST_FOREACH(proxy_output, char *, cp, tor_free(cp));
  571. smartlist_free(proxy_output);
  572. }
  573. return configuration_finished;
  574. }
  575. /** Register server managed proxy <b>mp</b> transports to state */
  576. static void
  577. register_server_proxy(const managed_proxy_t *mp)
  578. {
  579. tor_assert(mp->conf_state != PT_PROTO_COMPLETED);
  580. SMARTLIST_FOREACH_BEGIN(mp->transports, transport_t *, t) {
  581. save_transport_to_state(t->name, &t->addr, t->port);
  582. log_notice(LD_GENERAL, "Registered server transport '%s' at '%s'",
  583. t->name, fmt_addrport(&t->addr, t->port));
  584. control_event_transport_launched("server", t->name, &t->addr, t->port);
  585. } SMARTLIST_FOREACH_END(t);
  586. }
  587. /** Register all the transports supported by client managed proxy
  588. * <b>mp</b> to the bridge subsystem. */
  589. static void
  590. register_client_proxy(const managed_proxy_t *mp)
  591. {
  592. int r;
  593. tor_assert(mp->conf_state != PT_PROTO_COMPLETED);
  594. SMARTLIST_FOREACH_BEGIN(mp->transports, transport_t *, t) {
  595. transport_t *transport_tmp = transport_copy(t);
  596. r = transport_add(transport_tmp);
  597. switch (r) {
  598. case -1:
  599. log_notice(LD_GENERAL, "Could not add transport %s. Skipping.", t->name);
  600. transport_free(transport_tmp);
  601. break;
  602. case 0:
  603. log_info(LD_GENERAL, "Successfully registered transport %s", t->name);
  604. control_event_transport_launched("client", t->name, &t->addr, t->port);
  605. break;
  606. case 1:
  607. log_info(LD_GENERAL, "Successfully registered transport %s", t->name);
  608. control_event_transport_launched("client", t->name, &t->addr, t->port);
  609. transport_free(transport_tmp);
  610. break;
  611. }
  612. } SMARTLIST_FOREACH_END(t);
  613. }
  614. /** Register the transports of managed proxy <b>mp</b>. */
  615. static inline void
  616. register_proxy(const managed_proxy_t *mp)
  617. {
  618. if (mp->is_server)
  619. register_server_proxy(mp);
  620. else
  621. register_client_proxy(mp);
  622. }
  623. /** Free memory allocated by managed proxy <b>mp</b>. */
  624. STATIC void
  625. managed_proxy_destroy(managed_proxy_t *mp,
  626. int also_terminate_process)
  627. {
  628. SMARTLIST_FOREACH(mp->transports, transport_t *, t, transport_free(t));
  629. /* free the transports smartlist */
  630. smartlist_free(mp->transports);
  631. /* free the transports_to_launch smartlist */
  632. SMARTLIST_FOREACH(mp->transports_to_launch, char *, t, tor_free(t));
  633. smartlist_free(mp->transports_to_launch);
  634. /* remove it from the list of managed proxies */
  635. if (managed_proxy_list)
  636. smartlist_remove(managed_proxy_list, mp);
  637. /* free the argv */
  638. free_execve_args(mp->argv);
  639. /* free the outgoing proxy URI */
  640. tor_free(mp->proxy_uri);
  641. tor_process_handle_destroy(mp->process_handle, also_terminate_process);
  642. mp->process_handle = NULL;
  643. tor_free(mp);
  644. }
  645. /** Convert the tor proxy options to a URI suitable for TOR_PT_PROXY.
  646. * Return a newly allocated string containing the URI, or NULL if no
  647. * proxy is set. */
  648. STATIC char *
  649. get_pt_proxy_uri(void)
  650. {
  651. const or_options_t *options = get_options();
  652. char *uri = NULL;
  653. if (options->Socks4Proxy || options->Socks5Proxy || options->HTTPSProxy) {
  654. char addr[TOR_ADDR_BUF_LEN+1];
  655. if (options->Socks4Proxy) {
  656. tor_addr_to_str(addr, &options->Socks4ProxyAddr, sizeof(addr), 1);
  657. tor_asprintf(&uri, "socks4a://%s:%d", addr, options->Socks4ProxyPort);
  658. } else if (options->Socks5Proxy) {
  659. tor_addr_to_str(addr, &options->Socks5ProxyAddr, sizeof(addr), 1);
  660. if (!options->Socks5ProxyUsername && !options->Socks5ProxyPassword) {
  661. tor_asprintf(&uri, "socks5://%s:%d", addr, options->Socks5ProxyPort);
  662. } else {
  663. tor_asprintf(&uri, "socks5://%s:%s@%s:%d",
  664. options->Socks5ProxyUsername,
  665. options->Socks5ProxyPassword,
  666. addr, options->Socks5ProxyPort);
  667. }
  668. } else if (options->HTTPSProxy) {
  669. tor_addr_to_str(addr, &options->HTTPSProxyAddr, sizeof(addr), 1);
  670. if (!options->HTTPSProxyAuthenticator) {
  671. tor_asprintf(&uri, "http://%s:%d", addr, options->HTTPSProxyPort);
  672. } else {
  673. tor_asprintf(&uri, "http://%s@%s:%d", options->HTTPSProxyAuthenticator,
  674. addr, options->HTTPSProxyPort);
  675. }
  676. }
  677. }
  678. return uri;
  679. }
  680. /** Handle a configured or broken managed proxy <b>mp</b>. */
  681. static void
  682. handle_finished_proxy(managed_proxy_t *mp)
  683. {
  684. switch (mp->conf_state) {
  685. case PT_PROTO_BROKEN: /* if broken: */
  686. managed_proxy_destroy(mp, 1); /* annihilate it. */
  687. break;
  688. case PT_PROTO_FAILED_LAUNCH: /* if it failed before launching: */
  689. managed_proxy_destroy(mp, 0); /* destroy it but don't terminate */
  690. break;
  691. case PT_PROTO_CONFIGURED: /* if configured correctly: */
  692. if (mp->proxy_uri && !mp->proxy_supported) {
  693. log_warn(LD_CONFIG, "Managed proxy '%s' did not configure the "
  694. "specified outgoing proxy and will be terminated.",
  695. mp->argv[0]);
  696. managed_proxy_destroy(mp, 1); /* annihilate it. */
  697. break;
  698. }
  699. register_proxy(mp); /* register its transports */
  700. mp->conf_state = PT_PROTO_COMPLETED; /* and mark it as completed. */
  701. break;
  702. case PT_PROTO_INFANT:
  703. case PT_PROTO_LAUNCHED:
  704. case PT_PROTO_ACCEPTING_METHODS:
  705. case PT_PROTO_COMPLETED:
  706. default:
  707. log_warn(LD_CONFIG, "Unexpected state '%d' of managed proxy '%s'.",
  708. (int)mp->conf_state, mp->argv[0]);
  709. tor_assert(0);
  710. }
  711. unconfigured_proxies_n--;
  712. }
  713. /** Return true if the configuration of the managed proxy <b>mp</b> is
  714. finished. */
  715. static inline int
  716. proxy_configuration_finished(const managed_proxy_t *mp)
  717. {
  718. return (mp->conf_state == PT_PROTO_CONFIGURED ||
  719. mp->conf_state == PT_PROTO_BROKEN ||
  720. mp->conf_state == PT_PROTO_FAILED_LAUNCH);
  721. }
  722. /** This function is called when a proxy sends an {S,C}METHODS DONE message. */
  723. static void
  724. handle_methods_done(const managed_proxy_t *mp)
  725. {
  726. tor_assert(mp->transports);
  727. if (smartlist_len(mp->transports) == 0)
  728. log_notice(LD_GENERAL, "Managed proxy '%s' was spawned successfully, "
  729. "but it didn't launch any pluggable transport listeners!",
  730. mp->argv[0]);
  731. log_info(LD_CONFIG, "%s managed proxy '%s' configuration completed!",
  732. mp->is_server ? "Server" : "Client",
  733. mp->argv[0]);
  734. }
  735. /** Handle a configuration protocol <b>line</b> received from a
  736. * managed proxy <b>mp</b>. */
  737. STATIC void
  738. handle_proxy_line(const char *line, managed_proxy_t *mp)
  739. {
  740. log_info(LD_GENERAL, "Got a line from managed proxy '%s': (%s)",
  741. mp->argv[0], line);
  742. if (!strcmpstart(line, PROTO_ENV_ERROR)) {
  743. if (mp->conf_state != PT_PROTO_LAUNCHED)
  744. goto err;
  745. parse_env_error(line);
  746. goto err;
  747. } else if (!strcmpstart(line, PROTO_NEG_FAIL)) {
  748. if (mp->conf_state != PT_PROTO_LAUNCHED)
  749. goto err;
  750. log_warn(LD_CONFIG, "Managed proxy could not pick a "
  751. "configuration protocol version.");
  752. goto err;
  753. } else if (!strcmpstart(line, PROTO_NEG_SUCCESS)) {
  754. if (mp->conf_state != PT_PROTO_LAUNCHED)
  755. goto err;
  756. if (parse_version(line,mp) < 0)
  757. goto err;
  758. tor_assert(mp->conf_protocol != 0);
  759. mp->conf_state = PT_PROTO_ACCEPTING_METHODS;
  760. return;
  761. } else if (!strcmpstart(line, PROTO_CMETHODS_DONE)) {
  762. if (mp->conf_state != PT_PROTO_ACCEPTING_METHODS)
  763. goto err;
  764. handle_methods_done(mp);
  765. mp->conf_state = PT_PROTO_CONFIGURED;
  766. return;
  767. } else if (!strcmpstart(line, PROTO_SMETHODS_DONE)) {
  768. if (mp->conf_state != PT_PROTO_ACCEPTING_METHODS)
  769. goto err;
  770. handle_methods_done(mp);
  771. mp->conf_state = PT_PROTO_CONFIGURED;
  772. return;
  773. } else if (!strcmpstart(line, PROTO_CMETHOD_ERROR)) {
  774. if (mp->conf_state != PT_PROTO_ACCEPTING_METHODS)
  775. goto err;
  776. parse_client_method_error(line);
  777. goto err;
  778. } else if (!strcmpstart(line, PROTO_SMETHOD_ERROR)) {
  779. if (mp->conf_state != PT_PROTO_ACCEPTING_METHODS)
  780. goto err;
  781. parse_server_method_error(line);
  782. goto err;
  783. } else if (!strcmpstart(line, PROTO_CMETHOD)) {
  784. if (mp->conf_state != PT_PROTO_ACCEPTING_METHODS)
  785. goto err;
  786. if (parse_cmethod_line(line, mp) < 0)
  787. goto err;
  788. return;
  789. } else if (!strcmpstart(line, PROTO_SMETHOD)) {
  790. if (mp->conf_state != PT_PROTO_ACCEPTING_METHODS)
  791. goto err;
  792. if (parse_smethod_line(line, mp) < 0)
  793. goto err;
  794. return;
  795. } else if (!strcmpstart(line, PROTO_PROXY_DONE)) {
  796. if (mp->conf_state != PT_PROTO_ACCEPTING_METHODS)
  797. goto err;
  798. if (mp->proxy_uri) {
  799. mp->proxy_supported = 1;
  800. return;
  801. }
  802. /* No proxy was configured, this should log */
  803. } else if (!strcmpstart(line, PROTO_PROXY_ERROR)) {
  804. if (mp->conf_state != PT_PROTO_ACCEPTING_METHODS)
  805. goto err;
  806. parse_proxy_error(line);
  807. goto err;
  808. } else if (!strcmpstart(line, SPAWN_ERROR_MESSAGE)) {
  809. /* managed proxy launch failed: parse error message to learn why. */
  810. int retval, child_state, saved_errno;
  811. retval = tor_sscanf(line, SPAWN_ERROR_MESSAGE "%x/%x",
  812. &child_state, &saved_errno);
  813. if (retval == 2) {
  814. log_warn(LD_GENERAL,
  815. "Could not launch managed proxy executable at '%s' ('%s').",
  816. mp->argv[0], strerror(saved_errno));
  817. } else { /* failed to parse error message */
  818. log_warn(LD_GENERAL,"Could not launch managed proxy executable at '%s'.",
  819. mp->argv[0]);
  820. }
  821. mp->conf_state = PT_PROTO_FAILED_LAUNCH;
  822. return;
  823. }
  824. log_notice(LD_GENERAL, "Unknown line received by managed proxy (%s).", line);
  825. return;
  826. err:
  827. mp->conf_state = PT_PROTO_BROKEN;
  828. log_warn(LD_CONFIG, "Managed proxy at '%s' failed the configuration protocol"
  829. " and will be destroyed.", mp->argv[0]);
  830. }
  831. /** Parses an ENV-ERROR <b>line</b> and warns the user accordingly. */
  832. STATIC void
  833. parse_env_error(const char *line)
  834. {
  835. /* (Length of the protocol string) plus (a space) and (the first char of
  836. the error message) */
  837. if (strlen(line) < (strlen(PROTO_ENV_ERROR) + 2))
  838. log_notice(LD_CONFIG, "Managed proxy sent us an %s without an error "
  839. "message.", PROTO_ENV_ERROR);
  840. log_warn(LD_CONFIG, "Managed proxy couldn't understand the "
  841. "pluggable transport environment variables. (%s)",
  842. line+strlen(PROTO_ENV_ERROR)+1);
  843. }
  844. /** Handles a VERSION <b>line</b>. Updates the configuration protocol
  845. * version in <b>mp</b>. */
  846. STATIC int
  847. parse_version(const char *line, managed_proxy_t *mp)
  848. {
  849. if (strlen(line) < (strlen(PROTO_NEG_SUCCESS) + 2)) {
  850. log_warn(LD_CONFIG, "Managed proxy sent us malformed %s line.",
  851. PROTO_NEG_SUCCESS);
  852. return -1;
  853. }
  854. if (strcmp("1", line+strlen(PROTO_NEG_SUCCESS)+1)) { /* hardcoded temp */
  855. log_warn(LD_CONFIG, "Managed proxy tried to negotiate on version '%s'. "
  856. "We only support version '1'", line+strlen(PROTO_NEG_SUCCESS)+1);
  857. return -1;
  858. }
  859. mp->conf_protocol = PROTO_VERSION_ONE; /* temp. till more versions appear */
  860. return 0;
  861. }
  862. /** Parses {C,S}METHOD-ERROR <b>line</b> and warns the user
  863. * accordingly. If <b>is_server</b> it is an SMETHOD-ERROR,
  864. * otherwise it is a CMETHOD-ERROR. */
  865. static void
  866. parse_method_error(const char *line, int is_server)
  867. {
  868. const char* error = is_server ?
  869. PROTO_SMETHOD_ERROR : PROTO_CMETHOD_ERROR;
  870. /* (Length of the protocol string) plus (a space) and (the first char of
  871. the error message) */
  872. if (strlen(line) < (strlen(error) + 2))
  873. log_warn(LD_CONFIG, "Managed proxy sent us an %s without an error "
  874. "message.", error);
  875. log_warn(LD_CONFIG, "%s managed proxy encountered a method error. (%s)",
  876. is_server ? "Server" : "Client",
  877. line+strlen(error)+1);
  878. }
  879. /** A helper for parse_{c,s}method_line(), bootstraps its
  880. * functionalities. If <b>is_smethod</b> is true then the
  881. * the line to parse is a SMETHOD line otherwise it is a
  882. * CMETHOD line*/
  883. static int
  884. parse_method_line_helper(const char *line,
  885. managed_proxy_t *mp,
  886. int is_smethod)
  887. {
  888. int item_index = 0;
  889. int r;
  890. char *transport_name=NULL;
  891. char *args_string=NULL;
  892. char *addrport=NULL;
  893. int socks_ver=PROXY_NONE;
  894. char *address=NULL;
  895. uint16_t port = 0;
  896. const char *method_str = is_smethod ? PROTO_SMETHOD : PROTO_CMETHOD;
  897. const int min_args_count = is_smethod ? 3 : 4;
  898. tor_addr_t tor_addr;
  899. transport_t *transport=NULL;
  900. smartlist_t *items= smartlist_new();
  901. smartlist_split_string(items, line, NULL,
  902. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  903. if (smartlist_len(items) < min_args_count) {
  904. log_warn(LD_CONFIG, "Managed proxy sent us a %s line "
  905. "with too few arguments.", method_str);
  906. goto err;
  907. }
  908. tor_assert(!strcmp(smartlist_get(items, item_index),method_str));
  909. ++item_index;
  910. transport_name = smartlist_get(items,item_index);
  911. ++item_index;
  912. if (!string_is_C_identifier(transport_name)) {
  913. log_warn(LD_CONFIG, "Transport name is not a C identifier (%s).",
  914. transport_name);
  915. goto err;
  916. }
  917. /** Check for the proxy method sent to us in CMETHOD line. */
  918. if (!is_smethod) {
  919. const char *socks_ver_str = smartlist_get(items,item_index);
  920. ++item_index;
  921. if (!strcmp(socks_ver_str,"socks4")) {
  922. socks_ver = PROXY_SOCKS4;
  923. } else if (!strcmp(socks_ver_str,"socks5")) {
  924. socks_ver = PROXY_SOCKS5;
  925. } else {
  926. log_warn(LD_CONFIG, "Client managed proxy sent us a proxy protocol "
  927. "we don't recognize. (%s)", socks_ver_str);
  928. goto err;
  929. }
  930. }
  931. addrport = smartlist_get(items, item_index);
  932. ++item_index;
  933. if (tor_addr_port_split(LOG_WARN, addrport, &address, &port)<0) {
  934. log_warn(LD_CONFIG, "Error parsing transport address '%s'", addrport);
  935. goto err;
  936. }
  937. if (!port) {
  938. log_warn(LD_CONFIG,
  939. "Transport address '%s' has no port.", addrport);
  940. goto err;
  941. }
  942. if (tor_addr_parse(&tor_addr, address) < 0) {
  943. log_warn(LD_CONFIG, "Error parsing transport address '%s'", address);
  944. goto err;
  945. }
  946. /** Check for options in the SMETHOD line. */
  947. if (is_smethod && smartlist_len(items) > min_args_count) {
  948. /* Seems like there are also some [options] in the SMETHOD line.
  949. Let's see if we can parse them. */
  950. char *options_string = smartlist_get(items, item_index);
  951. log_debug(LD_CONFIG, "Got options_string: %s", options_string);
  952. if (!strcmpstart(options_string, "ARGS:")) {
  953. args_string = options_string+strlen("ARGS:");
  954. log_debug(LD_CONFIG, "Got ARGS: %s", args_string);
  955. }
  956. }
  957. transport = transport_new(&tor_addr, port, transport_name,
  958. socks_ver, args_string);
  959. smartlist_add(mp->transports, transport);
  960. /** Logs info about line parsing success for client or server */
  961. if (is_smethod) {
  962. log_info(LD_CONFIG, "Server transport %s at %s:%d.",
  963. transport_name, address, (int)port);
  964. } else {
  965. log_info(LD_CONFIG, "Transport %s at %s:%d with SOCKS %d. "
  966. "Attached to managed proxy.",
  967. transport_name, address, (int)port, socks_ver);
  968. }
  969. r=0;
  970. goto done;
  971. err:
  972. r = -1;
  973. done:
  974. SMARTLIST_FOREACH(items, char*, s, tor_free(s));
  975. smartlist_free(items);
  976. tor_free(address);
  977. return r;
  978. }
  979. /** Parses an SMETHOD <b>line</b> and if well-formed it registers the
  980. * new transport in <b>mp</b>. */
  981. STATIC int
  982. parse_smethod_line(const char *line, managed_proxy_t *mp)
  983. {
  984. /* Example of legit SMETHOD line:
  985. SMETHOD obfs2 0.0.0.0:25612 ARGS:secret=supersekrit,key=superkey */
  986. return parse_method_line_helper(line, mp, 1);
  987. }
  988. /** Parses a CMETHOD <b>line</b>, and if well-formed it registers
  989. * the new transport in <b>mp</b>. */
  990. STATIC int
  991. parse_cmethod_line(const char *line, managed_proxy_t *mp)
  992. {
  993. /* Example of legit CMETHOD line:
  994. CMETHOD obfs2 socks5 127.0.0.1:35713 */
  995. return parse_method_line_helper(line, mp, 0);
  996. }
  997. /** Parses an PROXY-ERROR <b>line</b> and warns the user accordingly. */
  998. STATIC void
  999. parse_proxy_error(const char *line)
  1000. {
  1001. /* (Length of the protocol string) plus (a space) and (the first char of
  1002. the error message) */
  1003. if (strlen(line) < (strlen(PROTO_PROXY_ERROR) + 2))
  1004. log_notice(LD_CONFIG, "Managed proxy sent us an %s without an error "
  1005. "message.", PROTO_PROXY_ERROR);
  1006. log_warn(LD_CONFIG, "Managed proxy failed to configure the "
  1007. "pluggable transport's outgoing proxy. (%s)",
  1008. line+strlen(PROTO_PROXY_ERROR)+1);
  1009. }
  1010. /** Return a newly allocated string that tor should place in
  1011. * TOR_PT_SERVER_TRANSPORT_OPTIONS while configuring the server
  1012. * manged proxy in <b>mp</b>. Return NULL if no such options are found. */
  1013. STATIC char *
  1014. get_transport_options_for_server_proxy(const managed_proxy_t *mp)
  1015. {
  1016. char *options_string = NULL;
  1017. smartlist_t *string_sl = smartlist_new();
  1018. tor_assert(mp->is_server);
  1019. /** Loop over the transports of the proxy. If we have options for
  1020. any of them, format them appropriately and place them in our
  1021. smartlist. Finally, join our smartlist to get the final
  1022. string. */
  1023. SMARTLIST_FOREACH_BEGIN(mp->transports_to_launch, const char *, transport) {
  1024. smartlist_t *options_tmp_sl = NULL;
  1025. options_tmp_sl = get_options_for_server_transport(transport);
  1026. if (!options_tmp_sl)
  1027. continue;
  1028. /** Loop over the options of this transport, escape them, and
  1029. place them in the smartlist. */
  1030. SMARTLIST_FOREACH_BEGIN(options_tmp_sl, const char *, options) {
  1031. char *escaped_opts = tor_escape_str_for_pt_args(options, ":;\\");
  1032. smartlist_add_asprintf(string_sl, "%s:%s",
  1033. transport, escaped_opts);
  1034. tor_free(escaped_opts);
  1035. } SMARTLIST_FOREACH_END(options);
  1036. SMARTLIST_FOREACH(options_tmp_sl, char *, c, tor_free(c));
  1037. smartlist_free(options_tmp_sl);
  1038. } SMARTLIST_FOREACH_END(transport);
  1039. if (smartlist_len(string_sl)) {
  1040. options_string = smartlist_join_strings(string_sl, ";", 0, NULL);
  1041. }
  1042. SMARTLIST_FOREACH(string_sl, char *, t, tor_free(t));
  1043. smartlist_free(string_sl);
  1044. return options_string;
  1045. }
  1046. /** Return the string that tor should place in TOR_PT_SERVER_BINDADDR
  1047. * while configuring the server managed proxy in <b>mp</b>. The
  1048. * string is stored in the heap, and it's the responsibility of
  1049. * the caller to deallocate it after its use. */
  1050. static char *
  1051. get_bindaddr_for_server_proxy(const managed_proxy_t *mp)
  1052. {
  1053. char *bindaddr_result = NULL;
  1054. char *bindaddr_tmp = NULL;
  1055. smartlist_t *string_tmp = smartlist_new();
  1056. tor_assert(mp->is_server);
  1057. SMARTLIST_FOREACH_BEGIN(mp->transports_to_launch, char *, t) {
  1058. bindaddr_tmp = get_stored_bindaddr_for_server_transport(t);
  1059. smartlist_add_asprintf(string_tmp, "%s-%s", t, bindaddr_tmp);
  1060. tor_free(bindaddr_tmp);
  1061. } SMARTLIST_FOREACH_END(t);
  1062. bindaddr_result = smartlist_join_strings(string_tmp, ",", 0, NULL);
  1063. SMARTLIST_FOREACH(string_tmp, char *, t, tor_free(t));
  1064. smartlist_free(string_tmp);
  1065. return bindaddr_result;
  1066. }
  1067. /** Return a newly allocated process_environment_t * for <b>mp</b>'s
  1068. * process. */
  1069. static process_environment_t *
  1070. create_managed_proxy_environment(const managed_proxy_t *mp)
  1071. {
  1072. const or_options_t *options = get_options();
  1073. /* Environment variables to be added to or set in mp's environment. */
  1074. smartlist_t *envs = smartlist_new();
  1075. /* XXXX The next time someone touches this code, shorten the name of
  1076. * set_environment_variable_in_smartlist, add a
  1077. * set_env_var_in_smartlist_asprintf function, and get rid of the
  1078. * silly extra envs smartlist. */
  1079. /* The final environment to be passed to mp. */
  1080. smartlist_t *merged_env_vars = get_current_process_environment_variables();
  1081. process_environment_t *env;
  1082. {
  1083. char *state_tmp = get_datadir_fname("pt_state/"); /* XXX temp */
  1084. smartlist_add_asprintf(envs, "TOR_PT_STATE_LOCATION=%s", state_tmp);
  1085. tor_free(state_tmp);
  1086. }
  1087. smartlist_add_strdup(envs, "TOR_PT_MANAGED_TRANSPORT_VER=1");
  1088. {
  1089. char *transports_to_launch =
  1090. smartlist_join_strings(mp->transports_to_launch, ",", 0, NULL);
  1091. smartlist_add_asprintf(envs,
  1092. mp->is_server ?
  1093. "TOR_PT_SERVER_TRANSPORTS=%s" :
  1094. "TOR_PT_CLIENT_TRANSPORTS=%s",
  1095. transports_to_launch);
  1096. tor_free(transports_to_launch);
  1097. }
  1098. if (mp->is_server) {
  1099. {
  1100. char *orport_tmp =
  1101. get_first_listener_addrport_string(CONN_TYPE_OR_LISTENER);
  1102. if (orport_tmp) {
  1103. smartlist_add_asprintf(envs, "TOR_PT_ORPORT=%s", orport_tmp);
  1104. tor_free(orport_tmp);
  1105. }
  1106. }
  1107. {
  1108. char *bindaddr_tmp = get_bindaddr_for_server_proxy(mp);
  1109. smartlist_add_asprintf(envs, "TOR_PT_SERVER_BINDADDR=%s", bindaddr_tmp);
  1110. tor_free(bindaddr_tmp);
  1111. }
  1112. {
  1113. char *server_transport_options =
  1114. get_transport_options_for_server_proxy(mp);
  1115. if (server_transport_options) {
  1116. smartlist_add_asprintf(envs, "TOR_PT_SERVER_TRANSPORT_OPTIONS=%s",
  1117. server_transport_options);
  1118. tor_free(server_transport_options);
  1119. }
  1120. }
  1121. /* XXXX Remove the '=' here once versions of obfsproxy which
  1122. * assert that this env var exists are sufficiently dead.
  1123. *
  1124. * (If we remove this line entirely, some joker will stick this
  1125. * variable in Tor's environment and crash PTs that try to parse
  1126. * it even when not run in server mode.) */
  1127. if (options->ExtORPort_lines) {
  1128. char *ext_or_addrport_tmp =
  1129. get_first_listener_addrport_string(CONN_TYPE_EXT_OR_LISTENER);
  1130. char *cookie_file_loc = get_ext_or_auth_cookie_file_name();
  1131. if (ext_or_addrport_tmp) {
  1132. smartlist_add_asprintf(envs, "TOR_PT_EXTENDED_SERVER_PORT=%s",
  1133. ext_or_addrport_tmp);
  1134. }
  1135. smartlist_add_asprintf(envs, "TOR_PT_AUTH_COOKIE_FILE=%s",
  1136. cookie_file_loc);
  1137. tor_free(ext_or_addrport_tmp);
  1138. tor_free(cookie_file_loc);
  1139. } else {
  1140. smartlist_add_asprintf(envs, "TOR_PT_EXTENDED_SERVER_PORT=");
  1141. }
  1142. /* All new versions of tor will keep stdin open, so PTs can use it
  1143. * as a reliable termination detection mechanism.
  1144. */
  1145. smartlist_add_asprintf(envs, "TOR_PT_EXIT_ON_STDIN_CLOSE=1");
  1146. } else {
  1147. /* If ClientTransportPlugin has a HTTPS/SOCKS proxy configured, set the
  1148. * TOR_PT_PROXY line.
  1149. */
  1150. if (mp->proxy_uri) {
  1151. smartlist_add_asprintf(envs, "TOR_PT_PROXY=%s", mp->proxy_uri);
  1152. }
  1153. }
  1154. SMARTLIST_FOREACH_BEGIN(envs, const char *, env_var) {
  1155. set_environment_variable_in_smartlist(merged_env_vars, env_var,
  1156. tor_free_, 1);
  1157. } SMARTLIST_FOREACH_END(env_var);
  1158. env = process_environment_make(merged_env_vars);
  1159. smartlist_free(envs);
  1160. SMARTLIST_FOREACH(merged_env_vars, void *, x, tor_free(x));
  1161. smartlist_free(merged_env_vars);
  1162. return env;
  1163. }
  1164. /** Create and return a new managed proxy for <b>transport</b> using
  1165. * <b>proxy_argv</b>. Also, add it to the global managed proxy list. If
  1166. * <b>is_server</b> is true, it's a server managed proxy. Takes ownership of
  1167. * <b>proxy_argv</b>.
  1168. *
  1169. * Requires that proxy_argv have at least one element. */
  1170. STATIC managed_proxy_t *
  1171. managed_proxy_create(const smartlist_t *with_transport_list,
  1172. char **proxy_argv, int is_server)
  1173. {
  1174. managed_proxy_t *mp = tor_malloc_zero(sizeof(managed_proxy_t));
  1175. mp->conf_state = PT_PROTO_INFANT;
  1176. mp->is_server = is_server;
  1177. mp->argv = proxy_argv;
  1178. mp->transports = smartlist_new();
  1179. mp->proxy_uri = get_pt_proxy_uri();
  1180. mp->transports_to_launch = smartlist_new();
  1181. SMARTLIST_FOREACH(with_transport_list, const char *, transport,
  1182. add_transport_to_proxy(transport, mp));
  1183. /* register the managed proxy */
  1184. if (!managed_proxy_list)
  1185. managed_proxy_list = smartlist_new();
  1186. smartlist_add(managed_proxy_list, mp);
  1187. unconfigured_proxies_n++;
  1188. assert_unconfigured_count_ok();
  1189. return mp;
  1190. }
  1191. /** Register proxy with <b>proxy_argv</b>, supporting transports in
  1192. * <b>transport_list</b>, to the managed proxy subsystem.
  1193. * If <b>is_server</b> is true, then the proxy is a server proxy.
  1194. *
  1195. * Takes ownership of proxy_argv.
  1196. *
  1197. * Requires that proxy_argv be a NULL-terminated array of command-line
  1198. * elements, containing at least one element.
  1199. **/
  1200. MOCK_IMPL(void,
  1201. pt_kickstart_proxy, (const smartlist_t *with_transport_list,
  1202. char **proxy_argv, int is_server))
  1203. {
  1204. managed_proxy_t *mp=NULL;
  1205. transport_t *old_transport = NULL;
  1206. if (!proxy_argv || !proxy_argv[0]) {
  1207. return;
  1208. }
  1209. mp = get_managed_proxy_by_argv_and_type(proxy_argv, is_server);
  1210. if (!mp) { /* we haven't seen this proxy before */
  1211. managed_proxy_create(with_transport_list, proxy_argv, is_server);
  1212. } else { /* known proxy. add its transport to its transport list */
  1213. if (mp->was_around_before_config_read) {
  1214. /* If this managed proxy was around even before we read the
  1215. config this time, it means that it was already enabled before
  1216. and is not useless and should be kept. If it's marked for
  1217. removal, unmark it and make sure that we check whether it
  1218. needs to be restarted. */
  1219. if (mp->marked_for_removal) {
  1220. mp->marked_for_removal = 0;
  1221. check_if_restarts_needed = 1;
  1222. }
  1223. /* For each new transport, check if the managed proxy used to
  1224. support it before the SIGHUP. If that was the case, make sure
  1225. it doesn't get removed because we might reuse it. */
  1226. SMARTLIST_FOREACH_BEGIN(with_transport_list, const char *, transport) {
  1227. old_transport = transport_get_by_name(transport);
  1228. if (old_transport)
  1229. old_transport->marked_for_removal = 0;
  1230. } SMARTLIST_FOREACH_END(transport);
  1231. }
  1232. SMARTLIST_FOREACH(with_transport_list, const char *, transport,
  1233. add_transport_to_proxy(transport, mp));
  1234. free_execve_args(proxy_argv);
  1235. }
  1236. }
  1237. /** Frees the array of pointers in <b>arg</b> used as arguments to
  1238. execve(2). */
  1239. STATIC void
  1240. free_execve_args(char **arg)
  1241. {
  1242. char **tmp = arg;
  1243. while (*tmp) /* use the fact that the last element of the array is a
  1244. NULL pointer to know when to stop freeing */
  1245. tor_free_(*tmp++);
  1246. tor_free(arg);
  1247. }
  1248. /** Tor will read its config.
  1249. * Prepare the managed proxy list so that proxies not used in the new
  1250. * config will shutdown, and proxies that need to spawn different
  1251. * transports will do so. */
  1252. void
  1253. pt_prepare_proxy_list_for_config_read(void)
  1254. {
  1255. if (!managed_proxy_list)
  1256. return;
  1257. assert_unconfigured_count_ok();
  1258. SMARTLIST_FOREACH_BEGIN(managed_proxy_list, managed_proxy_t *, mp) {
  1259. /* Destroy unconfigured proxies. */
  1260. if (mp->conf_state != PT_PROTO_COMPLETED) {
  1261. SMARTLIST_DEL_CURRENT(managed_proxy_list, mp);
  1262. managed_proxy_destroy(mp, 1);
  1263. unconfigured_proxies_n--;
  1264. continue;
  1265. }
  1266. tor_assert(mp->conf_state == PT_PROTO_COMPLETED);
  1267. /* Mark all proxies for removal, and also note that they have been
  1268. here before the config read. */
  1269. mp->marked_for_removal = 1;
  1270. mp->was_around_before_config_read = 1;
  1271. SMARTLIST_FOREACH(mp->transports_to_launch, char *, t, tor_free(t));
  1272. smartlist_clear(mp->transports_to_launch);
  1273. } SMARTLIST_FOREACH_END(mp);
  1274. assert_unconfigured_count_ok();
  1275. tor_assert(unconfigured_proxies_n == 0);
  1276. }
  1277. /** Return a smartlist containing the ports where our pluggable
  1278. * transports are listening. */
  1279. smartlist_t *
  1280. get_transport_proxy_ports(void)
  1281. {
  1282. smartlist_t *sl = NULL;
  1283. if (!managed_proxy_list)
  1284. return NULL;
  1285. /** XXX assume that external proxy ports have been forwarded
  1286. manually */
  1287. SMARTLIST_FOREACH_BEGIN(managed_proxy_list, const managed_proxy_t *, mp) {
  1288. if (!mp->is_server || mp->conf_state != PT_PROTO_COMPLETED)
  1289. continue;
  1290. if (!sl) sl = smartlist_new();
  1291. tor_assert(mp->transports);
  1292. SMARTLIST_FOREACH(mp->transports, const transport_t *, t,
  1293. smartlist_add_asprintf(sl, "%u:%u", t->port, t->port));
  1294. } SMARTLIST_FOREACH_END(mp);
  1295. return sl;
  1296. }
  1297. /** Return the pluggable transport string that we should display in
  1298. * our extra-info descriptor. If we shouldn't display such a string,
  1299. * or we have nothing to display, return NULL. The string is
  1300. * allocated on the heap and it's the responsibility of the caller to
  1301. * free it. */
  1302. char *
  1303. pt_get_extra_info_descriptor_string(void)
  1304. {
  1305. char *the_string = NULL;
  1306. smartlist_t *string_chunks = NULL;
  1307. if (!managed_proxy_list)
  1308. return NULL;
  1309. string_chunks = smartlist_new();
  1310. /* For each managed proxy, add its transports to the chunks list. */
  1311. SMARTLIST_FOREACH_BEGIN(managed_proxy_list, const managed_proxy_t *, mp) {
  1312. if ((!mp->is_server) || (mp->conf_state != PT_PROTO_COMPLETED))
  1313. continue;
  1314. tor_assert(mp->transports);
  1315. SMARTLIST_FOREACH_BEGIN(mp->transports, const transport_t *, t) {
  1316. char *transport_args = NULL;
  1317. /* If the transport proxy returned "0.0.0.0" as its address, and
  1318. * we know our external IP address, use it. Otherwise, use the
  1319. * returned address. */
  1320. const char *addrport = NULL;
  1321. uint32_t external_ip_address = 0;
  1322. if (tor_addr_is_null(&t->addr) &&
  1323. router_pick_published_address(get_options(),
  1324. &external_ip_address, 0) >= 0) {
  1325. tor_addr_t addr;
  1326. tor_addr_from_ipv4h(&addr, external_ip_address);
  1327. addrport = fmt_addrport(&addr, t->port);
  1328. } else {
  1329. addrport = fmt_addrport(&t->addr, t->port);
  1330. }
  1331. /* If this transport has any arguments with it, prepend a space
  1332. to them so that we can add them to the transport line. */
  1333. if (t->extra_info_args)
  1334. tor_asprintf(&transport_args, " %s", t->extra_info_args);
  1335. smartlist_add_asprintf(string_chunks,
  1336. "transport %s %s%s",
  1337. t->name, addrport,
  1338. transport_args ? transport_args : "");
  1339. tor_free(transport_args);
  1340. } SMARTLIST_FOREACH_END(t);
  1341. } SMARTLIST_FOREACH_END(mp);
  1342. if (smartlist_len(string_chunks) == 0) {
  1343. smartlist_free(string_chunks);
  1344. return NULL;
  1345. }
  1346. /* Join all the chunks into the final string. */
  1347. the_string = smartlist_join_strings(string_chunks, "\n", 1, NULL);
  1348. SMARTLIST_FOREACH(string_chunks, char *, s, tor_free(s));
  1349. smartlist_free(string_chunks);
  1350. return the_string;
  1351. }
  1352. /** Stringify the SOCKS arguments in <b>socks_args</b> according to
  1353. * 180_pluggable_transport.txt. The string is allocated on the heap
  1354. * and it's the responsibility of the caller to free it after use. */
  1355. char *
  1356. pt_stringify_socks_args(const smartlist_t *socks_args)
  1357. {
  1358. /* tmp place to store escaped socks arguments, so that we can
  1359. concatenate them up afterwards */
  1360. smartlist_t *sl_tmp = NULL;
  1361. char *escaped_string = NULL;
  1362. char *new_string = NULL;
  1363. tor_assert(socks_args);
  1364. tor_assert(smartlist_len(socks_args) > 0);
  1365. sl_tmp = smartlist_new();
  1366. SMARTLIST_FOREACH_BEGIN(socks_args, const char *, s) {
  1367. /* Escape ';' and '\'. */
  1368. escaped_string = tor_escape_str_for_pt_args(s, ";\\");
  1369. if (!escaped_string)
  1370. goto done;
  1371. smartlist_add(sl_tmp, escaped_string);
  1372. } SMARTLIST_FOREACH_END(s);
  1373. new_string = smartlist_join_strings(sl_tmp, ";", 0, NULL);
  1374. done:
  1375. SMARTLIST_FOREACH(sl_tmp, char *, s, tor_free(s));
  1376. smartlist_free(sl_tmp);
  1377. return new_string;
  1378. }
  1379. /** Return a string of the SOCKS arguments that we should pass to the
  1380. * pluggable transports proxy in <b>addr</b>:<b>port</b> according to
  1381. * 180_pluggable_transport.txt. The string is allocated on the heap
  1382. * and it's the responsibility of the caller to free it after use. */
  1383. char *
  1384. pt_get_socks_args_for_proxy_addrport(const tor_addr_t *addr, uint16_t port)
  1385. {
  1386. const smartlist_t *socks_args = NULL;
  1387. socks_args = get_socks_args_by_bridge_addrport(addr, port);
  1388. if (!socks_args)
  1389. return NULL;
  1390. return pt_stringify_socks_args(socks_args);
  1391. }
  1392. /** The tor config was read.
  1393. * Destroy all managed proxies that were marked by a previous call to
  1394. * prepare_proxy_list_for_config_read() and are not used by the new
  1395. * config. */
  1396. void
  1397. sweep_proxy_list(void)
  1398. {
  1399. if (!managed_proxy_list)
  1400. return;
  1401. assert_unconfigured_count_ok();
  1402. SMARTLIST_FOREACH_BEGIN(managed_proxy_list, managed_proxy_t *, mp) {
  1403. if (mp->marked_for_removal) {
  1404. SMARTLIST_DEL_CURRENT(managed_proxy_list, mp);
  1405. managed_proxy_destroy(mp, 1);
  1406. }
  1407. } SMARTLIST_FOREACH_END(mp);
  1408. assert_unconfigured_count_ok();
  1409. }
  1410. /** Release all storage held by the pluggable transports subsystem. */
  1411. void
  1412. pt_free_all(void)
  1413. {
  1414. if (transport_list) {
  1415. clear_transport_list();
  1416. smartlist_free(transport_list);
  1417. transport_list = NULL;
  1418. }
  1419. if (managed_proxy_list) {
  1420. /* If the proxy is in PT_PROTO_COMPLETED, it has registered its
  1421. transports and it's the duty of the circuitbuild.c subsystem to
  1422. free them. Otherwise, it hasn't registered its transports yet
  1423. and we should free them here. */
  1424. SMARTLIST_FOREACH(managed_proxy_list, managed_proxy_t *, mp, {
  1425. SMARTLIST_DEL_CURRENT(managed_proxy_list, mp);
  1426. managed_proxy_destroy(mp, 1);
  1427. });
  1428. smartlist_free(managed_proxy_list);
  1429. managed_proxy_list=NULL;
  1430. }
  1431. }
  1432. /** Return a newly allocated string equal to <b>string</b>, except that every
  1433. * character in <b>chars_to_escape</b> is preceded by a backslash. */
  1434. char *
  1435. tor_escape_str_for_pt_args(const char *string, const char *chars_to_escape)
  1436. {
  1437. char *new_string = NULL;
  1438. char *new_cp = NULL;
  1439. size_t length, new_length;
  1440. tor_assert(string);
  1441. length = strlen(string);
  1442. if (!length) /* If we were given the empty string, return the same. */
  1443. return tor_strdup("");
  1444. /* (new_length > SIZE_MAX) => ((length * 2) + 1 > SIZE_MAX) =>
  1445. (length*2 > SIZE_MAX - 1) => (length > (SIZE_MAX - 1)/2) */
  1446. if (length > (SIZE_MAX - 1)/2) /* check for overflow */
  1447. return NULL;
  1448. /* this should be enough even if all characters must be escaped */
  1449. new_length = (length * 2) + 1;
  1450. new_string = new_cp = tor_malloc(new_length);
  1451. while (*string) {
  1452. if (strchr(chars_to_escape, *string))
  1453. *new_cp++ = '\\';
  1454. *new_cp++ = *string++;
  1455. }
  1456. *new_cp = '\0'; /* NUL-terminate the new string */
  1457. return new_string;
  1458. }