1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
|
import time
import os
import pwd
import errno
import re
import subprocess
import signal
import tempfile
import random
import glob
from dogtail.config import config
def scratchFile(label): # pragma: no cover
"""Uses tempfile.NamedTemporaryFile() to create a unique tempfile in
config.scratchDir, with a filename like:
dogtail-headless-<label>.<random junk>"""
prefix = "dogtail-headless-"
return tempfile.NamedTemporaryFile(prefix="%s%s." % (prefix, label),
dir=config.scratchDir)
def testBinary(path): # pragma: no cover
if (path.startswith(os.path.sep) or
path.startswith(os.path.join('.', '')) or
path.startswith(os.path.join('..', ''))):
if not os.path.exists(path):
raise IOError(errno.ENOENT, "No such file", path)
if not os.access(path, os.X_OK):
raise IOError(errno.ENOEXEC, "Permission denied", path)
return True
def get_username(): # pragma: no cover
return pwd.getpwuid(os.getuid())[0]
class Subprocess(object): # pragma: no cover
def __init__(self, cmdList, environ=None):
testBinary(cmdList[0])
self.cmdList = cmdList
self.environ = environ
self._exitCode = None
def start(self):
if self.environ is None:
self.environ = os.environ
self.popen = subprocess.Popen(
self.cmdList, env=self.environ) # , stdout = subprocess.PIPE,
# stderr = subprocess.STDOUT, close_fds = True)
return self.popen.pid
def wait(self):
return self.popen.wait()
def stop(self):
# The following doesn't exist in python < 2.6, if you can believe it.
# self.popen.terminate()
os.kill(self.popen.pid, signal.SIGTERM)
@property
def exitCode(self):
if self._exitCode is None:
self._exitCode = self.wait()
return self._exitCode
class XServer(Subprocess): # pragma: no cover
def __init__(self, server="/usr/bin/Xorg",
xinitrc="/etc/X11/xinit/Xclients",
resolution="1024x768x16"):
"""resolution is only used with Xvfb."""
testBinary(server)
self.server = server
self._exitCode = None
self.xinit = "/usr/bin/xinit"
self.display = None
self.xinitrc = xinitrc
self.resolution = resolution
@staticmethod
def findFreeDisplay():
tmp = os.listdir('/tmp')
pattern = re.compile('\.X([0-9]+)-lock')
usedDisplays = []
for file in tmp:
match = re.match(pattern, file)
if match:
usedDisplays.append(int(match.groups()[0]))
if not usedDisplays:
return ':0'
usedDisplays.sort()
return ':' + str(usedDisplays[-1] + 1)
@property
def cmdList(self):
self.display = self.findFreeDisplay()
cmd = []
if self.xinit:
cmd.append(self.xinit)
if self.xinitrc:
cmd.append(self.xinitrc)
cmd.append('--')
cmd.append(self.server)
cmd.append(self.display)
cmd.extend(['-ac', '-noreset'])
if self.server.endswith('Xvfb'):
cmd.extend(['-screen', '0', self.resolution])
cmd.append('-shmem')
return cmd
def start(self):
print(' '.join(self.cmdList))
self.popen = subprocess.Popen(self.cmdList)
return self.popen.pid
class Script(Subprocess): # pragma: no cover
pass
class Session(object): # pragma: no cover
cookieName = "DOGTAIL_SESSION_COOKIE"
def __init__(self, sessionBinary, scriptCmdList=[], scriptDelay=20, logout=True):
testBinary(sessionBinary)
self.sessionBinary = sessionBinary
self.script = Script(scriptCmdList)
self.scriptDelay = scriptDelay
self.logout = logout
self.xserver = XServer()
self._cookie = None
self._environment = None
def start(self):
self.xinitrcFileObj = scratchFile('xinitrc')
self.xserver.xinitrc = self.xinitrcFileObj.name
self._buildXInitRC(self.xinitrcFileObj)
xServerPid = self.xserver.start()
time.sleep(self.scriptDelay)
self.script.environ = self.environment
scriptPid = self.script.start()
return (xServerPid, scriptPid)
@property
def environment(self):
def isSessionProcess(fileName):
try:
if os.path.realpath(path + 'exe') != ('/usr/bin/plasma-desktop'
if self.sessionBinary.split('/')[-1] == 'startkde'
else self.sessionBinary):
return False
except OSError:
return False
pid = fileName.split('/')[2]
if pid == 'self' or pid == str(os.getpid()):
return False
return True
def getEnvDict(fileName):
try:
envString = open(fileName, 'r').read()
except IOError:
return {}
envItems = envString.split('\x00')
envDict = {}
for item in envItems:
if not '=' in item:
continue
k, v = item.split('=', 1)
envDict[k] = v
return envDict
def isSessionEnv(envDict):
if not envDict:
return False
if envDict.get(self.cookieName, 'notacookie') == self.cookie:
return True
return False
for path in glob.glob('/proc/*/'):
if not isSessionProcess(path):
continue
envFile = path + 'environ'
envDict = getEnvDict(envFile)
if isSessionEnv(envDict):
# print path
# print envDict
self._environment = envDict
if not self._environment:
raise RuntimeError("Can't find our environment!")
return self._environment
def wait(self):
self.script.wait()
return self.xserver.wait()
def stop(self):
try:
self.script.stop()
except OSError:
pass
self.xserver.stop()
def attemptLogout(self):
logoutScript = Script('dogtail-logout',
environ=self.environment)
logoutScript.start()
logoutScript.wait()
@property
def cookie(self):
if not self._cookie:
self._cookie = "%X" % random.getrandbits(16)
return self._cookie
def _buildXInitRC(self, fileObj):
lines = [
"export %s=%s" % (self.cookieName, self.cookie),
"gsettings set org.gnome.desktop.interface toolkit-accessibility true",
". /etc/X11/xinit/xinitrc-common",
"export %s" % self.cookieName,
"exec -l $SHELL -c \"$CK_XINIT_SESSION $SSH_AGENT %s\"" %
(self.sessionBinary),
""]
fileObj.write('\n'.join(lines).strip())
fileObj.flush()
|