services.go 14 KB

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