aboutsummaryrefslogtreecommitdiffstats
path: root/lib/Iurt/RPM.pm
blob: de09ba41d2f9a04b44abcd41354fee688e6aa409 (plain)
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
package Iurt::RPM;

use base qw(Exporter);
use RPM4::Header;
use MDK::Common;
use strict;

our @EXPORT = qw(
    check_arch
    check_noarch
);

sub check_noarch {
    my ($rpm) = @_;
    my $hdr = RPM4::Header->new($rpm);

    # Stupid rpm doesn't return an empty list so we must check for (none)

    my ($build_archs) = $hdr->queryformat('%{BUILDARCHS}');

    if ($build_archs ne '(none)') {
	($build_archs) = $hdr->queryformat('[%{BUILDARCHS} ]');
	my @list = split ' ', $build_archs;
	return 1 if member('noarch', @list);
    }

    return 0;
}

sub check_arch {
    my ($rpm, $arch) = @_;
    my $hdr = RPM4::Header->new($rpm);

    # Stupid rpm doesn't return an empty list so we must check for (none)

    my ($exclusive_arch) = $hdr->queryformat('%{EXCLUSIVEARCH}');

    if ($exclusive_arch ne '(none)') {
	($exclusive_arch) = $hdr->queryformat('[%{EXCLUSIVEARCH} ]');
	my @list = split ' ', $exclusive_arch;
	return 0 unless member($arch, @list);
    }

    my ($exclude_arch) = $hdr->queryformat('[%{EXCLUDEARCH} ]');

    if ($exclude_arch ne '(none)') {
	($exclude_arch) = $hdr->queryformat('[%{EXCLUDEARCH} ]');
	my @list = split ' ', $exclude_arch;
	return 0 if member($arch, @list);
    }

    return 1;
}

1;
id='n259' href='#n259'>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 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980
# vim: set et ts=4 sw=4:
package ManaTools::Shared::Services;
#============================================================= -*-perl-*-

=head1 NAME

ManaTools::Shared::Services - shares the API to manage services

=head1 SYNOPSIS

use ManaTools::Shared::Services;

my $serv = ManaTools::Shared::Services->new();

my ($l, $on_services) = $serv->services();

=head1 DESCRIPTION

  This module aims to share all the API to manage system services,
  to be used from GUI applications or console.

  From the original code drakx services.

=head1 SUPPORT

You can find documentation for this module with the perldoc command:

perldoc ManaTools::Shared::Services

=head1 SEE ALSO

ManaTools::Shared

=head1 AUTHOR

Angelo Naselli <anaselli@linux.it>

=head1 COPYRIGHT and LICENSE

Copyright (C) 2013-2016, Angelo Naselli.

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2, as
published by the Free Software Foundation.

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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA

=head1 FUNCTIONS

=cut


use Moose;

use Sys::Syslog;
use Net::DBus;
use Net::DBus::Annotation qw(:auth);
use File::Basename;

use ManaTools::Shared::Locales;
use MDK::Common::Func qw(find);
use MDK::Common::File;
use MDK::Common::DataStructure qw(member);
use ManaTools::Shared::RunProgram qw(rooted);

has 'loc' => (
        is => 'rw',
        isa => 'ManaTools::Shared::Locales',
        lazy => 1,
        builder => '_localeInitialize',
);


sub _localeInitialize {
    my $self = shift;

    $self->loc(
        ManaTools::Shared::Locales->new(
            domain_name => 'manatools',
        )
    );
}


has 'dbus_systemd1_service' => (
    is       => 'rw',
    init_arg => undef,
    lazy     => 1,
    builder  => '_dbusServiceInitialize'
);

sub _dbusServiceInitialize {
    my $self = shift();

    my $bus = Net::DBus->system;
    $self->dbus_systemd1_service($bus->get_service("org.freedesktop.systemd1"));
}


has 'dbus_systemd1_object' => (
    is       => 'rw',
    init_arg => undef,
    lazy     => 1,
    builder  => '_dbusObjectInitialize'
);

sub _dbusObjectInitialize {
    my $self = shift();

    $self->dbus_systemd1_object($self->dbus_systemd1_service->get_object("/org/freedesktop/systemd1"));
}

has 'include_static_services' => (
    is  => 'rw',
    isa => 'Bool',
    default => 0
);

#=============================================================

=head2 attributes

=head3 service_info

    A HashRef collecting all the service information.
    if include_static_services (default is false) is set also static
    services are included.

=cut

#=============================================================
has 'service_info' => (
    is  => 'rw',
    traits    => ['Hash'],
    isa       => 'HashRef',
    handles   => {
        set_service_info   => 'set',
        get_service_info   => 'get',
        service_info_pairs => 'kv',
    },
    init_arg  => undef,
    lazy     => 1,
    builder  => '_serviceInfoInitialization'
);

