summaryrefslogtreecommitdiff
path: root/src/logic.cpp
blob: 170f566dc1bd79d0fb1aefe4265d51fe511aa87b (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
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
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
/*
 * Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
/*
 * @file        logic.cpp
 * @author      Janusz Kozerski (j.kozerski@samsung.com)
 * @version     1.0
 * @brief       This file is the implementation of SQL queries
 */
#include <stdexcept>
#include <tzplatform_config.h>
#include <app_control_internal.h>

#include <cchecker/logic.h>
#include <cchecker/log.h>
#include <cchecker/sql_query.h>
#include <cchecker/UIBackend.h>

using namespace std;

namespace CCHECKER {

namespace {
const char *const DB_PATH = tzplatform_mkpath(TZ_SYS_DB, ".cert-checker.db");
}

Logic::~Logic(void)
{
    clean();
}

void Logic::clean(void)
{
    LogDebug("Cert-checker cleaning.");

    // wait and join processing thread
    if (m_thread.joinable()) {
        LogDebug("Waiting for join processing thread");
        {
            std::lock_guard<std::mutex> lock(m_mutex_cv);
            set_should_exit();
            m_to_process.notify_one();
        }
        m_thread.join();
        LogDebug("Processing thread joined");
    }
    else
        LogDebug("No thread to join");

    if (m_proxy_connman)
        g_object_unref(m_proxy_connman);
    if (m_proxy_pkgmgr_install)
        g_object_unref(m_proxy_pkgmgr_install);
    if (m_proxy_pkgmgr_uninstall)
        g_object_unref(m_proxy_pkgmgr_uninstall);
    delete m_sqlquery;
}

Logic::Logic(void) :
        m_sqlquery(NULL),
        m_was_setup_called(false),
        m_is_online(false),
        m_is_online_enabled(false),
        m_should_exit(false),
        m_proxy_connman(NULL),
        m_proxy_pkgmgr_install(NULL),
        m_proxy_pkgmgr_uninstall(NULL)
{}

bool Logic::get_online() const
{
    return m_is_online;
}

void Logic::set_online(bool online)
{
    std::lock_guard<std::mutex> lock(m_mutex_cv);
    if (m_is_online == online)
        return;
    m_is_online = online;
    if (m_is_online) {
        m_is_online_enabled = true;
        m_to_process.notify_one();
    }
}

error_t Logic::setup_db()
{
    // TODO: If database doesn't exist -should we create a new one?
    Try {
        m_sqlquery = new DB::SqlQuery(DB_PATH);
    } Catch (runtime_error) {
        LogError("Error while creating SqlQuery object");
        return DATABASE_ERROR;
    }

    if(!m_sqlquery) {
        LogError("Cannot open database");
        return DATABASE_ERROR;
    }

    return NO_ERROR;
}

error_t  Logic::setup()
{
    // Check if setup was called
    if (m_was_setup_called) {
        LogError("You can call setup only once");
        return INTERNAL_ERROR;
    }
    m_was_setup_called = true;

    // Check if DB exists and create a new one if it doesn't
    error_t err = setup_db();
    if (err != NO_ERROR) {
        LogError("Database error");
        return err;
    }

    load_database_to_buffer();

    // run process thread - thread will be waiting on condition variable
    m_thread = std::thread(&Logic::process_all, this);

    // FIXME: pkgmanager API signal handling was temporarily replaced
    //        by dbus API

    // Add pkgmgr install callback
    LogDebug("register pkgmgr install event callback start");
    if (register_dbus_signal_handler(&m_proxy_pkgmgr_install,
            "org.tizen.slp.pkgmgr_status",
            "/org/tizen/slp/pkgmgr/install",
            "org.tizen.slp.pkgmgr.install",
            pkgmgr_install_callback) != NO_ERROR) {
        LogError("Error in register_pkgmgr_install_signal_handler");
        return REGISTER_CALLBACK_ERROR;
    }
    LogDebug("register pkgmgr install event callback success");

    // Add pkgmgr uninstall callback
    LogDebug("register pkgmgr uninstall event callback start");
    if (register_dbus_signal_handler(&m_proxy_pkgmgr_uninstall,
            "org.tizen.slp.pkgmgr_status",
            "/org/tizen/slp/pkgmgr/uninstall",
            "org.tizen.slp.pkgmgr.uninstall",
            pkgmgr_uninstall_callback) != NO_ERROR) {
        LogError("Error in register_pkgmgr_uninstall_signal_handler");
        return REGISTER_CALLBACK_ERROR;
    }
    LogDebug("register pkgmgr uninstall event callback success");

    // Add connman callback
    LogDebug("register connman event callback start");
    if (register_dbus_signal_handler(&m_proxy_connman,
            "net.connman",
            "/",
            "net.connman.Manager",
            connman_callback) != NO_ERROR) {
        LogError("Error in register_connman_signal_handler");
        return REGISTER_CALLBACK_ERROR;
    }
    LogDebug("register connman event callback success");

    set_connman_online_state();

    return NO_ERROR;
}

error_t Logic::register_dbus_signal_handler(GDBusProxy **proxy,
        const char *name,
        const char *object_path,
        const char *interface_name,
        void (*callback) (GDBusProxy *proxy,
                          gchar      *sender_name,
                          gchar      *signal_name,
                          GVariant   *parameters,
                          void *logic_ptr)
        )
{
    GError *error = NULL;
    GDBusProxyFlags flags = G_DBUS_PROXY_FLAGS_NONE;

    // Obtain a connection to the System Bus
    *proxy = g_dbus_proxy_new_for_bus_sync(G_BUS_TYPE_SYSTEM,
            flags,
            NULL, /* GDBusInterfaceInfo */
            name,
            object_path,
            interface_name,
            NULL, /* GCancellable */
            &error);

    if (*proxy == NULL) {
        if (error) {
            LogError("Error creating D-Bus proxy for /'" << interface_name <<"/': " << error->message);
            g_error_free(error);
        } else {
            LogError("Error creating D-Bus proxy for /'" << interface_name <<"/'. Unknown error");
        }
        return DBUS_ERROR;
    }

    // Connect to g-signal to receive signals from proxy
    if (g_signal_connect(*proxy, "g-signal", G_CALLBACK(callback), this) < 1) {
        LogError("g_signal_connect error while connecting " << interface_name);
        return REGISTER_CALLBACK_ERROR;
    }

    return NO_ERROR;
}

void Logic::set_connman_online_state()
{
    GError *error = NULL;
    GVariant *response;

    if (m_proxy_connman == NULL) {
        LogError("connman proxy is NULL");
        return;
    }

    response = g_dbus_proxy_call_sync (m_proxy_connman,
            "GetProperties",
            NULL, // GetProperties gets no parameters
            G_DBUS_CALL_FLAGS_NONE,
            -1, // Default timeout
            NULL,
            &error);

    if (error) {
        LogError("Error while calling connman GetProperties() Dbus API: " << error->message);
        g_error_free(error);
        return;
    }

    if (response == NULL) {
        // This should never happen
        return;
    }

    gchar *resp_g = g_variant_print(response, TRUE);
    std::string resp_s(resp_g);
    LogDebug("response: " << resp_s);
    g_free(resp_g);

    // Response should look like this:
    // ({'State': <'online'>, 'OfflineMode': <false>, 'SessionMode': <false>},)
    if (resp_s.find("'State': <'online'>", 0) != std::string::npos) {
        LogDebug("Connman has returned: online");
        set_online(true);
    }

    // free memory
    g_variant_unref(response);
}

// FIXME: pkgmgr callback doesn't receive signals with successful installation/uninstallation.
//        For now it will be replaced by low-level signal handling from DBUS.
void Logic::pkgmgr_install_callback(GDBusProxy */*proxy*/,
                                    gchar      */*sender_name*/,
                                    gchar      */*signal_name*/,
                                    GVariant   *parameters,
                                    void       *logic_ptr)
{
    LogDebug("----------------- pkgmgr_install_callback -----------------\n");

    Logic *logic = static_cast<Logic*> (logic_ptr);
    logic->pkgmgr_callback_internal(parameters, EVENT_INSTALL);
}

void Logic::pkgmgr_uninstall_callback(GDBusProxy */*proxy*/,
                                      gchar      */*sender_name*/,
                                      gchar      */*signal_name*/,
                                      GVariant   *parameters,
                                      void       *logic_ptr)
{
    LogDebug("----------------- pkgmgr_uninstall_callback -----------------\n");

    Logic *logic = static_cast<Logic*> (logic_ptr);
    logic->pkgmgr_callback_internal(parameters, EVENT_UNINSTALL);
}

void Logic::pkgmgr_callback_internal(GVariant       *parameters,
                                     pkgmgr_event_t event)
{
    gchar *parameters_g = g_variant_print(parameters, TRUE);
    std::string params_str = std::string(parameters_g);
    LogDebug("params: " << params_str);
    g_free (parameters_g);

    /* DBus message format from pkgmgr:
     * uint32 5001
     * string "/usr/share/widget_demo/mancala.wgt_-427832739"
     * string "wgt"
     * string "yKrWwxz1KX"
     * string "end"
     * string "ok"
     *
     * Check if numbers of children (vaules) fits - should be 6:
     */
    int num = g_variant_n_children(parameters);
    if (num != 6) {
        LogError("Wrong number of children in g_variant: " << num << ", but should be 6.");
        return;
    }

    guint32 uid = g_variant_get_uint32(g_variant_get_child_value(parameters, 0));
    const gchar *pkgid = g_variant_get_string(g_variant_get_child_value(parameters, 3), NULL);
    const gchar *state = g_variant_get_string(g_variant_get_child_value(parameters, 4), NULL);
    const gchar *status = g_variant_get_string(g_variant_get_child_value(parameters, 5), NULL);

    // FIXME: No information about app_id in the signal. Use stub.
    app_t app(TEMP_APP_ID, pkgid, uid, {});

    if (std::string(state) == "end" && std::string(status) == "ok") {
        if (event == EVENT_INSTALL) {
            LogDebug("Install: uid : " << uid << ", pkgid: " << pkgid <<
                    ", state: " << state << ", status: " << status);
            push_event(event_t(app, event_t::event_type_t::APP_INSTALL));
        }
        else if (event == EVENT_UNINSTALL) {
            LogDebug("Uninstall: uid : " << uid << ", pkgid: " << pkgid <<
                    ", state: " << state << ", status: " << status);
            push_event(event_t(app, event_t::event_type_t::APP_UNINSTALL));
        }
    }
    else
        LogDebug("Wrong state (" << std::string(state) << ") or status (" << std::string(status) << ")");
}

void Logic::connman_callback(GDBusProxy */*proxy*/,
                             gchar      */*sender_name*/,
                             gchar      *signal_name,
                             GVariant   *parameters,
                             void *logic_ptr)
{
    string signal_name_str = string(signal_name);
    if (signal_name_str != "PropertyChanged") {
        // Invalid param. Nothing to do here.
        return;
    }

    gchar *parameters_g = g_variant_print(parameters, TRUE);
    string params_str = string(parameters_g);
    g_free (parameters_g);

    Logic *logic = static_cast<Logic*> (logic_ptr);

    if (params_str == "('State', <'online'>)") {
        LogDebug("Device online");
        logic->set_online(true);
        logic->m_to_process.notify_one();
    }
    else if (params_str == "('State', <'offline'>)") {
        LogDebug("Device offline");
        logic->set_online(false);
    }
}

void Logic::add_ocsp_url(const string &issuer, const string &url, int64_t date)
{
    m_sqlquery->set_url(issuer, url, date);
}

void Logic::load_database_to_buffer()
{
    LogDebug("Loading database to the buffer");
    m_sqlquery->get_app_list(m_buffer);
}

/**
 * This function should move all event from queue to the buffer
 **/
void Logic::process_queue(void)
{
    event_t event;
    while(m_queue.pop_event(event)) {
        process_event(event);
    }
}

bool Logic::call_ui(const app_t &app)
{
    UI::UIBackend ui;

    if (ui.call_popup(app)) { // If calling popup or app_controll service will fail,
                                // do not remove application, and ask about it once again later
        LogDebug("Popup shown correctly. Application will be removed from DB and buffer");
        return true;
    }
    LogDebug("Popup error. Application will be marked to show popup later.");
    return false;
}

bool Logic::process_app(app_t& app) {
    // Check if app hasn't already been verified.
    // If yes then just try to display popup once again, and go the next app.
#if POPUP
    if (app.verified == app_t::verified_t::NO) {
        LogDebug(app.str() << " has been verified before. Popup should be shown.");
        return call_ui(app);
    }
#endif

    Certs::ocsp_response_t ret;
    ret = m_certs.check_ocsp(app);

    // If OCSP returns success or OCSP checking fails we should remove application from buffer and database
    if (ret == Certs::ocsp_response_t::OCSP_APP_OK ||
            ret == Certs::ocsp_response_t::OCSP_CERT_ERROR) {
        LogDebug(app.str() << " OCSP verified (or not available for app's chains)");
        return true;
    }
    else if (ret == Certs::ocsp_response_t::OCSP_APP_REVOKED) {
        LogDebug(app.str() << " certificate has been revoked. Popup should be shown");
        app.verified = app_t::verified_t::NO;
#if POPUP
// Do not remove app here - just waits for user answer from popup
// Temporary solution because notification framework doesn't work
        return call_ui(app);
#else
        return true;
#endif
    }
    else {
        LogDebug(app.str() << " should be checked again later");
        // If check_ocsp returns Certs::ocsp_response_t::OCSP_CHECK_AGAIN
        // app should be checked again later
    }
    return false;
}

void Logic::process_buffer(void)
{
    for (auto iter = m_buffer.begin(); iter != m_buffer.end();) {
        bool remove = process_app(*iter);
        auto prev = *iter;
        iter++;
        if (remove)
            remove_app_from_buffer_and_database(prev);
        app_processed();
    }
}

void Logic::push_event(event_t event)
{
    std::lock_guard<std::mutex> lock(m_mutex_cv);
    m_queue.push_event(std::move(event));
    m_to_process.notify_one();
}

void Logic::process_all()
{
    for(;;) {
        std::unique_lock<std::mutex> lock(m_mutex_cv);
        if (m_should_exit)
            break;  //lock will be unlocked upon destruction

        // don't sleep if there are online/installation/deinstallation events to process
        if(m_queue.empty() && !m_is_online_enabled) {
            LogDebug("Processing thread: waiting on condition");
            m_to_process.wait(lock); // spurious wakeups do not concern us
            LogDebug("Processing thread: running");
        }

        m_is_online_enabled = false;
        lock.unlock();

        process_queue();
        if (get_online())
            process_buffer();
        else
            LogDebug("No network. Buffer won't be processed");

        LogDebug("Processing done");
    }
}

void Logic::process_event(const event_t &event)
{
    if (event.event_type == event_t::event_type_t::APP_INSTALL) {
        // pulling out certificates from signatures
        app_t app = event.app;
        ocsp_urls_t ocsp_urls;
        m_certs.get_certificates(app, ocsp_urls);
        add_app_to_buffer_and_database(app);

        // Adding OCSP URLs - if found any
        if (!ocsp_urls.empty()){
            LogDebug("Some OCSP url has been found. Adding to database");
            for (auto iter = ocsp_urls.begin(); iter != ocsp_urls.end(); iter++){
                m_sqlquery->set_url(iter->issuer, iter->url, iter->date);
            }
        }
    }
    else if (event.event_type == event_t::event_type_t::APP_UNINSTALL) {
        remove_app_from_buffer_and_database(event.app);
    }
    else
        LogError("Unknown event type");
}

void Logic::add_app_to_buffer_and_database(const app_t &app)
{
    // First add app to DB
    if(!m_sqlquery->add_app_to_check_list(app)) {
        LogError("Failed to add " << app.str() << "to database");
        // We can do nothing about it. We can only log the error.
    }

    // Then add app to buffer - skip if already added.
    // FIXME: What to do if the same app will be installed twice?
    //        Add it twice to the buffer, or check if apps in buffer are unique?
    //        At the moment doubled apps are skipped.
    for (auto &iter : m_buffer) {
        if (iter.app_id == app.app_id &&
            iter.pkg_id == app.pkg_id &&
            iter.uid == app.uid) {
                LogDebug(app.str() << " already in buffer. Skip.");
                return;
        }
    }

    // Then add app to buffer
    m_buffer.push_back(app);
}

// Notice that this operator doesn't compare list of certificate, because it isn't needed here.
// This operator is implemented only for using in m_buffer.remove() method;
// Operator which compares certificates is implemented in tests.
bool operator ==(const app_t &app1, const app_t &app2)
{
    return app1.app_id == app2.app_id &&
            app1.pkg_id == app2.pkg_id &&
            app1.uid == app2.uid;
}

void Logic::remove_app_from_buffer_and_database(const app_t &app)
{
    // First remove app from DB
    m_sqlquery->remove_app_from_check_list(app);

    // Then remove app from buffer
    m_buffer.remove(app);
}

bool Logic::get_should_exit(void) const
{
    return m_should_exit;
}

void Logic::set_should_exit(void)
{
    m_should_exit = true;

}

} //CCHECKER