]> gitweb.pimeys.fr Git - NK2015_Client_Python_Alpha.git/blob - client.py
82a6071c7a501cf3b60736b805dcc58dcf0bb3e8
[NK2015_Client_Python_Alpha.git] / client.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 # Définition des fonctions de base de communication du client
5 # Pour l'instant ce script sert essentiellement à les charger en mémoire pour les utiliser à la main
6
7 import os, sys, string, time, random
8 import socket, ssl
9 import threading
10
11 import json
12 import hashlib
13
14 import client_config
15 reload(client_config)
16
17 from pprint import pprint
18
19 sys.path.append(client_config.rsa_path)
20 import monRSA
21
22 def full_read(socket):
23 """Lit un message complet sur la socket."""
24 # On récupère d'abord la taille du message
25 length_str = ''
26 char = socket.recv(1)
27 while char != '\n':
28 length_str += char
29 char = socket.recv(1)
30 total = int(length_str)
31 # On utilise une memoryview pour recevoir les données chunk par chunk efficacement
32 view = memoryview(bytearray(total))
33 next_offset = 0
34 while total - next_offset > 0:
35 recv_size = socket.recv_into(view[next_offset:], total - next_offset)
36 next_offset += recv_size
37 try:
38 msg = json.loads(view.tobytes())
39 except (TypeError, ValueError) as e:
40 raise NKNotJson("L'objet reçu n'est pas un JSON")
41 return msg
42
43 def connect(sock,where,port=None):
44 if port==None:
45 port=client_config.port
46 try:
47 ip={"ici":"localhost","vent":"vent.crans.org","eva":"eva.crans.org","cerebro":"cerebro.crans.org"}[where]
48 except:
49 ip=where
50 sock.connect((ip,port))
51 return ssl.wrap_socket(sock,ca_certs=client_config.ca_certfile)
52 # cert_reqs=ssl.CERT_NONE,ciphers="AES256-SHA")
53
54 def checkidentity(a):
55 c=a.getpeercert()
56 print c
57 c=dict([i[0] for i in c["subject"]])
58 awaited={'commonName': u'note.crans.org',
59 'countryName': u'FR',
60 'emailAddress': u'legallic@crans.org',
61 'localityName': u'Cachan',
62 'organizationName': u'BDE ENS Cachan',
63 'organizationalUnitName': u'Kfet',
64 'stateOrProvinceName': u'\xc3\x8ele de France'}
65 if all([c[cle]==awaited[cle] for cle in awaited.keys()]):
66 return
67 else:
68 raise KeyboardInterrupt("Imposteur !")
69
70 def hello(socket,version):
71 socket.send('["hello", "%s"]' % (version))
72 return lit(a)
73
74 def login(socket,user,mdp="",typ="bdd"):
75 if user in ["#1", "test"]:
76 a.write('["login", ["#1","plop","bdd",[[],[],false]]]')
77 elif user in ["vincent","moi"]:
78 a.write('["login", ["vincent","plop","special",[]]]')
79 elif user in ["toto"]:
80 a.write('["login", ["toto","plop","bdd",[[],[],false]]]')
81 else:
82 a.write('["login", ["%s","%s","%s",[[],[],false]]]'%(user,mdp,typ))
83 if mdp == "":
84 import getpass
85 mdp = getpass.getpass()
86 return lit(a)
87
88 def search(socket,term):
89 a.write('["search", %s]' % (term))
90 return lit(a)
91
92 def lit(socket):
93 try:
94 obj=full_read(socket)
95 if obj["retcode"]==0:
96 return obj['msg']
97 else:
98 print obj["errmsg"]
99 return obj["msg"]
100 except ssl.SSLError:
101 print "Rien à lire"
102
103 def do(stuff):
104 """Dirty, 'cause I'm lazy."""
105 global a
106 a.write(json.dumps(stuff))
107
108 if __name__=="__main__":
109 where=raw_input("quel serveur ?")
110 #port=int(raw_input("port ? "))
111 a=socket.socket()
112 a=connect(a,where)
113 a.settimeout(2)
114 #checkidentity(a)
115 print hello(a,"Python Client alpha")
116 try:
117 import secrets
118 user = secrets.user
119 password = secrets.password
120 except ImportError:
121 print "Y U no secrets.py !?"
122 exit(1)
123 print login(a,"20-100","plop")
124 print "Socket créée dans la variable \"a\""
125