File: agent_controller.c

package info (click to toggle)
gvm-libs 22.34.2-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 2,968 kB
  • sloc: ansic: 39,015; makefile: 26
file content (1358 lines) | stat: -rw-r--r-- 38,244 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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
/* SPDX-FileCopyrightText: 2019-2025 Greenbone AG
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 */

/**
 * @file agent_controller.c
 * @brief Agent Controller client implementation for agent management.
 *
 * This module provides the implementation of functions for interacting with
 * an Agent Controller service. It supports:
 *
 * - Building and configuring connections with authentication and TLS options
 * - Creating, updating, authorizing, and deleting agent records
 * - Managing agent data structures like agent lists, configurations, and
 * updates
 * - Memory-safe allocation and cleanup routines for agents and configurations
 *
 * The API abstracts the communication and management logic to simplify
 * higher-level applications interacting with managed agents.
 */

#undef G_LOG_DOMAIN
/**
 * @brief GLib logging domain.
 */
#define G_LOG_DOMAIN "libgvm agents"

#include "agent_controller.h"

#include "../http/httputils.h"
#include "../util/json.h"

#include <cjson/cJSON.h>
#include <stdio.h>
#include <time.h>

/**
 * @brief Struct holding the data for connecting with the agent controller.
 */
struct agent_controller_connector
{
  gchar *ca_cert;  /**< Path to CA certificate directory (if using HTTPS). */
  gchar *cert;     /**< Client certificate path. */
  gchar *key;      /**< Client private key path. */
  gchar *apikey;   /**< API key for authentication.(Optional) */
  gchar *host;     /**< Agent controller hostname or IP. */
  gint port;       /**< Port number of agent controller (default 8080?). */
  gchar *protocol; /**< "http" or "https". */
};

/**
 * @brief Initialize custom HTTP headers for Agent Controller requests.
 *
 * @param[in] apikey The Api Key to use for Authorization (optional).
 * @param[in] content_type Whether to add "Content-Type: application/json"
 * (TRUE/FALSE).
 *
 * @return A newly allocated `gvm_http_headers_t *` containing the headers.
 *         Must be freed with `gvm_http_headers_free()`.
 */
static gvm_http_headers_t *
init_custom_header (const gchar *apikey, gboolean content_type)
{
  gvm_http_headers_t *headers = gvm_http_headers_new ();

  // Set API KEY
  if (apikey)
    {
      GString *xapikey = g_string_new ("X-API-KEY: ");
      g_string_append (xapikey, apikey);

      if (!gvm_http_add_header (headers, xapikey->str))
        g_warning ("%s: Not possible to set API-KEY", __func__);

      g_string_free (xapikey, TRUE);
    }

  // Set Content-Type: application/json
  if (content_type)
    {
      if (!gvm_http_add_header (headers, "Content-Type: application/json"))
        g_warning ("%s: Failed to set Content-Type header", __func__);
    }

  return headers;
}

/**
 * @brief Sends an HTTP(S) request to the agent-control server.
 *
 * @param[in] conn          The `agent_controller_connector_t` containing server
 * and certificate details.
 * @param[in] method        The HTTP method (GET, POST, PUT, etc.).
 * @param[in] path          The request path (e.g., "/api/v1/admin/agents").
 * @param[in] payload       Optional request body payload.
 * @param[in] apikey        Optional Api key for Authorization header.
 *
 * @return Pointer to a `gvm_http_response_t` containing status code and body.
 *         Must be freed using `gvm_http_response_free()`.
 */
static gvm_http_response_t *
agent_controller_send_request (agent_controller_connector_t conn,
                               gvm_http_method_t method, const gchar *path,
                               const gchar *payload, const gchar *apikey)
{
  if (!conn)
    {
      g_warning ("%s: Missing connection", __func__);
      return NULL;
    }

  if (!conn->protocol || !conn->host || !path)
    {
      g_warning ("%s: Missing URL components", __func__);
      return NULL;
    }

  gchar *url = g_strdup_printf ("%s://%s:%d%s", conn->protocol, conn->host,
                                conn->port, path);

  gvm_http_headers_t *headers = init_custom_header (apikey, TRUE);

  gvm_http_response_t *http_response = gvm_http_request (
    url, method, payload, headers, conn->ca_cert, conn->cert, conn->key,
    NULL // No manual stream allocation
  );

  g_free (url);
  gvm_http_headers_free (headers);

  if (!http_response)
    {
      g_warning ("%s: HTTP request failed", __func__);
      return NULL;
    }

  return http_response;
}

/**
 * @brief Parse an ISO 8601 UTC datetime string into a time_t value.
 *
 * Parses a datetime string in the format "YYYY-MM-DDTHH:MM:SS.sssZ",
 * extracting the date and time components (ignoring milliseconds).
 * Returns the corresponding UTC time as a time_t value.
 *
 * @param[in] datetime_str The datetime string to parse.
 *
 * @return Parsed time as time_t, or 0 on failure.
 */
