-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
197 lines (156 loc) · 5.96 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
// Copyright (c) 2019 Alberto Bregliano
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
package main
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"flag"
"io/ioutil"
"log"
"net/http"
"os"
"time"
"github.com/axamon/hermes/hasher"
)
// seed per avere risutati hash personalizzati
const seed = "vvkidtbcjujhgffbjnvrngvrinvufjkvljreucecvfcj"
var timout = flag.Int64("timeout", 3, "tempo massimo per effettuare upload di un file")
var userid = flag.String("user", "pippo", "username")
var password = flag.String("pass", "pippo", "password")
var remoteAddr = flag.String("r", "127.0.0.1:8080", "default 127.0.0.1:8080")
var file = flag.String("file", "", "no default")
type info struct {
Name string `json:"name"`
Data string `json:"data"`
Hash string `json:"hash"`
}
func main() {
flag.Parse()
// Crea il contesto padre.
ctx, cancelmain := context.WithCancel(context.Background())
defer cancelmain()
// Recupera dal flag il file da inviare.
filedainviare := *file
// Verifica che il file esista.
fi, err := os.Stat(filedainviare)
if err != nil {
log.Printf("ERROR file %s non trovato: %s\n", filedainviare, err.Error())
return
}
// Dimensione file in MB.
sizefile := fi.Size() / 1024 / 1024
// Se il file è più grande di MB esce.
maxsize := int64(200)
if sizefile > maxsize {
log.Printf("ERROR Le dimensioni del file %s superano il livello massimo: %v > %d MB\n", filedainviare, sizefile, maxsize)
return
}
// Verifica che il server di upload remoto sia raggiungibile.
// testConn, err := net.DialTimeout("tcp", *remoteAddr, time.Duration(3*time.Second))
// if err != nil {
// log.Printf("Server remoto non raggiungibile, error: %s\n", err.Error())
// //return
// }
// Forza la chiusura della connessione di test.
//testConn.Close()
// fmt.Println(*remoteAddr) // debug
// Crea la URL da contattare con l'endpoint specifico per l'upload.
remoteURL := "https://" + *remoteAddr + "/upload" // ! TODO CAMBIARE IN HTTPS
// Imposta il timeout della connessione recuperandolo dal flag.
timeout := time.Duration(*timout) * time.Second
// Avvia l'upload del file.
err = upload(ctx, remoteURL, filedainviare, timeout)
if err != nil {
log.Printf("ERROR upload file %s non riuscito: %s\n", filedainviare, err.Error())
}
return
}
func upload(ctx context.Context, url, filedainviare string, timeout time.Duration) (err error) {
//! timeout Massimo tempo per terminare upload del file
ctx, cancelUpload := context.WithTimeout(ctx, timeout)
defer cancelUpload()
select {
// Se impiega troppo tempo.
case <-ctx.Done():
log.Printf("ERROR Ecceduto tempo massimo per upload file: %s\n", ctx.Err()) // prints "context deadline exceeded"
return
// Se tutto procede come si deve.
default:
// Apre file da inviare, non importa se zippato o meno.
file, err := os.Open(filedainviare)
if err != nil {
log.Printf("ERROR Impossible aprire file: %s errore: %s\n", filedainviare, err.Error())
}
defer file.Close()
// Salva il contenuto del file in memoria.
data, err := ioutil.ReadAll(file)
if err != nil {
log.Printf("ERROR Impossibile salvare contenuto file in memeoria: %s\n", err.Error())
}
// Encoda il file in base64.
encoded := base64.StdEncoding.EncodeToString(data)
if err != nil {
log.Printf("ERROR Impossibile encodare il contenuto file: %s\n", err.Error())
}
// Calcola hash del file con seed.
hash, err := hasher.FileWithSeed(filedainviare, seed)
if err != nil {
log.Printf("ERROR Impossibile ricavare hash del file %s: %s\n", filedainviare, err.Error())
}
// log.Println(hash) // debug
// Effettua il marshalling in json dai dati secondo il type info.
kvPairs, err := json.Marshal(info{Name: filedainviare, Data: encoded, Hash: hash})
if err != nil {
log.Printf("ERROR Impossibile efffettuare marshalling del file %s encodato: %s\n", filedainviare, err.Error())
}
// fmt.Printf("Sending JSON string '%s'\n", string(kvPairs)) // debug
// Crea la web request in POST aggiungendo il file encodato.
req, err := http.NewRequest("POST", url, bytes.NewBuffer(kvPairs))
if err != nil {
log.Printf("ERROR Impossibile creare web request di tipo POST: %s\n", err.Error())
}
// Aggiunge il contesto alla richiesta.
req.WithContext(ctx)
// Aggiunge header per processare json.
req.Header.Set("Content-Type", "application/json")
// Aggiunge autenticazione per il server remoto.
req.SetBasicAuth(*userid, *password)
// Crea client http.
client := &http.Client{}
// Invia la web request.
resp, err := client.Do(req)
if err != nil {
log.Println(err.Error(), req.Context().Value("NomeFile"))
return err
}
// Chiude il body della web response come da specifica.
defer resp.Body.Close()
//fmt.Println("Response: ", string(body))
switch resp.StatusCode == 200 {
case true:
log.Printf("INFO File %s trasferito correttamente\n", filedainviare)
case false:
log.Printf("ERROR Trasferimento del file %s non riuscito: %s\n", filedainviare, resp.Status)
}
}
return err
}