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