-
Notifications
You must be signed in to change notification settings - Fork 33
/
hawkbit-client.c
1512 lines (1252 loc) · 54.6 KB
/
hawkbit-client.c
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
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
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* SPDX-License-Identifier: LGPL-2.1-only
* SPDX-FileCopyrightText: 2021-2022 Bastian Krause <bst@pengutronix.de>, Pengutronix
* SPDX-FileCopyrightText: 2018-2020 Lasse K. Mikkelsen <lkmi@prevas.dk>, Prevas A/S (www.prevas.com)
*
* @file
* @brief Implementation of the hawkBit DDI API
*
* @see https://github.com/rauc/rauc-hawkbit
* @see https://eclipse.dev/hawkbit/apis/ddi_api/
*/
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#ifndef _XOPEN_SOURCE
#define _XOPEN_SOURCE
#endif
#include <string.h>
#include <time.h>
#include <errno.h>
#include <sys/statvfs.h>
#include <curl/curl.h>
#include <glib.h>
#include <glib-object.h>
#include <glib/gstdio.h>
#include <json-glib/json-glib.h>
#include <libgen.h>
#include <gio/gio.h>
#include <sys/reboot.h>
#include "json-helper.h"
#ifdef WITH_SYSTEMD
#include "sd-helper.h"
#endif
#include "hawkbit-client.h"
G_DEFINE_AUTOPTR_CLEANUP_FUNC(FILE, fclose)
G_DEFINE_AUTOPTR_CLEANUP_FUNC(CURL, curl_easy_cleanup)
gboolean run_once = FALSE;
static const gint MAX_RETRIES_ON_API_ERROR = 10;
/**
* @brief String representation of HTTP methods.
*/
static const char *HTTPMethod_STRING[] = {
"GET", "HEAD", "PUT", "POST", "PATCH", "DELETE"
};
/**
* @brief CURLcodes that should lead to download resuming, 0 terminated
*/
static const gint resumable_codes[] = {
CURLE_OPERATION_TIMEDOUT,
CURLE_COULDNT_RESOLVE_HOST,
CURLE_COULDNT_CONNECT,
CURLE_PARTIAL_FILE,
CURLE_SEND_ERROR,
CURLE_RECV_ERROR,
CURLE_HTTP2,
CURLE_HTTP2_STREAM,
0
};
static Config *hawkbit_config = NULL;
static GSourceFunc software_ready_cb;
static struct HawkbitAction *active_action = NULL;
static GThread *thread_download = NULL;
GQuark rhu_hawkbit_client_error_quark(void)
{
return g_quark_from_static_string("rhu_hawkbit_client_error_quark");
}
GQuark rhu_hawkbit_client_curl_error_quark(void)
{
return g_quark_from_static_string("rhu_hawkbit_client_curl_error_quark");
}
GQuark rhu_hawkbit_client_http_error_quark(void)
{
return g_quark_from_static_string("rhu_hawkbit_client_http_error_quark");
}
/**
* @brief Create and initialize an HawkbitAction.
*
* @return Pointer to initialized HawkbitAction..
*/
static struct HawkbitAction *action_new(void)
{
struct HawkbitAction *action = g_new0(struct HawkbitAction, 1);
g_mutex_init(&action->mutex);
g_cond_init(&action->cond);
action->id = NULL;
action->state = ACTION_STATE_NONE;
return action;
}
/**
* @brief Get available free space of a mounted file system.
*
* @param[in] path Absolute Path of a disk device node containing a mounted file system
* @param[out] free_space Pointer to goffset containing the free space in bytes
* @return TRUE if free space calculation succeeded, FALSE otherwise
*/
static gboolean get_available_space(const char *path, goffset *free_space, GError **error)
{
struct statvfs stat;
g_autofree gchar *npath = g_strdup(path);
const char *rpath = dirname(npath);
g_return_val_if_fail(path, FALSE);
g_return_val_if_fail(error == NULL || *error == NULL, FALSE);
if (statvfs(rpath, &stat)) {
int err = errno;
g_set_error(error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
"Failed to calculate free space for %s: %s", path, g_strerror(err));
return FALSE;
}
// the available free space is f_bsize * f_bavail
*free_space = (goffset) stat.f_bsize * (goffset) stat.f_bavail;
return TRUE;
}
/**
* @brief Calculate checksum for file.
*
* @param[in] fp File to read data from
* @param[in] type Desired type of checksum
* @param[out] checksum Calculated checksum digest hex string
* @param[out] error Error
* @return TRUE if checksum calculation succeeded, FALSE otherwise (error set)
*/
static gboolean get_file_checksum(FILE *fp, const GChecksumType type, gchar **checksum,
GError **error)
{
g_autoptr(GChecksum) ctx = g_checksum_new(type);
guchar buf[4096];
size_t r;
g_return_val_if_fail(fp, FALSE);
g_return_val_if_fail(checksum && *checksum == NULL, FALSE);
g_return_val_if_fail(error == NULL || *error == NULL, FALSE);
g_assert_nonnull(ctx);
fseek(fp, 0, SEEK_SET);
while (1) {
r = fread(buf, 1, sizeof(buf), fp);
if (ferror(fp)) {
g_set_error(error, G_FILE_ERROR, G_FILE_ERROR_FAILED, "Read failed");
return FALSE;
}
g_checksum_update(ctx, buf, r);
if (feof(fp))
break;
}
*checksum = g_strdup(g_checksum_get_string(ctx));
return TRUE;
}
/**
* @brief Add string to Curl headers, avoiding overwriting an existing
* non-empty list on failure.
*
* @param[out] headers curl_slist** of already set headers
* @param[in] string Header to add
* @param[out] error Error
* @return TRUE if string was added to headers successfully, FALSE otherwise (error set)
*/
static gboolean add_curl_header(struct curl_slist **headers, const char *string, GError **error)
{
struct curl_slist *temp = NULL;
g_return_val_if_fail(headers, FALSE);
g_return_val_if_fail(string, FALSE);
g_return_val_if_fail(error == NULL || *error == NULL, FALSE);
temp = curl_slist_append(*headers, string);
if (!temp) {
curl_slist_free_all(*headers);
g_set_error(error, RHU_HAWKBIT_CLIENT_CURL_ERROR, CURLE_FAILED_INIT,
"Could not add header %s", string);
return FALSE;
}
*headers = temp;
return TRUE;
}
/**
* @brief Returns the header required to authenticate against hawkBit, either target or gateway
* token.
*
* @return header required to authenticate against hawkBit
*/
static char* get_auth_header()
{
if (hawkbit_config->auth_token)
return g_strdup_printf("Authorization: TargetToken %s",
hawkbit_config->auth_token);
if (hawkbit_config->gateway_token)
return g_strdup_printf("Authorization: GatewayToken %s",
hawkbit_config->gateway_token);
g_return_val_if_reached(NULL);
}
/**
* @brief Add hawkBit authorization header to Curl headers.
*
* @param[out] headers curl_slist** of already set headers
* @param[out] error Error
* @return TRUE if authorization method set in config and header was added successfully, TRUE if no
* authorization method set, FALSE otherwise (error set)
*/
static gboolean set_auth_curl_header(struct curl_slist **headers, GError **error)
{
gboolean res = TRUE;
g_autofree gchar *token = NULL;
g_return_val_if_fail(error == NULL || *error == NULL, FALSE);
token = get_auth_header();
if (token)
res = add_curl_header(headers, token, error);
return res;
}
/**
* @brief Set common Curl options, namely user agent, connect timeout, SSL
* verify peer and SSL verify host options.
*
* @param[in] curl Curl handle
*/
static void set_default_curl_opts(CURL *curl)
{
g_return_if_fail(curl);
curl_easy_setopt(curl, CURLOPT_USERAGENT, HAWKBIT_USERAGENT);
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, hawkbit_config->connect_timeout);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, hawkbit_config->ssl_verify ? 1L : 0L);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, hawkbit_config->ssl_verify ? 1L : 0L);
}
/**
* @brief Download download_url to file.
*
* @param[in] download_url URL to download from
* @param[in] file Download destination
* @param[in] resume_from Offset to resume download from
* @param[out] sha1sum Calculated checksum or NULL
* @param[out] speed Average download speed
* @param[out] error Error
* @return TRUE if download succeeded, FALSE otherwise (error set)
*/
static gboolean get_binary(const gchar *download_url, const gchar *file, curl_off_t resume_from,
gchar **sha1sum, curl_off_t *speed, GError **error)
{
g_autoptr(CURL) curl = NULL;
g_autoptr(FILE) fp = NULL;
CURLcode curl_code;
glong http_code = 0;
struct curl_slist *headers = NULL;
g_return_val_if_fail(download_url, FALSE);
g_return_val_if_fail(file, FALSE);
g_return_val_if_fail(sha1sum == NULL || *sha1sum == NULL, FALSE);
g_return_val_if_fail(error == NULL || *error == NULL, FALSE);
if (resume_from)
g_debug("Resuming download from offset %" CURL_FORMAT_CURL_OFF_T, resume_from);
fp = g_fopen(file, (resume_from) ? "ab+" : "wb+");
if (!fp) {
int err = errno;
g_set_error(error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
"Failed to open %s for download: %s", file, g_strerror(err));
return FALSE;
}
curl = curl_easy_init();
if (!curl) {
g_set_error(error, RHU_HAWKBIT_CLIENT_CURL_ERROR, CURLE_FAILED_INIT,
"Unable to start libcurl easy session");
return FALSE;
}
set_default_curl_opts(curl);
curl_easy_setopt(curl, CURLOPT_URL, download_url);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 8L);
curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, 1L);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
// abort if slower than configured download rate during configured time span
curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, hawkbit_config->low_speed_time);
curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, hawkbit_config->low_speed_rate);
curl_easy_setopt(curl, CURLOPT_RESUME_FROM_LARGE, resume_from);
if (!set_auth_curl_header(&headers, error))
return FALSE;
// set up request headers
if (!add_curl_header(&headers, "Accept: application/octet-stream", error))
return FALSE;
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
// perform transfer
curl_code = curl_easy_perform(curl);
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
curl_easy_getinfo(curl, CURLINFO_SPEED_DOWNLOAD_T, speed);
curl_slist_free_all(headers);
if (curl_code != CURLE_OK) {
g_set_error(error, RHU_HAWKBIT_CLIENT_CURL_ERROR, curl_code, "%s",
curl_easy_strerror(curl_code));
return FALSE;
}
// consider ok/partial download/range not satisfiable (EOF reached) as success
if (http_code != 200 && http_code != 206 && http_code != 416) {
g_set_error(error, RHU_HAWKBIT_CLIENT_HTTP_ERROR, http_code,
"HTTP request failed: %ld", http_code);
return FALSE;
}
// if checksum enabled then return the value
if (sha1sum && !get_file_checksum(fp, G_CHECKSUM_SHA1, sha1sum, error))
return FALSE;
return TRUE;
}
/**
* @brief Curl callback writing REST response to RestPayload*->payload buffer.
*
* @see https://curl.haxx.se/libcurl/c/CURLOPT_WRITEFUNCTION.html
*/
static size_t curl_write_cb(const void *content, size_t size, size_t nmemb, void *data)
{
RestPayload *p = NULL;
size_t real_size = size * nmemb;
g_return_val_if_fail(content, 0);
g_return_val_if_fail(data, 0);
p = (RestPayload *) data;
p->payload = (gchar *) g_realloc(p->payload, p->size + real_size + 1);
// copy content to buffer
memcpy(&(p->payload[p->size]), content, real_size);
p->size += real_size;
p->payload[p->size] = '\0';
return real_size;
}
/**
* @brief Perform REST request with JSON data, expecting response JSON data.
*
* @param[in] method HTTP Method, e.g. GET
* @param[in] url URL used in HTTP REST request
* @param[in] jsonRequestBody REST request body. If NULL, no body is sent
* @param[out] jsonResponseParser Return location for a REST response or NULL to skip response
* parsing
* @param[out] error Error
* @return TRUE if request and response parser (if given) suceeded, FALSE otherwise (error set).
*/
static gboolean rest_request(enum HTTPMethod method, const gchar *url,
JsonBuilder *jsonRequestBody, JsonParser **jsonResponseParser,
GError **error)
{
g_autofree gchar *postdata = NULL;
g_autoptr(RestPayload) fetch_buffer = NULL;
struct curl_slist *headers = NULL;
g_autoptr(CURL) curl = NULL;
glong http_code = 0;
CURLcode res;
g_return_val_if_fail(url, FALSE);
g_return_val_if_fail(jsonResponseParser == NULL || *jsonResponseParser == NULL, FALSE);
g_return_val_if_fail(error == NULL || *error == NULL, FALSE);
curl = curl_easy_init();
if (!curl) {
g_set_error(error, RHU_HAWKBIT_CLIENT_CURL_ERROR, CURLE_FAILED_INIT,
"Unable to start libcurl easy session");
return FALSE;
}
// init response buffer
fetch_buffer = g_new0(RestPayload, 1);
fetch_buffer->size = 0;
fetch_buffer->payload = g_malloc0(DEFAULT_CURL_REQUEST_BUFFER_SIZE);
// set up CURL options
set_default_curl_opts(curl);
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, HTTPMethod_STRING[method]);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, hawkbit_config->timeout);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_write_cb);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fetch_buffer);
if (jsonRequestBody) {
g_autoptr(JsonGenerator) generator = json_generator_new();
g_autoptr(JsonNode) req_root = json_builder_get_root(jsonRequestBody);
g_autofree gchar *json_req_str = NULL;
json_generator_set_root(generator, req_root);
postdata = json_generator_to_data(generator, NULL);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postdata);
json_req_str = json_to_string(req_root, TRUE);
g_debug("Request body: %s", json_req_str);
}
// set up request headers
if (!add_curl_header(&headers, "Accept: application/json;charset=UTF-8", error))
return FALSE;
if (!set_auth_curl_header(&headers, error))
return FALSE;
if (jsonRequestBody &&
!add_curl_header(&headers, "Content-Type: application/json;charset=UTF-8", error))
return FALSE;
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
// perform request
res = curl_easy_perform(curl);
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
curl_slist_free_all(headers);
if (res != CURLE_OK) {
g_set_error(error, RHU_HAWKBIT_CLIENT_CURL_ERROR, res, "%s",
curl_easy_strerror(res));
return FALSE;
}
if (http_code != 200) {
g_set_error(error, RHU_HAWKBIT_CLIENT_HTTP_ERROR, http_code,
"HTTP request failed: %ld; server response: %s", http_code,
fetch_buffer->payload);
return FALSE;
}
if (jsonResponseParser && fetch_buffer->size > 0) {
// process JSON repsonse
g_autoptr(JsonParser) parser = json_parser_new_immutable();
JsonNode *resp_root = NULL;
g_autofree gchar *json_resp_str = NULL;
if (!json_parser_load_from_data(parser, fetch_buffer->payload, fetch_buffer->size,
error))
return FALSE;
resp_root = json_parser_get_root(parser);
json_resp_str = json_to_string(resp_root, TRUE);
g_debug("Response body: %s", json_resp_str);
*jsonResponseParser = g_steal_pointer(&parser);
}
return TRUE;
}
/**
* @brief Perform REST request with JSON data, expecting response JSON data. On HTTP error
* 409 (Conflict) and 429 (Too Many Requests), try again (up to MAX_RETRIES_ON_API_ERROR).
*
* @param[in] method HTTP Method, e.g. GET
* @param[in] url URL used in HTTP REST request
* @param[in] jsonRequestBody REST request body. If NULL, no body is sent
* @param[out] jsonResponseParser Return location for a REST response or NULL to skip response
* parsing
* @param[out] error Error
* @return TRUE if request and response parser (if given) suceeded, FALSE otherwise (error set).
*/
static gboolean rest_request_retriable(enum HTTPMethod method, const gchar *url,
JsonBuilder *jsonRequestBody,
JsonParser **jsonResponseParser, GError **error)
{
gboolean res, retry;
gint retry_count = 0;
GError *ierror = NULL;
g_return_val_if_fail(url, FALSE);
g_return_val_if_fail(jsonResponseParser == NULL || *jsonResponseParser == NULL, FALSE);
g_return_val_if_fail(error == NULL || *error == NULL, FALSE);
while (1) {
res = rest_request(method, url, jsonRequestBody, jsonResponseParser, &ierror);
retry = (g_error_matches(ierror, RHU_HAWKBIT_CLIENT_HTTP_ERROR, 409) ||
g_error_matches(ierror, RHU_HAWKBIT_CLIENT_HTTP_ERROR, 429)) &&
retry_count < MAX_RETRIES_ON_API_ERROR;
if (!retry)
break;
g_debug("%s Trying again (%d/%d)..", ierror->message, retry_count+1,
MAX_RETRIES_ON_API_ERROR);
g_clear_error(&ierror);
g_usleep(1000000);
retry_count++;
}
if (!res)
g_propagate_error(error, ierror);
return res;
}
/**
* @brief Build hawkBit JSON request.
*
* @see https://eclipse.dev/hawkbit/rest-api/rootcontroller-api-guide.html#_post_tenantcontrollerv1controlleriddeploymentbaseactionidfeedback
*
* @param[in] id hawkBit action ID or NULL (configData usecase)
* @param[in] detail Detail message or NULL (configData usecase)
* @param[in] finished hawkBit status of the result
* @param[in] execution hawkBit status of the action execution
* @param[in] attributes hawkBit controller attributes or NULL (feedback usecase)
* @return JsonBuilder* with built hawkBit request
*/
static JsonBuilder* json_build_status(const gchar *id, const gchar *detail, const gchar *finished,
const gchar *execution, GHashTable *attributes)
{
GHashTableIter iter;
gpointer key, value;
g_autoptr(JsonBuilder) builder = NULL;
time_t current_time;
struct tm time_info;
char timeString[16];
g_return_val_if_fail(finished, NULL);
g_return_val_if_fail(execution, NULL);
// get current time in UTC
time(¤t_time);
gmtime_r(¤t_time, &time_info);
strftime(timeString, sizeof(timeString), "%Y%m%dT%H%M%S", &time_info);
builder = json_builder_new();
// build json status
json_builder_begin_object(builder);
if (id) {
json_builder_set_member_name(builder, "id");
json_builder_add_string_value(builder, id);
}
json_builder_set_member_name(builder, "time");
json_builder_add_string_value(builder, timeString);
json_builder_set_member_name(builder, "status");
json_builder_begin_object(builder);
json_builder_set_member_name(builder, "result");
json_builder_begin_object(builder);
json_builder_set_member_name(builder, "finished");
json_builder_add_string_value(builder, finished);
json_builder_end_object(builder);
json_builder_set_member_name(builder, "execution");
json_builder_add_string_value(builder, execution);
if (detail) {
json_builder_set_member_name(builder, "details");
json_builder_begin_array(builder);
json_builder_add_string_value(builder, detail);
json_builder_end_array(builder);
}
json_builder_end_object(builder);
if (attributes) {
json_builder_set_member_name(builder, "data");
json_builder_begin_object(builder);
g_hash_table_iter_init(&iter, attributes);
while (g_hash_table_iter_next(&iter, &key, &value)) {
json_builder_set_member_name(builder, key);
json_builder_add_string_value(builder, value);
}
json_builder_end_object(builder);
}
json_builder_end_object(builder);
return g_steal_pointer(&builder);
}
/**
* @brief Send feedback to hawkBit.
*
* @param[in] url hawkBit URL used for request
* @param[in] id hawkBit action ID
* @param[in] detail Detail message
* @param[in] finished hawkBit status of the result
* @param[in] execution hawkBit status of the action execution
* @param[out] error Error
* @return TRUE if feedback was sent successfully, FALSE otherwise (error set)
*/
static gboolean feedback(const gchar *url, const gchar *id, const gchar *detail,
const gchar *finished, const gchar *execution, GError **error)
{
g_autoptr(JsonBuilder) builder = NULL;
gboolean res = FALSE;
g_return_val_if_fail(url, FALSE);
g_return_val_if_fail(id, FALSE);
g_return_val_if_fail(detail, FALSE);
g_return_val_if_fail(finished, FALSE);
g_return_val_if_fail(execution, FALSE);
g_return_val_if_fail(error == NULL || *error == NULL, FALSE);
if (!g_strcmp0(finished, "failure"))
g_warning("%s", detail);
else
g_message("%s", detail);
builder = json_build_status(id, detail, finished, execution, NULL);
res = rest_request_retriable(POST, url, builder, NULL, error);
if (!res)
g_prefix_error(error, "Failed to report \"%s\" feedback: ", detail);
return res;
}
/**
* @brief Send progress feedback to hawkBit (finished=none, execution=proceeding).
*
* @param[in] url hawkBit URL used for request
* @param[in] id hawkBit action ID
* @param[in] detail Detail message
* @param[out] error Error
* @return TRUE if feedback was sent successfully, FALSE otherwise (error set)
*/
static gboolean feedback_progress(const gchar *url, const gchar *id, const gchar *detail,
GError **error)
{
gboolean res = FALSE;
g_return_val_if_fail(url, FALSE);
g_return_val_if_fail(id, FALSE);
g_return_val_if_fail(detail, FALSE);
g_return_val_if_fail(error == NULL || *error == NULL, FALSE);
res = feedback(url, id, detail, "none", "proceeding", error);
g_prefix_error(error, "Progress feedback: ");
return res;
}
/**
* @brief Get polling sleep time from hawkBit JSON response.
*
* @param[in] root JsonNode* with hawkBit response
* @return time to sleep in seconds, either from JSON or (if not found) from config's retry_wait (or 5s during active action)
*/
static long json_get_sleeptime(JsonNode *root)
{
g_autofree gchar *sleeptime_str = NULL;
g_autoptr(GError) error = NULL;
struct tm time;
g_return_val_if_fail(root, 0L);
/* When processing an action, return fixed sleeptime of 5s to allow
* receiving cancelation requests etc.*/
g_mutex_lock(&active_action->mutex);
if (active_action->state == ACTION_STATE_PROCESSING ||
active_action->state == ACTION_STATE_DOWNLOADING ||
active_action->state == ACTION_STATE_CANCEL_REQUESTED) {
g_mutex_unlock(&active_action->mutex);
return 5L;
}
g_mutex_unlock(&active_action->mutex);
sleeptime_str = json_get_string(root, "$.config.polling.sleep", &error);
if (!sleeptime_str) {
g_warning("Polling sleep time not found: %s. Using fallback: %ds",
error->message, hawkbit_config->retry_wait);
return hawkbit_config->retry_wait;
}
strptime(sleeptime_str, "%T", &time);
return (time.tm_sec + (time.tm_min * 60) + (time.tm_hour * 60 * 60));
}
/**
* @brief Build API URL
*
* @param path[in] a printf()-like format string describing the API path or NULL for base path
* @param ... The arguments to be inserted in path
*
* @return a newly allocated full API URL
*/
__attribute__((__format__(__printf__, 1, 2)))
static gchar* build_api_url(const gchar *path, ...)
{
g_autofree gchar *buffer = NULL;
va_list args;
if (path) {
va_start(args, path);
buffer = g_strdup_vprintf(path, args);
va_end(args);
}
return g_strdup_printf(
"%s://%s/%s/controller/v1/%s%s%s",
hawkbit_config->ssl ? "https" : "http",
hawkbit_config->hawkbit_server, hawkbit_config->tenant_id,
hawkbit_config->controller_id,
buffer ? "/" : "",
buffer ? buffer : "");
}
gboolean hawkbit_progress(const gchar *msg)
{
g_autofree gchar *feedback_url = NULL;
g_autoptr(GError) error = NULL;
g_return_val_if_fail(msg, FALSE);
g_mutex_lock(&active_action->mutex);
feedback_url = build_api_url("deploymentBase/%s/feedback", active_action->id);
if (!feedback_progress(feedback_url, active_action->id, msg, &error))
g_warning("%s", error->message);
g_mutex_unlock(&active_action->mutex);
return G_SOURCE_REMOVE;
}
/**
* @brief Provide meta information that will allow the hawkBit to identify the device on a hardware
* level.
*
* @see https://eclipse.dev/hawkbit/rest-api/rootcontroller-api-guide.html#_put_tenantcontrollerv1controlleridconfigdata
*
* @param[out] error Error
* @return TRUE if identification succeeded, FALSE otherwise (error set)
*/
static gboolean identify(GError **error)
{
g_autofree gchar *put_config_data_url = NULL;
g_autoptr(JsonBuilder) builder = NULL;
g_return_val_if_fail(error == NULL || *error == NULL, FALSE);
g_debug("Providing meta information to hawkbit server");
put_config_data_url = build_api_url("configData");
builder = json_build_status(NULL, NULL, "success", "closed", hawkbit_config->device);
return rest_request_retriable(PUT, put_config_data_url, builder, NULL, error);
}
/**
* @brief Deletes RAUC bundle at config's bundle_download_location (if given).
*/
static void process_deployment_cleanup()
{
if (!hawkbit_config->bundle_download_location)
return;
if (!g_file_test(hawkbit_config->bundle_download_location, G_FILE_TEST_IS_REGULAR))
return;
if (g_remove(hawkbit_config->bundle_download_location))
g_warning("Failed to delete file: %s", hawkbit_config->bundle_download_location);
}
gboolean install_complete_cb(gpointer ptr)
{
gboolean res = FALSE;
g_autoptr(GError) error = NULL;
struct on_install_complete_userdata *result = ptr;
g_autofree gchar *feedback_url = NULL;
g_return_val_if_fail(ptr, FALSE);
g_mutex_lock(&active_action->mutex);
active_action->state = result->install_success ? ACTION_STATE_SUCCESS : ACTION_STATE_ERROR;
feedback_url = build_api_url("deploymentBase/%s/feedback", active_action->id);
res = feedback(
feedback_url, active_action->id,
result->install_success ? "Software bundle installed successfully."
: "Failed to install software bundle.",
result->install_success ? "success" : "failure",
"closed", &error);
if (!res)
g_warning("%s", error->message);
process_deployment_cleanup();
g_mutex_unlock(&active_action->mutex);
if (result->install_success && hawkbit_config->post_update_reboot) {
sync();
if (reboot(RB_AUTOBOOT) < 0)
g_critical("Failed to reboot: %s", g_strerror(errno));
}
return G_SOURCE_REMOVE;
}
/**
* @brief Thread to download given Artifact, verfiy its checksum, send hawkBit
* feedback and call software_ready_cb() callback on success.
*
* @param[in] data Artifact* to process
* @return gpointer being 1 (TRUE) if download succeeded, 0 (FALSE) otherwise. The return value is
* meant to be used with the GPOINTER_TO_INT() macro only.
* Note that if the download thread waited for installation to finish ('run_once' mode),
* TRUE means both installation and download succeeded.
*/
static gpointer download_thread(gpointer data)
{
struct on_new_software_userdata userdata = {
.install_progress_callback = (GSourceFunc) hawkbit_progress,
.install_complete_callback = install_complete_cb,
.file = hawkbit_config->bundle_download_location,
.auth_header = NULL,
.ssl_verify = hawkbit_config->ssl_verify,
.install_success = FALSE,
};
g_autoptr(GError) error = NULL, feedback_error = NULL;
g_autofree gchar *msg = NULL, *sha1sum = NULL;
g_autoptr(Artifact) artifact = data;
curl_off_t speed;
g_return_val_if_fail(data, NULL);
g_assert_nonnull(hawkbit_config->bundle_download_location);
g_mutex_lock(&active_action->mutex);
if (active_action->state == ACTION_STATE_CANCEL_REQUESTED)
goto cancel;
active_action->state = ACTION_STATE_DOWNLOADING;
g_mutex_unlock(&active_action->mutex);
g_message("Start downloading: %s", artifact->download_url);
while (1) {
gboolean resumable = FALSE;
GStatBuf bundle_stat;
curl_off_t resume_from = 0;
g_clear_pointer(&sha1sum, g_free);
// Download software bundle (artifact)
if (g_stat(hawkbit_config->bundle_download_location, &bundle_stat) == 0)
resume_from = (curl_off_t) bundle_stat.st_size;
if (get_binary(artifact->download_url, hawkbit_config->bundle_download_location,
resume_from, &sha1sum, &speed, &error))
break;
for (const gint *code = &resumable_codes[0]; *code; code++)
resumable |= g_error_matches(error, RHU_HAWKBIT_CLIENT_CURL_ERROR, *code);
if (!hawkbit_config->resume_downloads || !resumable) {
g_prefix_error(&error, "Download failed: ");
goto report_err;
}
g_debug("%s, resuming download..", curl_easy_strerror(error->code));
g_mutex_lock(&active_action->mutex);
if (active_action->state == ACTION_STATE_CANCEL_REQUESTED)
goto cancel;
g_mutex_unlock(&active_action->mutex);
g_clear_error(&error);
// sleep 0.5 s before attempting to resume download
g_usleep(500000);
}
// notify hawkbit that download is complete
msg = g_strdup_printf("Download complete. %.2f MB/s",
(double)speed/(1024*1024));
g_mutex_lock(&active_action->mutex);
if (!feedback_progress(artifact->feedback_url, active_action->id, msg, &error)) {
g_warning("%s", error->message);
g_clear_error(&error);
}
g_mutex_unlock(&active_action->mutex);
// validate checksum
if (g_strcmp0(artifact->sha1, sha1sum)) {
g_set_error(&error, RHU_HAWKBIT_CLIENT_ERROR, RHU_HAWKBIT_CLIENT_ERROR_DOWNLOAD,
"Software: %s V%s. Invalid checksum: %s expected %s", artifact->name,
artifact->version, sha1sum, artifact->sha1);
goto report_err;
}
g_mutex_lock(&active_action->mutex);
// skip installation if hawkBit asked us to do so
if (!artifact->do_install &&
(!artifact->maintenance_window || g_strcmp0(artifact->maintenance_window, "available") == 0)) {
active_action->state = ACTION_STATE_SUCCESS;
if (!feedback(artifact->feedback_url, active_action->id, "File checksum OK.", "success",
"downloaded", &feedback_error))
g_warning("%s", feedback_error->message);
g_mutex_unlock(&active_action->mutex);
return GINT_TO_POINTER(TRUE);
}
if (!feedback_progress(artifact->feedback_url, active_action->id, "File checksum OK.",
&error)) {
g_warning("%s", error->message);
g_clear_error(&error);
}
g_mutex_unlock(&active_action->mutex);
// last chance to cancel installation
g_mutex_lock(&active_action->mutex);
if (active_action->state == ACTION_STATE_CANCEL_REQUESTED)
goto cancel;
// skip installation if hawkBit asked us to do so
if (!artifact->do_install) {
active_action->state = ACTION_STATE_NONE;
g_mutex_unlock(&active_action->mutex);
return GINT_TO_POINTER(TRUE);
}
// start installation, cancelations are impossible now
active_action->state = ACTION_STATE_INSTALLING;
g_cond_signal(&active_action->cond);
g_mutex_unlock(&active_action->mutex);
software_ready_cb(&userdata);
return GINT_TO_POINTER(userdata.install_success);
report_err:
g_mutex_lock(&active_action->mutex);
if (!feedback(artifact->feedback_url, active_action->id, error->message, "failure",
"closed", &feedback_error))
g_warning("%s", feedback_error->message);
active_action->state = ACTION_STATE_ERROR;
cancel:
if (active_action->state == ACTION_STATE_CANCEL_REQUESTED)
active_action->state = ACTION_STATE_CANCELED;
process_deployment_cleanup();
g_cond_signal(&active_action->cond);
g_mutex_unlock(&active_action->mutex);
return GINT_TO_POINTER(FALSE);
}
/**
* @brief Start a RAUC HTTP streaming installation without prior bundle download.
* This skips the download thread and starts the install thread (via rauc_install()
* directly).
* Must be called under locked active_action->mutex.
*
* @param[in] artifcat Artifact* to install
* @param[out] error Error
* @return TRUE if installation prcessing succeeded, FALSE otherwise (error set).
* Note that this functions returns TRUE even for canceled/skipped installations.
*/
static gboolean start_streaming_installation(Artifact *artifact, GError **error)
{
g_autofree gchar *auth_header = get_auth_header();
struct on_new_software_userdata userdata = {
.install_progress_callback = (GSourceFunc) hawkbit_progress,
.install_complete_callback = install_complete_cb,
.file = artifact->download_url,
.auth_header = auth_header,
.ssl_verify = hawkbit_config->ssl_verify,
.install_success = FALSE,
};