static time_t
parse_datetime (const char *datetime_str)
{
  if (!datetime_str)
    return 0;

  struct tm tm = {0};
  int milliseconds = 0;

  // Read year, month, day, hour, minute, second
  if (sscanf (datetime_str, "%4d-%2d-%2dT%2d:%2d:%2d.%dZ", &tm.tm_year,
              &tm.tm_mon, &tm.tm_mday, &tm.tm_hour, &tm.tm_min, &tm.tm_sec,
              &milliseconds)
      != 7)
    {
      return (time_t) 0; // Failed
    }

  tm.tm_year -= 1900;
  tm.tm_mon -= 1;

  return timegm (&tm);
}

/**
 * @brief Parse a scan-agent-config JSON object into a newly allocated config
 * struct.
 *
 * @param[in] root  cJSON object representing the full scan-agent-config
 * payload.
 *
 * @return agent_controller_scan_agent_config_t on success; NULL on failure or
 *         if @p root is NULL / not a JSON object.
 *         Ownership of root remains with the caller; do not free any children
 *         retrieved with cJSON_GetObjectItem() individually.
 */
static agent_controller_scan_agent_config_t
agent_controller_parse_scan_agent_config (cJSON *root)
{
  if (!root || !cJSON_IsObject (root))
    return NULL;

  agent_controller_scan_agent_config_t cfg =
    agent_controller_scan_agent_config_new ();

  /* agent_control */
  cJSON *agent_control = cJSON_GetObjectItem (root, "agent_control");
  if (cJSON_IsObject (agent_control))
    {
      cJSON *retry = cJSON_GetObjectItem (agent_control, "retry");
      if (cJSON_IsObject (retry))
        {
          cfg->agent_control.retry.attempts =
            gvm_json_obj_int (retry, "attempts");
          cfg->agent_control.retry.delay_in_seconds =
            gvm_json_obj_int (retry, "delay_in_seconds");
          cfg->agent_control.retry.max_jitter_in_seconds =
            gvm_json_obj_int (retry, "max_jitter_in_seconds");
        }
    }

  /* agent_script_executor */
  cJSON *exec = cJSON_GetObjectItem (root, "agent_script_executor");
  if (cJSON_IsObject (exec))
    {
      cfg->agent_script_executor.bulk_size =
        gvm_json_obj_int (exec, "bulk_size");
      cfg->agent_script_executor.bulk_throttle_time_in_ms =
        gvm_json_obj_int (exec, "bulk_throttle_time_in_ms");
      cfg->agent_script_executor.indexer_dir_depth =
        gvm_json_obj_int (exec, "indexer_dir_depth");

      cJSON *cron = cJSON_GetObjectItem (exec, "scheduler_cron_time");
      if (cJSON_IsArray (cron))
        {
          GPtrArray *arr = g_ptr_array_new_with_free_func (g_free);
          int n = cJSON_GetArraySize (cron);

          for (int i = 0; i < n; ++i)
            {
              cJSON *it = cJSON_GetArrayItem (cron, i);
              if (cJSON_IsString (it) && it->valuestring
                  && it->valuestring[0] != '\0')
                {
                  g_ptr_array_add (arr, g_strdup (it->valuestring));
                }
            }

          if (arr->len > 0)
            cfg->agent_script_executor.scheduler_cron_time = arr;
          else
            g_ptr_array_free (arr, TRUE);
        }
    }

  /* heartbeat */
  cJSON *hb = cJSON_GetObjectItem (root, "heartbeat");
  if (cJSON_IsObject (hb))
    {
      cfg->heartbeat.interval_in_seconds =
        gvm_json_obj_int (hb, "interval_in_seconds");
      cfg->heartbeat.miss_until_inactive =
        gvm_json_obj_int (hb, "miss_until_inactive");
    }

  return cfg;
}

/**
 * @brief Parse a scan-agent-config JSON node into a newly allocated config
 * struct.
 *
 * @param[in] node  cJSON node representing the scan-agent-config payload.
 *                  May be an object, a JSON string, or NULL.
 *
 * @return agent_controller_scan_agent_config_t on success; NULL if node is
 *         NULL/JSON null/unparsable. Ownership of node remains with the
 *         caller; do not free any children retrieved with cJSON_GetObjectItem()
 *         individually.
 */
static agent_controller_scan_agent_config_t
agent_controller_parse_scan_agent_config_node (cJSON *node)
{
  if (!node || cJSON_IsNull (node))
    return NULL;

  if (cJSON_IsObject (node))
    return agent_controller_parse_scan_agent_config (node); /*may return NULL*/

  if (cJSON_IsString (node) && node->valuestring)
    {
      /* treat empty/whitespace string as absent */
      const char *s = node->valuestring;
      while (*s && g_ascii_isspace ((guchar) *s))
        ++s;
      if (*s == '\0')
        return NULL;

      return agent_controller_parse_scan_agent_config_string (s);
      /* may return NULL */
    }

  return NULL;
}

/**
 * @brief Serialize scan-agent-config struct to a minimal JSON string.
 *
 * @param [in] cfg agent config to convert as json object
 *
 * @return cJSON pointer containing scan agent config.
 */
