services.go 13 KB

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