forked from xaxaxa/workspace
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ifsrv
executable file
·374 lines (348 loc) · 10.7 KB
/
ifsrv
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# ifsrv.py - Interface service - network interface management daemon
#
# Copyright 2012 <xaxaxa@xaxaxa-mac>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
#***config file format***
#*global options*
# option (option name) (value)
#*config definition*
# config (name):
# option (name) (value)
# ...
# end
#*interface definition*
# iface (name):
# option (name) (value)
# ...
# end
#
#***global options***
# nowait: do not wait for the interface to be configured; (0|1)
#
#***config options***
# these are self explanatory: type(static|dhcp), address, netmask, gateway
#
#***interface options***
# nowait
# config: configurations for this interface; separated by space; they're tried in the order specified
import sys,os,select,threading,subprocess,time;
class WaitableEvent:
"""Provides an abstract object that can be used to resume select loops with
indefinite waits from another thread or process. This mimics the standard
threading.Event interface."""
def __init__(self):
self._read_fd, self._write_fd = os.pipe()
def wait(self, timeout=None):
rfds, wfds, efds = select.select([self._read_fd], [], [], timeout)
return self._read_fd in rfds
def isSet(self):
return self.wait(0)
def clear(self):
if self.isSet():
os.read(self._read_fd, 1)
def set(self):
if not self.isSet():
os.write(self._write_fd, b'1')
def fileno(self):
"""Return the FD number of the read side of the pipe, allows this object to
be used with select.select()."""
return self._read_fd
def __del__(self):
os.close(self._read_fd)
os.close(self._write_fd)
if sys.version_info < (3,):
range = xrange;
#list of options that are arrays; true indicates one line should be split;
array_opts={"configs": True, "address": True, "up": False, "unplug": False, "postconfig": False, "preconfig": False};
def parseoption(tmp,target):
optval=None;
i=tmp.find(" ");
if i<0: return;
a=(tmp[:i],tmp[i+1:]);
if a[0] in array_opts:
if array_opts[a[0]]: optval=a[1].split();
else: optval=[a[1]];
if a[0] in target:
target[a[0]].extend(optval);
return;
else: optval=a[1];
target[a[0]]=optval;
def readconfig(f):
obj={"options":{},"configs":{},"interfaces":{}};
cur_scope=(None,None);
while True:
tmp=f.readline();
if tmp==None or len(tmp)<=0: return obj;
a=tmp.split(); tmp=tmp.strip();
if len(a)<1: continue;
cmd=a[0];
#print(cmd[0]);
if cmd[0]=='#': continue;
if cmd=="option":
if cur_scope[0]==None:
parseoption(a[1:],obj["options"]);
else: parseoption(a[1:],cur_scope[1]["options"]);
continue;
#if cur_scope[0]==None: #global scope
if cmd=="iface": #add interface
iface={"name":a[1],"options":{}};
obj["interfaces"][a[1]]=iface;
cur_scope=("interface", iface);
continue;
elif cmd=="config": #add config
conf={"name":a[1],"options":{},"type":a[2]};
obj["configs"][a[1]]=conf;
cur_scope=("config", conf);
continue;
elif cmd=="end":
cur_scope=(None,None);
continue;
#command not recognized. treating it as an option
if cur_scope[0]==None:
parseoption(tmp,obj["options"]);
else: parseoption(tmp,cur_scope[1]["options"]);
return obj;
conf=None;
def kill_dhclient(iface):
try:
f=open("/var/run/dhclient-"+iface["name"]+".pid","r");
pid=int(f.readline().strip());
os.kill(pid,9);
#os.remove("/var/run/dhclient-"+iface["name"]+".pid");
except: pass;
try: os.remove("/var/run/dhclient-"+iface["name"]+".pid");
except: pass;
def init_iface(iface):
if "curconf" in iface: del iface["curconf"];
#if "configured" in iface: del iface["configured"];
kill_iface(iface);
os.spawnvp(os.P_WAIT,"ifconfig",("ifconfig",iface["name"],"up"));
os.spawnvp(os.P_WAIT,"ip",("ip","addr","flush","dev",iface["name"]));
os.spawnvp(os.P_WAIT,"ip",("ip","route","flush","dev",iface["name"]));
#os.spawnvp(os.P_WAIT,"dhclient",("dhclient","-x",iface["name"]));
kill_dhclient(iface);
#os.system("ifconfig "+iface["name"]);
def get_gateway(iface):
s=subprocess.check_output(("ip","route","show","dev",iface["name"]));
s=s.decode("utf-8");
#print(s);
s=s.split("\n");
for l in s:
#print(l);
tmp=l.split();
if len(tmp)>2:
if tmp[0]=="default" and tmp[1]=="via": return tmp[2];
return None;
def testconfig(iface,config=None):
if config==None: config=iface["curconf"];
if config==None: return False;
if "pingtest" in config["options"] and config["options"]["pingtest"]=="1":
t_o=2;
h=None;
if config["type"]=="static": h=config["options"]["gateway"];
elif config["type"]=="dhcp": h=get_gateway(iface);
if "pingtimeout" in config["options"]: t_o=int(config["options"]["pingtimeout"]);
if "pinghost" in config["options"]: h=config["options"]["pinghost"];
if h==None: print("warning: no gateway found, pinghost is not specified, and pingtest is enabled");
else: print("pinging "+h);
if h==None: return False;
pid=os.spawnvp(os.P_NOWAIT,"ping",("ping","-c","1","-w",str(t_o),h));
iface["pid"]=pid;
(pid,retv)=os.waitpid(pid,0);
try: del iface["pid"];
except: pass;
if retv!=0: return False;
#return retv==0;
#print("interface "+iface["name"]+" activated using config \""+config["name"]+"\"");
return True;
def apply_config(iface,config,is_thread=False): #apply config
init_iface(iface);
if config["type"]=="static":
print("setting ip addresses");
for addr in config["options"]["address"]:
pid=os.spawnvp(os.P_NOWAIT,"ip",("ip","addr","add","dev",iface["name"],"local",addr));
iface["pid"]=pid;
os.waitpid(pid,0);
try: del iface["pid"];
except: pass;
if "gateway" in config["options"]:
pid=os.spawnvp(os.P_NOWAIT,"ip",("ip","route","add","default","via",config["options"]["gateway"],"dev",iface["name"]));
iface["pid"]=pid;
os.waitpid(pid,0);
try: del iface["pid"];
except: pass;
elif config["type"]=="dhcp":
print("executing dhclient");
pid=os.spawnvp(os.P_NOWAIT,"dhclient",("dhclient","-pf","/var/run/dhclient-"+iface["name"]+".pid",iface["name"]));
iface["pid"]=pid;
os.waitpid(pid,0);
try: del iface["pid"];
except: pass;
if is_thread:
if testconfig(iface,config):
iface["curconf"]=config;
postup(iface);
return;
do_activate_iface(iface,True);
def do_activate_iface(iface,is_thread=False):
global conf;
configs=iface["options"]["configs"];
st=0;
if "st" in iface: st=iface["st"];
if st>=len(configs): st=0;
c=None;
for i in range(st,len(configs)):
c=conf["configs"][configs[i]];
if "nowait" in c["options"] and c["options"]["nowait"] and (not is_thread):
iface["st"]=i+1;
t=threading.Thread(target=apply_config,args=(iface,c,True));
#iface["thr"]=t;
t.start();
return;
apply_config(iface,c);
if testconfig(iface,c):
iface["curconf"]=c;
postup(iface);
return;
iface["curconf"]=c;
def activate_iface(iface,nowait=None):
if nowait==None: nowait=("nowait" in iface["options"] and iface["options"]["nowait"]=="1");
if nowait:
t=threading.Thread(target=do_activate_iface,args=(iface,True));
#iface["thr"]=t;
t.start();
else: do_activate_iface(iface);
def detect_cable(iface):
try:
f=open("/sys/class/net/"+iface["name"]+"/carrier","r");
s=f.readline().strip();
f.close();
return s!="0";
except: return True;
def loadconfig():
global conf;
if conf!=None: return;
f=open(sys.argv[1],'r');
conf=readconfig(f);
f.close();
if len(conf["interfaces"])<=0:
raise Error("at least one interface should be defined");
def kill_iface(iface):
try:
if "pid" in iface:
os.kill(iface["pid"],9);
except: pass
def execscr(s,iface):
global conf;
config=iface["curconf"];
for c in s:
print(c);
eval(c);
def postup(iface):
global conf;
config=iface["curconf"];
print("interface "+iface["name"]+" activated using config \""+config["name"]+"\"");
try:
if "up" in config["options"]: execscr(config["options"]["up"],iface);
except BaseException as (a): print a;
try:
if "up" in iface["options"]: execscr(iface["options"]["up"],iface);
except BaseException as (a): print a;
def run(evt=None):
global conf;
loadconfig();
for iface in conf["interfaces"]:
iface=conf["interfaces"][iface];
init_iface(iface);
iface["cable"]=detect_cable(iface);
if iface["cable"]: activate_iface(iface);
else: print(iface["name"]+" cable unplugged");
if evt!=None: evt.set();
while True:
time.sleep(5); #FIXME
for iface in conf["interfaces"]:
iface=conf["interfaces"][iface];
try:
tmp=detect_cable(iface);
if tmp and (not iface["cable"]): #cable was plugged in
#kill_iface(iface);
print(iface["name"]+" cable plugged");
activate_iface(iface,True);
elif iface["cable"] and (not tmp):
print(iface["name"]+" cable unplugged");
if "unplug" in iface["name"]["options"]: execscr(iface["name"]["options"]["unplug"],iface);
init_iface(iface);
iface["cable"]=tmp;
except: pass;
def do_start():
global conf;
loadconfig();
t_o=None;
if "timeout" in conf["options"]: t_o=float(conf["options"]["timeout"]);
evt=WaitableEvent();
tmp=os.fork();
if tmp==0: #child
run(evt);
elif tmp>0: #parent
if (not evt.wait(t_o)) and t_o>0: print("timed out waiting for interface config");
return tmp;
#print("dgsjdgghjasd");
return 0;
def stop():
global conf;
loadconfig();
try:
pidfile="/var/run/ifsrv-"+conf["interfaces"].keys()[0]+".pid";
try:
f=open(pidfile,"r");
pid=int(f.readline().strip());
os.kill(pid,9);
f.close();
except: pass;
os.remove(pidfile);
except: pass;
def start():
global conf;
loadconfig();
stop();
pid=do_start();
if pid>0:
pidfile="/var/run/ifsrv-"+conf["interfaces"].keys()[0]+".pid";
f=open(pidfile,"w+",0666);
f.write(str(pid)+"\n");
f.close();
def showconf():
global conf;
loadconfig();
print conf;
def restart():
start();
def main():
if len(sys.argv)<2:
print("to use ifsrv, put '#!/path/to/ifsrv' at the top of your config file and put the config file in /etc/init.d/ or whatever; don't forget to chmod it");
return 0;
if len(sys.argv)<3:
print("usage: %s (start|stop|restart)"%sys.argv[1]);
return 0;
eval(sys.argv[2]+"()");
return 0;
if __name__ == '__main__':
main();