static cJSON *
agent_controller_scan_agent_config_struct_to_cjson (
  agent_controller_scan_agent_config_t cfg)
{
  if (!cfg)
    return NULL;

  gchar *json = agent_controller_convert_scan_agent_config_string (cfg);
  if (!json)
    return cJSON_CreateObject ();

  cJSON *obj = cJSON_Parse (json);
  cJSON_free (json);

  return obj ? obj : cJSON_CreateObject ();
}

/**
 * @brief Parses a single agent JSON object into an agent_controller_agent_t.
 *
 * @param[in] item The cJSON object representing one agent.
 *
 * @return A newly allocated agent_controller_agent_t, or NULL if parsing fails.
 */
static agent_controller_agent_t
agent_controller_parse_agent (cJSON *item)
{
  if (!item)
    return NULL;

  agent_controller_agent_t agent = agent_controller_agent_new ();
  if (!agent)
    return NULL;

  const gchar *agent_id = gvm_json_obj_str (item, "agentid");
  const gchar *hostname = gvm_json_obj_str (item, "hostname");
  const gchar *conn_status = gvm_json_obj_str (item, "connection_status");
  const gchar *last_update_str = gvm_json_obj_str (item, "last_update");
  const gchar *last_updater_heartbeat_str =
    gvm_json_obj_str (item, "last_updater_heartbeat");

  agent->agent_id = agent_id ? g_strdup (agent_id) : NULL;
  agent->hostname = hostname ? g_strdup (hostname) : NULL;
  agent->authorized = cJSON_IsTrue (cJSON_GetObjectItem (item, "authorized"));
  agent->connection_status = conn_status ? g_strdup (conn_status) : NULL;

  if (last_update_str && *last_update_str)
    {
      agent->last_update = parse_datetime (last_update_str);
    }
  else
    {
      agent->last_update = 0;
    }

  if (last_updater_heartbeat_str && *last_updater_heartbeat_str)
    {
      agent->last_updater_heartbeat =
        parse_datetime (last_updater_heartbeat_str);
    }
  else
    {
      agent->last_updater_heartbeat = 0;
    }

  cJSON *ips_array = cJSON_GetObjectItem (item, "ip_addresses");
  if (ips_array && cJSON_IsArray (ips_array))
    {
      int ips_count = cJSON_GetArraySize (ips_array);
      agent->ip_address_count = ips_count;
      agent->ip_addresses =
        g_malloc0 (sizeof (gchar *) * (ips_count > 0 ? ips_count : 1));

      for (int j = 0; j < ips_count; ++j)
        {
          cJSON *ip_item = cJSON_GetArrayItem (ips_array, j);
          if (cJSON_IsString (ip_item))
            agent->ip_addresses[j] = g_strdup (ip_item->valuestring);
        }
    }

  /* Versions / platform */
  const gchar *upd_ver = gvm_json_obj_str (item, "updater_version");
  const gchar *agt_ver = gvm_json_obj_str (item, "agent_version");
  const gchar *os_str = gvm_json_obj_str (item, "operating_system");
  const gchar *arch = gvm_json_obj_str (item, "architecture");
  cJSON *update_to_latest_str = cJSON_GetObjectItem (item, "update_to_latest");

  agent->updater_version = upd_ver ? g_strdup (upd_ver) : NULL;
  agent->agent_version = agt_ver ? g_strdup (agt_ver) : NULL;
  agent->operating_system = os_str ? g_strdup (os_str) : NULL;
  agent->architecture = arch ? g_strdup (arch) : NULL;
  if (cJSON_IsBool (update_to_latest_str))
    agent->update_to_latest = cJSON_IsTrue (update_to_latest_str) ? 1 : 0;
  else
    agent->update_to_latest = 0;

  /* Config */
  cJSON *config_obj = cJSON_GetObjectItem (item, "config");
  agent->config = agent_controller_parse_scan_agent_config_node (config_obj);

  return agent;
}

/**
 * @brief Build a JSON payload for updating agents.
 *
 * @param[in] agents List of agents to include in the payload.
 * @param[in] update Optional update template to override agent fields.
 *
 * @return A newly allocated JSON string (unformatted) representing the update
 * payload. The caller is responsible for freeing the returned string using
 * `g_free()`.
 */
static gchar *
agent_controller_build_patch_payload (agent_controller_agent_list_t agents,
                                      agent_controller_agent_update_t update)
{
  if (!agents || agents->count <= 0)
    return NULL;

  cJSON *patch_body = cJSON_CreateObject ();

  for (int i = 0; i < agents->count; ++i)
    {
      agent_controller_agent_t agent = agents->agents[i];
      if (!agent || !agent->agent_id)
        continue;

      cJSON *agent_obj = cJSON_CreateObject ();

      // authorized
      int use_authorized = agent->authorized;
      if (update && update->authorized != -1)
        use_authorized = update->authorized;
      cJSON_AddBoolToObject (agent_obj, "authorized", use_authorized);

      /* config: prefer update->config if provided */
      cJSON *cfg_obj = NULL;
      if (update && update->config)
        {
          cfg_obj =
            agent_controller_scan_agent_config_struct_to_cjson (update->config);
          cJSON_AddItemToObject (agent_obj, "config", cfg_obj);
        }
      cJSON_AddItemToObject (patch_body, agent->agent_id, agent_obj);
    }

  gchar *payload = cJSON_PrintUnformatted (patch_body);
  cJSON_Delete (patch_body);

  return payload;
}

