/mandos/trunk

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/trunk

« back to all changes in this revision

Viewing changes to mandos

  • Committer: Teddy Hogeborn
  • Date: 2014-07-16 01:41:23 UTC
  • Revision ID: teddy@recompile.se-20140716014123-kc87e8yoyqkzo24u
plugin-runner: Bug Fix: Fix some memory leaks.

* plugin-runner.c (main): Free the individual direntries.

Show diffs side-by-side

added added

removed removed

Lines of Context:
11
11
# "AvahiService" class, and some lines in "main".
12
12
13
13
# Everything else is
14
 
# Copyright © 2008-2013 Teddy Hogeborn
15
 
# Copyright © 2008-2013 Björn Påhlsson
 
14
# Copyright © 2008-2014 Teddy Hogeborn
 
15
# Copyright © 2008-2014 Björn Påhlsson
16
16
17
17
# This program is free software: you can redistribute it and/or modify
18
18
# it under the terms of the GNU General Public License as published by
88
88
    except ImportError:
89
89
        SO_BINDTODEVICE = None
90
90
 
91
 
version = "1.6.2"
 
91
version = "1.6.6"
92
92
stored_state_file = "clients.pickle"
93
93
 
94
94
logger = logging.getLogger()
95
 
syslogger = (logging.handlers.SysLogHandler
96
 
             (facility = logging.handlers.SysLogHandler.LOG_DAEMON,
97
 
              address = str("/dev/log")))
 
95
syslogger = None
98
96
 
99
97
try:
100
98
    if_nametoindex = (ctypes.cdll.LoadLibrary
116
114
def initlogger(debug, level=logging.WARNING):
117
115
    """init logger and add loglevel"""
118
116
    
 
117
    global syslogger
 
118
    syslogger = (logging.handlers.SysLogHandler
 
119
                 (facility =
 
120
                  logging.handlers.SysLogHandler.LOG_DAEMON,
 
121
                  address = str("/dev/log")))
119
122
    syslogger.setFormatter(logging.Formatter
120
123
                           ('Mandos [%(process)d]: %(levelname)s:'
121
124
                            ' %(message)s'))
690
693
        # If a checker exists, make sure it is not a zombie
691
694
        try:
692
695
            pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
693
 
        except (AttributeError, OSError) as error:
694
 
            if (isinstance(error, OSError)
695
 
                and error.errno != errno.ECHILD):
696
 
                raise error
 
696
        except AttributeError:
 
697
            pass
 
698
        except OSError as error:
 
699
            if error.errno != errno.ECHILD:
 
700
                raise
697
701
        else:
698
702
            if pid:
699
703
                logger.warning("Checker was a zombie")
933
937
            # The byte_arrays option is not supported yet on
934
938
            # signatures other than "ay".
935
939
            if prop._dbus_signature != "ay":
936
 
                raise ValueError
 
940
                raise ValueError("Byte arrays not supported for non-"
 
941
                                 "'ay' signature {0!r}"
 
942
                                 .format(prop._dbus_signature))
937
943
            value = dbus.ByteArray(b''.join(chr(byte)
938
944
                                            for byte in value))
939
945
        prop(value)
1347
1353
                                       *args, **kwargs)
1348
1354
    
1349
1355
    def start_checker(self, *args, **kwargs):
1350
 
        old_checker = self.checker
1351
 
        if self.checker is not None:
1352
 
            old_checker_pid = self.checker.pid
1353
 
        else:
1354
 
            old_checker_pid = None
 
1356
        old_checker_pid = getattr(self.checker, "pid", None)
1355
1357
        r = Client.start_checker(self, *args, **kwargs)
1356
1358
        # Only if new checker process was started
