-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathftp_client.go
executable file
·457 lines (374 loc) · 7.94 KB
/
ftp_client.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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
package main
import (
"bytes"
"encoding/binary"
"encoding/json"
"fmt"
"github.com/Unknwon/log"
"net"
"os"
"runtime"
"strings"
)
const (
UploadCommond = "upload"
DownloadCommond = "download"
ShowCommond = "show"
SearchCommond = "search"
OperationSecOffset = 16
FileNameSecOffset = 256 + OperationSecOffset
FileSizeSecOffset = 8 + FileNameSecOffset
)
var DownloadDir string
var IPPort string
func Int32ToBytes(n int32) []byte {
tmp := int32(n)
bytesBuffer := bytes.NewBuffer([]byte{})
binary.Write(bytesBuffer, binary.BigEndian, tmp)
return bytesBuffer.Bytes()
}
func Int64ToBytes(n int64) []byte {
tmp := int64(n)
bytesBuffer := bytes.NewBuffer([]byte{})
binary.Write(bytesBuffer, binary.BigEndian, tmp)
return bytesBuffer.Bytes()
}
func BytesToInt32(b []byte) int32 {
bytesBuffer := bytes.NewBuffer(b)
var tmp int32
binary.Read(bytesBuffer, binary.BigEndian, &tmp)
return int32(tmp)
}
func BytesToInt64(b []byte) int64 {
bytesBuffer := bytes.NewBuffer(b)
var tmp int64
binary.Read(bytesBuffer, binary.BigEndian, &tmp)
return int64(tmp)
}
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 GetDir(fullPath string) string {
var lastIndex int = 0
if runtime.GOOS == "windows" {
lastIndex = strings.LastIndex(fullPath, "\\")
} else {
lastIndex = strings.LastIndex(fullPath, "/")
}
runes := []rune(fullPath)
l := lastIndex
if lastIndex > len(runes) {
l = len(runes)
}
return string(runes[0 : l+1])
}
func uploadFile(filePath string, done chan bool) error {
defer func() {
done <- true
}()
fileInfo, err := os.Stat(filePath)
if err != nil {
log.Error("This file not exist! " + err.Error())
return err
}
if fileInfo.IsDir() {
log.Error("This is a directory!")
return nil
}
var conn net.Conn
conn, err = net.Dial("tcp", IPPort)
if err != nil {
log.Error("Dial fail! " + err.Error())
return err
}
defer conn.Close()
buf := make([]byte, 1024)
//file size and name 16 + 256 + 8
copy(buf[0:], []byte(UploadCommond))
copy(buf[OperationSecOffset:], []byte(fileInfo.Name()))
copy(buf[FileNameSecOffset:], Int64ToBytes(fileInfo.Size()))
//fmt.Println(buf)
_, err = conn.Write(buf)
if err != nil {
log.Error(err.Error())
return err
}
//file content
var f *os.File
f, err = os.Open(filePath)
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 section count = %v.", 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
}
_, err = conn.Write(buf[0:n])
if err != nil {
log.Error(err.Error())
return err
}
}
return nil
}
func downloadFile(filePath string, done chan bool) error {
defer func() {
done <- true
}()
var err error
var conn net.Conn
conn, err = net.Dial("tcp", IPPort)
if err != nil {
log.Error("Dial fail! " + err.Error())
return err
}
defer conn.Close()
buf := make([]byte, 1024)
//send file name
copy(buf[0:], []byte(DownloadCommond))
copy(buf[OperationSecOffset:], []byte(filePath))
//fmt.Println(buf)
_, err = conn.Write(buf)
if err != nil {
log.Error(err.Error())
return err
}
var n int = 0
//get file size
n, err = conn.Read(buf)
if err != nil {
log.Error(err.Error())
return err
}
if n < 8 {
log.Error("Can not get file size!")
return err
}
var fullPath string
if runtime.GOOS == "windows" {
fullPath = DownloadDir + strings.Replace(filePath, "/", "\\", -1)
} else {
fullPath = DownloadDir + strings.Replace(filePath, "\\", "/", -1)
}
dir := GetDir(fullPath)
_, err = os.Stat(dir)
if err != nil {
if os.IsNotExist(err) {
err := os.MkdirAll(dir, os.ModePerm)
if err != nil {
log.Error(err.Error())
return err
}
}
}
var f *os.File
f, err = os.Create(fullPath)
if err != nil {
log.Error(err.Error())
return err
}
defer f.Close()
fileSize := BytesToInt64(buf[0:8])
if fileSize <= 1024 {
buf = make([]byte, fileSize)
} else {
buf = make([]byte, 1024)
}
log.Debug("file size = %v", fileSize)
var offset int64 = 0
for {
n, err = conn.Read(buf)
if err != nil {
log.Error(err.Error())
return err
}
//fmt.Println("data =", buf)
//fmt.Println("offset =", offset, ", n =", n)
_, 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 >= fileSize {
break
}
}
return nil
}
func showAllFiles() error {
conn, err := net.Dial("tcp", IPPort)
if err != nil {
log.Error("Dial fail! " + err.Error())
return err
}
defer conn.Close()
buf := make([]byte, 1024)
//file size and name 16 + 256 + 8
copy(buf[0:], []byte(ShowCommond))
//fmt.Println(buf)
_, err = conn.Write(buf)
if err != nil {
log.Error(err.Error())
return err
}
var n int = 0
//get file size
n, err = conn.Read(buf)
if err != nil {
log.Error(err.Error())
return err
}
fmt.Println("n =", n)
fmt.Println(string(GetValidByte(buf)))
return nil
}
func searchFiles(fileNames []string) error {
conn, err := net.Dial("tcp", IPPort)
if err != nil {
log.Error("Dial fail! " + err.Error())
return err
}
defer conn.Close()
buf := make([]byte, 1024)
//file size and name 16 + 256 + 8
copy(buf[0:], []byte(SearchCommond))
var offset int = OperationSecOffset
for _, fileName := range fileNames {
copy(buf[offset:], []byte(fileName))
offset += len(fileName)
if offset >= 1024 {
break
}
copy(buf[offset:], []byte("\n"))
offset += len("\n")
if offset >= 1024 {
break
}
}
_, err = conn.Write(buf)
if err != nil {
log.Error(err.Error())
return err
}
//get json
var n int = 0
n, err = conn.Read(buf)
if err != nil {
log.Error(err.Error())
return err
}
fileJson := buf[0:n]
//fmt.Println("n =", n)
//fmt.Println(string(fileJson))
fileMap := make(map[string]string)
json.Unmarshal(fileJson, &fileMap)
for file := range fileMap {
fmt.Println(file, ":", fileMap[file])
}
return nil
}
func ftpClientInit() {
if runtime.GOOS == "windows" {
DownloadDir = "D:\\download\\"
IPPort = "192.168.195.129:1263"
} else {
if home := os.Getenv("HOME"); home != "" {
DownloadDir = home + "/download/"
} else {
DownloadDir = "/download/"
}
IPPort = "127.0.0.1:1263"
}
log.Debug("DownloadDir = %v", DownloadDir)
log.Debug("IPPort = %v", IPPort)
}
func main() {
ftpClientInit()
args := os.Args[1:]
if len(args) == 0 {
log.Error("Need Args!")
return
}
op := args[0]
//log.Debug("op = %v.", op)
var done chan bool
var filePaths []string
switch op {
case UploadCommond:
if len(args) < 2 {
log.Error("Need file path!")
return
}
filePaths = args[1:]
log.Debug("file path = %v", filePaths)
if len(filePaths) > 0 {
done = make(chan bool, len(filePaths))
}
for _, filePath := range filePaths {
go uploadFile(filePath, done)
}
for i := 0; i < len(filePaths); i++ {
<-done
}
case DownloadCommond:
if len(args) < 2 {
log.Error("Need file path!")
return
}
filePaths = args[1:]
log.Debug("file path = %v", filePaths)
if len(filePaths) > 0 {
done = make(chan bool, len(filePaths))
}
for _, filePath := range filePaths {
go downloadFile(filePath, done)
}
for i := 0; i < len(filePaths); i++ {
<-done
}
case ShowCommond:
showAllFiles()
case SearchCommond:
if len(args) < 2 {
log.Error("Need file name!")
return
}
fileNames := args[1:]
searchFiles(fileNames)
default:
log.Error("Unknown commond!")
}
}