-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.go
241 lines (213 loc) · 5.88 KB
/
server.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
package server
import (
"bufio"
"crypto/tls"
"net"
"strconv"
"strings"
)
func Version() string {
return "0.2.1105"
}
// serverOpts contains parameters for server.NewServer()
type ServerOpts struct {
// The factory that will be used to create a new FTPDriver instance for
// each client connection. This is a mandatory option.
Factory DriverFactory
Auth Auth
// Server Name, Default is Go Ftp Server
Name string
// The hostname that the FTP server should listen on. Optional, defaults to
// "::", which means all hostnames on ipv4 and ipv6.
Hostname string
// The port that the FTP should listen on. Optional, defaults to 3000. In
// a production environment you will probably want to change this to 21.
Port int
// use tls, default is false
TLS bool
// if tls used, cert file is required
CertFile string
// if tls used, key file is required
KeyFile string
WelcomeMessage string
}
// Server is the root of your FTP application. You should instantiate one
// of these and call ListenAndServe() to start accepting client connections.
//
// Always use the NewServer() method to create a new Server.
type Server struct {
*ServerOpts
name string
listenTo string
driverFactory DriverFactory
logger *Logger
listener net.Listener
}
// serverOptsWithDefaults copies an ServerOpts struct into a new struct,
// then adds any default values that are missing and returns the new data.
func serverOptsWithDefaults(opts *ServerOpts) *ServerOpts {
var newOpts ServerOpts
if opts == nil {
opts = &ServerOpts{}
}
if opts.Hostname == "" {
newOpts.Hostname = "::"
} else {
newOpts.Hostname = opts.Hostname
}
if opts.Port == 0 {
newOpts.Port = 3000
} else {
newOpts.Port = opts.Port
}
newOpts.Factory = opts.Factory
if opts.Name == "" {
newOpts.Name = "Go FTP Server"
} else {
newOpts.Name = opts.Name
}
if opts.WelcomeMessage == "" {
newOpts.WelcomeMessage = defaultWelcomeMessage
} else {
newOpts.WelcomeMessage = opts.WelcomeMessage
}
if opts.Auth != nil {
newOpts.Auth = opts.Auth
}
newOpts.TLS = opts.TLS
newOpts.KeyFile = opts.KeyFile
newOpts.CertFile = opts.CertFile
return &newOpts
}
// NewServer initialises a new FTP server. Configuration options are provided
// via an instance of ServerOpts. Calling this function in your code will
// probably look something like this:
//
// factory := &MyDriverFactory{}
// server := server.NewServer(&server.ServerOpts{ Factory: factory })
//
// or:
//
// factory := &MyDriverFactory{}
// opts := &server.ServerOpts{
// Factory: factory,
// Port: 2000,
// Hostname: "127.0.0.1",
// }
// server := server.NewServer(opts)
//
func NewServer(opts *ServerOpts) *Server {
opts = serverOptsWithDefaults(opts)
s := new(Server)
s.ServerOpts = opts
s.listenTo = buildTcpString(opts.Hostname, opts.Port)
s.name = opts.Name
s.driverFactory = opts.Factory
s.logger = newLogger("")
return s
}
// NewConn constructs a new object that will handle the FTP protocol over
// an active net.TCPConn. The TCP connection should already be open before
// it is handed to this functions. driver is an instance of FTPDriver that
// will handle all auth and persistence details.
func (server *Server) newConn(tcpConn net.Conn, driver Driver, auth Auth) *Conn {
c := new(Conn)
c.namePrefix = "/"
c.conn = tcpConn
c.controlReader = bufio.NewReader(tcpConn)
c.controlWriter = bufio.NewWriter(tcpConn)
c.driver = driver
c.auth = auth
c.server = server
c.sessionId = newSessionId()
c.logger = newLogger(c.sessionId)
return c
}
func simpleTLSConfig(certFile, keyFile string) (*tls.Config, error) {
config := &tls.Config{}
if config.NextProtos == nil {
config.NextProtos = []string{"ftp"}
}
var err error
config.Certificates = make([]tls.Certificate, 1)
config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return nil, err
}
return config, nil
}
// ListenAndServe asks a new Server to begin accepting client connections. It
// accepts no arguments - all configuration is provided via the NewServer
// function.
//
// If the server fails to start for any reason, an error will be returned. Common
// errors are trying to bind to a privileged port or something else is already
// listening on the same port.
//
func (Server *Server) ListenAndServe() error {
/*laddr, err := net.ResolveTCPAddr("tcp", Server.listenTo)
if err != nil {
return err
}*/
var listener net.Listener
var err error
//fmt.Println("-------", *Server.ServerOpts)
if Server.ServerOpts.TLS {
//fmt.Println("use tls")
config, err := simpleTLSConfig(Server.CertFile, Server.KeyFile)
if err != nil {
return err
}
listener, err = tls.Listen("tcp", Server.listenTo, config)
} else {
listener, err = net.Listen("tcp", Server.listenTo)
}
if err != nil {
return err
}
Server.logger.Printf("%s listening on %d", Server.Name, Server.Port)
Server.listener = listener
for {
tcpConn, err := Server.listener.Accept()
if err != nil {
Server.logger.Printf("listening error: %v", err)
tcpConn.Close()
break
}
driver, err := Server.driverFactory.NewDriver()
if err != nil {
Server.logger.Printf("Error creating driver, aborting client connection: %v", err)
tcpConn.Close()
} else {
ftpConn := Server.newConn(tcpConn, driver, Server.Auth)
go ftpConn.Serve()
}
}
return nil
}
// Gracefully stops a server. Already connected clients will retain their connections
func (Server *Server) Shutdown() error {
if Server.listener != nil {
return Server.listener.Close()
}
// server wasnt even started
return nil
}
func buildTcpString(hostname string, port int) (result string) {
if strings.Contains(hostname, ":") {
// ipv6
if port == 0 {
result = "[" + hostname + "]"
} else {
result = "[" + hostname + "]:" + strconv.Itoa(port)
}
} else {
// ipv4
if port == 0 {
result = hostname
} else {
result = hostname + ":" + strconv.Itoa(port)
}
}
return
}