services.go 15 KB

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