/**
 * @brief Check if a JSON agent object reports an available update.
 *
 * Evaluates the boolean fields "agent_update_available" and
 * "updater_update_available" on the given item. Only strict JSON booleans
 * are considered; missing keys or non-boolean types are treated as FALSE.
 *
 * @param[in] item  cJSON object representing a single agent.
 *
 * @return TRUE if either "agent_update_available" or
 *         "updater_update_available" is TRUE; otherwise FALSE.
 */

static gboolean
agent_controller_json_has_update_available (cJSON *item)
{
  if (!item || !cJSON_IsObject (item))
    return FALSE;

  cJSON *a_up = cJSON_GetObjectItem (item, "agent_update_available");
  cJSON *u_up = cJSON_GetObjectItem (item, "updater_update_available");

  gboolean agent_up = cJSON_IsBool (a_up) && cJSON_IsTrue (a_up);
  gboolean updater_up = cJSON_IsBool (u_up) && cJSON_IsTrue (u_up);

  return agent_up || updater_up;
}

/**
 * @brief Ensure an error array exists and uses g_free on elements.
 * @param [in, out] errors GPointer Array for initialization
 */
static void
ensure_error_array (GPtrArray **errors)
{
  if (errors && *errors == NULL)
    *errors = g_ptr_array_new_with_free_func (g_free);
}

/**
 * @brief Add a single error message to errors, creating the array if needed.
 * @param [in,out] errors array to add error message
 * @param [in] msg error message
 */
static void
push_error (GPtrArray **errors, const gchar *msg)
{
  if (!errors || !msg || !*msg)
    return;
  ensure_error_array (errors);
  g_ptr_array_add (*errors, g_strdup (msg));
}

/**
 * @brief Parse a JSON response body and extract "errors" array into errors.
 *
 * @param [in] body body of the response
 * @param [out] errors parsed errors
 *
 */
static void
parse_errors_json_into_array (const gchar *body, GPtrArray **errors)
{
  if (!errors)
    return;

  /* cJSON requires NUL-terminated input; make a safe copy. */
  cJSON *root = cJSON_Parse (body);

  if (!root)
    {
      push_error (errors, "Request rejected (400): invalid JSON payload.");
      return;
    }

  const cJSON *errors_node = cJSON_GetObjectItemCaseSensitive (root, "errors");
  gboolean any_added = FALSE;

  if (cJSON_IsArray (errors_node))
    {
      int n = cJSON_GetArraySize (errors_node);
      for (int i = 0; i < n; ++i)
        {
          const cJSON *it = cJSON_GetArrayItem (errors_node, i);
          if (cJSON_IsString (it) && it->valuestring && *it->valuestring)
            {
              push_error (errors, it->valuestring);
              any_added = TRUE;
            }
        }
    }

  if (!any_added)
    {
      push_error (
        errors,
        "Request rejected (400), but no detailed errors were provided.");
    }

  cJSON_Delete (root);
}

/**
 * @brief Creates a new Agent Controller connector.
 */
agent_controller_connector_t
agent_controller_connector_new (void)
{
  return g_malloc0 (sizeof (struct agent_controller_connector));
}

/**
 * @brief Frees an Agent Controller connector.
 *
 * @param[in] connector Connector to be freed
 */
void
agent_controller_connector_free (agent_controller_connector_t connector)
{
  if (!connector)
    return;

  g_free (connector->ca_cert);
  g_free (connector->cert);
  g_free (connector->key);
  g_free (connector->host);
  g_free (connector->apikey);
  g_free (connector->protocol);

  g_free (connector);
}

/**
 * @brief Configures a connector with an option and its value.
 *
 * @param[in] conn Connector to configure
 * @param[in] opt Option type
 * @param[in] val Value to assign (expected type depends on the option)
 *
 * @return AGENT_CONTROLLER_OK on success, error code otherwise
 */
agent_controller_error_t
agent_controller_connector_builder (agent_controller_connector_t conn,
                                    agent_controller_connector_opts_t opt,
                                    const void *val)
{
  if (conn == NULL || val == NULL)
    return AGENT_CONTROLLER_INVALID_VALUE;

  switch (opt)
    {
    case AGENT_CONTROLLER_CA_CERT:
      conn->ca_cert = g_strdup ((const gchar *) val);
      break;
    case AGENT_CONTROLLER_CERT:
      conn->cert = g_strdup ((const gchar *) val);
      break;
    case AGENT_CONTROLLER_KEY:
      conn->key = g_strdup ((const gchar *) val);
      break;
    case AGENT_CONTROLLER_API_KEY:
      conn->apikey = g_strdup ((const gchar *) val);
      break;
    case AGENT_CONTROLLER_PROTOCOL:
      if (g_strcmp0 ((const gchar *) val, "http") != 0
          && g_strcmp0 ((const gchar *) val, "https") != 0)
        return AGENT_CONTROLLER_INVALID_VALUE;
      conn->protocol = g_strdup ((const gchar *) val);
      break;
    case AGENT_CONTROLLER_HOST:
      conn->host = g_strdup ((const gchar *) val);
      break;
    case AGENT_CONTROLLER_PORT:
      conn->port = *((const int *) val);
      break;
    default:
      return AGENT_CONTROLLER_INVALID_OPT;
    }

  return AGENT_CONTROLLER_OK;
}

