~jdstrand/ufw/ufw-xenial

« back to all changes in this revision

Viewing changes to src/util.py

  • Committer: Jamie Strandboge
  • Date: 2012-07-06 19:29:50 UTC
  • Revision ID: jamie@canonical.com-20120706192950-1whf5yyzv2v2xc6c
Release 0.32-0ubuntu1

* New upstream release featuring Python 3 port (LP: #1001657)
* debian/control:
  - clean up Depends and Build-Depends
  - Build-Depends on python3
  - add python-ufw for installing python2 modules
  - add X-Python3-Version: >= 3.2
  - update Vcs-Bzr
* add debian/python-ufw.install
* debian/rules:
  - use --install-layout=deb
  - adjust PYTHON to use python3
  - adjust PYVERS to use py3versions
  - add PYTHON2
  - run tests for both PYTHON and PYTHON2
  - run setup.py with both PYTHON and PYTHON2
  - use dh_python3 for ufw
  - use dh_python2 for python-ufw
* debian/ufw.lintian-overrides
  - remove old unneeded override
  - add postrm-does-not-call-updaterc.d-for-init.d-script since Ubuntu's
    debhelper adds code to postinst that does nothing on Ubuntu, but doesn't
    add the corresponding code to postrm
* New upstream release (Closes: 663677, Closes: 625681)
* debian/control: update to standards 3.9.3
* convert to source format 3.0 (quilt)
* 0001-optimize-boot.patch: only read in /etc/ufw/ufw.conf when disabled
* debian/rules: adjust to only install the application profiles when not
  Ubuntu
* debian/po/da.po: add Danish translation of debconf templates. Thanks to
  Joe Dalton (Closes: 666557)

Show diffs side-by-side

added added

removed removed

Lines of Context:
15
15
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
16
#
17
17
 
18
 
import codecs
 
18
from __future__ import print_function
19
19
import errno
20
20
import fcntl
21
21
import os
26
26
import subprocess
27
27
import sys
28
28
 
 
29
from functools import reduce
29
30
from tempfile import mkstemp
30
31
 
31
32
DEBUGGING = False
204
205
def open_file_read(fn):
205
206
    '''Opens the specified file read-only'''
206
207
    try:
207
 
        orig = codecs.open(fn, 'r', 'UTF-8')
 
208
        orig = open(fn, 'r')
208
209
    except Exception:
209
210
        raise
210
211
 
236
237
    if not fd:
237
238
        raise OSError(errno.ENOENT, "Not a valid file descriptor")
238
239
 
239
 
    if os.write(fd, out) <= 0:
 
240
    rc = -1
 
241
    if sys.version_info[0] >= 3:
 
242
        rc = os.write(fd, bytes(out, 'ascii'))
 
243
    else:
 
244
        rc = os.write(fd, out)
 
245
 
 
246
    if rc <= 0:
240
247
        raise OSError(errno.EIO, "Could not write to file descriptor")
241
248
 
242
249
 
265
272
    debug(command)
266
273
    try:
267
274
        sp = subprocess.Popen(command, stdout=subprocess.PIPE,
268
 
                              stderr=subprocess.STDOUT)
269
 
    except OSError, ex:
 
275
                              stderr=subprocess.STDOUT,
 
276
                              universal_newlines=True)
 
277
    except OSError as ex:
270
278
        return [127, str(ex)]
271
279
 
272
280
    out = sp.communicate()[0]
273
 
    return [sp.returncode, out]
 
281
    return [sp.returncode, str(out)]
274
282
 
275
283
 
276
284
def cmd_pipe(command1, command2):
278
286
    try:
279
287
        sp1 = subprocess.Popen(command1, stdout=subprocess.PIPE)
280
288
        sp2 = subprocess.Popen(command2, stdin=sp1.stdout)
281
 
    except OSError, ex:
 
289
    except OSError as ex:
282
290
        return [127, str(ex)]
283
291
 
284
292
    out = sp2.communicate()[0]
285
 
    return [sp2.returncode, out]
 
293
    return [sp2.returncode, str(out)]
 