1357
1359
        if (self.checker is not None
1702
1704
            logger.debug("Protocol version: %r", line)
1703
1705
            try:
1704
1706
                if int(line.strip().split()[0]) > 1:
1705
 
                    raise RuntimeError
 
1707
                    raise RuntimeError(line)
1706
1708
            except (ValueError, IndexError, RuntimeError) as error:
1707
1709
                logger.error("Unknown protocol version: %s", error)
1708
1710
                return
1915
1917
    
1916
1918
    def add_pipe(self, parent_pipe, proc):
1917
1919
        """Dummy function; override as necessary"""
1918
 
        raise NotImplementedError
 
1920
        raise NotImplementedError()
1919
1921
 
1920
1922
 
1921
1923
class IPv6_TCPServer(MultiprocessingMixInWithPipe,
2258
2260
            else:
2259
2261
                raise ValueError("Unknown suffix {0!r}"
2260
2262
                                 .format(suffix))
2261
 
        except (ValueError, IndexError) as e:
 
2263
        except IndexError as e:
2262
2264
            raise ValueError(*(e.args))
2263
2265
        timevalue += delta
2264
2266
    return timevalue
2335
2337
                        help="Directory to save/restore state in")
2336
2338
    parser.add_argument("--foreground", action="store_true",
2337
2339
                        help="Run in foreground", default=None)
 
2340
    parser.add_argument("--no-zeroconf", action="store_false",
 
2341
                        dest="zeroconf", help="Do not use Zeroconf",
 
2342
                        default=None)
2338
2343
    
2339
2344
    options = parser.parse_args()
2340
2345
    
2341
2346
    if options.check:
2342
2347
        import doctest
2343
 
        doctest.testmod()
2344
 
        sys.exit()
 
2348
        fail_count, test_count = doctest.testmod()
 
2349
        sys.exit(os.EX_OK if fail_count == 0 else 1)
2345
2350
    
2346
2351
    # Default values for config file for server-global settings
2347
2352
    server_defaults = { "interface": "",
2358
2363
                        "socket": "",
2359
2364
                        "statedir": "/var/lib/mandos",
2360
2365
                        "foreground": "False",
 
2366
                        "zeroconf": "True",
2361
2367
                        }
2362
2368
    
2363
2369
    # Parse config file for server-global settings
2390
2396
    for option in ("interface", "address", "port", "debug",
2391
2397
                   "priority", "servicename", "configdir",
2392
2398
                   "use_dbus", "use_ipv6", "debuglevel", "restore",
2393
 
                   "statedir", "socket", "foreground"):
 
2399
                   "statedir", "socket", "foreground", "zeroconf"):
2394
2400
        value = getattr(options, option)
2395
2401
        if value is not None:
2396
2402
            server_settings[option] = value
2401
2407
            server_settings[option] = unicode(server_settings[option])
2402
2408
    # Force all boolean options to be boolean
2403
2409
    for option in ("debug", "use_dbus", "use_ipv6", "restore",
2404
 
                   "foreground"):
 
2410
                   "foreground", "zeroconf"):
2405
2411
        server_settings[option] = bool(server_settings[option])
2406
2412
    # Debug implies foreground
2407
2413
    if server_settings["debug"]:
2410
2416
    
2411
2417
    ##################################################################
2412
2418
    
 
2419
    if (not server_settings["zeroconf"] and
 
2420
        not (server_settings["port"]
 
2421
             or server_settings["socket"] != "")):
 
2422
            parser.error("Needs port or socket to work without"
 
2423
                         " Zeroconf")
 
2424
    
2413
2425
    # For convenience
2414
2426
    debug = server_settings["debug"]
2415
2427
    debuglevel = server_settings["debuglevel"]
2418
2430
    stored_state_path = os.path.join(server_settings["statedir"],
2419
2431
                                     stored_state_file)
2420
2432
    foreground = server_settings["foreground"]
 
2433
    zeroconf = server_settings["zeroconf"]
2421
2434
    
2422
2435
    if debug:
2423
2436
        initlogger(debug, logging.DEBUG)
2444
2457
    global mandos_dbus_service
2445
2458
    mandos_dbus_service = None
2446
2459
    
 
2460
    socketfd = None
 
2461
    if server_settings["socket"] != "":
 
2462
        socketfd = server_settings["socket"]