sub _serviceInfoInitialization {
    my $self = shift();

    my %services = ();
    if ($self->_running_systemd()) {
        my $object     = $self->dbus_systemd1_object;
        my $properties = $object->ListUnits();

        foreach my $s (@{$properties}) {
            my $name = $s->[0];
            if (index($name, ".service") != -1) {
                my $st = eval{$object->GetUnitFileState($name)} if $name !~ /.*\@.*$/g;
                $name =~ s|.service||;
                if (!$st) {
                    if ($name !~ /.*\@$/g &&
                        (-e "/usr/lib/systemd/system/$name.service" or -e "/etc/rc.d/init.d/$name") &&
                        ! -l "/usr/lib/systemd/system/$name.service") {
                            $st = 'enabled';
                        }
                }
                if ($st && ($self->include_static_services() || $st ne 'static')) {
                    $services{$name} = {
                        'name' => $s->[0],
                        'description' => $s->[1],
                        'load_state' => $s->[2],
                        'active_state' => $s->[3],
                        'sub_state' => $s->[4],
                        'unit_path' => $s->[6],
                        'enabled'   => $st eq 'enabled',
                    };
                }
            }
        }

        my $unit_files = $object->ListUnitFiles();
        foreach my $s (@{$unit_files}) {
            my $name = $s->[0];
            my $st = $s->[1];
            if (index($name, ".service") != -1) {
                $name = File::Basename::basename($name, ".service");
                if (!$services{$name} &&
                    $name !~ /.*\@$/g &&
                    (-e $s->[0] or -e "/etc/rc.d/init.d/$name") &&
                    ! -l $s->[0] && ($st eq "disabled" || $st eq "enabled")) {
                    my $wantedby = $self->_WantedBy($s->[0]);
                    if ($wantedby) {
                        my $descr = $self->getUnitProperty($name, 'Description');

                        $services{$name} = {
                            'name'        => $name,
                            'description' => $descr,
                            'enabled'     => $st eq "enabled",
                        };
                    }
                }
            }
        }
    }

    return \%services;
}

#=============================================================

=head2 description

=head3 INPUT

name: Service Name

=head3 OUTPUT

Description: Service description

=head3 DESCRIPTION

THis function return the description for the given service

=cut

