services.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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/buildinfo"
  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(*buildinfo.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. // During any delayed or hung shutdown, periodically dump profiles to help
  214. // diagnose the cause.
  215. signalProfileDumperStop := make(chan struct{}, 1)
  216. go func() {
  217. tickSeconds := 10
  218. ticker := time.NewTicker(time.Duration(tickSeconds) * time.Second)
  219. defer ticker.Stop()
  220. for i := tickSeconds; i <= 60; i += tickSeconds {
  221. select {
  222. case <-signalProfileDumperStop:
  223. return
  224. case <-ticker.C:
  225. filenameSuffix := fmt.Sprintf("delayed_shutdown_%ds", i)
  226. outputProcessProfiles(supportServices.Config, filenameSuffix)
  227. }
  228. }
  229. }()
  230. close(shutdownBroadcast)
  231. waitGroup.Wait()
  232. close(signalProfileDumperStop)
  233. return err
  234. }
  235. func getRuntimeMetrics() LogFields {
  236. numGoroutine := runtime.NumGoroutine()
  237. var memStats runtime.MemStats
  238. runtime.ReadMemStats(&memStats)
  239. lastGC := ""
  240. if memStats.LastGC > 0 {
  241. lastGC = time.Unix(0, int64(memStats.LastGC)).UTC().Format(time.RFC3339)
  242. }
  243. return LogFields{
  244. "num_goroutine": numGoroutine,
  245. "heap_alloc": memStats.HeapAlloc,
  246. "heap_sys": memStats.HeapSys,
  247. "heap_idle": memStats.HeapIdle,
  248. "heap_inuse": memStats.HeapInuse,
  249. "heap_released": memStats.HeapReleased,
  250. "heap_objects": memStats.HeapObjects,
  251. "num_gc": memStats.NumGC,
  252. "num_forced_gc": memStats.NumForcedGC,
  253. "last_gc": lastGC,
  254. }
  255. }
  256. func outputProcessProfiles(config *Config, filenameSuffix string) {
  257. log.WithContextFields(getRuntimeMetrics()).Info("runtime_metrics")
  258. if config.ProcessProfileOutputDirectory != "" {
  259. common.WriteRuntimeProfiles(
  260. CommonLogger(log),
  261. config.ProcessProfileOutputDirectory,
  262. filenameSuffix,
  263. config.ProcessBlockProfileDurationSeconds,
  264. config.ProcessCPUProfileDurationSeconds)
  265. }
  266. }
  267. func logServerLoad(server *TunnelServer) {
  268. protocolStats, regionStats := server.GetLoadStats()
  269. serverLoad := getRuntimeMetrics()
  270. serverLoad["event_name"] = "server_load"
  271. serverLoad["establish_tunnels"] = server.GetEstablishTunnels()
  272. for protocol, stats := range protocolStats {
  273. serverLoad[protocol] = stats
  274. }
  275. log.LogRawFieldsWithTimestamp(serverLoad)
  276. for region, regionProtocolStats := range regionStats {
  277. serverLoad := LogFields{
  278. "event_name": "server_load",
  279. "region": region,
  280. }
  281. for protocol, stats := range regionProtocolStats {
  282. serverLoad[protocol] = stats
  283. }
  284. log.LogRawFieldsWithTimestamp(serverLoad)
  285. }
  286. }
  287. // SupportServices carries common and shared data components
  288. // across different server components. SupportServices implements a
  289. // hot reload of traffic rules, psinet database, and geo IP database
  290. // components, which allows these data components to be refreshed
  291. // without restarting the server process.
  292. type SupportServices struct {
  293. Config *Config
  294. TrafficRulesSet *TrafficRulesSet
  295. OSLConfig *osl.Config
  296. PsinetDatabase *psinet.Database
  297. GeoIPService *GeoIPService
  298. DNSResolver *DNSResolver
  299. TunnelServer *TunnelServer
  300. PacketTunnelServer *tun.Server
  301. TacticsServer *tactics.Server
  302. Blocklist *Blocklist
  303. }
  304. // NewSupportServices initializes a new SupportServices.
  305. func NewSupportServices(config *Config) (*SupportServices, error) {
  306. trafficRulesSet, err := NewTrafficRulesSet(config.TrafficRulesFilename)
  307. if err != nil {
  308. return nil, common.ContextError(err)
  309. }
  310. oslConfig, err := osl.NewConfig(config.OSLConfigFilename)
  311. if err != nil {
  312. return nil, common.ContextError(err)
  313. }
  314. psinetDatabase, err := psinet.NewDatabase(config.PsinetDatabaseFilename)
  315. if err != nil {
  316. return nil, common.ContextError(err)
  317. }
  318. geoIPService, err := NewGeoIPService(
  319. config.GeoIPDatabaseFilenames, config.DiscoveryValueHMACKey)
  320. if err != nil {
  321. return nil, common.ContextError(err)
  322. }
  323. dnsResolver, err := NewDNSResolver(config.DNSResolverIPAddress)
  324. if err != nil {
  325. return nil, common.ContextError(err)
  326. }
  327. blocklist, err := NewBlocklist(config.BlocklistFilename)
  328. if err != nil {
  329. return nil, common.ContextError(err)
  330. }
  331. tacticsServer, err := tactics.NewServer(
  332. CommonLogger(log),
  333. getTacticsAPIParameterLogFieldFormatter(),
  334. getTacticsAPIParameterValidator(config),
  335. config.TacticsConfigFilename)
  336. if err != nil {
  337. return nil, common.ContextError(err)
  338. }
  339. return &SupportServices{
  340. Config: config,
  341. TrafficRulesSet: trafficRulesSet,
  342. OSLConfig: oslConfig,
  343. PsinetDatabase: psinetDatabase,
  344. GeoIPService: geoIPService,
  345. DNSResolver: dnsResolver,
  346. TacticsServer: tacticsServer,
  347. Blocklist: blocklist,
  348. }, nil
  349. }
  350. // Reload reinitializes traffic rules, psinet database, and geo IP database
  351. // components. If any component fails to reload, an error is logged and
  352. // Reload proceeds, using the previous state of the component.
  353. func (support *SupportServices) Reload() {
  354. reloaders := append(
  355. []common.Reloader{
  356. support.TrafficRulesSet,
  357. support.OSLConfig,
  358. support.PsinetDatabase,
  359. support.TacticsServer,
  360. support.Blocklist},
  361. support.GeoIPService.Reloaders()...)
  362. // Note: established clients aren't notified when tactics change after a
  363. // reload; new tactics will be obtained on the next client handshake or
  364. // tactics request.
  365. // Take these actions only after the corresponding Reloader has reloaded.
  366. // In both the traffic rules and OSL cases, there is some impact from state
  367. // reset, so the reset should be avoided where possible.
  368. reloadPostActions := map[common.Reloader]func(){
  369. support.TrafficRulesSet: func() { support.TunnelServer.ResetAllClientTrafficRules() },
  370. support.OSLConfig: func() { support.TunnelServer.ResetAllClientOSLConfigs() },
  371. }
  372. for _, reloader := range reloaders {
  373. if !reloader.WillReload() {
  374. // Skip logging
  375. continue
  376. }
  377. // "reloaded" flag indicates if file was actually reloaded or ignored
  378. reloaded, err := reloader.Reload()
  379. if reloaded {
  380. if action, ok := reloadPostActions[reloader]; ok {
  381. action()
  382. }
  383. }
  384. if err != nil {
  385. log.WithContextFields(
  386. LogFields{
  387. "reloader": reloader.LogDescription(),
  388. "error": err}).Error("reload failed")
  389. // Keep running with previous state
  390. } else {
  391. log.WithContextFields(
  392. LogFields{
  393. "reloader": reloader.LogDescription(),
  394. "reloaded": reloaded}).Info("reload success")
  395. }
  396. }
  397. }