Support PyUSB 1.0, too
[gnuk/gnuk.git] / tool / gpg_agent.py
1 """
2 gpg_agent.py - a library to connect gpg-agent
3
4 Copyright (C) 2013 Free Software Initiative of Japan
5 Author: NIIBE Yutaka <gniibe@fsij.org>
6
7 This file is a part of Gnuk, a GnuPG USB Token implementation.
8
9 Gnuk is free software: you can redistribute it and/or modify it
10 under the terms of the GNU General Public License as published by
11 the Free Software Foundation, either version 3 of the License, or
12 (at your option) any later version.
13
14 Gnuk is distributed in the hope that it will be useful, but WITHOUT
15 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
16 or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
17 License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 """
22
23 import platform, os, socket
24 IS_WINDOWS=(platform.system() == 'Windows')
25
26 BUFLEN=1024
27
28 class gpg_agent(object):
29     def __init__(self):
30         if IS_WINDOWS:
31             home = os.getenv("HOME")
32             if not home:
33                 home = os.getenv("APPDATA")
34             comm_port = os.path.join(home, "gnupg", "S.gpg-agent")
35             #
36             f = open(comm_port, "rb", 0)
37             infostr = f.read()
38             f.close()
39             #
40             info = infostr.split('\n', 1)
41             port = int(info[0])
42             nonce = info[1]
43             s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
44             s.connect(("localhost", port))
45             s.send(nonce)
46         else:
47             infostr = os.getenv("GPG_AGENT_INFO")
48             info = infostr.split(':', 2)
49             path = info[0]
50             s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
51             s.connect(path)
52         self.sock = s
53         self.buf_remained = ""
54         self.response = None
55
56     def read_line(self):
57         line = ""
58         if self.buf_remained != "":
59             chunk = self.buf_remained
60         else:
61             chunk = self.sock.recv(BUFLEN)
62         while True:
63             pos = chunk.find('\n')
64             if pos >= 0:
65                 self.buf_remained = chunk[pos+1:]
66                 line = line + chunk[0:pos]
67                 return line
68             else:
69                 line = line + chunk
70                 chunk = self.sock.recv(BUFLEN)
71
72     def get_response(self):
73         r = self.response
74         result = ""
75         while True:
76             i = r.find('%')
77             if i < 0:
78                 result += r
79                 break
80             hex_str = r[i+1:i+3]
81             result += r[0:i]
82             result += chr(int(hex_str,16))
83             r = r[i+3:]
84         return result
85
86     def send_command(self, cmd):
87         self.sock.send(cmd)
88         self.response = ""
89         while True:
90             while True:
91                 l = self.read_line()
92                 if l[0] != '#':
93                     break
94             if l[0] == 'D':
95                 self.response += l[2:]
96             elif l[0] == 'O' and l[1] == 'K':
97                 return True
98             elif l[0] == 'E' and l[1] == 'R' and l[2] == 'R':
99                 return False
100             else:                    # XXX: S, INQUIRE, END
101                 return False
102
103     def close(self):
104         self.sock.send('BYE\n')
105         bye = self.read_line()
106         self.sock.close()
107         return bye              # "OK closing connection"
108
109 # Test
110 if __name__ == '__main__':
111     g = gpg_agent()
112     print g.read_line()
113     print g.send_command("KEYINFO --list --data\n")
114     kl_str = g.get_response()
115     kl_str = kl_str[0:-1]
116     kl = kl_str.split('\n')
117     import re
118     kl_o3 = [kg for kg in kl if re.search("OPENPGP\\.3", kg)]
119     print kl_o3
120     kg = kl_o3[0].split(' ')[0]
121     print g.send_command("READKEY %s\n" % kg)
122     r = g.get_response()
123     import binascii
124     print binascii.hexlify(r)
125     print g.close()