interface.debug flag
[electrum-nvc.git] / lib / interface.py
1 #!/usr/bin/env python
2 #
3 # Electrum - lightweight Bitcoin client
4 # Copyright (C) 2011 thomasv@gitorious
5 #
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18
19
20 import random, ast, re, errno, os
21 import threading, traceback, sys, time, json, Queue
22 import socks
23 import socket
24 import ssl
25
26 from version import ELECTRUM_VERSION, PROTOCOL_VERSION
27 from util import print_error, print_msg
28 from simple_config import SimpleConfig
29
30
31 DEFAULT_TIMEOUT = 5
32 proxy_modes = ['socks4', 'socks5', 'http']
33
34
35 def check_cert(host, cert):
36     from OpenSSL import crypto as c
37     _cert = c.load_certificate(c.FILETYPE_PEM, cert)
38
39     m = "host: %s\n"%host
40     m += "has_expired: %s\n"% _cert.has_expired()
41     m += "pubkey: %s bits\n" % _cert.get_pubkey().bits()
42     m += "serial number: %s\n"% _cert.get_serial_number() 
43     #m += "issuer: %s\n"% _cert.get_issuer()
44     #m += "algo: %s\n"% _cert.get_signature_algorithm() 
45     m += "version: %s\n"% _cert.get_version()
46     print_msg(m)
47
48
49 def cert_has_expired(cert_path):
50     try:
51         import OpenSSL
52     except:
53         print_error("Warning: cannot import OpenSSL")
54         return False
55     from OpenSSL import crypto as c
56     with open(cert_path) as f:
57         cert = f.read()
58     _cert = c.load_certificate(c.FILETYPE_PEM, cert)
59     return _cert.has_expired()
60
61
62 def check_certificates():
63     config = SimpleConfig()
64     mydir = os.path.join(config.path, "certs")
65     certs = os.listdir(mydir)
66     for c in certs:
67         print c
68         p = os.path.join(mydir,c)
69         with open(p) as f:
70             cert = f.read()
71         check_cert(c, cert)
72     
73
74 def cert_verify_hostname(s):
75     # hostname verification (disabled)
76     from backports.ssl_match_hostname import match_hostname, CertificateError
77     try:
78         match_hostname(s.getpeercert(True), host)
79         print_error("hostname matches", host)
80     except CertificateError, ce:
81         print_error("hostname did not match", host)
82
83
84
85 class Interface(threading.Thread):
86
87
88     def __init__(self, config=None):
89
90         if config is None:
91             config = SimpleConfig()
92
93         threading.Thread.__init__(self)
94         self.daemon = True
95         self.config = config
96         self.connect_event = threading.Event()
97
98         self.subscriptions = {}
99         self.lock = threading.Lock()
100
101         self.rtime = 0
102         self.bytes_received = 0
103         self.is_connected = False
104         self.poll_interval = 1
105
106         self.debug = False # dump network messages. can be changed at runtime using the console
107
108         #json
109         self.message_id = 0
110         self.unanswered_requests = {}
111         self.pending_transactions_for_notifications= []
112
113         # parse server
114         self.server = config.get('server')
115         host, port, protocol = self.server.split(':')
116         port = int(port)
117             
118         if protocol not in 'ghst':
119             raise BaseException('Unknown protocol: %s'%protocol)
120
121         self.host = host
122         self.port = port
123         self.protocol = protocol
124         self.use_ssl = ( protocol in 'sg' )
125         self.proxy = self.parse_proxy_options(config.get('proxy'))
126         if self.proxy:
127             self.proxy_mode = proxy_modes.index(self.proxy["mode"]) + 1
128
129
130
131
132
133     def queue_json_response(self, c):
134
135         # uncomment to debug
136         if self.debug:
137             print_error( "<--",c )
138
139         msg_id = c.get('id')
140         error = c.get('error')
141         
142         if error:
143             print_error("received error:", c)
144             if msg_id is not None:
145                 with self.lock: 
146                     method, params, callback = self.unanswered_requests.pop(msg_id)
147                 callback(self,{'method':method, 'params':params, 'error':error, 'id':msg_id})
148
149             return
150
151         if msg_id is not None:
152             with self.lock: 
153                 method, params, callback = self.unanswered_requests.pop(msg_id)
154             result = c.get('result')
155
156         else:
157             # notification
158             method = c.get('method')
159             params = c.get('params')
160
161             if method == 'blockchain.numblocks.subscribe':
162                 result = params[0]
163                 params = []
164
165             elif method == 'blockchain.headers.subscribe':
166                 result = params[0]
167                 params = []
168
169             elif method == 'blockchain.address.subscribe':
170                 addr = params[0]
171                 result = params[1]
172                 params = [addr]
173
174             with self.lock:
175                 for k,v in self.subscriptions.items():
176                     if (method, params) in v:
177                         callback = k
178                         break
179                 else:
180                     print_error( "received unexpected notification", method, params)
181                     print_error( self.subscriptions )
182                     return
183
184
185         callback(self, {'method':method, 'params':params, 'result':result, 'id':msg_id})
186
187
188     def on_version(self, i, result):
189         self.server_version = result
190
191
192     def start_http(self):
193         self.session_id = None
194         self.is_connected = True
195         self.connection_msg = ('https' if self.use_ssl else 'http') + '://%s:%d'%( self.host, self.port )
196         try:
197             self.poll()
198         except:
199             print_error("http init session failed")
200             self.is_connected = False
201             return
202
203         if self.session_id:
204             print_error('http session:',self.session_id)
205             self.is_connected = True
206         else:
207             self.is_connected = False
208
209     def run_http(self):
210         self.is_connected = True
211         while self.is_connected:
212             try:
213                 if self.session_id:
214                     self.poll()
215                 time.sleep(self.poll_interval)
216             except socket.gaierror:
217                 break
218             except socket.error:
219                 break
220             except:
221                 traceback.print_exc(file=sys.stdout)
222                 break
223             
224         self.is_connected = False
225
226                 
227     def poll(self):
228         self.send([])
229
230
231     def send_http(self, messages, callback):
232         import urllib2, json, time, cookielib
233         print_error( "send_http", messages )
234         
235         if self.proxy:
236             socks.setdefaultproxy(self.proxy_mode, self.proxy["host"], int(self.proxy["port"]) )
237             socks.wrapmodule(urllib2)
238
239         cj = cookielib.CookieJar()
240         opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
241         urllib2.install_opener(opener)
242
243         t1 = time.time()
244
245         data = []
246         for m in messages:
247             method, params = m
248             if type(params) != type([]): params = [params]
249             data.append( { 'method':method, 'id':self.message_id, 'params':params } )
250             self.unanswered_requests[self.message_id] = method, params, callback
251             self.message_id += 1
252
253         if data:
254             data_json = json.dumps(data)
255         else:
256             # poll with GET
257             data_json = None 
258
259             
260         headers = {'content-type': 'application/json'}
261         if self.session_id:
262             headers['cookie'] = 'SESSION=%s'%self.session_id
263
264         try:
265             req = urllib2.Request(self.connection_msg, data_json, headers)
266             response_stream = urllib2.urlopen(req, timeout=DEFAULT_TIMEOUT)
267         except:
268             return
269
270         for index, cookie in enumerate(cj):
271             if cookie.name=='SESSION':
272                 self.session_id = cookie.value
273
274         response = response_stream.read()
275         self.bytes_received += len(response)
276         if response: 
277             response = json.loads( response )
278             if type(response) is not type([]):
279                 self.queue_json_response(response)
280             else:
281                 for item in response:
282                     self.queue_json_response(item)
283
284         if response: 
285             self.poll_interval = 1
286         else:
287             if self.poll_interval < 15: 
288                 self.poll_interval += 1
289         #print self.poll_interval, response
290
291         self.rtime = time.time() - t1
292         self.is_connected = True
293
294
295
296
297     def start_tcp(self):
298
299         self.connection_msg = self.host + ':%d' % self.port
300
301         if self.proxy is not None:
302
303             socks.setdefaultproxy(self.proxy_mode, self.proxy["host"], int(self.proxy["port"]))
304             socket.socket = socks.socksocket
305             # prevent dns leaks, see http://stackoverflow.com/questions/13184205/dns-over-proxy
306             def getaddrinfo(*args):
307                 return [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (args[0], args[1]))]
308             socket.getaddrinfo = getaddrinfo
309
310         if self.use_ssl:
311             cert_path = os.path.join( self.config.get('path'), 'certs', self.host)
312
313             if not os.path.exists(cert_path):
314                 is_new = True
315                 # get server certificate.
316                 # Do not use ssl.get_server_certificate because it does not work with proxy
317                 s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
318                 try:
319                     s.connect((self.host, self.port))
320                 except:
321                     # print_error("failed to connect", self.host, self.port)
322                     return
323
324                 try:
325                     s = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_SSLv3, cert_reqs=ssl.CERT_NONE, ca_certs=None)
326                 except ssl.SSLError, e:
327                     print_error("SSL error:", self.host, e)
328                     return
329                 dercert = s.getpeercert(True)
330                 s.close()
331                 cert = ssl.DER_cert_to_PEM_cert(dercert)
332                 temporary_path = cert_path + '.temp'
333                 with open(temporary_path,"w") as f:
334                     f.write(cert)
335
336             else:
337                 is_new = False
338
339
340         s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
341         s.settimeout(2)
342         s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
343
344         try:
345             s.connect(( self.host.encode('ascii'), int(self.port)))
346         except:
347             print_error("failed to connect", self.host, self.port)
348             return
349
350         if self.use_ssl:
351             try:
352                 s = ssl.wrap_socket(s,
353                                     ssl_version=ssl.PROTOCOL_SSLv3,
354                                     cert_reqs=ssl.CERT_REQUIRED,
355                                     ca_certs= (temporary_path if is_new else cert_path),
356                                     do_handshake_on_connect=True)
357             except ssl.SSLError, e:
358                 print_error("SSL error:", self.host, e)
359                 if e.errno != 1:
360                     return
361                 if is_new:
362                     os.rename(temporary_path, cert_path + '.rej')
363                 else:
364                     if cert_has_expired(cert_path):
365                         print_error("certificate has expired:", cert_path)
366                         os.unlink(cert_path)
367                     else:
368                         print_msg("wrong certificate", self.host)
369                 return
370             except:
371                 print_error("wrap_socket failed", self.host)
372                 traceback.print_exc(file=sys.stdout)
373                 return
374
375             if is_new:
376                 print_error("saving certificate for", self.host)
377                 os.rename(temporary_path, cert_path)
378
379         s.settimeout(60)
380         self.s = s
381         self.is_connected = True
382         print_error("connected to", self.host, self.port)
383
384
385     def run_tcp(self):
386         try:
387             #if self.use_ssl: self.s.do_handshake()
388             out = ''
389             while self.is_connected:
390                 try: 
391                     timeout = False
392                     msg = self.s.recv(1024)
393                 except socket.timeout:
394                     timeout = True
395                 except ssl.SSLError:
396                     timeout = True
397                 except socket.error, err:
398                     if err.errno in [11, 10035]:
399                         print_error("socket errno", err.errno)
400                         time.sleep(0.1)
401                         continue
402                     else:
403                         traceback.print_exc(file=sys.stdout)
404                         raise
405
406                 if timeout:
407                     # ping the server with server.version, as a real ping does not exist yet
408                     self.send([('server.version', [ELECTRUM_VERSION, PROTOCOL_VERSION])], self.on_version)
409                     continue
410
411                 out += msg
412                 self.bytes_received += len(msg)
413                 if msg == '': 
414                     self.is_connected = False
415
416                 while True:
417                     s = out.find('\n')
418                     if s==-1: break
419                     c = out[0:s]
420                     out = out[s+1:]
421                     c = json.loads(c)
422                     self.queue_json_response(c)
423
424         except:
425             traceback.print_exc(file=sys.stdout)
426
427         self.is_connected = False
428
429
430     def send_tcp(self, messages, callback):
431         """return the ids of the requests that we sent"""
432         out = ''
433         ids = []
434         for m in messages:
435             method, params = m 
436             request = json.dumps( { 'id':self.message_id, 'method':method, 'params':params } )
437             self.unanswered_requests[self.message_id] = method, params, callback
438             ids.append(self.message_id)
439             if self.debug:
440                 print "-->", request
441             self.message_id += 1
442             out += request + '\n'
443         while out:
444             try:
445                 sent = self.s.send( out )
446                 out = out[sent:]
447             except socket.error,e:
448                 if e[0] in (errno.EWOULDBLOCK,errno.EAGAIN):
449                     print_error( "EAGAIN: retrying")
450                     time.sleep(0.1)
451                     continue
452                 else:
453                     traceback.print_exc(file=sys.stdout)
454                     # this happens when we get disconnected
455                     print_error( "Not connected, cannot send" )
456                     return None
457         return ids
458
459
460
461
462
463     def start_interface(self):
464
465         if self.protocol in 'st':
466             self.start_tcp()
467         elif self.protocol in 'gh':
468             self.start_http()
469
470         self.connect_event.set()
471
472
473
474     def stop_subscriptions(self):
475         for callback in self.subscriptions.keys():
476             callback(self, None)
477         self.subscriptions = {}
478
479
480     def send(self, messages, callback):
481
482         sub = []
483         for message in messages:
484             m, v = message
485             if m[-10:] == '.subscribe':
486                 sub.append(message)
487
488         if sub:
489             with self.lock:
490                 if self.subscriptions.get(callback) is None: 
491                     self.subscriptions[callback] = []
492                 for message in sub:
493                     if message not in self.subscriptions[callback]:
494                         self.subscriptions[callback].append(message)
495
496         if not self.is_connected: 
497             print_error("interface: trying to send while not connected")
498             return
499
500         if self.protocol in 'st':
501             with self.lock:
502                 out = self.send_tcp(messages, callback)
503         else:
504             # do not use lock, http is synchronous
505             out = self.send_http(messages, callback)
506
507         return out
508
509
510     def parse_proxy_options(self, s):
511         if type(s) == type({}): return s  # fixme: type should be fixed
512         if type(s) != type(""): return None  
513         if s.lower() == 'none': return None
514         proxy = { "mode":"socks5", "host":"localhost" }
515         args = s.split(':')
516         n = 0
517         if proxy_modes.count(args[n]) == 1:
518             proxy["mode"] = args[n]
519             n += 1
520         if len(args) > n:
521             proxy["host"] = args[n]
522             n += 1
523         if len(args) > n:
524             proxy["port"] = args[n]
525         else:
526             proxy["port"] = "8080" if proxy["mode"] == "http" else "1080"
527         return proxy
528
529
530
531     def stop(self):
532         if self.is_connected and self.protocol in 'st' and self.s:
533             self.s.shutdown(socket.SHUT_RDWR)
534             self.s.close()
535
536
537     def is_up_to_date(self):
538         return self.unanswered_requests == {}
539
540
541
542     def start(self, queue):
543         self.queue = queue
544         threading.Thread.start(self)
545
546
547     def run(self):
548         self.start_interface()
549         if self.is_connected:
550             self.send([('server.version', [ELECTRUM_VERSION, PROTOCOL_VERSION])], self.on_version)
551             self.change_status()
552             self.run_tcp() if self.protocol in 'st' else self.run_http()
553         self.change_status()
554         
555
556     def change_status(self):
557         #print "change status", self.server, self.is_connected
558         self.queue.put(self)
559
560
561
562 if __name__ == "__main__":
563
564     check_certificates()