File: emitters.cpp

package info (click to toggle)
dnf5 5.4.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 17,960 kB
  • sloc: cpp: 94,312; python: 3,370; xml: 1,073; ruby: 600; sql: 250; ansic: 232; sh: 104; perl: 62; makefile: 30
file content (243 lines) | stat: -rw-r--r-- 8,889 bytes parent folder | download
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
// Copyright Contributors to the DNF5 project.
// Copyright (C) 2022 Red Hat, Inc.
// SPDX-License-Identifier: LGPL-2.0-or-later
//
// This file is part of libdnf: https://github.com/rpm-software-management/dnf5/
//
// Libdnf is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// Libdnf 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with libdnf.  If not, see <https://www.gnu.org/licenses/>.

#include "emitters.hpp"

#include "email_message.hpp"

#include <curl/curl.h>
#include <libdnf5/base/transaction_package.hpp>
#include <libdnf5/utils/bgettext/bgettext-lib.h>
#include <libdnf5/utils/format.hpp>
#include <stdio.h>
#include <string.h>

#include <cstdio>
#include <fstream>
#include <iomanip>
#include <iostream>

namespace dnf5 {

constexpr const char * MOTD_FILENAME = "/etc/motd.d/dnf5-automatic";
enum class AutomaticStage { CHECK, DOWNLOAD, APPLY };

int Emitter::upgrades_count() {
    int count = 0;
    for (const auto & pkg : transaction.get_transaction_packages()) {
        if (transaction_item_action_is_outbound(pkg.get_action())) {
            ++count;
        }
    }
    return count;
}

std::string Emitter::short_message() {
    std::string message;

    auto stage = AutomaticStage::CHECK;
    if (config_automatic.config_commands.apply_updates.get_value()) {
        stage = AutomaticStage::APPLY;
    } else if (config_automatic.config_commands.download_updates.get_value()) {
        stage = AutomaticStage::DOWNLOAD;
    }

    if (success) {
        if (transaction.empty()) {
            message = _("No new upgrades available.");
        } else {
            switch (stage) {
                case AutomaticStage::CHECK:
                    message = _("{} packages can be upgraded.");
                    break;
                case AutomaticStage::DOWNLOAD:
                    message = _("{} new upgrades have been downloaded.");
                    break;
                case AutomaticStage::APPLY:
                    message = _("{} new upgrades have been installed.");
                    break;
            }
            message = libdnf5::utils::sformat(message, upgrades_count());
        }
    } else {
        switch (stage) {
            case AutomaticStage::CHECK:
                message = _("Failed to check for upgrades.");
                break;
            case AutomaticStage::DOWNLOAD:
                message = _("Failed to download upgrades.");
                break;
            case AutomaticStage::APPLY:
                message = _("Failed to install upgrades.");
                break;
        }
    }
    return message;
}

void EmitterStdIO::notify() {
    std::cout << short_message() << std::endl;
    auto output = output_stream.str();
    if (!output.empty()) {
        std::cout << std::endl;
        std::cout << output;
    }
}

void EmitterMotd::notify() {
    std::ofstream motd_file_stream(MOTD_FILENAME);
    if (!motd_file_stream.is_open()) {
        return;
    }
    motd_file_stream << "dnf5-automatic: " << short_message() << std::endl;
    motd_file_stream.close();
}

std::string quote(std::string_view str) {
    std::ostringstream temp_stream;
    temp_stream << std::quoted(str);
    return temp_stream.str();
}

void EmitterCommand::notify() {
    std::string command_format = config_automatic.config_command.command_format.get_value();
    std::string command = libdnf5::utils::sformat(command_format, fmt::arg("body", quote(output_stream.str())));

    FILE * command_pipe = popen(command.c_str(), "w");
    if (command_pipe) {
        std::string stdin_format = config_automatic.config_command.stdin_format.get_value();
        fputs(libdnf5::utils::sformat(stdin_format, fmt::arg("body", output_stream.str())).c_str(), command_pipe);
        std::fflush(command_pipe);
        pclose(command_pipe);
    }
}

void EmitterCommandEmail::notify() {
    std::string command_format = config_automatic.config_command_email.command_format.get_value();
    std::string email_from = config_automatic.config_command_email.email_from.get_value();
    std::string email_to;
    for (const auto & email : config_automatic.config_command_email.email_to.get_value()) {
        if (!email_to.empty()) {
            email_to += " ";
        }
        email_to += quote(email);
    }
    std::string subject = libdnf5::utils::sformat(
        _("[{}] dnf5-automatic: {}"), config_automatic.config_emitters.system_name.get_value(), short_message());

    std::string command_string = libdnf5::utils::sformat(
        command_format,
        fmt::arg("body", quote(output_stream.str())),
        fmt::arg("subject", quote(subject)),
        fmt::arg("email_from", quote(email_from)),
        fmt::arg("email_to", email_to));

    FILE * command_pipe = popen(command_string.c_str(), "w");
    if (command_pipe) {
        std::string stdin_format = config_automatic.config_command_email.stdin_format.get_value();
        fputs(libdnf5::utils::sformat(stdin_format, fmt::arg("body", output_stream.str())).c_str(), command_pipe);
        std::fflush(command_pipe);
        pclose(command_pipe);
    }
}

void EmitterEmail::notify() {
    EmailMessage message;
    std::string subject = libdnf5::utils::sformat(
        _("[{}] dnf5-automatic: {}"), config_automatic.config_emitters.system_name.get_value(), short_message());

    std::vector<std::string> to = config_automatic.config_email.email_to.get_value();
    std::string from = config_automatic.config_email.email_from.get_value();
    message.set_to(to);
    message.set_from(from);
    message.set_subject(subject);
    message.set_body(output_stream);

    {
        // use curl to send the message
        std::string payload = message.str();
        std::string tls = config_automatic.config_email.email_tls.get_value();

        CURL * curl;
        CURLcode res = CURLE_OK;
        struct curl_slist * recipients = NULL;

        curl = curl_easy_init();
        if (curl) {
            // TODO(mblaha): option for switching the debugging messages on?
            // curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);

            curl_easy_setopt(curl, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);

            const char * protocol = "smtp";
            if (tls == "starttls") {
                curl_easy_setopt(curl, CURLOPT_USE_SSL, (long)CURLUSESSL_ALL);
            } else if (tls == "yes") {
                protocol = "smtps";
            }

            // TODO(mblaha): check smtp protocol availability?
            curl_version_info_data * ver;
            ver = curl_version_info(CURLVERSION_NOW);
            bool protocol_supported = false;
            for (auto ptr = ver->protocols; *ptr; ++ptr) {
                if (strcmp(*ptr, protocol) == 0) {
                    protocol_supported = true;
                    break;
                }
            }
            if (protocol_supported) {
                std::string email_host = libdnf5::utils::sformat(
                    "{}://{}:{}/",
                    protocol,
                    config_automatic.config_email.email_host.get_value(),
                    config_automatic.config_email.email_port.get_value());
                curl_easy_setopt(curl, CURLOPT_URL, email_host.c_str());

                curl_easy_setopt(curl, CURLOPT_MAIL_FROM, from.c_str());

                for (const auto & eml : to) {
                    recipients = curl_slist_append(recipients, eml.c_str());
                }
                curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, recipients);

                FILE * payload_file = fmemopen(payload.data(), payload.size(), "r");
                curl_easy_setopt(curl, CURLOPT_READDATA, payload_file);

                curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);

                res = curl_easy_perform(curl);
                fclose(payload_file);
                if (res != CURLE_OK) {
                    std::cerr << "libcurl error while sending e-mail: " << curl_easy_strerror(res) << std::endl;
                }
            } else {
                std::cerr << "Error: installed version of libcurl does not support " << protocol
                          << " protocol. Cannot use \"email\" emitter to send the results. On Fedora please check that "
                             "libcurl package is installed."
                          << std::endl;
            }

            curl_slist_free_all(recipients);
            curl_easy_cleanup(curl);
        }
    }
}

}  // namespace dnf5