/**
 * @brief Allocates and initializes a new agent structure.
 *
 * @return agent_controller_agent_t pointer
 */
agent_controller_agent_t
agent_controller_agent_new (void)
{
  agent_controller_agent_t agent =
    g_malloc0 (sizeof (struct agent_controller_agent));
  return agent;
}

/**
 * @brief Frees an agent structure.
 *
 * @param[in] agent to be freed
 */
void
agent_controller_agent_free (agent_controller_agent_t agent)
{
  if (!agent)
    return;

  g_free (agent->agent_id);
  g_free (agent->hostname);
  g_free (agent->connection_status);

  if (agent->ip_addresses)
    {
      for (int i = 0; i < agent->ip_address_count; ++i)
        g_free (agent->ip_addresses[i]);
      g_free (agent->ip_addresses);
    }

  agent_controller_scan_agent_config_free (agent->config);
  g_free (agent->updater_version);
  g_free (agent->agent_version);
  g_free (agent->operating_system);
  g_free (agent->architecture);
  g_free (agent);
}

/**
 * @brief Allocates a new list to hold a specified number of agents.
 *
 * @param[in] count Number of agents the list should hold
 *
 * @return agent_controller_agent_list_t
 */
agent_controller_agent_list_t
agent_controller_agent_list_new (int count)
{
  if (count < 0)
    return NULL;

  agent_controller_agent_list_t list =
    g_malloc0 (sizeof (struct agent_controller_agent_list));
  list->count = count;
  list->agents = g_malloc0 (sizeof (agent_controller_agent_t) * (count + 1));
  return list;
}

/**
 * @brief Frees an agent list structure.
 *
 * @param[in] list to be freed
 */
void
agent_controller_agent_list_free (agent_controller_agent_list_t list)
{
  if (!list)
    return;

  if (list->agents)
    {
      for (int i = 0; i < list->count; ++i)
        agent_controller_agent_free (list->agents[i]);
      g_free (list->agents);
    }

  g_free (list);
}

/**
 * @brief Allocates and initializes a new agent update structure.
 *
 * @return agent_controller_agent_update_t pointer
 */
agent_controller_agent_update_t
agent_controller_agent_update_new (void)
{
  agent_controller_agent_update_t update =
    g_malloc0 (sizeof (struct agent_controller_agent_update));

  update->authorized = -1;
  update->config = NULL;

  return update;
}

/**
 * @brief Frees an agent update structure.
 *
 * @param[in] update to be freed
 */
void
agent_controller_agent_update_free (agent_controller_agent_update_t update)
{
  if (!update)
    return;

  if (update->config)
    {
      agent_controller_scan_agent_config_free (update->config);
    }

  g_free (update);
}

/**
 * @brief Allocate/zero a new scan agent config.
 */
agent_controller_scan_agent_config_t
agent_controller_scan_agent_config_new (void)
{
  return g_malloc0 (sizeof (struct agent_controller_scan_agent_config));
}

/**
 * @brief Free a scan agent config.
 *
 * @param[in] cfg to be freed
 */
void
agent_controller_scan_agent_config_free (
  agent_controller_scan_agent_config_t cfg)
{
  if (!cfg)
    return;

  if (cfg->agent_script_executor.scheduler_cron_time)
    {
      g_ptr_array_free (cfg->agent_script_executor.scheduler_cron_time, TRUE);
      cfg->agent_script_executor.scheduler_cron_time = NULL;
    }

  g_free (cfg);
}

/**
 * @brief Fetches the list of agents from the Agent Controller.
 *
 * @param[in] conn Active connector to the Agent Controller
 *
 * @return List of agents on success, NULL on failure
 */
agent_controller_agent_list_t
agent_controller_get_agents (agent_controller_connector_t conn)
{
  if (!conn)
    {
      g_warning ("%s: Connector is NULL", __func__);
      return NULL;
    }

  gvm_http_response_t *response = agent_controller_send_request (
    conn, GET, "/api/v1/admin/agents", NULL, conn->apikey);

  if (!response)
    {
      g_warning ("%s: Failed to get response", __func__);
      return NULL;
    }

  if (response->http_status != 200)
    {
      g_debug ("%s: Received HTTP status %ld", __func__, response->http_status);
      gvm_http_response_free (response);
      return NULL;
    }

  cJSON *root = cJSON_Parse (response->data);
  if (!root || !cJSON_IsArray (root))
    {
      g_warning ("%s: Failed to parse JSON array", __func__);
      if (root)
        cJSON_Delete (root);
      gvm_http_response_free (response);
      return NULL;
    }

  int count = cJSON_GetArraySize (root);
  agent_controller_agent_list_t agent_list =
    agent_controller_agent_list_new (count);

  if (!agent_list)
    {
      g_warning ("%s: Failed to initialize Agent List. Count: %d", __func__,
                 count);
      return NULL;
    }

  int valid_index = 0;
  for (int i = 0; i < count; ++i)
    {
      cJSON *item = cJSON_GetArrayItem (root, i);
      agent_controller_agent_t agent = agent_controller_parse_agent (item);
      if (agent)
        agent_list->agents[valid_index++] = agent;
    }
  agent_list->count = valid_index;

  cJSON_Delete (root);
  gvm_http_response_free (response);

  return agent_list;
}

