-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathftp_server.go
executable file
·385 lines (322 loc) · 7.09 KB
/
ftp_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
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
package main
import (
"bytes"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"github.com/Unknwon/log"
"io/ioutil"
"net"
"os"
"path/filepath"
"runtime"
"strings"
)
const (
UploadCommond = "upload"
DownloadCommond = "download"
ShowCommond = "show"
SearchCommond = "search"
OperationSecOffset = 16
FileNameSecOffset = 256 + OperationSecOffset
FileSizeSecOffset = 8 + FileNameSecOffset
)
var UploadDir string
func GetValidByte(src []byte) []byte {
var str_buf []byte
for _, v := range src {
if v != 0 {
str_buf = append(str_buf, v)
} else {
break
}
}
return str_buf
}
func convertToFileNames(fileNames []byte) []string {
var fileList []string
var startIndex int = 0
for i, v := range fileNames {
if v != 0 {
if v == 10 {
fileList = append(fileList, string(fileNames[startIndex:i]))
startIndex = i + 1
}
} else {
break
}
}
return fileList
}
func getFilePath(rootDir, file string) string {
var filePath string
filepath.Walk(rootDir, func(path string, f os.FileInfo, err error) error {
if f == nil {
log.Error(err.Error())
return err
}
if f.IsDir() {
return nil
}
//log.Debug("%v", path)
if f.Name() == file {
//log.Debug("Find it!")
filePath, _ = filepath.Rel(rootDir, path)
return errors.New("Found it!")
}
return nil
})
return filePath
}
func BytesToInt64(b []byte) int64 {
bytesBuffer := bytes.NewBuffer(b)
var tmp int64
binary.Read(bytesBuffer, binary.BigEndian, &tmp)
return int64(tmp)
}
func Int64ToBytes(n int64) []byte {
tmp := int64(n)
bytesBuffer := bytes.NewBuffer([]byte{})
binary.Write(bytesBuffer, binary.BigEndian, tmp)
return bytesBuffer.Bytes()
}
func GetDir(fullPath string) string {
lastIndex := strings.LastIndex(fullPath, "/")
runes := []rune(fullPath)
l := lastIndex
if lastIndex > len(runes) {
l = len(runes)
}
return string(runes[0 : l+1])
}
func uploadFile(conn net.Conn, name string, size int64) error {
fmt.Println("file name =", name, ", size =", size)
_, err := os.Stat(UploadDir)
if err != nil {
if os.IsNotExist(err) {
err := os.MkdirAll(UploadDir, os.ModePerm)
if err != nil {
log.Error(err.Error())
return err
}
}
}
var f *os.File
f, err = os.Create(UploadDir + name)
if err != nil {
log.Error(err.Error())
return err
}
defer f.Close()
var buf []byte
if size <= 1024 {
buf = make([]byte, size)
} else {
buf = make([]byte, 1024)
}
var n int = 0
var offset int64 = 0
for {
n, err = conn.Read(buf)
if err != nil {
log.Error(err.Error())
return err
}
//fmt.Println("read data size =", n, ", data =", buf)
_, err = f.Seek(offset, 0)
if err != nil {
log.Error("Seek fail!")
return err
}
_, err = f.Write(buf[0:n])
if err != nil {
log.Error(err.Error())
return err
}
offset += int64(n)
if offset >= size {
break
}
}
return nil
}
func downloadFile(conn net.Conn, name string) error {
fmt.Println("file name =", name)
fileInfo, err := os.Stat(UploadDir + name)
if err != nil {
log.Error(err.Error())
return err
}
if fileInfo.IsDir() {
log.Error("This is a directory!")
return err
}
buf := make([]byte, 1024)
//send file size
copy(buf[0:], Int64ToBytes(fileInfo.Size()))
_, err = conn.Write(buf)
if err != nil {
log.Error(err.Error())
return err
}
//send file data
var f *os.File
f, err = os.Open(UploadDir + name)
if err != nil {
log.Error(err.Error())
return err
}
defer f.Close()
var oneFileSectionSize int64 = 1024
var fileSectionCount int64 = 0
fileSize := fileInfo.Size()
if fileSize%oneFileSectionSize != 0 {
fileSectionCount = fileSize/oneFileSectionSize + 1
} else {
fileSectionCount = fileSize / oneFileSectionSize
}
log.Debug("file size = %v, file section count = %v.", fileSize, fileSectionCount)
var n int = 0
for i := int64(0); i < fileSectionCount; i++ {
_, err = f.Seek(i*oneFileSectionSize, 0)
if err != nil {
log.Error("Seek fail!")
return err
}
n, err = f.Read(buf)
if err != nil {
log.Error(err.Error())
return err
}
//fmt.Println("data =", buf[0:n])
//time.Sleep(10 * time.Millisecond)
_, err = conn.Write(buf[0:n])
if err != nil {
log.Error(err.Error())
return err
}
}
return nil
}
func showFile(conn net.Conn) error {
buf := make([]byte, 0, 1024)
//send file list
files, err := ioutil.ReadDir(UploadDir)
if err != nil {
log.Error(err.Error())
return err
}
for _, file := range files {
buf = append(buf, []byte(file.Name())...)
buf = append(buf, []byte("\n")...)
}
fmt.Println(string(buf))
_, err = conn.Write(buf)
if err != nil {
log.Error(err.Error())
return err
}
return nil
}
func searchFiles(conn net.Conn, fileList []string) error {
fileMap := make(map[string]string)
for _, file := range fileList {
fileMap[file] = getFilePath(UploadDir, file)
}
fileJson, err := json.Marshal(fileMap)
fmt.Println(string(fileJson))
var n int
n, err = conn.Write(fileJson)
if err != nil {
log.Error(err.Error())
return err
}
fmt.Printf("Send %v size data.", n)
return nil
}
func handleConn(conn net.Conn) {
defer conn.Close()
log.Debug("Net = %v, Addr = %v.", conn.LocalAddr().Network(), conn.LocalAddr().String())
log.Debug("Remote net = %v, Remote addr = %v.", conn.RemoteAddr().Network(), conn.RemoteAddr().String())
var n int = 0
buf := make([]byte, 1024)
n, err := conn.Read(buf)
if err != nil {
log.Error(err.Error())
return
}
if n < FileSizeSecOffset {
log.Error("Read bytes too little!")
return
}
var op string = string(GetValidByte(buf[0:OperationSecOffset]))
switch op {
case UploadCommond:
fmt.Println("Operation is upload.")
fileName := string(GetValidByte(buf[OperationSecOffset:FileNameSecOffset]))
fileSize := BytesToInt64(buf[FileNameSecOffset:FileSizeSecOffset])
err = uploadFile(conn, fileName, fileSize)
if err != nil {
log.Error(err.Error())
}
return
case DownloadCommond:
fmt.Println("Operation is download.")
filePath := string(GetValidByte(buf[OperationSecOffset:FileNameSecOffset]))
err = downloadFile(conn, filePath)
if err != nil {
log.Error(err.Error())
}
return
case ShowCommond:
fmt.Println("Operation is show.")
err = showFile(conn)
if err != nil {
log.Error(err.Error())
}
return
case SearchCommond:
fmt.Println("Operation is search.")
fileNames := convertToFileNames(buf[OperationSecOffset:])
err = searchFiles(conn, fileNames)
if err != nil {
log.Error(err.Error())
}
return
default:
fmt.Println("Unknown operation!")
return
}
}
func ftpServerInit() {
if runtime.GOOS == "windows" {
UploadDir = "D:\\filetransferdir\\"
} else {
if home := os.Getenv("HOME"); home != "" {
UploadDir = home + "/filetransferdir/"
} else {
UploadDir = "/filetransferdir/"
}
}
log.Debug("UploadDir = %v", UploadDir)
}
func main() {
ftpServerInit()
ln, err := net.Listen("tcp", ":1263")
if err != nil {
log.Error(err.Error())
return
}
defer ln.Close()
log.Debug("Net = %v, Addr = %v.", ln.Addr().Network(), ln.Addr().String())
for {
log.Debug("New connection!")
conn, err := ln.Accept()
if err != nil {
log.Error(err.Error())
return
}
go handleConn(conn)
}
}