#=============================================================
sub description {
    my ($self, $name) = @_;

    my %services = (
acpid => $self->loc->N_("Listen and dispatch ACPI events from the kernel"),
alsa => $self->loc->N_("Launch the ALSA (Advanced Linux Sound Architecture) sound system"),
anacron => $self->loc->N_("Anacron is a periodic command scheduler."),
apmd => $self->loc->N_("apmd is used for monitoring battery status and logging it via syslog.
It can also be used for shutting down the machine when the battery is low."),
atd => $self->loc->N_("Runs commands scheduled by the at command at the time specified when
at was run, and runs batch commands when the load average is low enough."),
'avahi-deamon' => $self->loc->N_("Avahi is a ZeroConf daemon which implements an mDNS stack"),
chronyd => $self->loc->N_("An NTP client/server"),
cpufreq => $self->loc->N_("Set CPU frequency settings"),
crond => $self->loc->N_("cron is a standard UNIX program that runs user-specified programs
at periodic scheduled times. vixie cron adds a number of features to the basic
UNIX cron, including better security and more powerful configuration options."),
cups => $self->loc->N_("Common UNIX Printing System (CUPS) is an advanced printer spooling system"),
dm => $self->loc->N_("Launches the graphical display manager"),
fam => $self->loc->N_("FAM is a file monitoring daemon. It is used to get reports when files change.
It is used by GNOME and KDE"),
g15daemon => $self->loc->N_("G15Daemon allows users access to all extra keys by decoding them and
pushing them back into the kernel via the linux UINPUT driver. This driver must be loaded
before g15daemon can be used for keyboard access. The G15 LCD is also supported. By default,
with no other clients active, g15daemon will display a clock. Client applications and
scripts can access the LCD via a simple API."),
gpm => $self->loc->N_("GPM adds mouse support to text-based Linux applications such the
Midnight Commander. It also allows mouse-based console cut-and-paste operations,
and includes support for pop-up menus on the console."),
haldaemon => $self->loc->N_("HAL is a daemon that collects and maintains information about hardware"),
harddrake => $self->loc->N_("HardDrake runs a hardware probe, and optionally configures
new/changed hardware."),
httpd => $self->loc->N_("Apache is a World Wide Web server. It is used to serve HTML files and CGI."),
inet => $self->loc->N_("The internet superserver daemon (commonly called inetd) starts a
variety of other internet services as needed. It is responsible for starting
many services, including telnet, ftp, rsh, and rlogin. Disabling inetd disables
all of the services it is responsible for."),
ip6tables => $self->loc->N_("Automates a packet filtering firewall with ip6tables"),
iptables => $self->loc->N_("Automates a packet filtering firewall with iptables"),
irqbalance => $self->loc->N_("Evenly distributes IRQ load across multiple CPUs for enhanced performance"),
keytable => $self->loc->N_("This package loads the selected keyboard map as set in
/etc/sysconfig/keyboard.  This can be selected using the kbdconfig utility.
You should leave this enabled for most machines."),
kheader => $self->loc->N_("Automatic regeneration of kernel header in /boot for
/usr/include/linux/{autoconf,version}.h"),
kudzu => $self->loc->N_("Automatic detection and configuration of hardware at boot."),
'laptop-mode' => $self->loc->N_("Tweaks system behavior to extend battery life"),
linuxconf => $self->loc->N_("Linuxconf will sometimes arrange to perform various tasks
at boot-time to maintain the system configuration."),
lpd => $self->loc->N_("lpd is the print daemon required for lpr to work properly. It is
basically a server that arbitrates print jobs to printer(s)."),
lvs => $self->loc->N_("Linux Virtual Server, used to build a high-performance and highly
available server."),
mandi => $self->loc->N_("Monitors the network (Interactive Firewall and wireless)"),
mdadm => $self->loc->N_("Software RAID monitoring and management"),
messagebus => $self->loc->N_("DBUS is a daemon which broadcasts notifications of system events and other messages"),
msec => $self->loc->N_("Enables MSEC security policy on system startup"),
named => $self->loc->N_("named (BIND) is a Domain Name Server (DNS) that is used to resolve host names to IP addresses."),
netconsole => $self->loc->N_("Initializes network console logging"),
netfs => $self->loc->N_("Mounts and unmounts all Network File System (NFS), SMB (Lan
Manager/Windows), and NCP (NetWare) mount points."),
network => $self->loc->N_("Activates/Deactivates all network interfaces configured to start
at boot time."),
'network-auth' => $self->loc->N_("Requires network to be up if enabled"),
'network-up' => $self->loc->N_("Wait for the hotplugged network to be up"),
nfs => $self->loc->N_("NFS is a popular protocol for file sharing across TCP/IP networks.
This service provides NFS server functionality, which is configured via the
/etc/exports file."),
nfslock => $self->loc->N_("NFS is a popular protocol for file sharing across TCP/IP
networks. This service provides NFS file locking functionality."),
ntpd => $self->loc->N_("Synchronizes system time using the Network Time Protocol (NTP)"),
numlock => $self->loc->N_("Automatically switch on numlock key locker under console
and Xorg at boot."),
oki4daemon => $self->loc->N_("Support the OKI 4w and compatible winprinters."),
partmon => $self->loc->N_("Checks if a partition is close to full up"),
pcmcia => $self->loc->N_("PCMCIA support is usually to support things like ethernet and
modems in laptops.  It will not get started unless configured so it is safe to have
it installed on machines that do not need it."),
portmap => $self->loc->N_("The portmapper manages RPC connections, which are used by
protocols such as NFS and NIS. The portmap server must be running on machines
which act as servers for protocols which make use of the RPC mechanism."),
portreserve => $self->loc->N_("Reserves some TCP ports"),
postfix => $self->loc->N_("Postfix is a Mail Transport Agent, which is the program that moves mail from one machine to another."),
random => $self->loc->N_("Saves and restores system entropy pool for higher quality random
number generation."),
rawdevices => $self->loc->N_("Assign raw devices to block devices (such as hard disk drive
partitions), for the use of applications such as Oracle or DVD players"),
resolvconf => $self->loc->N_("Nameserver information manager"),
routed => $self->loc->N_("The routed daemon allows for automatic IP router table updated via
the Routing Information Protocol. While RIP is widely used on small networks, more complex
routing protocols are needed for complex networks."),
rstatd => $self->loc->N_("The rstat protocol allows users on a network to retrieve
performance metrics for any machine on that network."),
rsyslog => $self->loc->N_("Syslog is the facility by which many daemons use to log messages to various system log files.  It is a good idea to always run rsyslog."),
rusersd => $self->loc->N_("The rusers protocol allows users on a network to identify who is
logged in on other responding machines."),
rwhod => $self->loc->N_("The rwho protocol lets remote users get a list of all of the users
logged into a machine running the rwho daemon (similar to finger)."),
saned => $self->loc->N_("SANE (Scanner Access Now Easy) enables to access scanners, video cameras, ..."),
shorewall => $self->loc->N_("Packet filtering firewall"),
smb => $self->loc->N_("The SMB/CIFS protocol enables to share access to files & printers and also integrates with a Windows Server domain"),
sound => $self->loc->N_("Launch the sound system on your machine"),
'speech-dispatcherd' => $self->loc->N_("layer for speech analysis"),
sshd => $self->loc->N_("Secure Shell is a network protocol that allows data to be exchanged over a secure channel between two computers"),
syslog => $self->loc->N_("Syslog is the facility by which many daemons use to log messages
to various system log files.  It is a good idea to always run syslog."),
'udev-post' => $self->loc->N_("Moves the generated persistent udev rules to /etc/udev/rules.d"),
usb => $self->loc->N_("Load the drivers for your usb devices."),
vnStat => $self->loc->N_("A lightweight network traffic monitor"),
xfs => $self->loc->N_("Starts the X Font Server."),
xinetd => $self->loc->N_("Starts other deamons on demand."),
    );

    my $s = $services{$name};
    if ($s) {
        $s = $self->loc->N($s);
    }
    elsif ($self->get_service_info($name)) {
        $s = $self->get_service_info($name)->{description};
    }
    else {
        my $file = "/usr/lib/systemd/system/$name.service";
        if (-e $file) {
                $s = MDK::Common::File::cat_($file);
                $s = $s =~ /^Description=(.*)/mg ? $1 : '';
        } else {
                $file = MDK::Common::Func::find { -e $_ } map { "$_/$name" } '/etc/rc.d/init.d', '/etc/init.d', '/etc/xinetd.d';
                $s = MDK::Common::File::cat_($file);
                $s =~ s/\\\s*\n#\s*//mg;
                $s =
                        $s =~ /^#\s+(?:Short-)?[dD]escription:\s+(.*?)^(?:[^#]|# {0,2}\S)/sm ? $1 :
                        $s =~ /^#\s*(.*?)^[^#]/sm ? $1 : '';

                $s =~ s/#\s*//mg;
        }
    }
    $s =~ s/\n/ /gm; $s =~ s/\s+$//;
    $s;
}


#=============================================================

=head2 set_service

=head3 INPUT

    $service: Service name
    $enable:  enable/disable service

=head3 DESCRIPTION

    This function enable/disable at boot the given service

=cut

#=============================================================
sub set_service {
    my ($self, $service, $enable) = @_;

    my @xinetd_services = map { $_->[0] } $self->xinetd_services();

    # NOTE EnableUnitFiles and DisableUnitFiles don't work with legacy services
    #      and return file not found
    my $legacy = -e "/etc/rc.d/init.d/$service";

    if (MDK::Common::DataStructure::member($service, @xinetd_services)) {
        $ENV{PATH} = "/usr/bin:/usr/sbin";
        ManaTools::Shared::RunProgram::rooted("", "/usr/sbin/chkconfig", $enable ? "--add" : "--del", $service);
    } elsif (!$legacy && ($self->_running_systemd() || $self->_has_systemd())) {
        $service = $service . ".service";
        my $dbus_object = $self->dbus_systemd1_object;
        if ($enable) {
            $dbus_object->EnableUnitFiles(dbus_auth_interactive, [$service], 0, 1);
        }
        else {
            $dbus_object->DisableUnitFiles(dbus_auth_interactive, [$service], 0);
        }
        # reload local cache
        $self->_systemd_services(1);
    } else {
        my $script = "/etc/rc.d/init.d/$service";
        $ENV{PATH} = "/usr/bin:/usr/sbin";
        ManaTools::Shared::RunProgram::rooted("", "/usr/sbin/chkconfig", $enable ? "--add" : "--del", $service);
        #- FIXME: handle services with no chkconfig line and with no Default-Start levels in LSB header
        if ($enable && MDK::Common::File::cat_("$script") =~ /^#\s+chkconfig:\s+-/m) {
            $ENV{PATH} = "/usr/bin:/usr/sbin";
            ManaTools::Shared::RunProgram::rooted("", "/usr/sbin/chkconfig", "--level", "35", $service, "on");
        }
    }
}

sub _run_action {
    my ($self, $service, $action) = @_;
    if ($self->_running_systemd()) {
        my $object     = $self->dbus_systemd1_object;
        if ($action eq 'start') {
            $object->StartUnit(dbus_auth_interactive, "$service.service", 'fail');
        }
        elsif ($action eq 'stop') {
            $object->StopUnit(dbus_auth_interactive, "$service.service", 'fail');
        }
        else {
            $object->RestartUnit(dbus_auth_interactive, "$service.service", 'fail');
        }
        # reload local cache