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