2447
2463
    tcp_server = MandosServer((server_settings["address"],
2448
2464
                               server_settings["port"]),
2449
2465
                              ClientHandler,
2453
2469
                              gnutls_priority=
2454
2470
                              server_settings["priority"],
2455
2471
                              use_dbus=use_dbus,
2456
 
                              socketfd=(server_settings["socket"]
2457
 
                                        or None))
 
2472
                              socketfd=socketfd)
2458
2473
    if not foreground:
2459
2474
        pidfilename = "/run/mandos.pid"
2460
2475
        if not os.path.isdir("/run/."):
2481
2496
        os.setuid(uid)
2482
2497
    except OSError as error:
2483
2498
        if error.errno != errno.EPERM:
2484
 
            raise error
 
2499
            raise
2485
2500
    
2486
2501
    if debug:
2487
2502
        # Enable all possible GnuTLS debugging
2530
2545
            use_dbus = False
2531
2546
            server_settings["use_dbus"] = False
2532
2547
            tcp_server.use_dbus = False
2533
 
    protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2534
 
    service = AvahiServiceToSyslog(name =
2535
 
                                   server_settings["servicename"],
2536
 
                                   servicetype = "_mandos._tcp",
2537
 
                                   protocol = protocol, bus = bus)
2538
 
    if server_settings["interface"]:
2539
 
        service.interface = (if_nametoindex
2540
 
                             (str(server_settings["interface"])))
 
2548
    if zeroconf:
 
2549
        protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
 
2550
        service = AvahiServiceToSyslog(name =
 
2551
                                       server_settings["servicename"],
 
2552
                                       servicetype = "_mandos._tcp",
 
2553
                                       protocol = protocol, bus = bus)
 
2554
        if server_settings["interface"]:
 
2555
            service.interface = (if_nametoindex
 
2556
                                 (str(server_settings["interface"])))
2541
2557
    
2542
2558
    global multiprocessing_manager
2543
2559
    multiprocessing_manager = multiprocessing.Manager()
2737
2753
    
2738
2754
    def cleanup():
2739
2755
        "Cleanup function; run on exit"
2740
 
        service.cleanup()
 
2756
        if zeroconf:
 
2757
            service.cleanup()
2741
2758
        
2742
2759
        multiprocessing.active_children()
2743
2760
        wnull.close()
2792
2809
            else:
2793
2810
                logger.warning("Could not save persistent state:",
2794
2811
                               exc_info=e)
2795
 
                raise e
 
2812
                raise
2796
2813
        
2797
2814
        # Delete all clients, and settings from config
2798
2815
        while tcp_server.clients:
2822
2839
    tcp_server.server_activate()
2823
2840
    
2824
2841
    # Find out what port we got
2825
 
    service.port = tcp_server.socket.getsockname()[1]
 
2842
    if zeroconf:
 
2843
        service.port = tcp_server.socket.getsockname()[1]
2826
2844
    if use_ipv6:
2827
2845
        logger.info("Now listening on address %r, port %d,"
2828
2846
                    " flowinfo %d, scope_id %d",
2834
2852
    #service.interface = tcp_server.socket.getsockname()[3]
2835
2853
    
2836
2854
    try:
2837
 
        # From the Avahi example code
2838
 
        try:
2839
 
            service.activate()
2840
 
        except dbus.exceptions.DBusException as error:
2841
 
            logger.critical("D-Bus Exception", exc_info=error)
2842
 
            cleanup()
2843
 
            sys.exit(1)
2844
 
        # End of Avahi example code
 
2855
        if zeroconf:
 
2856
            # From the Avahi example code
 
2857
            try:
 
2858
                service.activate()
 
2859
            except dbus.exceptions.DBusException as error:
 
2860
                logger.critical("D-Bus Exception", exc_info=error)
 
2861
                cleanup()
 
2862
                sys.exit(1)
 
2863
            # End of Avahi example code
2845
2864
        
2846
2865
        gobject.io_add_watch(tcp_server.fileno(), gobject.IO_IN,
2847
2866
                             lambda *args, **kwargs: