services.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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. if config.DumpProfilesOnStopEstablishTunnels(
  197. tunnelServer.GetEstablishedClientCount()) {
  198. // Run the profile dump in a goroutine and don't block this loop. Shutdown
  199. // doesn't wait for any running outputProcessProfiles to complete.
  200. go func() {
  201. outputProcessProfiles(supportServices.Config, "stop_establish_tunnels")
  202. }()
  203. }
  204. case <-resumeEstablishingTunnelsSignal:
  205. tunnelServer.SetEstablishTunnels(true)
  206. case <-reloadSupportServicesSignal:
  207. supportServices.Reload()
  208. case <-logServerLoadSignal:
  209. // Signal profiles writes first to ensure some diagnostics are
  210. // available in case logServerLoad hangs (which has happened
  211. // in the past due to a deadlock bug).
  212. select {
  213. case signalProcessProfiles <- struct{}{}:
  214. default:
  215. }
  216. logServerLoad(tunnelServer)
  217. case <-systemStopSignal:
  218. log.WithTrace().Info("shutdown by system")
  219. break loop
  220. case err = <-errorChannel:
  221. log.WithTraceFields(LogFields{"error": err}).Error("service failed")
  222. break loop
  223. }
  224. }
  225. // During any delayed or hung shutdown, periodically dump profiles to help
  226. // diagnose the cause. Shutdown doesn't wait for any running
  227. // outputProcessProfiles to complete.
  228. signalProfileDumperStop := make(chan struct{})
  229. go func() {
  230. tickSeconds := 10
  231. ticker := time.NewTicker(time.Duration(tickSeconds) * time.Second)
  232. defer ticker.Stop()
  233. for i := tickSeconds; i <= 60; i += tickSeconds {
  234. select {
  235. case <-signalProfileDumperStop:
  236. return
  237. case <-ticker.C:
  238. filenameSuffix := fmt.Sprintf("delayed_shutdown_%ds", i)
  239. outputProcessProfiles(supportServices.Config, filenameSuffix)
  240. }
  241. }
  242. }()
  243. close(shutdownBroadcast)
  244. waitGroup.Wait()
  245. close(signalProfileDumperStop)
  246. return err
  247. }
  248. func getRuntimeMetrics() LogFields {
  249. numGoroutine := runtime.NumGoroutine()
  250. var memStats runtime.MemStats
  251. runtime.ReadMemStats(&memStats)
  252. lastGC := ""
  253. if memStats.LastGC > 0 {
  254. lastGC = time.Unix(0, int64(memStats.LastGC)).UTC().Format(time.RFC3339)
  255. }
  256. return LogFields{
  257. "num_goroutine": numGoroutine,
  258. "heap_alloc": memStats.HeapAlloc,
  259. "heap_sys": memStats.HeapSys,
  260. "heap_idle": memStats.HeapIdle,
  261. "heap_inuse": memStats.HeapInuse,
  262. "heap_released": memStats.HeapReleased,
  263. "heap_objects": memStats.HeapObjects,
  264. "num_gc": memStats.NumGC,
  265. "num_forced_gc": memStats.NumForcedGC,
  266. "last_gc": lastGC,
  267. }
  268. }
  269. func outputProcessProfiles(config *Config, filenameSuffix string) {
  270. log.WithTraceFields(getRuntimeMetrics()).Info("runtime_metrics")
  271. if config.ProcessProfileOutputDirectory != "" {
  272. common.WriteRuntimeProfiles(
  273. CommonLogger(log),
  274. config.ProcessProfileOutputDirectory,
  275. filenameSuffix,
  276. config.ProcessBlockProfileDurationSeconds,
  277. config.ProcessCPUProfileDurationSeconds)
  278. }
  279. }
  280. func logServerLoad(server *TunnelServer) {
  281. protocolStats, regionStats := server.GetLoadStats()
  282. serverLoad := getRuntimeMetrics()
  283. serverLoad["event_name"] = "server_load"
  284. establishTunnels, establishLimitedCount := server.GetEstablishTunnelsMetrics()
  285. serverLoad["establish_tunnels"] = establishTunnels
  286. serverLoad["establish_tunnels_limited_count"] = establishLimitedCount
  287. for protocol, stats := range protocolStats {
  288. serverLoad[protocol] = stats
  289. }
  290. log.LogRawFieldsWithTimestamp(serverLoad)
  291. for region, regionProtocolStats := range regionStats {
  292. serverLoad := LogFields{
  293. "event_name": "server_load",
  294. "region": region,
  295. }
  296. for protocol, stats := range regionProtocolStats {
  297. serverLoad[protocol] = stats
  298. }
  299. log.LogRawFieldsWithTimestamp(serverLoad)
  300. }
  301. }
  302. func logIrregularTunnel(
  303. support *SupportServices,
  304. listenerTunnelProtocol string,
  305. listenerPort int,
  306. clientIP string,
  307. tunnelError error,
  308. logFields LogFields) {
  309. if logFields == nil {
  310. logFields = make(LogFields)
  311. }
  312. logFields["event_name"] = "irregular_tunnel"
  313. logFields["listener_protocol"] = listenerTunnelProtocol
  314. logFields["listener_port_number"] = listenerPort
  315. support.GeoIPService.Lookup(clientIP).SetLogFields(logFields)
  316. logFields["tunnel_error"] = tunnelError.Error()
  317. log.LogRawFieldsWithTimestamp(logFields)
  318. }
  319. // SupportServices carries common and shared data components
  320. // across different server components. SupportServices implements a
  321. // hot reload of traffic rules, psinet database, and geo IP database
  322. // components, which allows these data components to be refreshed
  323. // without restarting the server process.
  324. type SupportServices struct {
  325. Config *Config
  326. TrafficRulesSet *TrafficRulesSet
  327. OSLConfig *osl.Config
  328. PsinetDatabase *psinet.Database
  329. GeoIPService *GeoIPService
  330. DNSResolver *DNSResolver
  331. TunnelServer *TunnelServer
  332. PacketTunnelServer *tun.Server
  333. TacticsServer *tactics.Server
  334. Blocklist *Blocklist
  335. }
  336. // NewSupportServices initializes a new SupportServices.
  337. func NewSupportServices(config *Config) (*SupportServices, error) {
  338. trafficRulesSet, err := NewTrafficRulesSet(config.TrafficRulesFilename)
  339. if err != nil {
  340. return nil, errors.Trace(err)
  341. }
  342. oslConfig, err := osl.NewConfig(config.OSLConfigFilename)
  343. if err != nil {
  344. return nil, errors.Trace(err)
  345. }
  346. psinetDatabase, err := psinet.NewDatabase(config.PsinetDatabaseFilename)
  347. if err != nil {
  348. return nil, errors.Trace(err)
  349. }
  350. geoIPService, err := NewGeoIPService(
  351. config.GeoIPDatabaseFilenames, config.DiscoveryValueHMACKey)
  352. if err != nil {
  353. return nil, errors.Trace(err)
  354. }
  355. dnsResolver, err := NewDNSResolver(config.DNSResolverIPAddress)
  356. if err != nil {
  357. return nil, errors.Trace(err)
  358. }
  359. blocklist, err := NewBlocklist(config.BlocklistFilename)
  360. if err != nil {
  361. return nil, errors.Trace(err)
  362. }
  363. tacticsServer, err := tactics.NewServer(
  364. CommonLogger(log),
  365. getTacticsAPIParameterLogFieldFormatter(),
  366. getTacticsAPIParameterValidator(config),
  367. config.TacticsConfigFilename)
  368. if err != nil {
  369. return nil, errors.Trace(err)
  370. }
  371. return &SupportServices{
  372. Config: config,
  373. TrafficRulesSet: trafficRulesSet,
  374. OSLConfig: oslConfig,
  375. PsinetDatabase: psinetDatabase,
  376. GeoIPService: geoIPService,
  377. DNSResolver: dnsResolver,
  378. TacticsServer: tacticsServer,
  379. Blocklist: blocklist,
  380. }, nil
  381. }
  382. // Reload reinitializes traffic rules, psinet database, and geo IP database
  383. // components. If any component fails to reload, an error is logged and
  384. // Reload proceeds, using the previous state of the component.
  385. func (support *SupportServices) Reload() {
  386. reloaders := append(
  387. []common.Reloader{
  388. support.TrafficRulesSet,
  389. support.OSLConfig,
  390. support.PsinetDatabase,
  391. support.TacticsServer,
  392. support.Blocklist},
  393. support.GeoIPService.Reloaders()...)
  394. // Note: established clients aren't notified when tactics change after a
  395. // reload; new tactics will be obtained on the next client handshake or
  396. // tactics request.
  397. // Take these actions only after the corresponding Reloader has reloaded.
  398. // In both the traffic rules and OSL cases, there is some impact from state
  399. // reset, so the reset should be avoided where possible.
  400. reloadPostActions := map[common.Reloader]func(){
  401. support.TrafficRulesSet: func() { support.TunnelServer.ResetAllClientTrafficRules() },
  402. support.OSLConfig: func() { support.TunnelServer.ResetAllClientOSLConfigs() },
  403. }
  404. for _, reloader := range reloaders {
  405. if !reloader.WillReload() {
  406. // Skip logging
  407. continue
  408. }
  409. // "reloaded" flag indicates if file was actually reloaded or ignored
  410. reloaded, err := reloader.Reload()
  411. if reloaded {
  412. if action, ok := reloadPostActions[reloader]; ok {
  413. action()
  414. }
  415. }
  416. if err != nil {
  417. log.WithTraceFields(
  418. LogFields{
  419. "reloader": reloader.LogDescription(),
  420. "error": err}).Error("reload failed")
  421. // Keep running with previous state
  422. } else {
  423. log.WithTraceFields(
  424. LogFields{
  425. "reloader": reloader.LogDescription(),
  426. "reloaded": reloaded}).Info("reload success")
  427. }
  428. }
  429. }