0b1cba430a7e293b69aa021b154559b8d7e5b3f5
[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 Exception:
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, server, config = None):
89
90         threading.Thread.__init__(self)
91         self.daemon = True
92         self.config = config if config is not None else SimpleConfig()
93         self.connect_event = threading.Event()
94
95         self.subscriptions = {}
96         self.lock = threading.Lock()
97
98         self.rtime = 0
99         self.bytes_received = 0
100         self.is_connected = False
101         self.poll_interval = 1
102
103         self.debug = False # dump network messages. can be changed at runtime using the console
104
105         #json
106         self.message_id = 0
107         self.unanswered_requests = {}
108
109         # parse server
110         self.server = server
111         try:
112             host, port, protocol = self.server.split(':')
113             port = int(port)
114         except Exception:
115             self.server = None
116             return
117
118         if protocol not in 'ghst':
119             raise Exception('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(self.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 Exception:
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 Exception:
221                 traceback.print_exc(file=sys.stdout)
222                 break
223             
224         self.is_connected = False
225
226                 
227     def poll(self):
228         self.send([], None)
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         ids = []
247         for m in messages:
248             method, params = m
249             if type(params) != type([]): params = [params]
250             data.append( { 'method':method, 'id':self.message_id, 'params':params } )
251             self.unanswered_requests[self.message_id] = method, params, callback
252             ids.append(self.message_id)
253             self.message_id += 1
254
255         if data:
256             data_json = json.dumps(data)
257         else:
258             # poll with GET
259             data_json = None 
260
261             
262         headers = {'content-type': 'application/json'}
263         if self.session_id:
264             headers['cookie'] = 'SESSION=%s'%self.session_id
265
266         try:
267             req = urllib2.Request(self.connection_msg, data_json, headers)
268             response_stream = urllib2.urlopen(req, timeout=DEFAULT_TIMEOUT)
269         except Exception:
270             return
271
272         for index, cookie in enumerate(cj):
273             if cookie.name=='SESSION':
274                 self.session_id = cookie.value
275
276         response = response_stream.read()
277         self.bytes_received += len(response)
278         if response: 
279             response = json.loads( response )
280             if type(response) is not type([]):
281                 self.queue_json_response(response)
282             else:
283                 for item in response:
284                     self.queue_json_response(item)
285
286         if response: 
287             self.poll_interval = 1
288         else:
289             if self.poll_interval < 15: 
290                 self.poll_interval += 1
291         #print self.poll_interval, response
292
293         self.rtime = time.time() - t1
294         self.is_connected = True
295         return ids
296
297
298
299
300     def start_tcp(self):
301
302         self.connection_msg = self.host + ':%d' % self.port
303
304         if self.proxy is not None:
305
306             socks.setdefaultproxy(self.proxy_mode, self.proxy["host"], int(self.proxy["port"]))
307             socket.socket = socks.socksocket
308             # prevent dns leaks, see http://stackoverflow.com/questions/13184205/dns-over-proxy
309             def getaddrinfo(*args):
310                 return [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (args[0], args[1]))]
311             socket.getaddrinfo = getaddrinfo
312
313         if self.use_ssl:
314             cert_path = os.path.join( self.config.path, 'certs', self.host)
315
316             if not os.path.exists(cert_path):
317                 is_new = True
318                 # get server certificate.
319                 # Do not use ssl.get_server_certificate because it does not work with proxy
320                 try:
321                     l = socket.getaddrinfo(self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM)
322                 except socket.gaierror:
323                     print_error("error: cannot resolve", self.host)
324                     return
325
326                 for res in l:
327                     try:
328                         s = socket.socket( res[0], socket.SOCK_STREAM )
329                         s.connect(res[4])
330                     except:
331                         s = None
332                         continue
333
334                     try:
335                         s = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_SSLv3, cert_reqs=ssl.CERT_NONE, ca_certs=None)
336                     except ssl.SSLError, e:
337                         print_error("SSL error retrieving SSL certificate:", self.host, e)
338                         s = None
339
340                     break
341
342                 if s is None:
343                     return
344
345                 dercert = s.getpeercert(True)
346                 s.close()
347                 cert = ssl.DER_cert_to_PEM_cert(dercert)
348                 # workaround android bug
349                 cert = re.sub("([^\n])-----END CERTIFICATE-----","\\1\n-----END CERTIFICATE-----",cert)
350                 temporary_path = cert_path + '.temp'
351                 with open(temporary_path,"w") as f:
352                     f.write(cert)
353
354             else:
355                 is_new = False
356
357         try:
358             addrinfo = socket.getaddrinfo(self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM)
359         except socket.gaierror:
360             print_error("error: cannot resolve", self.host)
361             return
362
363         for res in addrinfo:
364             try:
365                 s = socket.socket( res[0], socket.SOCK_STREAM )
366                 s.settimeout(2)
367                 s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
368                 s.connect(res[4])
369             except:
370                 s = None
371                 continue
372             break
373
374         if s is None:
375             print_error("failed to connect", self.host, self.port)
376             return
377
378         if self.use_ssl:
379             try:
380                 s = ssl.wrap_socket(s,
381                                     ssl_version=ssl.PROTOCOL_SSLv3,
382                                     cert_reqs=ssl.CERT_REQUIRED,
383                                     ca_certs= (temporary_path if is_new else cert_path),
384                                     do_handshake_on_connect=True)
385             except ssl.SSLError, e:
386                 print_error("SSL error:", self.host, e)
387                 if e.errno != 1:
388                     return
389                 if is_new:
390                     rej = cert_path + '.rej'
391                     if os.path.exists(rej):
392                         os.unlink(rej)
393                     os.rename(temporary_path, rej)
394                 else:
395                     if cert_has_expired(cert_path):
396                         print_error("certificate has expired:", cert_path)
397                         os.unlink(cert_path)
398                     else:
399                         print_error("wrong certificate", self.host)
400                 return
401             except Exception:
402                 print_error("wrap_socket failed", self.host)
403                 traceback.print_exc(file=sys.stdout)
404                 return
405
406             if is_new:
407                 print_error("saving certificate for", self.host)
408                 os.rename(temporary_path, cert_path)
409
410         s.settimeout(60)
411         self.s = s
412         self.is_connected = True
413         print_error("connected to", self.host, self.port)
414
415
416     def run_tcp(self):
417         try:
418             #if self.use_ssl: self.s.do_handshake()
419             out = ''
420             while self.is_connected:
421                 try: 
422                     timeout = False
423                     msg = self.s.recv(1024)
424                 except socket.timeout:
425                     timeout = True
426                 except ssl.SSLError:
427                     timeout = True
428                 except socket.error, err:
429                     if err.errno == 60:
430                         timeout = True
431                     elif err.errno in [11, 10035]:
432                         print_error("socket errno", err.errno)
433                         time.sleep(0.1)
434                         continue
435                     else:
436                         traceback.print_exc(file=sys.stdout)
437                         raise
438
439                 if timeout:
440                     # ping the server with server.version, as a real ping does not exist yet
441                     self.send([('server.version', [ELECTRUM_VERSION, PROTOCOL_VERSION])], self.on_version)
442                     continue
443
444                 out += msg
445                 self.bytes_received += len(msg)
446                 if msg == '': 
447                     self.is_connected = False
448
449                 while True:
450                     s = out.find('\n')
451                     if s==-1: break
452                     c = out[0:s]
453                     out = out[s+1:]
454                     c = json.loads(c)
455                     self.queue_json_response(c)
456
457         except Exception:
458             traceback.print_exc(file=sys.stdout)
459
460         self.is_connected = False
461
462
463     def send_tcp(self, messages, callback):
464         """return the ids of the requests that we sent"""
465         out = ''
466         ids = []
467         for m in messages:
468             method, params = m 
469             request = json.dumps( { 'id':self.message_id, 'method':method, 'params':params } )
470             self.unanswered_requests[self.message_id] = method, params, callback
471             ids.append(self.message_id)
472             if self.debug:
473                 print "-->", request
474             self.message_id += 1
475             out += request + '\n'
476         while out:
477             try:
478                 sent = self.s.send( out )
479                 out = out[sent:]
480             except socket.error,e:
481                 if e[0] in (errno.EWOULDBLOCK,errno.EAGAIN):
482                     print_error( "EAGAIN: retrying")
483                     time.sleep(0.1)
484                     continue
485                 else:
486                     traceback.print_exc(file=sys.stdout)
487                     # this happens when we get disconnected
488                     print_error( "Not connected, cannot send" )
489                     return None
490         return ids
491
492
493
494
495
496     def start_interface(self):
497
498         if self.protocol in 'st':
499             self.start_tcp()
500         elif self.protocol in 'gh':
501             self.start_http()
502
503         self.connect_event.set()
504
505
506
507     def stop_subscriptions(self):
508         for callback in self.subscriptions.keys():
509             callback(self, None)
510         self.subscriptions = {}
511
512
513     def send(self, messages, callback):
514
515         sub = []
516         for message in messages:
517             m, v = message
518             if m[-10:] == '.subscribe':
519                 sub.append(message)
520
521         if sub:
522             with self.lock:
523                 if self.subscriptions.get(callback) is None: 
524                     self.subscriptions[callback] = []
525                 for message in sub:
526                     if message not in self.subscriptions[callback]:
527                         self.subscriptions[callback].append(message)
528
529         if not self.is_connected: 
530             print_error("interface: trying to send while not connected")
531             return
532
533         if self.protocol in 'st':
534             with self.lock:
535                 out = self.send_tcp(messages, callback)
536         else:
537             # do not use lock, http is synchronous
538             out = self.send_http(messages, callback)
539
540         return out
541
542
543     def parse_proxy_options(self, s):
544         if type(s) == type({}): return s  # fixme: type should be fixed
545         if type(s) != type(""): return None  
546         if s.lower() == 'none': return None
547         proxy = { "mode":"socks5", "host":"localhost" }
548         args = s.split(':')
549         n = 0
550         if proxy_modes.count(args[n]) == 1:
551             proxy["mode"] = args[n]
552             n += 1
553         if len(args) > n:
554             proxy["host"] = args[n]
555             n += 1
556         if len(args) > n:
557             proxy["port"] = args[n]
558         else:
559             proxy["port"] = "8080" if proxy["mode"] == "http" else "1080"
560         return proxy
561
562
563
564     def stop(self):
565         if self.is_connected and self.protocol in 'st' and self.s:
566             self.s.shutdown(socket.SHUT_RDWR)
567             self.s.close()
568
569         self.is_connected = False
570
571
572     def is_up_to_date(self):
573         return self.unanswered_requests == {}
574
575
576
577     def start(self, queue = None, wait = False):
578         if not self.server:
579             return
580         self.queue = queue if queue else Queue.Queue()
581         threading.Thread.start(self)
582         if wait:
583             self.connect_event.wait()
584
585
586     def run(self):
587         self.start_interface()
588         if self.is_connected:
589             self.send([('server.version', [ELECTRUM_VERSION, PROTOCOL_VERSION])], self.on_version)
590             self.change_status()
591             self.run_tcp() if self.protocol in 'st' else self.run_http()
592         self.change_status()
593         
594
595     def change_status(self):
596         #print "change status", self.server, self.is_connected
597         self.queue.put(self)
598
599
600     def synchronous_get(self, requests, timeout=100000000):
601         queue = Queue.Queue()
602         ids = self.send(requests, lambda i,r: queue.put(r))
603         id2 = ids[:]
604         res = {}
605         while ids:
606             r = queue.get(True, timeout)
607             _id = r.get('id')
608             if _id in ids:
609                 ids.remove(_id)
610                 res[_id] = r.get('result')
611         out = []
612         for _id in id2:
613             out.append(res[_id])
614         return out
615
616
617 if __name__ == "__main__":
618
619     check_certificates()