services.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  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. "math/rand"
  26. "os"
  27. "os/signal"
  28. "path/filepath"
  29. "runtime"
  30. "runtime/pprof"
  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/osl"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tactics"
  37. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tun"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/server/psinet"
  39. )
  40. // RunServices initializes support functions including logging and GeoIP services;
  41. // and then starts the server components and runs them until os.Interrupt or
  42. // os.Kill signals are received. The config determines which components are run.
  43. func RunServices(configJSON []byte) error {
  44. rand.Seed(int64(time.Now().Nanosecond()))
  45. config, err := LoadConfig(configJSON)
  46. if err != nil {
  47. log.WithContextFields(LogFields{"error": err}).Error("load config failed")
  48. return common.ContextError(err)
  49. }
  50. err = InitLogging(config)
  51. if err != nil {
  52. log.WithContextFields(LogFields{"error": err}).Error("init logging failed")
  53. return common.ContextError(err)
  54. }
  55. supportServices, err := NewSupportServices(config)
  56. if err != nil {
  57. log.WithContextFields(LogFields{"error": err}).Error("init support services failed")
  58. return common.ContextError(err)
  59. }
  60. log.WithContextFields(*common.GetBuildInfo().ToMap()).Info("startup")
  61. waitGroup := new(sync.WaitGroup)
  62. shutdownBroadcast := make(chan struct{})
  63. errors := make(chan error)
  64. tunnelServer, err := NewTunnelServer(supportServices, shutdownBroadcast)
  65. if err != nil {
  66. log.WithContextFields(LogFields{"error": err}).Error("init tunnel server failed")
  67. return common.ContextError(err)
  68. }
  69. supportServices.TunnelServer = tunnelServer
  70. if config.RunPacketTunnel {
  71. packetTunnelServer, err := tun.NewServer(&tun.ServerConfig{
  72. Logger: CommonLogger(log),
  73. SudoNetworkConfigCommands: config.PacketTunnelSudoNetworkConfigCommands,
  74. GetDNSResolverIPv4Addresses: supportServices.DNSResolver.GetAllIPv4,
  75. GetDNSResolverIPv6Addresses: supportServices.DNSResolver.GetAllIPv6,
  76. EgressInterface: config.PacketTunnelEgressInterface,
  77. DownstreamPacketQueueSize: config.PacketTunnelDownstreamPacketQueueSize,
  78. SessionIdleExpirySeconds: config.PacketTunnelSessionIdleExpirySeconds,
  79. })
  80. if err != nil {
  81. log.WithContextFields(LogFields{"error": err}).Error("init packet tunnel failed")
  82. return common.ContextError(err)
  83. }
  84. supportServices.PacketTunnelServer = packetTunnelServer
  85. }
  86. // After this point, errors should be delivered to the "errors" channel and
  87. // orderly shutdown should flow through to the end of the function to ensure
  88. // all workers are synchronously stopped.
  89. if config.RunPacketTunnel {
  90. supportServices.PacketTunnelServer.Start()
  91. waitGroup.Add(1)
  92. go func() {
  93. defer waitGroup.Done()
  94. <-shutdownBroadcast
  95. supportServices.PacketTunnelServer.Stop()
  96. }()
  97. }
  98. if config.RunLoadMonitor() {
  99. waitGroup.Add(1)
  100. go func() {
  101. waitGroup.Done()
  102. ticker := time.NewTicker(time.Duration(config.LoadMonitorPeriodSeconds) * time.Second)
  103. defer ticker.Stop()
  104. for {
  105. select {
  106. case <-shutdownBroadcast:
  107. return
  108. case <-ticker.C:
  109. logServerLoad(tunnelServer)
  110. }
  111. }
  112. }()
  113. }
  114. if config.RunPeriodicGarbageCollection() {
  115. waitGroup.Add(1)
  116. go func() {
  117. waitGroup.Done()
  118. ticker := time.NewTicker(time.Duration(config.PeriodicGarbageCollectionSeconds) * time.Second)
  119. defer ticker.Stop()
  120. for {
  121. select {
  122. case <-shutdownBroadcast:
  123. return
  124. case <-ticker.C:
  125. runtime.GC()
  126. }
  127. }
  128. }()
  129. }
  130. if config.RunWebServer() {
  131. waitGroup.Add(1)
  132. go func() {
  133. defer waitGroup.Done()
  134. err := RunWebServer(supportServices, shutdownBroadcast)
  135. select {
  136. case errors <- err:
  137. default:
  138. }
  139. }()
  140. }
  141. // The tunnel server is always run; it launches multiple
  142. // listeners, depending on which tunnel protocols are enabled.
  143. waitGroup.Add(1)
  144. go func() {
  145. defer waitGroup.Done()
  146. err := tunnelServer.Run()
  147. select {
  148. case errors <- err:
  149. default:
  150. }
  151. }()
  152. // Shutdown doesn't wait for the outputProcessProfiles goroutine
  153. // to complete, as it may be sleeping while running a "block" or
  154. // CPU profile.
  155. signalProcessProfiles := make(chan struct{}, 1)
  156. go func() {
  157. for {
  158. select {
  159. case <-signalProcessProfiles:
  160. outputProcessProfiles(supportServices.Config)
  161. case <-shutdownBroadcast:
  162. return
  163. }
  164. }
  165. }()
  166. // In addition to the actual signal handling here, there is
  167. // a list of signals that need to be passed through panicwrap
  168. // in 'github.com/Psiphon-Labs/psiphon-tunnel-core/Server/main.go'
  169. // where 'panicwrap.Wrap' is called. The handled signals below, and the
  170. // list there must be kept in sync to ensure proper signal handling
  171. // An OS signal triggers an orderly shutdown
  172. systemStopSignal := make(chan os.Signal, 1)
  173. signal.Notify(systemStopSignal, os.Interrupt, os.Kill, syscall.SIGTERM)
  174. // SIGUSR1 triggers a reload of support services
  175. reloadSupportServicesSignal := make(chan os.Signal, 1)
  176. signal.Notify(reloadSupportServicesSignal, syscall.SIGUSR1)
  177. // SIGUSR2 triggers an immediate load log and optional process profile output
  178. logServerLoadSignal := make(chan os.Signal, 1)
  179. signal.Notify(logServerLoadSignal, syscall.SIGUSR2)
  180. // SIGTSTP triggers tunnelServer to stop establishing new tunnels
  181. stopEstablishingTunnelsSignal := make(chan os.Signal, 1)
  182. signal.Notify(stopEstablishingTunnelsSignal, syscall.SIGTSTP)
  183. // SIGCONT triggers tunnelServer to resume establishing new tunnels
  184. resumeEstablishingTunnelsSignal := make(chan os.Signal, 1)
  185. signal.Notify(resumeEstablishingTunnelsSignal, syscall.SIGCONT)
  186. err = nil
  187. loop:
  188. for {
  189. select {
  190. case <-stopEstablishingTunnelsSignal:
  191. tunnelServer.SetEstablishTunnels(false)
  192. case <-resumeEstablishingTunnelsSignal:
  193. tunnelServer.SetEstablishTunnels(true)
  194. case <-reloadSupportServicesSignal:
  195. supportServices.Reload()
  196. case <-logServerLoadSignal:
  197. // Signal profiles writes first to ensure some diagnostics are
  198. // available in case logServerLoad hangs (which has happened
  199. // in the past due to a deadlock bug).
  200. select {
  201. case signalProcessProfiles <- *new(struct{}):
  202. default:
  203. }
  204. logServerLoad(tunnelServer)
  205. case <-systemStopSignal:
  206. log.WithContext().Info("shutdown by system")
  207. break loop
  208. case err = <-errors:
  209. log.WithContextFields(LogFields{"error": err}).Error("service failed")
  210. break loop
  211. }
  212. }
  213. close(shutdownBroadcast)
  214. waitGroup.Wait()
  215. return err
  216. }
  217. func getRuntimeMetrics() LogFields {
  218. numGoroutine := runtime.NumGoroutine()
  219. var memStats runtime.MemStats
  220. runtime.ReadMemStats(&memStats)
  221. lastGC := ""
  222. if memStats.LastGC > 0 {
  223. lastGC = time.Unix(0, int64(memStats.LastGC)).UTC().Format(time.RFC3339)
  224. }
  225. return LogFields{
  226. "num_goroutine": numGoroutine,
  227. "heap_alloc": memStats.HeapAlloc,
  228. "heap_sys": memStats.HeapSys,
  229. "heap_idle": memStats.HeapIdle,
  230. "heap_inuse": memStats.HeapInuse,
  231. "heap_released": memStats.HeapReleased,
  232. "heap_objects": memStats.HeapObjects,
  233. "num_gc": memStats.NumGC,
  234. "num_forced_gc": memStats.NumForcedGC,
  235. "last_gc": lastGC,
  236. }
  237. }
  238. func outputProcessProfiles(config *Config) {
  239. log.WithContextFields(getRuntimeMetrics()).Info("runtime_metrics")
  240. if config.ProcessProfileOutputDirectory != "" {
  241. openProfileFile := func(profileName string) *os.File {
  242. fileName := filepath.Join(
  243. config.ProcessProfileOutputDirectory, profileName+".profile")
  244. file, err := os.OpenFile(
  245. fileName, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
  246. if err != nil {
  247. log.WithContextFields(
  248. LogFields{
  249. "error": err,
  250. "fileName": fileName}).Error("open profile file failed")
  251. return nil
  252. }
  253. return file
  254. }
  255. writeProfile := func(profileName string) {
  256. file := openProfileFile(profileName)
  257. if file == nil {
  258. return
  259. }
  260. err := pprof.Lookup(profileName).WriteTo(file, 1)
  261. file.Close()
  262. if err != nil {
  263. log.WithContextFields(
  264. LogFields{
  265. "error": err,
  266. "profileName": profileName}).Error("write profile failed")
  267. }
  268. }
  269. // TODO: capture https://golang.org/pkg/runtime/debug/#WriteHeapDump?
  270. // May not be useful in its current state, as per:
  271. // https://groups.google.com/forum/#!topic/golang-dev/cYAkuU45Qyw
  272. // Write goroutine, heap, and threadcreate profiles
  273. // https://golang.org/pkg/runtime/pprof/#Profile
  274. writeProfile("goroutine")
  275. writeProfile("heap")
  276. writeProfile("threadcreate")
  277. // Write block profile (after sampling)
  278. // https://golang.org/pkg/runtime/pprof/#Profile
  279. if config.ProcessBlockProfileDurationSeconds > 0 {
  280. log.WithContext().Info("start block profiling")
  281. runtime.SetBlockProfileRate(1)
  282. time.Sleep(
  283. time.Duration(config.ProcessBlockProfileDurationSeconds) * time.Second)
  284. runtime.SetBlockProfileRate(0)
  285. log.WithContext().Info("end block profiling")
  286. writeProfile("block")
  287. }
  288. // Write CPU profile (after sampling)
  289. // https://golang.org/pkg/runtime/pprof/#StartCPUProfile
  290. if config.ProcessCPUProfileDurationSeconds > 0 {
  291. file := openProfileFile("cpu")
  292. if file != nil {
  293. log.WithContext().Info("start cpu profiling")
  294. err := pprof.StartCPUProfile(file)
  295. if err != nil {
  296. log.WithContextFields(
  297. LogFields{"error": err}).Error("StartCPUProfile failed")
  298. } else {
  299. time.Sleep(time.Duration(
  300. config.ProcessCPUProfileDurationSeconds) * time.Second)
  301. pprof.StopCPUProfile()
  302. log.WithContext().Info("end cpu profiling")
  303. }
  304. file.Close()
  305. }
  306. }
  307. }
  308. }
  309. func logServerLoad(server *TunnelServer) {
  310. protocolStats, regionStats := server.GetLoadStats()
  311. serverLoad := getRuntimeMetrics()
  312. serverLoad["event_name"] = "server_load"
  313. serverLoad["establish_tunnels"] = server.GetEstablishTunnels()
  314. for protocol, stats := range protocolStats {
  315. serverLoad[protocol] = stats
  316. }
  317. log.LogRawFieldsWithTimestamp(serverLoad)
  318. for region, regionProtocolStats := range regionStats {
  319. serverLoad := LogFields{
  320. "event_name": "server_load",
  321. "region": region,
  322. }
  323. for protocol, stats := range regionProtocolStats {
  324. serverLoad[protocol] = stats
  325. }
  326. log.LogRawFieldsWithTimestamp(serverLoad)
  327. }
  328. }
  329. // SupportServices carries common and shared data components
  330. // across different server components. SupportServices implements a
  331. // hot reload of traffic rules, psinet database, and geo IP database
  332. // components, which allows these data components to be refreshed
  333. // without restarting the server process.
  334. type SupportServices struct {
  335. Config *Config
  336. TrafficRulesSet *TrafficRulesSet
  337. OSLConfig *osl.Config
  338. PsinetDatabase *psinet.Database
  339. GeoIPService *GeoIPService
  340. DNSResolver *DNSResolver
  341. TunnelServer *TunnelServer
  342. PacketTunnelServer *tun.Server
  343. TacticsServer *tactics.Server
  344. }
  345. // NewSupportServices initializes a new SupportServices.
  346. func NewSupportServices(config *Config) (*SupportServices, error) {
  347. trafficRulesSet, err := NewTrafficRulesSet(config.TrafficRulesFilename)
  348. if err != nil {
  349. return nil, common.ContextError(err)
  350. }
  351. oslConfig, err := osl.NewConfig(config.OSLConfigFilename)
  352. if err != nil {
  353. return nil, common.ContextError(err)
  354. }
  355. psinetDatabase, err := psinet.NewDatabase(config.PsinetDatabaseFilename)
  356. if err != nil {
  357. return nil, common.ContextError(err)
  358. }
  359. geoIPService, err := NewGeoIPService(
  360. config.GeoIPDatabaseFilenames, config.DiscoveryValueHMACKey)
  361. if err != nil {
  362. return nil, common.ContextError(err)
  363. }
  364. dnsResolver, err := NewDNSResolver(config.DNSResolverIPAddress)
  365. if err != nil {
  366. return nil, common.ContextError(err)
  367. }
  368. tacticsServer, err := tactics.NewServer(
  369. CommonLogger(log),
  370. getTacticsAPIParameterLogFieldFormatter(),
  371. getTacticsAPIParameterValidator(config),
  372. config.TacticsConfigFilename)
  373. if err != nil {
  374. return nil, common.ContextError(err)
  375. }
  376. return &SupportServices{
  377. Config: config,
  378. TrafficRulesSet: trafficRulesSet,
  379. OSLConfig: oslConfig,
  380. PsinetDatabase: psinetDatabase,
  381. GeoIPService: geoIPService,
  382. DNSResolver: dnsResolver,
  383. TacticsServer: tacticsServer,
  384. }, nil
  385. }
  386. // Reload reinitializes traffic rules, psinet database, and geo IP database
  387. // components. If any component fails to reload, an error is logged and
  388. // Reload proceeds, using the previous state of the component.
  389. func (support *SupportServices) Reload() {
  390. reloaders := append(
  391. []common.Reloader{
  392. support.TrafficRulesSet,
  393. support.OSLConfig,
  394. support.PsinetDatabase,
  395. support.TacticsServer},
  396. support.GeoIPService.Reloaders()...)
  397. // Note: established clients aren't notified when tactics change after a
  398. // reload; new tactics will be obtained on the next client handshake or
  399. // tactics request.
  400. // Take these actions only after the corresponding Reloader has reloaded.
  401. // In both the traffic rules and OSL cases, there is some impact from state
  402. // reset, so the reset should be avoided where possible.
  403. reloadPostActions := map[common.Reloader]func(){
  404. support.TrafficRulesSet: func() { support.TunnelServer.ResetAllClientTrafficRules() },
  405. support.OSLConfig: func() { support.TunnelServer.ResetAllClientOSLConfigs() },
  406. }
  407. for _, reloader := range reloaders {
  408. if !reloader.WillReload() {
  409. // Skip logging
  410. continue
  411. }
  412. // "reloaded" flag indicates if file was actually reloaded or ignored
  413. reloaded, err := reloader.Reload()
  414. if reloaded {
  415. if action, ok := reloadPostActions[reloader]; ok {
  416. action()
  417. }
  418. }
  419. if err != nil {
  420. log.WithContextFields(
  421. LogFields{
  422. "reloader": reloader.LogDescription(),
  423. "error": err}).Error("reload failed")
  424. // Keep running with previous state
  425. } else {
  426. log.WithContextFields(
  427. LogFields{
  428. "reloader": reloader.LogDescription(),
  429. "reloaded": reloaded}).Info("reload success")
  430. }
  431. }
  432. }