-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
292 lines (255 loc) · 8.57 KB
/
main.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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
// Description: This is the main file of the ftp server
// The main function starts the ftp server and the ftps server
// The ftp server is started on port 21 and the ftps server is started on port 990
// The ftp server is started with the TryListenAndServeTLSe function and the ftps server is started with the TryListenAndServeTLS function
// The ftp server and the ftpes server are started with the TryListenAndServe function
// The ftpes server are started with the TryListenAndServeTLSe function
// The ftps server are started with the TryListenAndServeTLS function
// you can run it with the docker-compose file in the root of the project
package main
import (
"context"
"embed"
"fmt"
"github.com/lmittmann/tint"
"github.com/telebroad/fileserver/filesystem"
"github.com/telebroad/fileserver/ftp"
"github.com/telebroad/fileserver/httphandler"
"github.com/telebroad/fileserver/sftp"
"github.com/telebroad/fileserver/users"
"io/fs"
"log/slog"
"mime"
"net/http"
"os"
"os/signal"
"strconv"
"strings"
"time"
)
var (
//go:embed keys
keysDir embed.FS
)
func main() {
// setting up the slog logger
logger := setupLogger()
slog.SetDefault(logger)
logger.Debug("Starting FTP server")
env, err := GetEnv(logger)
if err != nil {
logger.Error("Error getting environment", "error", err)
os.Exit(1)
}
// create a new user
u := GetUsers(logger)
// file system
localFS := filesystem.NewLocalFS(env.FtpServerRoot)
// ftp server
ftpServer, err := ftp.NewServer(env.FtpAddr, localFS, u)
if err != nil {
fmt.Println("Error starting ftp server", "error", err)
return
}
ftpServer.SetLogger(logger.With("module", "ftp-server"))
// seting the public server ip for passive mode
err = ftpServer.SetPublicServerIPv4(env.FtpServerIPv4)
if err != nil {
fmt.Println("Error setting public server ip", "error", err)
return
}
// setting the passive ports range
ftpServer.PasvMinPort = env.PasvMinPort
ftpServer.PasvMaxPort = env.PasvMaxPort
// starting the ftp server
// TLSe means that the server start with tls encryption but it can be upgraded to tls encryption
err = ftpServer.TryListenAndServeTLSe(env.CrtFile, env.KeyFile, time.Second)
if err != nil {
logger.Error("Error starting ftp server", "error", err)
return
}
logger.Info("FTP server started", "port", env.FtpAddr)
// ftps server
ftpsServer, err := ftp.NewServer(env.FtpsAddr, localFS, u)
err = ftpServer.SetPublicServerIPv4(env.FtpServerIPv4)
if err != nil {
logger.Error("Error setting public server ip", "error", err)
return
}
ftpsServer.SetLogger(logger.With("module", "ftps-server"))
ftpsServer.PasvMinPort = env.PasvMinPort
ftpsServer.PasvMaxPort = env.PasvMaxPort
// ONLY ACCEPT TLS CONNECTIONS
err = ftpsServer.TryListenAndServeTLS(env.CrtFile, env.KeyFile, time.Second)
if err != nil {
logger.Error("Error starting ftps server", "error", err)
return
}
logger.Info("FTPS server started", "port", env.FtpsAddr)
// sftp server
sftpServer := sftp.NewSFTPServer(env.SftpAddr, localFS, u)
sftpServer.SetLogger(logger.With("module", "sftp-server"))
// adding a directory with private keys
// ecdsa, rsa, ed25519
fs.WalkDir(keysDir, ".", func(path string, d fs.DirEntry, err error) error {
if d == nil || d.IsDir() {
return nil
}
file, err := fs.ReadFile(keysDir, path)
if err != nil {
return err
}
sftpServer.SetPrivateKey(path, file)
return nil
})
// starting the sftp server
err = sftpServer.TryListenAndServe(time.Second)
if err != nil {
logger.Error("Error starting sftp server", "error", err)
return
}
logger.Info("SFTP server started", "port", env.SftpAddr)
// http file server support read and write and delete files
router := http.NewServeMux()
// add mime types
addMimTypes()
router.Handle("/static/{pathname...}", httphandler.NewFileServerHandler("/static", localFS, u))
httpServer := &httphandler.Server{
Server: &http.Server{
Addr: os.Getenv("HTTP_SERVER_ADDR"),
Handler: router,
},
}
router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "<html><body>")
fmt.Fprintf(w, "<h1>Welcome to the filesystem server</h1>")
fmt.Fprintf(w, `<h2>file server is at <a href="/static">/static</a></h2>`)
fmt.Fprintf(w, "</body></html>")
})
// try is the same of listen and serve but with a timeout if no error is returned it returns nil
err = httpServer.TryListenAndServe(time.Second)
if err != nil {
logger.Error("Error starting http server", "error", err)
}
// https server
httpsServer := &httphandler.Server{
Server: &http.Server{
Addr: os.Getenv("HTTPS_SERVER_ADDR"),
Handler: router,
}}
err = httpsServer.TryListenAndServeTLS(env.CrtFile, env.KeyFile, time.Second)
if err != nil {
logger.Error("Error starting https server", "error", err)
}
// graceful shutdown all servers
stopChan := make(chan os.Signal, 1)
signal.Notify(stopChan, os.Interrupt)
<-stopChan
ftpServer.Close(fmt.Errorf("ftp server closed by signal"))
ftpsServer.Close(fmt.Errorf("ftps server closed by signal"))
sftpServer.Close()
ctx, cancel := context.WithTimeoutCause(context.Background(), 5*time.Second, fmt.Errorf("http server closed by signal"))
defer cancel()
httpServer.Shutdown(ctx)
httpsServer.Shutdown(ctx)
}
func setupLogger() *slog.Logger {
logLevel := slog.LevelInfo
AddSource := false
switch os.Getenv("LOG_LEVEL") {
case "DEBUG":
logLevel = slog.LevelDebug
AddSource = true
case "INFO":
logLevel = slog.LevelInfo
case "WARN":
logLevel = slog.LevelWarn
case "ERROR":
logLevel = slog.LevelError
}
handlerOptions := &tint.Options{
AddSource: AddSource,
Level: logLevel, // Only log messages of level INFO and above
ReplaceAttr: nil,
}
handler := tint.NewHandler(os.Stdout, handlerOptions)
logger := slog.New(handler).With("app", "filesystem-server")
logger.Handler()
logger.Info("Logger initialized", "level", logLevel)
return logger
}
// GetUsers returns a new ftp.Users with the default user
func GetUsers(logger *slog.Logger) *users.LocalUsers {
Users := users.NewLocalUsers(logger)
// load the default user
DefaultUser := os.Getenv("DEFAULT_USER")
DefaultPass := os.Getenv("DEFAULT_PASS")
DefaultIp := os.Getenv("DEFAULT_IP")
DefaultIps := strings.Split(DefaultIp, ",")
logger.Debug("DEFAULT_USER is", "username", DefaultUser)
logger.Debug("DEFAULT_PASS is", "password", DefaultPass)
logger.Debug("DEFAULT_IP is", "Allowed form origin IPs", DefaultIp)
if DefaultUser == "" || DefaultPass == "" {
logger.Info("DEFAULT_USER or DEFAULT_PASS is empty, not creating default user")
return Users
}
user1 := Users.Add(DefaultUser, DefaultPass)
for _, ip := range DefaultIps {
if ip == "" {
continue
}
user1.AddIP(strings.Trim(ip, " \n\r\t"))
}
return Users
}
// Environment is the environment of the server
type Environment struct {
FtpAddr string
FtpsAddr string
SftpAddr string
CrtFile string
KeyFile string
FtpServerIPv4 string
FtpServerRoot string
PasvMinPort int
PasvMaxPort int
}
// GetEnv returns a new Environment with the environment variables
func GetEnv(logger *slog.Logger) (env *Environment, err error) {
env = &Environment{}
// this is the bublic ip of the server FOR PASV mode
env.FtpServerIPv4 = os.Getenv("FTP_SERVER_IPV4")
if env.FtpServerIPv4 == "" {
// Set a default FTP_SERVER_IPV4 if the environment variable is not set
fmt.Println("FTP_SERVER_IPV4 was empty so Getting public ip from ipify.org...")
env.FtpServerIPv4, err = ftp.GetServerPublicIP()
if err != nil {
return nil, fmt.Errorf("error getting public ip: %w", err)
}
// Set a default port if the environment variable is not set
}
env.FtpAddr = os.Getenv("FTP_SERVER_ADDR")
env.FtpsAddr = os.Getenv("FTPS_SERVER_ADDR")
env.SftpAddr = os.Getenv("SFTP_SERVER_ADDR")
env.FtpServerRoot = os.Getenv("FTP_SERVER_ROOT")
logger.Debug("FTP_SERVER_ADDR is", "ADDR", env.FtpAddr)
logger.Debug("FTPS_SERVER_ADDR is", "ADDR", env.FtpsAddr)
logger.Debug("FTP_SERVER_IPV4 is", "IP", env.FtpServerIPv4)
logger.Debug("FTP_SERVER_ROOT is", "ROOT", env.FtpServerRoot)
// convert port string to int
env.PasvMinPort, _ = strconv.Atoi(os.Getenv("PASV_MIN_PORT"))
env.PasvMaxPort, _ = strconv.Atoi(os.Getenv("PASV_MAX_PORT"))
logger.Debug("PASV_MIN_PORT is", "PORT", env.PasvMinPort)
logger.Debug("PASV_MAX_PORT is", "PORT", env.PasvMaxPort)
// load the crt and key files
env.CrtFile = os.Getenv("CRT_FILE")
logger.Debug("CRT_FILE is ", "file", env.CrtFile)
env.KeyFile = os.Getenv("KEY_FILE")
logger.Debug("KEY_FILE is ", "file", env.KeyFile)
return
}
func addMimTypes() {
mime.AddExtensionType(".wav", "audio/wave")
mime.AddExtensionType(".wav", "audio/wav")
}