/**
 * @brief Updates properties of a list of agents.
 *
 * @param[in] conn Active connector
 * @param[in] agents List of agents to update
 * @param[in] update Update information
 * @param[out] errors  If non-NULL and an HTTP 4xx occurs, will be set to a
 * GPtrArray* of gchar* error messages (caller takes ownership and must free)
 *
 * @return RESP_CODE_OK (0) on success, RESP_CODE_ERR (-1) on failure
 */
int
agent_controller_update_agents (agent_controller_connector_t conn,
                                agent_controller_agent_list_t agents,
                                agent_controller_agent_update_t update,
                                GPtrArray **errors)
{
  if (!conn || !agents || !update)
    {
      g_warning ("%s: Invalid connection, agent list, or update override",
                 __func__);
      return AGENT_RESP_ERR;
    }

  gchar *payload = agent_controller_build_patch_payload (agents, update);
  if (!payload)
    {
      g_warning ("%s: Failed to build PATCH payload", __func__);
      return AGENT_RESP_ERR;
    }

  gvm_http_response_t *response = agent_controller_send_request (
    conn, PATCH, "/api/v1/admin/agents", payload, conn->apikey);

  g_free (payload);

  if (!response)
    {
      g_warning ("%s: Failed to get response", __func__);
      return AGENT_RESP_ERR;
    }

  if (response->http_status == 400 || response->http_status == 422)
    {
      if (response->data)
        {
          parse_errors_json_into_array (response->data, errors);
        }
      else
        {
          gchar *msg =
            g_strdup_printf ("Request rejected (%ld), empty response body.",
                             response->http_status);
          push_error (errors, msg);
          g_free (msg);
        }

      gvm_http_response_free (response);
      return AGENT_RESP_ERR;
    }

  if (response->http_status != 200)
    {
      g_warning ("%s: Received HTTP status %ld", __func__,
                 response->http_status);
      gvm_http_response_free (response);
      return AGENT_RESP_ERR;
    }

  gvm_http_response_free (response);

  return AGENT_RESP_OK;
}

/**
 * @brief Deletes a list of agents.
 *
 * @param[in] conn Active connector
 * @param[in] agents List of agents to delete
 *
 * @return RESP_CODE_OK (0) on success, RESP_CODE_ERR (-1) on failure
 */
int
agent_controller_delete_agents (agent_controller_connector_t conn,
                                agent_controller_agent_list_t agents)
{
  if (!conn || !agents)
    {
      g_warning ("%s: Invalid connection or agent list", __func__);
      return AGENT_RESP_ERR;
    }

  cJSON *payload_array = cJSON_CreateArray ();
  if (!payload_array)
    {
      g_warning ("%s: Failed to create JSON array", __func__);
      return AGENT_RESP_ERR;
    }

  for (int i = 0; i < agents->count; ++i)
    {
      agent_controller_agent_t agent = agents->agents[i];
      if (agent && agent->agent_id)
        {
          cJSON_AddItemToArray (payload_array,
                                cJSON_CreateString (agent->agent_id));
        }
    }

  gchar *payload = cJSON_PrintUnformatted (payload_array);
  cJSON_Delete (payload_array);

  if (!payload)
    {
      g_warning ("%s: Failed to build JSON payload", __func__);
      return AGENT_RESP_ERR;
    }

  gvm_http_response_t *response = agent_controller_send_request (
    conn, POST, "/api/v1/admin/agents/delete", payload, conn->apikey);

  g_free (payload);

  if (!response)
    {
      g_warning ("%s: Failed to get response", __func__);
      return AGENT_RESP_ERR;
    }

  if (response->http_status != 200)
    {
      g_warning ("%s: Received HTTP status %ld", __func__,
                 response->http_status);
      gvm_http_response_free (response);
      return AGENT_RESP_ERR;
    }

  gvm_http_response_free (response);

  return AGENT_RESP_OK;
}

/**
 * @brief Updates scan agent config globally
 *
 * @param[in] cfg  Scan-agent configuration to serialize. Must not be NULL.
 *
 * @return Newly allocated, unformatted JSON string on success; NULL on failure
 *         The caller owns the returned string and must free it with
 *         cJSON_free().
 */
