services.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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
  20. import (
  21. "os"
  22. "os/signal"
  23. "sync"
  24. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  25. )
  26. func RunServices(encodedConfig []byte) error {
  27. config, err := LoadConfig(encodedConfig)
  28. if err != nil {
  29. log.WithContextFields(LogFields{"error": err}).Error("load config failed")
  30. return psiphon.ContextError(err)
  31. }
  32. // TODO: init logging
  33. waitGroup := new(sync.WaitGroup)
  34. shutdownBroadcast := make(chan struct{})
  35. errors := make(chan error)
  36. // TODO: optional services (e.g., run SSH only)
  37. waitGroup.Add(1)
  38. go func() {
  39. defer waitGroup.Done()
  40. err := RunWebServer(config, shutdownBroadcast)
  41. select {
  42. case errors <- err:
  43. default:
  44. }
  45. }()
  46. waitGroup.Add(1)
  47. go func() {
  48. defer waitGroup.Done()
  49. err := RunSSHServer(config, shutdownBroadcast)
  50. select {
  51. case errors <- err:
  52. default:
  53. }
  54. }()
  55. waitGroup.Add(1)
  56. go func() {
  57. defer waitGroup.Done()
  58. err := RunObfuscatedSSHServer(config, shutdownBroadcast)
  59. select {
  60. case errors <- err:
  61. default:
  62. }
  63. }()
  64. // An OS signal triggers an orderly shutdown
  65. systemStopSignal := make(chan os.Signal, 1)
  66. signal.Notify(systemStopSignal, os.Interrupt, os.Kill)
  67. err = nil
  68. select {
  69. case <-systemStopSignal:
  70. log.WithContext().Info("shutdown by system")
  71. case err = <-errors:
  72. log.WithContextFields(LogFields{"error": err}).Error("service failed")
  73. }
  74. close(shutdownBroadcast)
  75. waitGroup.Wait()
  76. return err
  77. }