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