294
 
 
295
# TODO: this is pretty horrible. We should be using only unicode strings
 
296
#       internally and decode() when printing rather than doing this.
 
297
def _print(output, s):
 
298
    '''Implement our own print statement that will output utf-8 when
 
299
       appropriate.'''
 
300
    try: # python3
 
301
        writer = output.buffer
 
302
    except:
 
303
        writer = output
 
304
 
 
305
    try:
 
306
        out = s.encode('utf-8', 'ignore')
 
307
    except:
 
308
        out = s
 
309
 
 
310
    writer.write(bytes(out))
 
311
    output.flush()
286
312
 
287
313
 
288
314
def error(out, do_exit=True):
289
315
    '''Print error message and exit'''
290
316
    try:
291
 
        print >> sys.stderr, "ERROR: %s" % (out)
 
317
        _print(sys.stderr, 'ERROR: %s\n' % out)
292
318
    except IOError:
293
319
        pass
294
320
 
299
325
def warn(out):
300
326
    '''Print warning message'''
301
327
    try:
302
 
        print >> sys.stderr, "WARN: %s" % (out)
 
328
        _print(sys.stderr, 'WARN: %s\n' % out)
303
329
    except IOError:
304
330
        pass
305
331
 
306
332
 
307
 
def msg(out, output=sys.stdout):
 
333
def msg(out, output=sys.stdout, newline=True):
308
334
    '''Print message'''
309
335
    try:
310
 
        print >> output, "%s" % (out)
 
336
        if newline:
 
337
            _print(output, '%s\n' % out)
 
338
        else:
 
339
            _print(output, '%s' % out)
311
340
    except IOError:
312
341
        pass
313
342
 
316
345
    '''Print debug message'''
317
346
    if DEBUGGING:
318
347
        try:
319
 
            print >> sys.stderr, "DEBUG: %s" % (out)
 
348
            _print(sys.stderr, 'DEBUG: %s\n' % out)
320
349
        except IOError:
321
350
            pass
322
351
 
370
399
        raise IOError("Couldn't find '%s'" % (name))
371
400
 
372
401
    try:
373
 
        ppid = file(name).readlines()[0].split()[3]
 
402
        ppid = open(name).readlines()[0].split()[3]
374
403
    except Exception:
375
404
        raise
376
405
 
400
429
        raise ValueError(err_msg)
401
430
 
402
431
    try:
403
 
        exe = file(path).readlines()[0].split()[1]
 
432
        exe = open(path).readlines()[0].split()[1]
404
433
    except Exception:
405
434
        err_msg = _("Could not find executable for '%s'") % (path)
406
435
        raise ValueError(err_msg)
462
491
            raise ValueError
463
492
 
464
493
        mbits = 0
465
 
        bits = long(struct.unpack('>L', socket.inet_aton(nm))[0])
 
494
 
 
495
        # python3 doesn't have long(). We could technically use int() here
 
496
        # since python2 guarantees at least 32 bits for int(), but this helps
 
497
        # future-proof.
 
498
        try:
 
499
            bits = long(struct.unpack('>L', socket.inet_aton(nm))[0])
 
500
        except NameError:
 
501
            bits = int(struct.unpack('>L', socket.inet_aton(nm))[0])
 
502
 
466
503
        found_one = False
467
504
        for n in range(32):
468
505
            if (bits >> n) & 1 == 1:
498
535
    else:
499
536
        if not _valid_cidr_netmask(cidr, v6):
500
537
            raise ValueError
501
 
        bits = 0L
 
538
 
 
539
        # python3 doesn't have long(). We could technically use int() here
 
540
        # since python2 guarantees at least 32 bits for int(), but this helps
 
541
        # future-proof.
 
542
        try:
 
543
            bits = long(0)
 
544
        except NameError:
 
545
            bits = 0
 
546
 
502
547
        for n in range(32):
503
548
            if n < int(cidr):
504
549
                bits |= 1 << 31 - n
531
576
            raise
532
577
 
533
578
    # Now have dotted quad host and nm, find the network
