services.go 13 KB

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