gchar *
agent_controller_convert_scan_agent_config_string (
  agent_controller_scan_agent_config_t cfg)
{
  if (!cfg)
    return NULL;

  cJSON *root = cJSON_CreateObject ();

  /* ---------- agent_control.retry ---------- */

  cJSON *agent_control = cJSON_CreateObject ();
  cJSON *retry = cJSON_CreateObject ();
  cJSON_AddNumberToObject (retry, "attempts",
                           cfg->agent_control.retry.attempts);
  cJSON_AddNumberToObject (retry, "delay_in_seconds",
                           cfg->agent_control.retry.delay_in_seconds);
  cJSON_AddNumberToObject (retry, "max_jitter_in_seconds",
                           cfg->agent_control.retry.max_jitter_in_seconds);
  cJSON_AddItemToObject (agent_control, "retry", retry);
  cJSON_AddItemToObject (root, "agent_control", agent_control);

  /* ---------- agent_script_executor ---------- */

  cJSON *exec = cJSON_CreateObject ();
  cJSON_AddNumberToObject (exec, "bulk_size",
                           cfg->agent_script_executor.bulk_size);
  cJSON_AddNumberToObject (exec, "bulk_throttle_time_in_ms",
                           cfg->agent_script_executor.bulk_throttle_time_in_ms);
  cJSON_AddNumberToObject (exec, "indexer_dir_depth",
                           cfg->agent_script_executor.indexer_dir_depth);

  const GPtrArray *arr = cfg->agent_script_executor.scheduler_cron_time;
  if (arr && arr->len > 0)
    {
      cJSON *cron = cJSON_CreateArray ();
      for (guint i = 0; i < arr->len; ++i)
        {
          const gchar *expr = g_ptr_array_index ((GPtrArray *) arr, i);
          if (expr && *expr)
            cJSON_AddItemToArray (cron, cJSON_CreateString (expr));
        }

      if (cJSON_GetArraySize (cron) > 0)
        cJSON_AddItemToObject (exec, "scheduler_cron_time", cron);
      else
        cJSON_Delete (cron);
    }

  cJSON_AddItemToObject (root, "agent_script_executor", exec);

  /* ---------- heartbeat ---------- */

  cJSON *hb = cJSON_CreateObject ();
  cJSON_AddNumberToObject (hb, "interval_in_seconds",
                           cfg->heartbeat.interval_in_seconds);
  cJSON_AddNumberToObject (hb, "miss_until_inactive",
                           cfg->heartbeat.miss_until_inactive);
  cJSON_AddItemToObject (root, "heartbeat", hb);

  /* If nothing set, root returns empty → "{}" */
  gchar *payload = cJSON_PrintUnformatted (root);
  cJSON_Delete (root);
  return payload;
}

/**
 * @brief Parse a scan-agent-config from a JSON string into a newly allocated
 struct.

 * @param[in] config  NUL-terminated JSON text. Must represent a JSON object.
 *
 * @return Newly allocated agent_controller_scan_agent_config_t on success;
 *         NULL if config is NULL, the JSON cannot be parsed, or the root
 *         is not a JSON object.
 */
agent_controller_scan_agent_config_t
agent_controller_parse_scan_agent_config_string (const gchar *config)
{
  if (!config)
    return NULL;

  cJSON *root = cJSON_Parse (config);
  if (!root)
    {
      g_warning ("%s: JSON parse failed", __func__);
      return NULL;
    }
  agent_controller_scan_agent_config_t cfg =
    agent_controller_parse_scan_agent_config (root);
  cJSON_Delete (root);
  return cfg;
}

/**
 * @brief Retrieves the scan-agent configuration.
 *
 * @param[in] conn Active agent controller connector
 *
 * @return Newly allocated agent_controller_scan_agent_config_t on success,
 *         NULL on failure. Caller must free the returned object with
 *         agent_controller_scan_agent_config_free().
 */
agent_controller_scan_agent_config_t
agent_controller_get_scan_agent_config (agent_controller_connector_t conn)
{
  if (!conn)
    {
      g_warning ("%s: Connector is NULL", __func__);
      return NULL;
    }

  gvm_http_response_t *response = agent_controller_send_request (
    conn, GET, "/api/v1/admin/scan-agent-config", NULL, conn->apikey);
  if (!response)
    {
      g_warning ("%s: No response", __func__);
      return NULL;
    }

  if (response->http_status < 200 || response->http_status >= 300)
    {
      g_warning ("%s: HTTP %ld", __func__, response->http_status);
      gvm_http_response_free (response);
      return NULL;
    }

  cJSON *root = cJSON_Parse (response->data);
  if (!root)
    {
      g_warning ("%s: JSON parse failed", __func__);
      gvm_http_response_free (response);
      return NULL;
    }

  agent_controller_scan_agent_config_t cfg =
    agent_controller_parse_scan_agent_config (root);

  cJSON_Delete (root);
  gvm_http_response_free (response);
  return cfg;
}

/**
 * @brief Updates the scan-agent configuration.
 *
 * @param[in] conn Connector to the Agent Controller
 * @param[in] cfg  Configuration to apply
 * @param[out] errors  If non-NULL and an HTTP 4xx occurs, will be set to a
 * GPtrArray* of gchar* error messages (caller takes ownership and must free)
 *
 * @return AGENT_RESP_OK (0) on success, AGENT_RESP_ERR (-1) on failure.
 *         The caller retains ownership of cfg.
 */