534
 
    host_bits = long(struct.unpack('>L', socket.inet_aton(host))[0])
535
 
    nm_bits = long(struct.unpack('>L', socket.inet_aton(nm))[0])
 
579
 
 
580
    # python3 doesn't have long(). We could technically use int() here
 
581
    # since python2 guarantees at least 32 bits for int(), but this helps
 
582
    # future-proof.
 
583
    try:
 
584
        host_bits = long(struct.unpack('>L', socket.inet_aton(host))[0])
 
585
        nm_bits = long(struct.unpack('>L', socket.inet_aton(nm))[0])
 
586
    except NameError:
 
587
        host_bits = int(struct.unpack('>L', socket.inet_aton(host))[0])
 
588
        nm_bits = int(struct.unpack('>L', socket.inet_aton(nm))[0])
536
589
 
537
590
    network_bits = host_bits & nm_bits
538
591
    network = socket.inet_ntoa(struct.pack('>L', network_bits))
560
613
                                                     orig_host))
561
614
 
562
615
    # Get the host bits
563
 
    host_bits = 0L
 
616
    try: # python3 doesn't have long()
 
617
        host_bits = long(0)
 
618
    except NameError:
 
619
        host_bits = 0
 
620
 
564
621
    for i in range(8):
565
622
        n = dec2bin(unpacked[i], 16)
566
623
        for j in range(16):
567
624
            host_bits |= (1 & int(n[j])) <<(127-j-i*16)
568
625
 
569
626
    # Create netmask bits
570
 
    nm_bits = 0L
 
627
    try: # python3 doesn't have long()
 
628
        nm_bits = long(0)
 
629
    except NameError:
 
630
        nm_bits = 0
 
631
 
571
632
    for i in range(128):
572
633
        if i < int(netmask):
573
634
            nm_bits |= 1 << (128 - 1) - i
675
736
        else:
676
737
            item['exe'] = tmp[5].split('/')[1]
677
738
 
678
 
        if not d.has_key(proto):
 
739
        if proto not in d:
679
740
            d[proto] = dict()
680
741
            d[proto][port] = []
681
742
        else:
682
 
            if not d[proto].has_key(port):
 
743
            if port not in d[proto]:
683
744
                d[proto][port] = []
684
745
        d[proto][port].append(item)
685
746
 
694
755
        if not os.path.exists(proc):
695
756
            raise OSError(errno.ENOENT, "'%s' does not exist" % proc)
696
757
 
697
 
        for line in file(proc).readlines():
 
758
        for line in open(proc).readlines():
698
759
            tmp = line.split()
699
760
            if ifname == tmp[5]:
700
761
                addr = ":".join( \
731
792
 
732
793
    matched = ""
733
794
    if v6:
734
 
        for line in file(proc).readlines():
 
795
        for line in open(proc).readlines():
735
796
            tmp = line.split()
736
797
            ifname = tmp[5].strip()
737
798
 
745
806
                matched = ifname
746
807
                break
747
808
    else:
748
 
        for line in file(proc).readlines():
 
809
        for line in open(proc).readlines():
749
810
            if ':' not in line:
750
811
                continue
751
812
            ifname = line.split(':')[0].strip()
826
887
 
827
888
    lst = []
828
889
    skipped_first = False
829
 
    lines = file(fn).readlines()
 
890
    lines = open(fn).readlines()
830
891
    for line in lines:
831
892
        fields = line.split()
832
893
        if not skipped_first:
880
941
 
881
942
    inodes = _get_proc_inodes()
882
943
 
883
 
    protocols = proc_net_data.keys()
 
944
    protocols = list(proc_net_data.keys())
884
945
    protocols.sort()
885
946
 
886
947
    s = ""
889
950
            addr = convert_proc_address(laddr)
890
951
 
891
952
            exe = "-"
892
 
            if inodes.has_key(int(inode)):
 
953
            if int(inode) in inodes:
893
954
                exe = inodes[int(inode)]
894
955
            s += "%-5s %-46s %-11s %-5s %-11s %s\n" % (p,
895
956
                                                       "%s:%s" % (addr, port),