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