int
agent_controller_update_scan_agent_config (
  agent_controller_connector_t conn, agent_controller_scan_agent_config_t cfg,
  GPtrArray **errors)
{
  if (!conn || !cfg)
    {
      g_warning ("%s: Invalid args", __func__);
      return AGENT_RESP_ERR;
    }

  gchar *payload = agent_controller_convert_scan_agent_config_string (cfg);
  if (!payload)
    {
      g_warning ("%s: Failed to build payload", __func__);
      return AGENT_RESP_ERR;
    }

  gvm_http_response_t *response = agent_controller_send_request (
    conn, PUT, "/api/v1/admin/scan-agent-config", payload, conn->apikey);

  cJSON_free (payload);

  if (!response)
    {
      g_warning ("%s: No response", __func__);
      return AGENT_RESP_ERR;
    }

  if (response->http_status == 400 || response->http_status == 422)
    {
      if (response->data)
        {
          parse_errors_json_into_array (response->data, errors);
        }
      else
        {
          gchar *msg =
            g_strdup_printf ("Request rejected (%ld), empty response body.",
                             response->http_status);
          push_error (errors, msg);
          g_free (msg);
        }

      gvm_http_response_free (response);
      return AGENT_RESP_ERR;
    }

  if (response->http_status < 200 || response->http_status >= 300)
    {
      g_warning ("%s: HTTP %ld", __func__, response->http_status);
      gvm_http_response_free (response);
      return AGENT_RESP_ERR;
    }

  gvm_http_response_free (response);
  return AGENT_RESP_OK;
}

/**
 * @brief Fetch agents that have an update available.
 *
 * @param[in] conn Connector to the Agent Controller
 *
 * @return List of agents on success (count may be 0 if none qualify),
 *         NULL on failure. Free with agent_controller_agent_list_free().
 */
agent_controller_agent_list_t
agent_controller_get_agents_with_updates (agent_controller_connector_t conn)
{
  if (!conn)
    {
      g_warning ("%s: Connector is NULL", __func__);
      return NULL;
    }

  gvm_http_response_t *response = agent_controller_send_request (
    conn, GET, "/api/v1/admin/agents/updates", NULL, conn->apikey);

  if (!response)
    {
      g_warning ("%s: Failed to get response", __func__);
      return NULL;
    }

  if (response->http_status != 200)
    {
      g_warning ("%s: Received HTTP status %ld", __func__,
                 response->http_status);
      gvm_http_response_free (response);
      return NULL;
    }

  cJSON *root = cJSON_Parse (response->data);
  if (!root || !cJSON_IsArray (root))
    {
      g_warning ("%s: Failed to parse JSON array", __func__);
      if (root)
        cJSON_Delete (root);
      gvm_http_response_free (response);
      return NULL;
    }

  int count = cJSON_GetArraySize (root);
  agent_controller_agent_list_t agent_list =
    agent_controller_agent_list_new (count);

  int valid_index = 0;
  for (int i = 0; i < count; ++i)
    {
      cJSON *item = cJSON_GetArrayItem (root, i);
      if (!agent_controller_json_has_update_available (item))
        continue;

      agent_controller_agent_t agent = agent_controller_parse_agent (item);
      if (agent)
        agent_list->agents[valid_index++] = agent;
    }
  agent_list->count = valid_index;

  cJSON_Delete (root);
  gvm_http_response_free (response);

  return agent_list;
}

/**
 * @brief Build a JSON payload for creating a scan in the agent controller.
 *
 * @param[in] agents List of agents to include in the payload.
 *
 * @return A newly allocated JSON string representing the create-scan payload.
 *         The caller is responsible for freeing the returned string using
 *         g_free().
 */
gchar *
agent_controller_build_create_scan_payload (
  agent_controller_agent_list_t agents)
{
  if (!agents)
    return NULL;

  cJSON *root = cJSON_CreateObject ();

  cJSON *target = cJSON_CreateObject ();
  cJSON *hosts = cJSON_CreateArray ();

  // Iterate over agents and add agent_id to "hosts"
  for (int i = 0; i < agents->count; ++i)
    {
      agent_controller_agent_t agent = agents->agents[i];
      if (!agent || !agent->agent_id)
        continue;

      if (agent && agent->agent_id && *agent->agent_id)
        cJSON_AddItemToArray (hosts, cJSON_CreateString (agent->agent_id));
    }

  cJSON_AddItemToObject (target, "hosts", hosts);
  cJSON_AddItemToObject (root, "target", target);

  // vts (empty array)
  cJSON *vts = cJSON_CreateArray ();
  cJSON_AddItemToObject (root, "vts", vts);

  gchar *payload = cJSON_PrintUnformatted (root);
  cJSON_Delete (root);

  return payload;
}

/**
 * @brief Extract the scan_id from a create-scan response body.
 *
 * @param[in] body JSON string response from the agent controller.
 *
 * @return A newly allocated string containing the scan_id, or NULL if not
 * found. Caller must free with g_free().
 */
gchar *
agent_controller_get_scan_id (const gchar *body)
{
  if (!body)
    return NULL;

  cJSON *root = cJSON_Parse (body);
  if (!root)
    return NULL;

  const char *scan_id = gvm_json_obj_str (root, "scan_id");
  gchar *result = scan_id ? g_strdup (scan_id) : NULL;

  cJSON_Delete (root);
  return result;
}