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