services.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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. supportServices, 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(supportServices, shutdownBroadcast)
  74. if err != nil {
  75. return errors.Trace(err)
  76. }
  77. supportServices.TunnelServer = tunnelServer
  78. if config.RunPacketTunnel {
  79. packetTunnelServer, err := tun.NewServer(&tun.ServerConfig{
  80. Logger: CommonLogger(log),
  81. SudoNetworkConfigCommands: config.PacketTunnelSudoNetworkConfigCommands,
  82. GetDNSResolverIPv4Addresses: supportServices.DNSResolver.GetAllIPv4,
  83. GetDNSResolverIPv6Addresses: supportServices.DNSResolver.GetAllIPv6,
  84. EgressInterface: config.PacketTunnelEgressInterface,
  85. DownstreamPacketQueueSize: config.PacketTunnelDownstreamPacketQueueSize,
  86. SessionIdleExpirySeconds: config.PacketTunnelSessionIdleExpirySeconds,
  87. AllowBogons: config.AllowBogons,
  88. })
  89. if err != nil {
  90. return errors.Trace(err)
  91. }
  92. supportServices.PacketTunnelServer = packetTunnelServer
  93. }
  94. if config.RunPacketManipulator {
  95. packetManipulatorConfig, err := makePacketManipulatorConfig(supportServices)
  96. if err != nil {
  97. return errors.Trace(err)
  98. }
  99. packetManipulator, err := packetman.NewManipulator(packetManipulatorConfig)
  100. if err != nil {
  101. return errors.Trace(err)
  102. }
  103. supportServices.PacketManipulator = packetManipulator
  104. }
  105. // After this point, errors should be delivered to the errors channel and
  106. // orderly shutdown should flow through to the end of the function to ensure
  107. // all workers are synchronously stopped.
  108. if config.RunPacketTunnel {
  109. supportServices.PacketTunnelServer.Start()
  110. waitGroup.Add(1)
  111. go func() {
  112. defer waitGroup.Done()
  113. <-shutdownBroadcast
  114. supportServices.PacketTunnelServer.Stop()
  115. }()
  116. }
  117. if config.RunPacketManipulator {
  118. err := supportServices.PacketManipulator.Start()
  119. if err != nil {
  120. select {
  121. case errorChannel <- err:
  122. default:
  123. }
  124. } else {
  125. waitGroup.Add(1)
  126. go func() {
  127. defer waitGroup.Done()
  128. <-shutdownBroadcast
  129. supportServices.PacketManipulator.Stop()
  130. }()
  131. }
  132. }
  133. if config.RunLoadMonitor() {
  134. waitGroup.Add(1)
  135. go func() {
  136. waitGroup.Done()
  137. ticker := time.NewTicker(time.Duration(config.LoadMonitorPeriodSeconds) * time.Second)
  138. defer ticker.Stop()
  139. for {
  140. select {
  141. case <-shutdownBroadcast:
  142. return
  143. case <-ticker.C:
  144. logServerLoad(tunnelServer)
  145. }
  146. }
  147. }()
  148. }
  149. if config.RunPeriodicGarbageCollection() {
  150. waitGroup.Add(1)
  151. go func() {
  152. waitGroup.Done()
  153. ticker := time.NewTicker(config.periodicGarbageCollection)
  154. defer ticker.Stop()
  155. for {
  156. select {
  157. case <-shutdownBroadcast:
  158. return
  159. case <-ticker.C:
  160. debug.FreeOSMemory()
  161. }
  162. }
  163. }()
  164. }
  165. if config.RunWebServer() {
  166. waitGroup.Add(1)
  167. go func() {
  168. defer waitGroup.Done()
  169. err := RunWebServer(supportServices, shutdownBroadcast)
  170. select {
  171. case errorChannel <- err:
  172. default:
  173. }
  174. }()
  175. }
  176. // The tunnel server is always run; it launches multiple
  177. // listeners, depending on which tunnel protocols are enabled.
  178. waitGroup.Add(1)
  179. go func() {
  180. defer waitGroup.Done()
  181. err := tunnelServer.Run()
  182. select {
  183. case errorChannel <- err:
  184. default:
  185. }
  186. }()
  187. // Shutdown doesn't wait for the outputProcessProfiles goroutine
  188. // to complete, as it may be sleeping while running a "block" or
  189. // CPU profile.
  190. signalProcessProfiles := make(chan struct{}, 1)
  191. go func() {
  192. for {
  193. select {
  194. case <-signalProcessProfiles:
  195. outputProcessProfiles(supportServices.Config, "")
  196. case <-shutdownBroadcast:
  197. return
  198. }
  199. }
  200. }()
  201. // In addition to the actual signal handling here, there is
  202. // a list of signals that need to be passed through panicwrap
  203. // in 'github.com/Psiphon-Labs/psiphon-tunnel-core/Server/main.go'
  204. // where 'panicwrap.Wrap' is called. The handled signals below, and the
  205. // list there must be kept in sync to ensure proper signal handling
  206. // An OS signal triggers an orderly shutdown
  207. systemStopSignal := make(chan os.Signal, 1)
  208. signal.Notify(systemStopSignal, os.Interrupt, syscall.SIGTERM)
  209. // SIGUSR1 triggers a reload of support services
  210. reloadSupportServicesSignal := make(chan os.Signal, 1)
  211. signal.Notify(reloadSupportServicesSignal, syscall.SIGUSR1)
  212. // SIGUSR2 triggers an immediate load log and optional process profile output
  213. logServerLoadSignal := make(chan os.Signal, 1)
  214. signal.Notify(logServerLoadSignal, syscall.SIGUSR2)
  215. // SIGTSTP triggers tunnelServer to stop establishing new tunnels
  216. stopEstablishingTunnelsSignal := make(chan os.Signal, 1)
  217. signal.Notify(stopEstablishingTunnelsSignal, syscall.SIGTSTP)
  218. // SIGCONT triggers tunnelServer to resume establishing new tunnels
  219. resumeEstablishingTunnelsSignal := make(chan os.Signal, 1)
  220. signal.Notify(resumeEstablishingTunnelsSignal, syscall.SIGCONT)
  221. err = nil
  222. loop:
  223. for {
  224. select {
  225. case <-stopEstablishingTunnelsSignal:
  226. tunnelServer.SetEstablishTunnels(false)
  227. if config.DumpProfilesOnStopEstablishTunnels(
  228. tunnelServer.GetEstablishedClientCount()) {
  229. // Run the profile dump in a goroutine and don't block this loop. Shutdown
  230. // doesn't wait for any running outputProcessProfiles to complete.
  231. go func() {
  232. outputProcessProfiles(supportServices.Config, "stop_establish_tunnels")
  233. }()
  234. }
  235. case <-resumeEstablishingTunnelsSignal:
  236. tunnelServer.SetEstablishTunnels(true)
  237. case <-reloadSupportServicesSignal:
  238. supportServices.Reload()
  239. case <-logServerLoadSignal:
  240. // Signal profiles writes first to ensure some diagnostics are
  241. // available in case logServerLoad hangs (which has happened
  242. // in the past due to a deadlock bug).
  243. select {
  244. case signalProcessProfiles <- struct{}{}:
  245. default:
  246. }
  247. logServerLoad(tunnelServer)
  248. case <-systemStopSignal:
  249. log.WithTrace().Info("shutdown by system")
  250. break loop
  251. case err = <-errorChannel:
  252. break loop
  253. }
  254. }
  255. // During any delayed or hung shutdown, periodically dump profiles to help
  256. // diagnose the cause. Shutdown doesn't wait for any running
  257. // outputProcessProfiles to complete.
  258. signalProfileDumperStop := make(chan struct{})
  259. go func() {
  260. tickSeconds := 10
  261. ticker := time.NewTicker(time.Duration(tickSeconds) * time.Second)
  262. defer ticker.Stop()
  263. for i := tickSeconds; i <= 60; i += tickSeconds {
  264. select {
  265. case <-signalProfileDumperStop:
  266. return
  267. case <-ticker.C:
  268. filenameSuffix := fmt.Sprintf("delayed_shutdown_%ds", i)
  269. outputProcessProfiles(supportServices.Config, filenameSuffix)
  270. }
  271. }
  272. }()
  273. close(shutdownBroadcast)
  274. waitGroup.Wait()
  275. close(signalProfileDumperStop)
  276. return err
  277. }
  278. func getRuntimeMetrics() LogFields {
  279. numGoroutine := runtime.NumGoroutine()
  280. var memStats runtime.MemStats
  281. runtime.ReadMemStats(&memStats)
  282. lastGC := ""
  283. if memStats.LastGC > 0 {
  284. lastGC = time.Unix(0, int64(memStats.LastGC)).UTC().Format(time.RFC3339)
  285. }
  286. return LogFields{
  287. "num_goroutine": numGoroutine,
  288. "heap_alloc": memStats.HeapAlloc,
  289. "heap_sys": memStats.HeapSys,
  290. "heap_idle": memStats.HeapIdle,
  291. "heap_inuse": memStats.HeapInuse,
  292. "heap_released": memStats.HeapReleased,
  293. "heap_objects": memStats.HeapObjects,
  294. "num_gc": memStats.NumGC,
  295. "num_forced_gc": memStats.NumForcedGC,
  296. "last_gc": lastGC,
  297. }
  298. }
  299. func outputProcessProfiles(config *Config, filenameSuffix string) {
  300. log.WithTraceFields(getRuntimeMetrics()).Info("runtime_metrics")
  301. if config.ProcessProfileOutputDirectory != "" {
  302. common.WriteRuntimeProfiles(
  303. CommonLogger(log),
  304. config.ProcessProfileOutputDirectory,
  305. filenameSuffix,
  306. config.ProcessBlockProfileDurationSeconds,
  307. config.ProcessCPUProfileDurationSeconds)
  308. }
  309. }
  310. func logServerLoad(server *TunnelServer) {
  311. protocolStats, regionStats := server.GetLoadStats()
  312. serverLoad := getRuntimeMetrics()
  313. serverLoad["event_name"] = "server_load"
  314. establishTunnels, establishLimitedCount := server.GetEstablishTunnelsMetrics()
  315. serverLoad["establish_tunnels"] = establishTunnels
  316. serverLoad["establish_tunnels_limited_count"] = establishLimitedCount
  317. for protocol, stats := range protocolStats {
  318. serverLoad[protocol] = stats
  319. }
  320. log.LogRawFieldsWithTimestamp(serverLoad)
  321. for region, regionProtocolStats := range regionStats {
  322. serverLoad := LogFields{
  323. "event_name": "server_load",
  324. "region": region,
  325. }
  326. for protocol, stats := range regionProtocolStats {
  327. serverLoad[protocol] = stats
  328. }
  329. log.LogRawFieldsWithTimestamp(serverLoad)
  330. }
  331. }
  332. func logIrregularTunnel(
  333. support *SupportServices,
  334. listenerTunnelProtocol string,
  335. listenerPort int,
  336. clientIP string,
  337. tunnelError error,
  338. logFields LogFields) {
  339. if logFields == nil {
  340. logFields = make(LogFields)
  341. }
  342. logFields["event_name"] = "irregular_tunnel"
  343. logFields["listener_protocol"] = listenerTunnelProtocol
  344. logFields["listener_port_number"] = listenerPort
  345. support.GeoIPService.Lookup(clientIP).SetLogFields(logFields)
  346. logFields["tunnel_error"] = tunnelError.Error()
  347. log.LogRawFieldsWithTimestamp(logFields)
  348. }
  349. // SupportServices carries common and shared data components
  350. // across different server components. SupportServices implements a
  351. // hot reload of traffic rules, psinet database, and geo IP database
  352. // components, which allows these data components to be refreshed
  353. // without restarting the server process.
  354. type SupportServices struct {
  355. Config *Config
  356. TrafficRulesSet *TrafficRulesSet
  357. OSLConfig *osl.Config
  358. PsinetDatabase *psinet.Database
  359. GeoIPService *GeoIPService
  360. DNSResolver *DNSResolver
  361. TunnelServer *TunnelServer
  362. PacketTunnelServer *tun.Server
  363. TacticsServer *tactics.Server
  364. Blocklist *Blocklist
  365. PacketManipulator *packetman.Manipulator
  366. }
  367. // NewSupportServices initializes a new SupportServices.
  368. func NewSupportServices(config *Config) (*SupportServices, error) {
  369. trafficRulesSet, err := NewTrafficRulesSet(config.TrafficRulesFilename)
  370. if err != nil {
  371. return nil, errors.Trace(err)
  372. }
  373. oslConfig, err := osl.NewConfig(config.OSLConfigFilename)
  374. if err != nil {
  375. return nil, errors.Trace(err)
  376. }
  377. psinetDatabase, err := psinet.NewDatabase(config.PsinetDatabaseFilename)
  378. if err != nil {
  379. return nil, errors.Trace(err)
  380. }
  381. geoIPService, err := NewGeoIPService(
  382. config.GeoIPDatabaseFilenames, config.DiscoveryValueHMACKey)
  383. if err != nil {
  384. return nil, errors.Trace(err)
  385. }
  386. dnsResolver, err := NewDNSResolver(config.DNSResolverIPAddress)
  387. if err != nil {
  388. return nil, errors.Trace(err)
  389. }
  390. blocklist, err := NewBlocklist(config.BlocklistFilename)
  391. if err != nil {
  392. return nil, errors.Trace(err)
  393. }
  394. tacticsServer, err := tactics.NewServer(
  395. CommonLogger(log),
  396. getTacticsAPIParameterLogFieldFormatter(),
  397. getTacticsAPIParameterValidator(config),
  398. config.TacticsConfigFilename)
  399. if err != nil {
  400. return nil, errors.Trace(err)
  401. }
  402. return &SupportServices{
  403. Config: config,
  404. TrafficRulesSet: trafficRulesSet,
  405. OSLConfig: oslConfig,
  406. PsinetDatabase: psinetDatabase,
  407. GeoIPService: geoIPService,
  408. DNSResolver: dnsResolver,
  409. TacticsServer: tacticsServer,
  410. Blocklist: blocklist,
  411. }, nil
  412. }
  413. // Reload reinitializes traffic rules, psinet database, and geo IP database
  414. // components. If any component fails to reload, an error is logged and
  415. // Reload proceeds, using the previous state of the component.
  416. func (support *SupportServices) Reload() {
  417. reloaders := append(
  418. []common.Reloader{
  419. support.TrafficRulesSet,
  420. support.OSLConfig,
  421. support.PsinetDatabase,
  422. support.TacticsServer,
  423. support.Blocklist},
  424. support.GeoIPService.Reloaders()...)
  425. // Note: established clients aren't notified when tactics change after a
  426. // reload; new tactics will be obtained on the next client handshake or
  427. // tactics request.
  428. // Take these actions only after the corresponding Reloader has reloaded.
  429. // In both the traffic rules and OSL cases, there is some impact from state
  430. // reset, so the reset should be avoided where possible.
  431. reloadPostActions := map[common.Reloader]func(){
  432. support.TrafficRulesSet: func() { support.TunnelServer.ResetAllClientTrafficRules() },
  433. support.OSLConfig: func() { support.TunnelServer.ResetAllClientOSLConfigs() },
  434. }
  435. if support.Config.RunPacketManipulator {
  436. reloadPostActions[support.TacticsServer] = func() {
  437. err := reloadPacketManipulationSpecs(support)
  438. if err != nil {
  439. log.WithTraceFields(
  440. LogFields{"error": errors.Trace(err)}).Warning(
  441. "failed to reload packet manipulation specs")
  442. }
  443. }
  444. }
  445. for _, reloader := range reloaders {
  446. if !reloader.WillReload() {
  447. // Skip logging
  448. continue
  449. }
  450. // "reloaded" flag indicates if file was actually reloaded or ignored
  451. reloaded, err := reloader.Reload()
  452. if reloaded {
  453. if action, ok := reloadPostActions[reloader]; ok {
  454. action()
  455. }
  456. }
  457. if err != nil {
  458. log.WithTraceFields(
  459. LogFields{
  460. "reloader": reloader.LogDescription(),
  461. "error": err}).Error("reload failed")
  462. // Keep running with previous state
  463. } else {
  464. log.WithTraceFields(
  465. LogFields{
  466. "reloader": reloader.LogDescription(),
  467. "reloaded": reloaded}).Info("reload success")
  468. }
  469. }
  470. }