Now debug mode is a configuration variable.
[toast/tdyndns.git] / cgi-bin / dyndns.py
1 #!/usr/bin/python2.7
2 """Dynamic DNS script. Expects URLs from routers in the form
3 https://info.colgarra.priv.at/dyndns/dyndns.py?username=<username>&password=<pass>&hostname=<domain>&myip=<ipaddr>
4 """
5
6 import re
7 import cgi
8 import pwd
9 from subprocess import call
10 import ipaddr
11
12
13 # Configuration
14 PASSWORD = 'hygCithOrs5'
15 ZONE = '.dyn.colgarra.priv.at'
16 DEBUG = False
17
18
19 # Just for debugging:
20 if DEBUG:
21         import cgitb
22         cgitb.enable()
23
24
25 fields = cgi.FieldStorage()
26
27 # the following fields are supported by most dyndns providers
28 # if a parameter is not provided, the .getvalue method returns None
29 username = fields.getvalue('username')
30 password = fields.getvalue('password')
31 hostname = fields.getvalue('hostname')
32 myip     = fields.getvalue('myip')
33 wildcard = fields.getvalue('wildcard')
34 mx       = fields.getvalue('mx')
35 backmx   = fields.getvalue('backmx')
36 offline  = fields.getvalue('offline')
37
38
39 try:
40         # check username
41         user_info = pwd.getpwnam(username) # returns a key error if the user does not exist
42         if user_info.pw_uid < 1000:
43                 raise RuntimeError('Invalid user name')
44
45         # check password
46         if password != PASSWORD:
47                 raise RuntimeError('Invalid password')
48
49         # check hostname
50         if re.match(r'[-0-9a-z]+(\.[-0-9a-z]+)*$', hostname) is None:
51                 raise RuntimeError('Invalid host name')
52
53         # strip zone
54         hostname = hostname.strip()
55         if hostname.endswith(ZONE):
56                 hostname = hostname[:-len(ZONE)]
57
58         # check IP address
59         ip = ipaddr.IPAddress(myip) # throws axception if the IP address is not valid
60         if isinstance(ip, ipaddr.IPv4Address):
61                 type = 'A'
62         elif isinstance(ip, ipaddr.IPv6Address):
63                 type = 'AAAA'
64         else:
65                 raise RuntimeError('Unknown IP address type')
66
67         # access granted
68         print "Content-Type: text/html"
69         print
70         call(['sudo', '/usr/local/bin/nsupdate_dyndns', hostname, myip, type])
71         print "OK"
72
73
74 except:
75         # access denied
76         print "Content-Type: text/html"
77         print "Status: 403 Forbidden"
78         print
79         print "Denied"
80