services.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  1. /*
  2. * Copyright (c) 2016, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. // Package server implements the core tunnel functionality of a Psiphon server.
  20. // The main function is RunServices, which runs one or all of a Psiphon API web server,
  21. // a tunneling SSH server, and an Obfuscated SSH protocol server. The server configuration
  22. // is created by the GenerateConfig function.
  23. package server
  24. import (
  25. "fmt"
  26. "math/rand"
  27. "os"
  28. "os/signal"
  29. "runtime"
  30. "runtime/debug"
  31. "sync"
  32. "syscall"
  33. "time"
  34. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/buildinfo"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  37. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/osl"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/packetman"
  39. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tactics"
  40. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tun"
  41. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/server/psinet"
  42. )
  43. // RunServices initializes support functions including logging and GeoIP services;
  44. // and then starts the server components and runs them until os.Interrupt or
  45. // os.Kill signals are received. The config determines which components are run.
  46. func RunServices(configJSON []byte) (retErr error) {
  47. loggingInitialized := false
  48. defer func() {
  49. if retErr != nil && loggingInitialized {
  50. log.WithTraceFields(LogFields{"error": retErr}).Error("RunServices failed")
  51. }
  52. }()
  53. rand.Seed(int64(time.Now().Nanosecond()))
  54. config, err := LoadConfig(configJSON)
  55. if err != nil {
  56. return errors.Trace(err)
  57. }
  58. err = InitLogging(config)
  59. if err != nil {
  60. return errors.Trace(err)
  61. }
  62. loggingInitialized = true
  63. support, err := NewSupportServices(config)
  64. if err != nil {
  65. return errors.Trace(err)
  66. }
  67. startupFields := buildinfo.GetBuildInfo().ToMap()
  68. startupFields["GODEBUG"] = os.Getenv("GODEBUG")
  69. log.WithTraceFields(startupFields).Info("startup")
  70. waitGroup := new(sync.WaitGroup)
  71. shutdownBroadcast := make(chan struct{})
  72. errorChannel := make(chan error, 1)
  73. tunnelServer, err := NewTunnelServer(support, shutdownBroadcast)
  74. if err != nil {
  75. return errors.Trace(err)
  76. }
  77. support.TunnelServer = tunnelServer
  78. if config.RunPacketTunnel {
  79. packetTunnelServer, err := tun.NewServer(&tun.ServerConfig{
  80. Logger: CommonLogger(log),
  81. SudoNetworkConfigCommands: config.PacketTunnelSudoNetworkConfigCommands,
  82. GetDNSResolverIPv4Addresses: support.DNSResolver.GetAllIPv4,
  83. GetDNSResolverIPv6Addresses: support.DNSResolver.GetAllIPv6,
  84. EnableDNSFlowTracking: config.PacketTunnelEnableDNSFlowTracking,
  85. EgressInterface: config.PacketTunnelEgressInterface,
  86. DownstreamPacketQueueSize: config.PacketTunnelDownstreamPacketQueueSize,
  87. SessionIdleExpirySeconds: config.PacketTunnelSessionIdleExpirySeconds,
  88. AllowBogons: config.AllowBogons,
  89. })
  90. if err != nil {
  91. return errors.Trace(err)
  92. }
  93. support.PacketTunnelServer = packetTunnelServer
  94. }
  95. if config.RunPacketManipulator {
  96. packetManipulatorConfig, err := makePacketManipulatorConfig(support)
  97. if err != nil {
  98. return errors.Trace(err)
  99. }
  100. packetManipulator, err := packetman.NewManipulator(packetManipulatorConfig)
  101. if err != nil {
  102. return errors.Trace(err)
  103. }
  104. support.PacketManipulator = packetManipulator
  105. }
  106. support.discovery = makeDiscovery(support)
  107. // After this point, errors should be delivered to the errors channel and
  108. // orderly shutdown should flow through to the end of the function to ensure
  109. // all workers are synchronously stopped.
  110. if config.RunPacketTunnel {
  111. support.PacketTunnelServer.Start()
  112. waitGroup.Add(1)
  113. go func() {
  114. defer waitGroup.Done()
  115. <-shutdownBroadcast
  116. support.PacketTunnelServer.Stop()
  117. }()
  118. }
  119. if config.RunPacketManipulator {
  120. err := support.PacketManipulator.Start()
  121. if err != nil {
  122. select {
  123. case errorChannel <- err:
  124. default:
  125. }
  126. } else {
  127. waitGroup.Add(1)
  128. go func() {
  129. defer waitGroup.Done()
  130. <-shutdownBroadcast
  131. support.PacketManipulator.Stop()
  132. }()
  133. }
  134. }
  135. err = support.discovery.Start()
  136. if err != nil {
  137. select {
  138. case errorChannel <- err:
  139. default:
  140. }
  141. } else {
  142. waitGroup.Add(1)
  143. go func() {
  144. defer waitGroup.Done()
  145. <-shutdownBroadcast
  146. support.discovery.Stop()
  147. }()
  148. }
  149. if config.RunLoadMonitor() {
  150. waitGroup.Add(1)
  151. go func() {
  152. waitGroup.Done()
  153. ticker := time.NewTicker(time.Duration(config.LoadMonitorPeriodSeconds) * time.Second)
  154. defer ticker.Stop()
  155. logNetworkBytes := true
  156. previousNetworkBytesReceived, previousNetworkBytesSent, err := getNetworkBytesTransferred()
  157. if err != nil {
  158. log.WithTraceFields(LogFields{"error": errors.Trace(err)}).Error("failed to get initial network bytes transferred")
  159. // If getNetworkBytesTransferred fails, stop logging network
  160. // bytes for the lifetime of this process, in case there's a
  161. // persistent issue with /proc/net/dev data.
  162. logNetworkBytes = false
  163. }
  164. for {
  165. select {
  166. case <-shutdownBroadcast:
  167. return
  168. case <-ticker.C:
  169. var networkBytesReceived, networkBytesSent int64
  170. if logNetworkBytes {
  171. currentNetworkBytesReceived, currentNetworkBytesSent, err := getNetworkBytesTransferred()
  172. if err != nil {
  173. log.WithTraceFields(LogFields{"error": errors.Trace(err)}).Error("failed to get current network bytes transferred")
  174. logNetworkBytes = false
  175. } else {
  176. networkBytesReceived = currentNetworkBytesReceived - previousNetworkBytesReceived
  177. networkBytesSent = currentNetworkBytesSent - previousNetworkBytesSent
  178. previousNetworkBytesReceived, previousNetworkBytesSent = currentNetworkBytesReceived, currentNetworkBytesSent
  179. }
  180. }
  181. // In the rare case that /proc/net/dev rx or tx counters
  182. // wrap around or are reset, networkBytesReceived or
  183. // networkBytesSent may be < 0. logServerLoad will not
  184. // log these negative values.
  185. logServerLoad(support, logNetworkBytes, networkBytesReceived, networkBytesSent)
  186. }
  187. }
  188. }()
  189. }
  190. if config.RunPeriodicGarbageCollection() {
  191. waitGroup.Add(1)
  192. go func() {
  193. waitGroup.Done()
  194. ticker := time.NewTicker(config.periodicGarbageCollection)
  195. defer ticker.Stop()
  196. for {
  197. select {
  198. case <-shutdownBroadcast:
  199. return
  200. case <-ticker.C:
  201. debug.FreeOSMemory()
  202. }
  203. }
  204. }()
  205. }
  206. // The tunnel server is always run; it launches multiple
  207. // listeners, depending on which tunnel protocols are enabled.
  208. waitGroup.Add(1)
  209. go func() {
  210. defer waitGroup.Done()
  211. err := tunnelServer.Run()
  212. select {
  213. case errorChannel <- err:
  214. default:
  215. }
  216. }()
  217. // Shutdown doesn't wait for the outputProcessProfiles goroutine
  218. // to complete, as it may be sleeping while running a "block" or
  219. // CPU profile.
  220. signalProcessProfiles := make(chan struct{}, 1)
  221. go func() {
  222. for {
  223. select {
  224. case <-signalProcessProfiles:
  225. outputProcessProfiles(support.Config, "")
  226. case <-shutdownBroadcast:
  227. return
  228. }
  229. }
  230. }()
  231. // In addition to the actual signal handling here, there is
  232. // a list of signals that need to be passed through panicwrap
  233. // in 'github.com/Psiphon-Labs/psiphon-tunnel-core/Server/main.go'
  234. // where 'panicwrap.Wrap' is called. The handled signals below, and the
  235. // list there must be kept in sync to ensure proper signal handling
  236. // An OS signal triggers an orderly shutdown
  237. systemStopSignal := make(chan os.Signal, 1)
  238. signal.Notify(systemStopSignal, os.Interrupt, syscall.SIGTERM)
  239. // SIGUSR1 triggers a reload of support services
  240. reloadSupportServicesSignal := makeSIGUSR1Channel()
  241. // SIGUSR2 triggers an immediate load log and optional process profile output
  242. logServerLoadSignal := makeSIGUSR2Channel()
  243. // SIGTSTP triggers tunnelServer to stop establishing new tunnels
  244. stopEstablishingTunnelsSignal := makeSIGTSTPChannel()
  245. // SIGCONT triggers tunnelServer to resume establishing new tunnels
  246. resumeEstablishingTunnelsSignal := makeSIGCONTChannel()
  247. err = nil
  248. loop:
  249. for {
  250. select {
  251. case <-stopEstablishingTunnelsSignal:
  252. tunnelServer.SetEstablishTunnels(false)
  253. if config.DumpProfilesOnStopEstablishTunnels(
  254. tunnelServer.GetEstablishedClientCount()) {
  255. // Run the profile dump in a goroutine and don't block this loop. Shutdown
  256. // doesn't wait for any running outputProcessProfiles to complete.
  257. go func() {
  258. outputProcessProfiles(support.Config, "stop_establish_tunnels")
  259. }()
  260. }
  261. case <-resumeEstablishingTunnelsSignal:
  262. tunnelServer.SetEstablishTunnels(true)
  263. case <-reloadSupportServicesSignal:
  264. support.Reload()
  265. case <-logServerLoadSignal:
  266. // Signal profiles writes first to ensure some diagnostics are
  267. // available in case logServerLoad hangs (which has happened
  268. // in the past due to a deadlock bug).
  269. select {
  270. case signalProcessProfiles <- struct{}{}:
  271. default:
  272. }
  273. logServerLoad(support, false, 0, 0)
  274. case <-systemStopSignal:
  275. log.WithTrace().Info("shutdown by system")
  276. break loop
  277. case err = <-errorChannel:
  278. break loop
  279. }
  280. }
  281. // During any delayed or hung shutdown, periodically dump profiles to help
  282. // diagnose the cause. Shutdown doesn't wait for any running
  283. // outputProcessProfiles to complete.
  284. signalProfileDumperStop := make(chan struct{})
  285. go func() {
  286. tickSeconds := 10
  287. ticker := time.NewTicker(time.Duration(tickSeconds) * time.Second)
  288. defer ticker.Stop()
  289. for i := tickSeconds; i <= 60; i += tickSeconds {
  290. select {
  291. case <-signalProfileDumperStop:
  292. return
  293. case <-ticker.C:
  294. filenameSuffix := fmt.Sprintf("delayed_shutdown_%ds", i)
  295. outputProcessProfiles(support.Config, filenameSuffix)
  296. }
  297. }
  298. }()
  299. close(shutdownBroadcast)
  300. waitGroup.Wait()
  301. close(signalProfileDumperStop)
  302. return err
  303. }
  304. func getRuntimeMetrics() LogFields {
  305. numGoroutine := runtime.NumGoroutine()
  306. var memStats runtime.MemStats
  307. runtime.ReadMemStats(&memStats)
  308. lastGC := ""
  309. if memStats.LastGC > 0 {
  310. lastGC = time.Unix(0, int64(memStats.LastGC)).UTC().Format(time.RFC3339)
  311. }
  312. return LogFields{
  313. "num_goroutine": numGoroutine,
  314. "heap_alloc": memStats.HeapAlloc,
  315. "heap_sys": memStats.HeapSys,
  316. "heap_idle": memStats.HeapIdle,
  317. "heap_inuse": memStats.HeapInuse,
  318. "heap_released": memStats.HeapReleased,
  319. "heap_objects": memStats.HeapObjects,
  320. "num_gc": memStats.NumGC,
  321. "num_forced_gc": memStats.NumForcedGC,
  322. "last_gc": lastGC,
  323. }
  324. }
  325. func outputProcessProfiles(config *Config, filenameSuffix string) {
  326. log.WithTraceFields(getRuntimeMetrics()).Info("runtime_metrics")
  327. if config.ProcessProfileOutputDirectory != "" {
  328. common.WriteRuntimeProfiles(
  329. CommonLogger(log),
  330. config.ProcessProfileOutputDirectory,
  331. filenameSuffix,
  332. config.ProcessBlockProfileDurationSeconds,
  333. config.ProcessCPUProfileDurationSeconds)
  334. }
  335. }
  336. func logServerLoad(support *SupportServices, logNetworkBytes bool, networkBytesReceived int64, networkBytesSent int64) {
  337. serverLoad := getRuntimeMetrics()
  338. serverLoad["event_name"] = "server_load"
  339. if logNetworkBytes {
  340. // Negative values, which may occur due to counter wrap arounds, are
  341. // omitted.
  342. if networkBytesReceived >= 0 {
  343. serverLoad["network_bytes_received"] = networkBytesReceived
  344. }
  345. if networkBytesSent >= 0 {
  346. serverLoad["network_bytes_sent"] = networkBytesSent
  347. }
  348. }
  349. establishTunnels, establishLimitedCount :=
  350. support.TunnelServer.GetEstablishTunnelsMetrics()
  351. serverLoad["establish_tunnels"] = establishTunnels
  352. serverLoad["establish_tunnels_limited_count"] = establishLimitedCount
  353. serverLoad.Add(support.ReplayCache.GetMetrics())
  354. serverLoad.Add(support.ServerTacticsParametersCache.GetMetrics())
  355. upstreamStats, protocolStats, regionStats :=
  356. support.TunnelServer.GetLoadStats()
  357. for name, value := range upstreamStats {
  358. serverLoad[name] = value
  359. }
  360. for protocol, stats := range protocolStats {
  361. serverLoad[protocol] = stats
  362. }
  363. log.LogRawFieldsWithTimestamp(serverLoad)
  364. for region, regionProtocolStats := range regionStats {
  365. serverLoad := LogFields{
  366. "event_name": "server_load",
  367. "region": region,
  368. }
  369. for protocol, stats := range regionProtocolStats {
  370. serverLoad[protocol] = stats
  371. }
  372. log.LogRawFieldsWithTimestamp(serverLoad)
  373. }
  374. }
  375. func logIrregularTunnel(
  376. support *SupportServices,
  377. listenerTunnelProtocol string,
  378. listenerPort int,
  379. peerIP string,
  380. tunnelError error,
  381. logFields LogFields) {
  382. if logFields == nil {
  383. logFields = make(LogFields)
  384. }
  385. logFields["event_name"] = "irregular_tunnel"
  386. logFields["listener_protocol"] = listenerTunnelProtocol
  387. logFields["listener_port_number"] = listenerPort
  388. logFields["tunnel_error"] = tunnelError.Error()
  389. // Note: logging with the "client_" prefix for legacy compatibility; it
  390. // would be more correct to use the prefix "peer_".
  391. support.GeoIPService.Lookup(peerIP).SetClientLogFields(logFields)
  392. log.LogRawFieldsWithTimestamp(logFields)
  393. }
  394. // SupportServices carries common and shared data components
  395. // across different server components. SupportServices implements a
  396. // hot reload of traffic rules, psinet database, and geo IP database
  397. // components, which allows these data components to be refreshed
  398. // without restarting the server process.
  399. type SupportServices struct {
  400. // TODO: make all fields non-exported, none are accessed outside
  401. // of this package.
  402. Config *Config
  403. TrafficRulesSet *TrafficRulesSet
  404. OSLConfig *osl.Config
  405. PsinetDatabase *psinet.Database
  406. GeoIPService *GeoIPService
  407. DNSResolver *DNSResolver
  408. TunnelServer *TunnelServer
  409. PacketTunnelServer *tun.Server
  410. TacticsServer *tactics.Server
  411. Blocklist *Blocklist
  412. PacketManipulator *packetman.Manipulator
  413. ReplayCache *ReplayCache
  414. ServerTacticsParametersCache *ServerTacticsParametersCache
  415. discovery *Discovery
  416. }
  417. // NewSupportServices initializes a new SupportServices.
  418. func NewSupportServices(config *Config) (*SupportServices, error) {
  419. trafficRulesSet, err := NewTrafficRulesSet(config.TrafficRulesFilename)
  420. if err != nil {
  421. return nil, errors.Trace(err)
  422. }
  423. oslConfig, err := osl.NewConfig(config.OSLConfigFilename)
  424. if err != nil {
  425. return nil, errors.Trace(err)
  426. }
  427. psinetDatabase, err := psinet.NewDatabase(config.PsinetDatabaseFilename)
  428. if err != nil {
  429. return nil, errors.Trace(err)
  430. }
  431. geoIPService, err := NewGeoIPService(config.GeoIPDatabaseFilenames)
  432. if err != nil {
  433. return nil, errors.Trace(err)
  434. }
  435. dnsResolver, err := NewDNSResolver(config.DNSResolverIPAddress)
  436. if err != nil {
  437. return nil, errors.Trace(err)
  438. }
  439. blocklist, err := NewBlocklist(config.BlocklistFilename)
  440. if err != nil {
  441. return nil, errors.Trace(err)
  442. }
  443. tacticsServer, err := tactics.NewServer(
  444. CommonLogger(log),
  445. getTacticsAPIParameterLogFieldFormatter(),
  446. getTacticsAPIParameterValidator(config),
  447. config.TacticsConfigFilename)
  448. if err != nil {
  449. return nil, errors.Trace(err)
  450. }
  451. support := &SupportServices{
  452. Config: config,
  453. TrafficRulesSet: trafficRulesSet,
  454. OSLConfig: oslConfig,
  455. PsinetDatabase: psinetDatabase,
  456. GeoIPService: geoIPService,
  457. DNSResolver: dnsResolver,
  458. TacticsServer: tacticsServer,
  459. Blocklist: blocklist,
  460. }
  461. support.ReplayCache = NewReplayCache(support)
  462. support.ServerTacticsParametersCache =
  463. NewServerTacticsParametersCache(support)
  464. return support, nil
  465. }
  466. // Reload reinitializes traffic rules, psinet database, and geo IP database
  467. // components. If any component fails to reload, an error is logged and
  468. // Reload proceeds, using the previous state of the component.
  469. func (support *SupportServices) Reload() {
  470. reloaders := append(
  471. []common.Reloader{
  472. support.TrafficRulesSet,
  473. support.OSLConfig,
  474. support.PsinetDatabase,
  475. support.TacticsServer,
  476. support.Blocklist},
  477. support.GeoIPService.Reloaders()...)
  478. reloadDiscovery := func(reloadedTactics bool) {
  479. err := support.discovery.reload(reloadedTactics)
  480. if err != nil {
  481. log.WithTraceFields(
  482. LogFields{"error": errors.Trace(err)}).Warning(
  483. "failed to reload discovery")
  484. return
  485. }
  486. }
  487. // Note: established clients aren't notified when tactics change after a
  488. // reload; new tactics will be obtained on the next client handshake or
  489. // tactics request.
  490. reloadTactics := func() {
  491. // Don't use stale tactics.
  492. support.ReplayCache.Flush()
  493. support.ServerTacticsParametersCache.Flush()
  494. err := support.TunnelServer.ReloadTactics()
  495. if err != nil {
  496. log.WithTraceFields(
  497. LogFields{"error": errors.Trace(err)}).Warning(
  498. "failed to reload tunnel server tactics")
  499. }
  500. if support.Config.RunPacketManipulator {
  501. err := reloadPacketManipulationSpecs(support)
  502. if err != nil {
  503. log.WithTraceFields(
  504. LogFields{"error": errors.Trace(err)}).Warning(
  505. "failed to reload packet manipulation specs")
  506. }
  507. }
  508. reloadDiscovery(true)
  509. }
  510. // Take these actions only after the corresponding Reloader has reloaded.
  511. // In both the traffic rules and OSL cases, there is some impact from state
  512. // reset, so the reset should be avoided where possible.
  513. //
  514. // Note: if both tactics and psinet are reloaded at the same time and
  515. // the discovery strategy tactic has changed, then discovery will be reloaded
  516. // twice.
  517. reloadPostActions := map[common.Reloader]func(){
  518. support.TrafficRulesSet: func() { support.TunnelServer.ResetAllClientTrafficRules() },
  519. support.OSLConfig: func() { support.TunnelServer.ResetAllClientOSLConfigs() },
  520. support.TacticsServer: reloadTactics,
  521. support.PsinetDatabase: func() { reloadDiscovery(false) },
  522. }
  523. for _, reloader := range reloaders {
  524. if !reloader.WillReload() {
  525. // Skip logging
  526. continue
  527. }
  528. // "reloaded" flag indicates if file was actually reloaded or ignored
  529. reloaded, err := reloader.Reload()
  530. if reloaded {
  531. if action, ok := reloadPostActions[reloader]; ok {
  532. action()
  533. }
  534. }
  535. if err != nil {
  536. log.WithTraceFields(
  537. LogFields{
  538. "reloader": reloader.LogDescription(),
  539. "error": err}).Error("reload failed")
  540. // Keep running with previous state
  541. } else {
  542. log.WithTraceFields(
  543. LogFields{
  544. "reloader": reloader.LogDescription(),
  545. "reloaded": reloaded}).Info("reload success")
  546. }
  547. }
  548. }