services.go 13 KB

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