workaround android bug with ssl certificates
[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, 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         self.pending_transactions_for_notifications= []
109
110         # parse server
111         self.server = server
112         host, port, protocol = self.server.split(':')
113         port = int(port)
114             
115         if protocol not in 'ghst':
116             raise BaseException('Unknown protocol: %s'%protocol)
117
118         self.host = host
119         self.port = port
120         self.protocol = protocol
121         self.use_ssl = ( protocol in 'sg' )
122         self.proxy = self.parse_proxy_options(self.config.get('proxy'))
123         if self.proxy:
124             self.proxy_mode = proxy_modes.index(self.proxy["mode"]) + 1
125
126
127
128
129
130     def queue_json_response(self, c):
131
132         # uncomment to debug
133         if self.debug:
134             print_error( "<--",c )
135
136         msg_id = c.get('id')
137         error = c.get('error')
138         
139         if error:
140             print_error("received error:", c)
141             if msg_id is not None:
142                 with self.lock: 
143                     method, params, callback = self.unanswered_requests.pop(msg_id)
144                 callback(self,{'method':method, 'params':params, 'error':error, 'id':msg_id})
145
146             return
147
148         if msg_id is not None:
149             with self.lock: 
150                 method, params, callback = self.unanswered_requests.pop(msg_id)
151             result = c.get('result')
152
153         else:
154             # notification
155             method = c.get('method')
156             params = c.get('params')
157
158             if method == 'blockchain.numblocks.subscribe':
159                 result = params[0]
160                 params = []
161
162             elif method == 'blockchain.headers.subscribe':
163                 result = params[0]
164                 params = []
165
166             elif method == 'blockchain.address.subscribe':
167                 addr = params[0]
168                 result = params[1]
169                 params = [addr]
170
171             with self.lock:
172                 for k,v in self.subscriptions.items():
173                     if (method, params) in v:
174                         callback = k
175                         break
176                 else:
177                     print_error( "received unexpected notification", method, params)
178                     print_error( self.subscriptions )
179                     return
180
181
182         callback(self, {'method':method, 'params':params, 'result':result, 'id':msg_id})
183
184
185     def on_version(self, i, result):
186         self.server_version = result
187
188
189     def start_http(self):
190         self.session_id = None
191         self.is_connected = True
192         self.connection_msg = ('https' if self.use_ssl else 'http') + '://%s:%d'%( self.host, self.port )
193         try:
194             self.poll()
195         except:
196             print_error("http init session failed")
197             self.is_connected = False
198             return
199
200         if self.session_id:
201             print_error('http session:',self.session_id)
202             self.is_connected = True
203         else:
204             self.is_connected = False
205
206     def run_http(self):
207         self.is_connected = True
208         while self.is_connected:
209             try:
210                 if self.session_id:
211                     self.poll()
212                 time.sleep(self.poll_interval)
213             except socket.gaierror:
214                 break
215             except socket.error:
216                 break
217             except:
218                 traceback.print_exc(file=sys.stdout)
219                 break
220             
221         self.is_connected = False
222
223                 
224     def poll(self):
225         self.send([], None)
226
227
228     def send_http(self, messages, callback):
229         import urllib2, json, time, cookielib
230         print_error( "send_http", messages )
231         
232         if self.proxy:
233             socks.setdefaultproxy(self.proxy_mode, self.proxy["host"], int(self.proxy["port"]) )
234             socks.wrapmodule(urllib2)
235
236         cj = cookielib.CookieJar()
237         opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
238         urllib2.install_opener(opener)
239
240         t1 = time.time()
241
242         data = []
243         for m in messages:
244             method, params = m
245             if type(params) != type([]): params = [params]
246             data.append( { 'method':method, 'id':self.message_id, 'params':params } )
247             self.unanswered_requests[self.message_id] = method, params, callback
248             self.message_id += 1
249
250         if data:
251             data_json = json.dumps(data)
252         else:
253             # poll with GET
254             data_json = None 
255
256             
257         headers = {'content-type': 'application/json'}
258         if self.session_id:
259             headers['cookie'] = 'SESSION=%s'%self.session_id
260
261         try:
262             req = urllib2.Request(self.connection_msg, data_json, headers)
263             response_stream = urllib2.urlopen(req, timeout=DEFAULT_TIMEOUT)
264         except:
265             return
266
267         for index, cookie in enumerate(cj):
268             if cookie.name=='SESSION':
269                 self.session_id = cookie.value
270
271         response = response_stream.read()
272         self.bytes_received += len(response)
273         if response: 
274             response = json.loads( response )
275             if type(response) is not type([]):
276                 self.queue_json_response(response)
277             else:
278                 for item in response:
279                     self.queue_json_response(item)
280
281         if response: 
282             self.poll_interval = 1
283         else:
284             if self.poll_interval < 15: 
285                 self.poll_interval += 1
286         #print self.poll_interval, response
287
288         self.rtime = time.time() - t1
289         self.is_connected = True
290
291
292
293
294     def start_tcp(self):
295
296         self.connection_msg = self.host + ':%d' % self.port
297
298         if self.proxy is not None:
299
300             socks.setdefaultproxy(self.proxy_mode, self.proxy["host"], int(self.proxy["port"]))
301             socket.socket = socks.socksocket
302             # prevent dns leaks, see http://stackoverflow.com/questions/13184205/dns-over-proxy
303             def getaddrinfo(*args):
304                 return [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (args[0], args[1]))]
305             socket.getaddrinfo = getaddrinfo
306
307         if self.use_ssl:
308             cert_path = os.path.join( self.config.path, 'certs', self.host)
309
310             if not os.path.exists(cert_path):
311                 is_new = True
312                 # get server certificate.
313                 # Do not use ssl.get_server_certificate because it does not work with proxy
314                 s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
315                 try:
316                     s.connect((self.host, self.port))
317                 except:
318                     # print_error("failed to connect", self.host, self.port)
319                     return
320
321                 try:
322                     s = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_SSLv3, cert_reqs=ssl.CERT_NONE, ca_certs=None)
323                 except ssl.SSLError, e:
324                     print_error("SSL error:", self.host, e)
325                     return
326                 dercert = s.getpeercert(True)
327                 s.close()
328                 cert = ssl.DER_cert_to_PEM_cert(dercert)
329                 # workaround android bug
330                 cert = cert.replace("==-----END CERTIFICATE-----", "==\n-----END CERTIFICATE-----")
331                 temporary_path = cert_path + '.temp'
332                 with open(temporary_path,"w") as f:
333                     f.write(cert)
334
335             else:
336                 is_new = False
337
338
339         s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
340         s.settimeout(2)
341         s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
342
343         try:
344             s.connect(( self.host.encode('ascii'), int(self.port)))
345         except:
346             print_error("failed to connect", self.host, self.port)
347             return
348
349         if self.use_ssl:
350             try:
351                 s = ssl.wrap_socket(s,
352                                     ssl_version=ssl.PROTOCOL_SSLv3,
353                                     cert_reqs=ssl.CERT_REQUIRED,
354                                     ca_certs= (temporary_path if is_new else cert_path),
355                                     do_handshake_on_connect=True)
356             except ssl.SSLError, e:
357                 print_error("SSL error:", self.host, e)
358                 if e.errno != 1:
359                     return
360                 if is_new:
361                     os.rename(temporary_path, cert_path + '.rej')
362                 else:
363                     if cert_has_expired(cert_path):
364                         print_error("certificate has expired:", cert_path)
365                         os.unlink(cert_path)
366                     else:
367                         print_msg("wrong certificate", self.host)
368                 return
369             except:
370                 print_error("wrap_socket failed", self.host)
371                 traceback.print_exc(file=sys.stdout)
372                 return
373
374             if is_new:
375                 print_error("saving certificate for", self.host)
376                 os.rename(temporary_path, cert_path)
377
378         s.settimeout(60)
379         self.s = s
380         self.is_connected = True
381         print_error("connected to", self.host, self.port)
382
383
384     def run_tcp(self):
385         try:
386             #if self.use_ssl: self.s.do_handshake()
387             out = ''
388             while self.is_connected:
389                 try: 
390                     timeout = False
391                     msg = self.s.recv(1024)
392                 except socket.timeout:
393                     timeout = True
394                 except ssl.SSLError:
395                     timeout = True
396                 except socket.error, err:
397                     if err.errno in [11, 10035]:
398                         print_error("socket errno", err.errno)
399                         time.sleep(0.1)
400                         continue
401                     else:
402                         traceback.print_exc(file=sys.stdout)
403                         raise
404
405                 if timeout:
406                     # ping the server with server.version, as a real ping does not exist yet
407                     self.send([('server.version', [ELECTRUM_VERSION, PROTOCOL_VERSION])], self.on_version)
408                     continue
409
410                 out += msg
411                 self.bytes_received += len(msg)
412                 if msg == '': 
413                     self.is_connected = False
414
415                 while True:
416                     s = out.find('\n')
417                     if s==-1: break
418                     c = out[0:s]
419                     out = out[s+1:]
420                     c = json.loads(c)
421                     self.queue_json_response(c)
422
423         except:
424             traceback.print_exc(file=sys.stdout)
425
426         self.is_connected = False
427
428
429     def send_tcp(self, messages, callback):
430         """return the ids of the requests that we sent"""
431         out = ''
432         ids = []
433         for m in messages:
434             method, params = m 
435             request = json.dumps( { 'id':self.message_id, 'method':method, 'params':params } )
436             self.unanswered_requests[self.message_id] = method, params, callback
437             ids.append(self.message_id)
438             if self.debug:
439                 print "-->", request
440             self.message_id += 1
441             out += request + '\n'
442         while out:
443             try:
444                 sent = self.s.send( out )
445                 out = out[sent:]
446             except socket.error,e:
447                 if e[0] in (errno.EWOULDBLOCK,errno.EAGAIN):
448                     print_error( "EAGAIN: retrying")
449                     time.sleep(0.1)
450                     continue
451                 else:
452                     traceback.print_exc(file=sys.stdout)
453                     # this happens when we get disconnected
454                     print_error( "Not connected, cannot send" )
455                     return None
456         return ids
457
458
459
460
461
462     def start_interface(self):
463
464         if self.protocol in 'st':
465             self.start_tcp()
466         elif self.protocol in 'gh':
467             self.start_http()
468
469         self.connect_event.set()
470
471
472
473     def stop_subscriptions(self):
474         for callback in self.subscriptions.keys():
475             callback(self, None)
476         self.subscriptions = {}
477
478
479     def send(self, messages, callback):
480
481         sub = []
482         for message in messages:
483             m, v = message
484             if m[-10:] == '.subscribe':
485                 sub.append(message)
486
487         if sub:
488             with self.lock:
489                 if self.subscriptions.get(callback) is None: 
490                     self.subscriptions[callback] = []
491                 for message in sub:
492                     if message not in self.subscriptions[callback]:
493                         self.subscriptions[callback].append(message)
494
495         if not self.is_connected: 
496             print_error("interface: trying to send while not connected")
497             return
498
499         if self.protocol in 'st':
500             with self.lock:
501                 out = self.send_tcp(messages, callback)
502         else:
503             # do not use lock, http is synchronous
504             out = self.send_http(messages, callback)
505
506         return out
507
508
509     def parse_proxy_options(self, s):
510         if type(s) == type({}): return s  # fixme: type should be fixed
511         if type(s) != type(""): return None  
512         if s.lower() == 'none': return None
513         proxy = { "mode":"socks5", "host":"localhost" }
514         args = s.split(':')
515         n = 0
516         if proxy_modes.count(args[n]) == 1:
517             proxy["mode"] = args[n]
518             n += 1
519         if len(args) > n:
520             proxy["host"] = args[n]
521             n += 1
522         if len(args) > n:
523             proxy["port"] = args[n]
524         else:
525             proxy["port"] = "8080" if proxy["mode"] == "http" else "1080"
526         return proxy
527
528
529
530     def stop(self):
531         if self.is_connected and self.protocol in 'st' and self.s:
532             self.s.shutdown(socket.SHUT_RDWR)
533             self.s.close()
534
535
536     def is_up_to_date(self):
537         return self.unanswered_requests == {}
538
539
540
541     def start(self, queue = None, wait = False):
542         self.queue = queue if queue else Queue.Queue()
543         threading.Thread.start(self)
544         if wait:
545             self.connect_event.wait()
546
547
548     def run(self):
549         self.start_interface()
550         if self.is_connected:
551             self.send([('server.version', [ELECTRUM_VERSION, PROTOCOL_VERSION])], self.on_version)
552             self.change_status()
553             self.run_tcp() if self.protocol in 'st' else self.run_http()
554         self.change_status()
555         
556
557     def change_status(self):
558         #print "change status", self.server, self.is_connected
559         self.queue.put(self)
560
561
562
563 if __name__ == "__main__":
564
565     check_certificates()