forked from open-horizon/edge-sync-service
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
220 lines (199 loc) · 7.4 KB
/
http.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
package base
import (
"context"
"crypto/tls"
"fmt"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"runtime"
"strings"
"github.com/open-horizon/edge-sync-service/common"
"github.com/open-horizon/edge-utilities/logger"
"github.com/open-horizon/edge-utilities/logger/log"
)
var secureHTTPServer http.Server
var unsecureHTTPServer http.Server
func startHTTPServer(ipAddress string, registerHandlers bool, swaggerFile string) common.SyncServiceError {
secureHTTPServer = http.Server{}
unsecureHTTPServer = http.Server{}
secureHTTPServer.Addr =
fmt.Sprintf("%s:%d", common.Configuration.ListeningAddress,
common.Configuration.SecureListeningPort)
unsecureHTTPServer.Addr =
fmt.Sprintf("%s:%d", common.Configuration.ListeningAddress,
common.Configuration.UnsecureListeningPort)
// When running embedded in app, there is no API serving nor swagger serving
if common.ServingAPIs {
if registerHandlers {
setupAPIServer()
}
if common.Configuration.ListeningType == common.ListeningSecurely {
setupSwaggerServing(swaggerFile, true, ipAddress, common.Configuration.SecureListeningPort)
} else if common.Configuration.ListeningType != common.ListeningUnix &&
common.Configuration.ListeningType != common.ListeningSecureUnix {
setupSwaggerServing(swaggerFile, false, ipAddress, common.Configuration.UnsecureListeningPort)
}
}
// An embedded CSS needs to Serve the SPI stuff if it allows ESSs to connect via HTTP
if common.ServingAPIs || (common.Configuration.NodeType == common.CSS &&
common.Configuration.CommunicationProtocol != common.MQTTProtocol &&
common.Configuration.CommunicationProtocol != common.WIoTP) {
if common.Configuration.ListeningType == common.ListeningSecurely ||
common.Configuration.ListeningType == common.ListeningBoth ||
common.Configuration.ListeningType == common.ListeningSecureUnix {
err := setupServerTLSConfig()
if err != nil {
return &common.SetupError{Message: fmt.Sprintf("Failed to setup TLS. Error: %s", err)}
}
}
if common.Configuration.ListeningType == common.ListeningBoth {
listener, err := net.Listen("tcp", unsecureHTTPServer.Addr)
if err != nil {
return &common.SetupError{Message: fmt.Sprintf("Failed to listen on %s. Error: %s", unsecureHTTPServer.Addr, err)}
}
go startHTTPServerHelper(false, listener)
}
if common.Configuration.ListeningType == common.ListeningUnsecurely {
listener, err := net.Listen("tcp", unsecureHTTPServer.Addr)
if err != nil {
return &common.SetupError{Message: fmt.Sprintf("Failed to listen on %s. Error: %s", unsecureHTTPServer.Addr, err)}
}
go startHTTPServerHelper(false, listener)
} else if common.Configuration.ListeningType != common.ListeningUnix &&
common.Configuration.ListeningType != common.ListeningSecureUnix {
listener, err := net.Listen("tcp", secureHTTPServer.Addr)
if err != nil {
return &common.SetupError{Message: fmt.Sprintf("Failed to listen on %s. Error: %s", secureHTTPServer.Addr, err)}
}
go startHTTPServerHelper(true, listener)
} else {
var listener net.Listener
var socketFile string
if strings.HasPrefix(common.Configuration.ListeningAddress, "/") {
socketFile = common.Configuration.ListeningAddress
} else {
socketFile = common.Configuration.PersistenceRootPath + common.Configuration.ListeningAddress
}
if err := os.Remove(socketFile); err != nil && !os.IsNotExist(err) {
return &common.SetupError{Message: fmt.Sprintf("Failed to remove Unix Socket listening. Error: %s", err)}
}
unixAddress, err := net.ResolveUnixAddr("unix", socketFile)
if err != nil {
return &common.SetupError{Message: fmt.Sprintf("Failed to setup Unix Socket listening. Error: %s", err)}
}
listener, err = net.ListenUnix("unix", unixAddress)
if err != nil {
return &common.SetupError{Message: fmt.Sprintf("Failed to setup Unix Socket listening. Error: %s", err)}
}
go startHTTPServerHelper(common.Configuration.ListeningType == common.ListeningSecureUnix, listener)
}
}
return nil
}
func startHTTPServerHelper(secure bool, listener net.Listener) {
common.GoRoutineStarted()
var err error
if secure {
if common.Configuration.ListeningType != common.ListeningSecureUnix {
if log.IsLogging(logger.INFO) {
log.Info("Listening on %d for HTTPS", common.Configuration.SecureListeningPort)
}
} else {
if log.IsLogging(logger.INFO) {
log.Info("Listening on %s for UNIX (securely)", listener.Addr().String())
}
}
err = secureHTTPServer.ServeTLS(listener, "", "")
} else {
if common.Configuration.ListeningType != common.ListeningUnix {
if log.IsLogging(logger.INFO) {
log.Info("Listening on %d for HTTP", common.Configuration.UnsecureListeningPort)
}
} else {
if log.IsLogging(logger.INFO) {
log.Info("Listening on %s for UNIX", listener.Addr().String())
}
}
err = unsecureHTTPServer.Serve(listener)
}
if err == http.ErrServerClosed {
if log.IsLogging(logger.TRACE) {
log.Trace(err.Error())
}
common.GoRoutineEnded()
} else {
if log.IsLogging(logger.FATAL) {
log.Fatal(err.Error())
}
}
}
func stopHTTPServing() {
if common.Configuration.UnsecureListeningPort != 0 {
if err := unsecureHTTPServer.Shutdown(context.Background()); err != nil {
if log.IsLogging(logger.ERROR) {
log.Error(err.Error())
}
}
}
if len(common.Configuration.ServerCertificate) != 0 {
if err := secureHTTPServer.Shutdown(context.Background()); err != nil {
if log.IsLogging(logger.ERROR) {
log.Error(err.Error())
}
}
}
}
func setupServerTLSConfig() error {
var certFile, keyFile string
if strings.HasPrefix(common.Configuration.ServerCertificate, "/") {
certFile = common.Configuration.ServerCertificate
} else {
certFile = common.Configuration.PersistenceRootPath + common.Configuration.ServerCertificate
}
if strings.HasPrefix(common.Configuration.ServerKey, "/") {
keyFile = common.Configuration.ServerKey
} else {
keyFile = common.Configuration.PersistenceRootPath + common.Configuration.ServerKey
}
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
if _, ok := err.(*os.PathError); ok {
// The ServerCertificate and ServerKey are likely pem file contents
cert, err = tls.X509KeyPair([]byte(common.Configuration.ServerCertificate), []byte(common.Configuration.ServerKey))
}
}
if err == nil {
secureHTTPServer.TLSConfig = &tls.Config{Certificates: []tls.Certificate{cert}}
}
return err
}
func setupSwaggerServing(swaggerFile string, securely bool, ipAddress string, port uint16) {
if len(swaggerFile) != 0 {
_, srcFile, _, ok := runtime.Caller(0)
if !ok {
if log.IsLogging(logger.ERROR) {
log.Error("Failed to get source file of http.go. Can't serve Swagger UI")
}
return
}
sourceDir := filepath.Dir(srcFile)
servedDir, _ := filepath.Abs(sourceDir + "/../../swagger-ui")
var protocol string
if securely {
protocol = "https"
} else {
protocol = "http"
}
swaggerFileURL := url.QueryEscape(fmt.Sprintf("%s://%s:%d/swagger.json", protocol, ipAddress, port))
redirectURL := fmt.Sprintf("%s://%s:%d/swagger-ui/index.html?url=%s", protocol, ipAddress, port, swaggerFileURL)
http.Handle("/swagger", http.RedirectHandler(redirectURL, http.StatusPermanentRedirect))
http.Handle("/swagger-ui/", http.StripPrefix("/swagger-ui", http.FileServer(http.Dir(servedDir))))
http.HandleFunc("/swagger.json",
func(writer http.ResponseWriter, request *http.Request) {
http.ServeFile(writer, request, swaggerFile)
})
}
}