-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection.go
329 lines (267 loc) · 7.46 KB
/
connection.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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
package server
import (
"bufio"
"fmt"
"io"
"log"
"net"
"os"
"time"
"os/signal"
"syscall"
"sync"
"github.com/dnutiu/simplFT/server/config"
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
)
// ConfigPath is used by the config package to find the path of the config file.
var ConfigPath string
// ConfigName is used by the config package to find the config file.
var ConfigName string
// uploadDirectory is the directory where the files will be uploaded
var uploadDirectory string
// uploadTimeout is the amount in seconds the server will wait for a file to be uploaded
var uploadTimeout time.Duration
// uploadEnabled holds true of false, if in the config upload was enabled when the upload server was started.
var uploadEnabled bool
// Shutdown is the shutdown where SIGINT and SIGTERM is send too
var Shutdown = make(chan os.Signal)
var ftpShutdown = make(chan struct{})
var uploadShutdown = make(chan struct{})
var uploadListener net.Listener
var ftpListener net.Listener
// All connected clients
var clients map[Client]bool
// Client interface provides the blueprints for the Client that is used by the server.
type Client interface {
Connection() net.Conn // Connection returns the connection stream.
SetConnection(conn net.Conn) // SetConnection sets the connection for the client.
Disconnect() // Disconnect closes the Client's connections and clears up resources.
Stack() *StringStack // Returns the underlying String Stack.
}
// FTPClient represents a FTPClient connection, it holds a root cage and the underlying connection.
type FTPClient struct {
rootCage *StringStack // rootCage is a StringStack that is used to represent the current directory the client is in.
connection net.Conn
}
// Stack returns the root cage stack.
func (c *FTPClient) Stack() *StringStack {
return c.rootCage
}
// SetStack sets the stack for the FTPClient.
func (c *FTPClient) SetStack(stack *StringStack) {
c.rootCage = stack
}
// Connection returns the Connection of the client.
func (c *FTPClient) Connection() net.Conn {
return c.connection
}
// SetConnection sets the given connection to the client.
func (c *FTPClient) SetConnection(conn net.Conn) {
c.connection = conn
}
// Disconnects the client.
func (c *FTPClient) Disconnect() {
c.connection.Close()
}
func shutdownHandler() {
for {
select {
case <-Shutdown:
log.Println("Shutdown signal received")
var wg sync.WaitGroup
wg.Add(1)
go func() { // Disconnect all the clients.
for k := range clients {
k.Disconnect()
}
wg.Done()
}()
wg.Wait()
ShutdownUploadServer()
ShutdownFtpServer()
return
}
}
}
func ShutdownUploadServer() {
if uploadEnabled == true {
if uploadListener != nil {
uploadListener.Close()
}
uploadShutdown <- struct{}{}
}
}
func ShutdownFtpServer() {
if ftpListener != nil {
ftpListener.Close()
}
ftpShutdown <- struct{}{}
}
func Init() {
signal.Notify(Shutdown, syscall.SIGINT, syscall.SIGTERM)
clients = make(map[Client]bool)
go shutdownHandler()
config.InitializeConfiguration(ConfigName, ConfigPath)
config.ChangeCallback(func(event fsnotify.Event) {
log.Println("Configuration reloaded successfully!")
})
}
func HandleConnection(client Client) {
defer client.Disconnect()
defer func() {
if r := recover(); r != nil {
log.Println("PANIC: ", r)
recoveryError, ok := r.(string)
if ok {
io.WriteString(client.Connection(), fmt.Sprintf("PANIC: %s", recoveryError))
}
}
}()
log.Println(client.Connection().RemoteAddr(), "has connected.")
clients[client] = true
// Process input
input := bufio.NewScanner(client.Connection())
for input.Scan() {
log.Println(client.Connection().RemoteAddr(), ":", input.Text())
err := ProcessInput(client, input.Text())
if err != nil {
log.Println(err)
io.WriteString(client.Connection(), err.Error()+"\n")
}
}
// Client has left.
delete(clients, client)
log.Println(client.Connection().RemoteAddr(), "has disconnected.")
}
func StartFtpServer(wg *sync.WaitGroup) error {
defer wg.Done()
Addr := viper.GetString("address")
Port := viper.GetInt("port")
DirDepth := viper.GetInt("maxDirDepth")
BasePath = viper.GetString("absoluteServePath")
// Start the server
var err error
ftpListener, err = net.Listen("tcp", fmt.Sprintf("%s:%d", Addr, Port))
if err != nil {
log.Fatal(err)
return err
}
defer ftpListener.Close()
log.Println("Hello world!")
log.Println("Ftp server running on:", Addr, "port", Port)
for {
conn, err := ftpListener.Accept()
// Handle shutdown
select {
case <-ftpShutdown:
goto exit
default:
if err != nil {
log.Print(err)
continue
}
client := FTPClient{}
client.SetStack(MakeStringStack(DirDepth))
client.SetConnection(conn)
go HandleConnection(&client)
}
}
exit:
log.Println("Ftp server exited.")
return nil
}
func HandleUpload(conn net.Conn) {
// Initialize Client
client := FTPClient{}
client.SetStack(MakeStringStack(2))
// Upload directory
client.Stack().Push(uploadDirectory)
client.SetConnection(conn)
defer client.Disconnect()
// Create the file on the disk and make sure that the filename is random.
var filename = randSeq(10)
var _, err = os.Stat(MakePathFromStringStack(client.Stack()) + filename)
for !os.IsNotExist(err) {
filename = randSeq(10)
_, err = os.Stat(MakePathFromStringStack(client.Stack()) + filename)
}
// This channel will be used to store the uploadResult
c1 := make(chan error, 1)
log.Println(conn.RemoteAddr().String() + " is uploading something.")
clients[&client] = true
// Create a new Go routine for uploading
go func() {
err := UploadFile(&client, filename)
c1 <- err
}()
// Wait for either UploadResult or Timeout
select {
case result := <-c1:
{
if result == nil {
io.WriteString(conn, filename)
log.Println(conn.RemoteAddr().String() + "'s upload finished.")
} else {
log.Println(fmt.Sprintf("%s: %s %s", "HandleUpload", conn.RemoteAddr().String(), result.Error()))
client.Stack().Push(filename)
os.Remove(MakePathFromStringStack(client.Stack()))
io.WriteString(conn, result.Error())
}
conn.Close()
}
case <-time.After(time.Second * uploadTimeout):
{
io.WriteString(conn, "Timeout")
conn.Close()
}
}
delete(clients, &client)
}
// StartUploadServer starts the uploading server
func StartUploadServer(wg *sync.WaitGroup) error {
defer wg.Done()
var err error
uploadEnabled = viper.GetBool("upload.enabled")
if uploadEnabled == false {
log.Println("Uploading not enabled. To enable modify the config file and restart the server")
return ErrUploadServerFailure
}
addr := viper.GetString("upload.address")
port := viper.GetInt("upload.port")
uploadDirectory = viper.GetString("upload.directory")
uploadTimeout = time.Duration(viper.GetInt("upload.timeout"))
uploadListener, err = net.Listen("tcp", fmt.Sprintf("%s:%d", addr, port))
if err != nil {
log.Println(err)
goto exit
}
defer uploadListener.Close()
err = os.Mkdir(BasePath+"/"+uploadDirectory, 0740)
if err != nil {
if _, err := os.Stat(BasePath + "/" + uploadDirectory); err != nil {
if os.IsNotExist(err) {
log.Println("Can't create upload directory!")
goto exit
}
}
}
log.Println("Upload server running on:", addr, "port", port)
for {
conn, err := uploadListener.Accept()
// Handle shutdown
select {
case <-uploadShutdown:
goto exit
default:
if err != nil {
log.Print(err)
continue
}
go HandleUpload(conn)
}
}
exit:
log.Println("Upload server exited.")
return nil
}