19
19
import datetime
20
20
21
21
import logging
22
- import logging . handlers
23
- # # TODO: replace print by logger
22
+
23
+ logger = logging . getLogger ( 'd4-pyclient' )
24
24
25
25
def generate_uuid (filename ):
26
26
sensor_uuid = str (uuid .uuid4 ())
@@ -63,8 +63,6 @@ def pack_d4_data(version, type, sensor_uuid, hmac_key, data, destination):
63
63
d4_header = create_d4_header (version , type , sensor_uuid , hmac_key , data )
64
64
d4_data = d4_header + data
65
65
66
- print (data )
67
-
68
66
# Send data
69
67
send_d4_data (destination , d4_data )
70
68
@@ -77,7 +75,8 @@ def send_d4_data(destination, d4_data):
77
75
78
76
def get_config_from_file (filename , r_type = 'str' ):
79
77
if not os .path .isfile (filename ):
80
- print ('error config file not found' )
78
+ logger .error ('config file not found: {}' .format (filename ))
79
+ sys .exit (1 )
81
80
82
81
with open (filename , 'r' ) as f :
83
82
config = f .read ()
@@ -88,7 +87,8 @@ def get_config_from_file(filename, r_type='str'):
88
87
try :
89
88
config = int (config )
90
89
except :
91
- print ('error config file, invalid type' )
90
+ logger .error ('config file: {}, invalid type' .format (filename ))
91
+ sys .exit (1 )
92
92
else :
93
93
config = config .encode ()
94
94
return config
@@ -107,7 +107,8 @@ def get_sensor_uuid(config_dir):
107
107
108
108
def load_config (config_dir ):
109
109
if not os .path .isdir (config_dir ):
110
- print ('error config file not found' )
110
+ logger .error ('This config directory is invalid: {},' .format (filename ))
111
+ sys .exit (1 )
111
112
112
113
# HMAC Key
113
114
dict_config = {}
@@ -117,26 +118,30 @@ def load_config(config_dir):
117
118
filename = os .path .join (config_dir , 'type' )
118
119
dict_config ['type' ] = get_config_from_file (filename , r_type = 'int' )
119
120
if dict_config ['type' ] < 0 and dict_config ['type' ] > 255 :
120
- print ('error, unsuported type' )
121
+ logger .error ('unsuported d4 type: {}' .format (dict_config ['type' ]))
122
+ sys .exit (1 )
121
123
122
124
filename = os .path .join (config_dir , 'version' )
123
125
dict_config ['version' ] = get_config_from_file (filename , r_type = 'int' )
124
126
if dict_config ['version' ] < 0 :
125
- print ('error, unsuported type' )
127
+ logger .error ('invalid version: {}' .format (dict_config ['version' ]))
128
+ sys .exit (1 )
126
129
127
130
filename = os .path .join (config_dir , 'snaplen' )
128
131
dict_config ['snaplen' ] = get_config_from_file (filename , r_type = 'int' )
129
- if dict_config ['snaplen' ] < 0 :
130
- print ('error, unsuported type' )
132
+ if dict_config ['snaplen' ] <= 0 :
133
+ logger .error ('invalid snaplen' )
134
+ sys .exit (1 )
131
135
132
136
# Sensor UUID
133
137
dict_config ['uuid' ] = get_sensor_uuid (config_dir )
134
138
return dict_config
135
139
136
- def get_destination (config_dir , verify_cert = True ):
140
+ def get_destination (config_dir , check_certificate = True ):
137
141
filename = os .path .join (config_dir , 'destination' )
138
142
if not os .path .isfile (filename ):
139
- print ('error destination file not found' )
143
+ logger .error ('destination file not found: {}' .format (filename ))
144
+ sys .exit (1 )
140
145
141
146
with open (filename , 'r' ) as f :
142
147
destination = f .read ().replace ('\n ' , '' )
@@ -147,13 +152,15 @@ def get_destination(config_dir, verify_cert=True):
147
152
else :
148
153
if not ':' in destination :
149
154
# port = 80 ?
150
- print ('error, destination' )
155
+ logger .error ('The destination is invalid' )
156
+ sys .exit (1 )
151
157
host , port = destination .rsplit (':' , 1 )
152
158
# verify port
153
159
try :
154
160
port = int (port )
155
161
except :
156
- print ('error, invalid port' )
162
+ logger .error ('Invalid port' )
163
+ sys .exit (1 )
157
164
# verify address
158
165
try :
159
166
host = str (ipaddress .ip_address (host ))
@@ -163,8 +170,8 @@ def get_destination(config_dir, verify_cert=True):
163
170
try :
164
171
host = socket .gethostbyname (host )
165
172
except :
166
- print ('Destination Host: Name or service not known' )
167
- print ( host )
173
+ logger . error ('Destination Host: Name or service not known' )
174
+ sys . exit ( 1 )
168
175
169
176
s = socket .socket (socket .AF_INET , socket .SOCK_STREAM )
170
177
# TCP Keepalive
@@ -173,11 +180,8 @@ def get_destination(config_dir, verify_cert=True):
173
180
s .setsockopt (socket .IPPROTO_TCP , socket .TCP_KEEPIDLE , 15 )
174
181
s .setsockopt (socket .IPPROTO_TCP , socket .TCP_KEEPINTVL , 15 )
175
182
176
- ## TODO: add flag
177
- verify_cert = False
178
-
179
183
# SSL
180
- if verify_cert :
184
+ if check_certificate :
181
185
cert_reqs_option = ssl .CERT_REQUIRED
182
186
else :
183
187
cert_reqs_option = ssl .CERT_NONE
@@ -187,39 +191,34 @@ def get_destination(config_dir, verify_cert=True):
187
191
try :
188
192
client_socket .connect ((host , port ))
189
193
except ConnectionRefusedError :
190
- print ( 'error, Connection to {}:{} refused' .format (host , port ))
194
+ logger . error ( ' Connection to {}:{} refused' .format (host , port ))
191
195
sys .exit (1 )
192
196
except ssl .SSLError as e :
193
- print (e )
197
+ logger . error (e )
194
198
sys .exit (1 )
195
199
return client_socket
196
200
197
201
198
202
def get_metaheader_json (config_dir ):
199
203
filename = os .path .join (config_dir , 'metaheader.json' )
200
204
if not os .path .isfile (filename ):
201
- print ('error metaheader file not found' )
205
+ logger .error ('Metaheader file not found: {}' .format (filename ))
206
+ sys .exit (1 )
202
207
203
208
with open (filename , 'rb' ) as f :
204
209
metaheader = f .read ()
205
210
try :
206
211
metaheader = json .loads (metaheader )
207
212
except :
208
- print ('error, invalid json file' )
213
+ logger .error ('The JSON file is invalid' )
214
+ sys .exit (1 )
209
215
return json .dumps (metaheader ).encode ()
210
216
211
- if __name__ == "__main__" :
212
- parser = argparse .ArgumentParser ()
213
- parser .add_argument ('-c' , '--config' ,help = 'config_directory' ,type = str , dest = 'config' , required = True )
214
- args = parser .parse_args ()
215
- config_dir = args .config
216
-
217
+ def read_and_send_data (config_dir , check_certificate ):
217
218
config = load_config (config_dir )
218
- destination = get_destination (config_dir )
219
+ destination = get_destination (config_dir , check_certificate = check_certificate )
219
220
220
221
buffer = b''
221
- # config['type'] = 2
222
- config ['snaplen' ] = 64
223
222
224
223
# handle extended type
225
224
if config ['type' ] == 2 or config ['type' ] == 254 :
@@ -234,18 +233,28 @@ def get_metaheader_json(config_dir):
234
233
try :
235
234
for data in io .open (sys .stdin .fileno (), mode = 'rb' , buffering = 0 ):
236
235
237
- print (data )
238
-
239
236
if data :
240
237
buffer = buffer + data
241
238
buffer = prepare_data (config ['version' ], config ['type' ], config ['uuid' ], config ['key' ], config ['snaplen' ], buffer , destination )
242
239
243
240
pack_d4_data (config ['version' ], config ['type' ], config ['uuid' ], config ['key' ], buffer , destination )
244
- destination .close ()
241
+ if not isinstance (destination , str ):
242
+ destination .shutdown (socket .SHUT_RDWR )
245
243
246
244
# Send buffer content
247
245
except KeyboardInterrupt :
248
246
# Pack data
249
247
buffer = prepare_data (config ['version' ], config ['type' ], config ['uuid' ], config ['key' ], config ['snaplen' ], buffer , destination )
250
248
pack_d4_data (config ['version' ], config ['type' ], config ['uuid' ], config ['key' ], buffer , destination )
251
- destination .close ()
249
+ if not isinstance (destination , str ):
250
+ destination .shutdown (socket .SHUT_RDWR )
251
+
252
+ if __name__ == "__main__" :
253
+ parser = argparse .ArgumentParser ()
254
+ parser .add_argument ('-c' , '--config' ,help = 'config directory' ,type = str , dest = 'config' , required = True )
255
+ parser .add_argument ('-cc' , '--check_certificate' ,help = 'check server certificate' , action = "store_true" )
256
+ args = parser .parse_args ()
257
+ config_dir = args .config
258
+ check_certificate = args .check_certificate
259
+
260
+ read_and_send_data (config_dir , check_certificate )
0 commit comments