-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathdto.c
More file actions
1841 lines (1677 loc) · 63.8 KB
/
dto.c
File metadata and controls
1841 lines (1677 loc) · 63.8 KB
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
/******************************************************************************/
/* Copyright 2021 Keyfactor */
/* 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 */
/* thespecific language governing permissions and limitations under the */
/* License. */
/******************************************************************************/
#include "dto.h"
#include "lib/json.h"
#include "logging.h"
#include <errno.h>
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
/******************************************************************************/
/***************************** LOCAL DEFINES *********************************/
/******************************************************************************/
#define MAX_BUF_LEN 1024 /* Maximum buffer length */
/******************************************************************************/
/************************ LOCAL GLOBAL STRUCTURES *****************************/
/******************************************************************************/
/******************************************************************************/
/************************** LOCAL GLOBAL VARIABLES ****************************/
/******************************************************************************/
/******************************************************************************/
/************************ LOCAL FUNCTION DEFINITIONS **************************/
/******************************************************************************/
/**
* @brief Free memory allocated for an AgentApiResult structure
*
* @param[in] result The AgentApiResult structure to free
* @return None
*/
static void AgentApiResult_free(AgentApiResult_t result) {
if (result.Error.Message) {
free(result.Error.Message);
result.Error.Message = NULL;
}
if (result.Error.CodeString) {
free(result.Error.CodeString);
result.Error.CodeString = NULL;
}
} /* AgentApiResult_free */
/**
* @brief Parse an AgentApiResult from a JSON node
*
* @param[in] jsonResult JSON node containing the result data
* @return AgentApiResult_t structure populated from JSON
*/
static AgentApiResult_t AgentApiResult_fromJsonNode(JsonNode *jsonResult) {
AgentApiResult_t result;
JsonNode *jsonError = NULL;
char *tempString = NULL;
if (jsonResult) {
result.Status = json_get_member_number(jsonResult, "Status", 0);
jsonError = json_find_member(jsonResult, "Error");
if (jsonError) {
result.Error.Code = json_get_member_number(jsonError, "Code", 0);
tempString = json_get_member_string(jsonError, "CodeString");
if (NULL == tempString) {
result.Error.CodeString =
json_get_member_string(jsonError, "HResult");
} else {
result.Error.CodeString = tempString;
}
result.Error.Message = json_get_member_string(jsonError, "Message");
} else {
result.Error.Code = 0;
result.Error.CodeString = NULL;
result.Error.Message = NULL;
}
} else {
result.Status = STAT_ERR;
result.Error.Code = 999;
result.Error.Message = strdup("Unknown Error");
result.Error.CodeString = strdup("Unknown Error");
}
return result;
} /* AgentApiResult_fromJsonNode */
/**
* @brief Log an AgentApiResult and update status/message
*
* @param[in] result The AgentApiResult to log
* @param[in,out] pMessage Pointer to message string to append error details
* @param[in,out] pStatus Pointer to status to update if result status is worse
* @return true if result status is success, false if error or warning
*/
bool AgentApiResult_log(AgentApiResult_t result, char **pMessage,
enum AgentApiResultStatus *pStatus) {
int messageLen = 20;
char *introBuf = NULL;
char buf[MAX_BUF_LEN];
log_trace("%s::%s(%d) : Decoding agent api result", LOG_INF);
if (pStatus && *pStatus < result.Status) {
*pStatus = result.Status;
}
if (result.Status == STAT_ERR || result.Status == STAT_WARN) {
introBuf =
(result.Status == STAT_ERR ? strdup("Error") : strdup("Warning"));
if (result.Error.Message && result.Error.CodeString) {
messageLen = 20 + strlen(result.Error.Message) +
strlen(result.Error.CodeString);
} else if (result.Error.Message) {
messageLen = 20 + strlen(result.Error.Message);
}
snprintf(buf, sizeof(buf), "%s: %s (%s)\n",
introBuf ? introBuf : "Unknown",
result.Error.Message ? result.Error.Message : "No message",
result.Error.CodeString ? result.Error.CodeString : "No code");
log_error("%s::%s(%d) : %s", LOG_INF, buf);
if (pMessage && *pMessage) {
log_trace("%s::%s(%d) : reallocating pMessage", LOG_INF);
char *newMessage =
realloc(*pMessage, strlen(*pMessage) + messageLen);
if (newMessage) {
*pMessage = newMessage;
strcat(*pMessage, buf);
} else {
log_error("%s::%s(%d) : Failed to reallocate pMessage",
LOG_INF);
}
}
}
if (NULL != introBuf) {
free(introBuf);
}
if ((result.Status == STAT_ERR) || (result.Status == STAT_WARN)) {
return false;
} else {
return true;
}
} /* AgentApiResult_log */
/**
* @brief Allocate and initialize a new ClientParameter structure
*
* @param[in] key The parameter key string (will be duplicated)
* @param[in] value The parameter value string (will be duplicated)
* @return Pointer to newly allocated ClientParameter_t, or NULL on failure
*/
static ClientParameter_t *ClientParameter_new(const char *key,
const char *value) {
// ReSharper disable once CppDFAMemoryLeak
// Ownership of cp is transferred to the caller, which stores it in either
// SessionRegisterReq_t->ClientParameters[] or
// SessionRegisterResp_t->Session.ClientParameters[]. In both cases it is
// freed via ClientParameter_free() called from SessionRegisterReq_free()
// or SessionRegisterResp_free() respectively.
ClientParameter_t *cp = calloc(1, sizeof(ClientParameter_t));
if (!cp) {
log_error("%s::%s(%d) : Out of memory", LOG_INF);
return NULL;
}
if (key) {
cp->Key = strdup(key);
if (!cp->Key) {
log_error("%s::%s(%d) : Failed to allocate Key", LOG_INF);
free(cp);
return NULL;
}
} else {
cp->Key = NULL;
}
if (value) {
cp->Value = strdup(value);
if (!cp->Value) {
log_error("%s::%s(%d) : Failed to allocate Value", LOG_INF);
free(cp->Key);
free(cp);
return NULL;
}
} else {
cp->Value = NULL;
}
// ReSharper disable once CppDFAMemoryLeak
// Ownership of cp is transferred to the caller, which stores it in either
// SessionRegisterReq_t->ClientParameters[] or
// SessionRegisterResp_t->Session.ClientParameters[]. In both cases it is
// freed via ClientParameter_free() called from SessionRegisterReq_free()
// or SessionRegisterResp_free() respectively.
return cp;
} /* ClientParameter_new */
/**
* @brief Free memory allocated for a ClientParameter structure
*
* @param[in] cliParam Pointer to ClientParameter to free
* @return None
*/
static void ClientParameter_free(ClientParameter_t *cliParam) {
if (cliParam) {
if (cliParam->Key) {
free(cliParam->Key);
cliParam->Key = NULL;
}
if (cliParam->Value) {
free(cliParam->Value);
cliParam->Value = NULL;
}
free(cliParam);
}
} /* ClientParameter_free */
/**
* @brief Add an additional ClientParameter to the session request
*
* Add a new key-value pair to the ClientParameters array after the
* ClientParameterPath has been processed.
*
* @param[in,out] req Pointer to the SessionRegisterRequest to modify
* @param[in] key The parameter key string
* @param[in] value The parameter value string
* @return true on success, false on failure
*/
bool SessionRegisterReq_addNewClientParameter(SessionRegisterReq_t *req,
const char *key,
const char *value) {
bool bResult = false;
int index;
if (!req) {
log_error("%s::%s(%d) : Null pointer dereference - req is NULL",
LOG_INF);
return false;
}
index = req->ClientParameters_count;
req->ClientParameters_count++;
log_trace("%s::%s(%d) Increasing parameter count to %d", LOG_INF,
req->ClientParameters_count);
req->ClientParameters =
realloc(req->ClientParameters,
(req->ClientParameters_count * sizeof(ClientParameter_t *)));
if (NULL == req->ClientParameters) {
log_error("%s::%s(%d) : Out of memory error", LOG_INF);
return false;
}
// ReSharper disable once CppDFAMemoryLeak
// False positive: ClientParameter_t allocated here is stored in
// req->ClientParameters[] which is owned by the SessionRegisterReq_t
// struct. It is freed via the ClientParameter_free() loop inside
// SessionRegisterReq_free(), which is called by all callers once they are
// done with the request.
req->ClientParameters[index] = ClientParameter_new(key, value);
if (NULL != req->ClientParameters[index]) {
log_trace("%s::%s(%d) : Successfully added key= %s with "
"value= %s to ClientParameters",
LOG_INF, key, value);
bResult = true;
} else {
log_error("%s::%s(%d) : Error adding new client parameters"
" to SessionRegisterRequest",
LOG_INF);
bResult = false;
/* Reset things */
free(req->ClientParameters[index]);
req->ClientParameters_count--;
}
return bResult;
} /* SessionRegisterReq_addNewClientParameter */
/**
* @brief Allocate and initialize a new SessionRegisterRequest structure
*
* Creates a new session registration request and optionally loads client
* parameters from a JSON file.
*
* @param[in] clientParamPath Path to JSON file containing client parameters
* (optional)
* @return Pointer to newly allocated SessionRegisterReq_t, or NULL on failure
*/
SessionRegisterReq_t *SessionRegisterReq_new(char *clientParamPath) {
SessionRegisterReq_t *req = calloc(1, sizeof(*req));
if (!req) {
log_error("%s::%s(%d) : Out of memory", LOG_INF);
return NULL;
}
req->Capabilities_count = 0;
req->TenantId = strdup("00000000-0000-0000-0000-000000000000");
req->ClientParameters_count = 0;
if (clientParamPath) {
log_trace("%s::%s(%d) : Found client parameters -- adding them"
" to the session",
LOG_INF);
FILE *fp = fopen(clientParamPath, "r");
if (fp) {
/* Client parameter file should never be anywhere near this long */
char buf[4096];
size_t len = fread(buf, 1, 4095, fp);
buf[len++] = '\0';
JsonNode *jsonRoot = json_decode(buf);
if (jsonRoot && jsonRoot->tag == JSON_OBJECT) {
JsonNode *curNode;
int nodeCount = 0;
json_foreach(curNode, jsonRoot) { /* Loop first to get
* count */
if (curNode->tag == JSON_STRING) {
nodeCount++;
}
}
req->ClientParameters =
calloc(nodeCount, sizeof(*req->ClientParameters));
req->ClientParameters_count = nodeCount;
nodeCount = 0;
json_foreach(curNode, jsonRoot) {
if (curNode->tag == JSON_STRING && curNode->key &&
curNode->u.string_) {
// ReSharper disable once CppDFAMemoryLeak
// False positive: ClientParameter_t instances allocated
// here are stored in req->ClientParameters[] which is
// owned by the SessionRegisterReq_t struct returned to
// the caller. They are freed via the
// ClientParameter_free() loop inside
// SessionRegisterReq_free(), which is called by all
// callers of SessionRegisterReq_new() once they are
// done with the request.
req->ClientParameters[nodeCount++] =
ClientParameter_new(curNode->key,
curNode->u.string_);
}
}
json_delete(jsonRoot);
} else {
log_error("%s::%s(%d) : Contents of %s are not valid JSON",
LOG_INF, clientParamPath);
}
(void)fclose(fp); /* Deallocate memory associated with this
* file */
} else {
int err = errno;
log_error(
"%s::%s(%d) : Unable to open client parameter file %s: %s",
LOG_INF, clientParamPath, strerror(err));
}
}
return req;
} /* SessionRegisterReq_new */
/**
* @brief Free memory allocated for a SessionRegisterRequest structure
*
* @param[in] req Pointer to SessionRegisterReq_t to free
* @return None
*/
void SessionRegisterReq_free(SessionRegisterReq_t *req) {
if (req) {
if (req->TenantId) {
free(req->TenantId);
req->TenantId = NULL;
}
if (req->ClientMachine) {
free(req->ClientMachine);
req->ClientMachine = NULL;
}
/* Agent Platform is an enum, no need to free */
if (req->Capabilities) {
for (int i = 0; i < req->Capabilities_count; ++i) {
free(req->Capabilities[i]);
req->Capabilities[i] = NULL;
}
free(req->Capabilities);
req->Capabilities = NULL;
}
/* Capabilities count is an int, no need to free */
/* Agent version is an int, no need to free */
if (req->AgentId) {
free(req->AgentId);
req->AgentId = NULL;
}
/* Free the entire array */
if (req->ClientParameters) {
for (int i = 0; i < req->ClientParameters_count; ++i) {
ClientParameter_free(req->ClientParameters[i]);
req->ClientParameters[i] = NULL;
}
free(req->ClientParameters);
req->ClientParameters = NULL;
}
/* ClientParameters_count is an int, no need to free */
if (req->CSR) {
free(req->CSR);
req->CSR = NULL;
}
free(req);
req = NULL;
}
} /* SessionRegisterReq_free */
/**
* @brief Convert a SessionRegisterRequest to JSON string
*
* @param[in] req Pointer to SessionRegisterReq_t to serialize
* @return Newly allocated JSON string, or NULL on failure. Caller must free.
*/
char *SessionRegisterReq_toJson(SessionRegisterReq_t *req) {
char *jsonString = NULL;
if (req) {
JsonNode *jsonRoot = json_mkobject();
json_append_member(jsonRoot, "AgentPlatform",
json_mknumber(req->AgentPlatform));
json_append_member(jsonRoot, "AgentVersion",
json_mknumber(req->AgentVersion));
if (req->TenantId) {
json_append_member(jsonRoot, "TenantId",
json_mkstring(req->TenantId));
} else {
json_append_member(jsonRoot, "TenantId", json_mknull());
}
if (req->ClientMachine) {
json_append_member(jsonRoot, "ClientMachine",
json_mkstring(req->ClientMachine));
} else {
json_append_member(jsonRoot, "ClientMachine", json_mknull());
}
if (req->CSR) {
json_append_member(jsonRoot, "CSR", json_mkstring(req->CSR));
} else {
json_append_member(jsonRoot, "CSR", json_mknull());
}
if (req->AgentId) {
json_append_member(jsonRoot, "AgentId",
json_mkstring(req->AgentId));
} else {
json_append_member(jsonRoot, "AgentId", json_mknull());
}
JsonNode *jsonCaps = json_mkarray();
if (req->Capabilities) {
for (int i = 0; i < req->Capabilities_count; ++i) {
if (req->Capabilities[i]) {
json_append_element(jsonCaps,
json_mkstring(req->Capabilities[i]));
}
}
}
json_append_member(jsonRoot, "Capabilities", jsonCaps);
JsonNode *jsonCliParams = json_mkobject();
if (req->ClientParameters) {
for (int i = 0; i < req->ClientParameters_count; ++i) {
if (req->ClientParameters[i] && req->ClientParameters[i]->Key) {
json_append_member(
jsonCliParams, req->ClientParameters[i]->Key,
json_mkstring(req->ClientParameters[i]->Value));
}
}
}
json_append_member(jsonRoot, "ClientParameters", jsonCliParams);
jsonString = json_encode(jsonRoot);
json_delete(jsonRoot);
}
return jsonString;
} /* SessionRegisterReq_toJson */
/**
* @brief Free memory allocated for a SessionJob structure
*
* @param[in] job Pointer to SessionJob_t to free
* @return None
*/
void SessionJob_free(SessionJob_t *job) {
if (job) {
if (job->CompletionEndpoint) {
free(job->CompletionEndpoint);
job->CompletionEndpoint = NULL;
}
if (job->ConfigurationEndpoint) {
free(job->ConfigurationEndpoint);
job->ConfigurationEndpoint = NULL;
}
if (job->Cron) {
free(job->Cron);
job->Cron = NULL;
}
if (job->JobId) {
free(job->JobId);
job->JobId = NULL;
}
if (job->JobTypeId) {
free(job->JobTypeId);
job->JobTypeId = NULL;
}
if (job->Schedule) {
free(job->Schedule);
job->Schedule = NULL;
}
free(job);
}
} /* SessionJob_free */
/**
* @brief Free all jobs in a SessionRegisterResponse
*
* Frees the Jobs array and all individual SessionJob structures within
* the response, but does not free the response itself.
*
* @param[in,out] resp Pointer to SessionRegisterResp_t containing jobs to free
* @return None
*/
void SessionRegisterResp_freeJobs(SessionRegisterResp_t *resp) {
int lp = 0;
if (!resp) {
log_error("%s::%s(%d) : Null pointer dereference - resp is NULL",
LOG_INF);
return;
}
if (!resp->Session.Jobs) {
log_error("%s::%s(%d) : Null pointer dereference - resp->Session.Jobs "
"is NULL",
LOG_INF);
return;
}
while (lp < resp->Session.Jobs_count) {
if (resp->Session.Jobs[lp]) {
log_info("%s::%s(%d) : Freeing job # %s", LOG_INF,
resp->Session.Jobs[lp]->JobId
? resp->Session.Jobs[lp]->JobId
: "(null)");
SessionJob_free(resp->Session.Jobs[lp]);
resp->Session.Jobs[lp] = NULL;
}
lp++;
}
if (resp->Session.Jobs) {
free(resp->Session.Jobs);
resp->Session.Jobs = NULL;
}
return;
} /* SessionRegisterResp_freeJobs */
/**
* @brief Free memory allocated for a SessionRegisterResponse structure
*
* Note: This does NOT free the Jobs array. Call SessionRegisterResp_freeJobs()
* first if jobs need to be freed.
*
* @param[in] resp Pointer to SessionRegisterResp_t to free
* @return None
*/
void SessionRegisterResp_free(SessionRegisterResp_t *resp) {
if (resp) {
AgentApiResult_free(resp->Result);
if (resp->Session.AgentId) {
free(resp->Session.AgentId);
resp->Session.AgentId = NULL;
}
if (resp->Session.Token) {
free(resp->Session.Token);
resp->Session.Token = NULL;
}
if (resp->Session.ClientMachine) {
free(resp->Session.ClientMachine);
resp->Session.ClientMachine = NULL;
}
if (resp->Session.Certificate) {
free(resp->Session.Certificate);
resp->Session.Certificate = NULL;
}
if (resp->Session.Jobs) {
#if defined(__NEVER_COMPILE_THIS__)
/*
* Ownership of these will be handed off & freed elsewhere
*/
/*
* for(int i = 0; i < resp->Session.Jobs_count; ++i)
*/
/*
* {
*/
/* SessionJob_free(resp->Session.Jobs[i]); */
/* resp->Session.Jobs[i] = NULL; */
/*
* }
*/
#endif /* Never Compile this Code */
free(resp->Session.Jobs);
resp->Session.Jobs = NULL;
}
if (resp->Session.ClientParameters) {
for (int i = 0; i < resp->Session.ClientParameters_count; ++i) {
ClientParameter_free(resp->Session.ClientParameters[i]);
resp->Session.ClientParameters[i] = NULL;
}
free(resp->Session.ClientParameters);
resp->Session.ClientParameters = NULL;
}
free(resp);
}
} /* SessionRegisterResp_free */
/**
* @brief Parse a SessionJob from a JSON node
*
* @param[in] jsonJob JSON node containing the job data
* @return Pointer to newly allocated SessionJob_t, or NULL on failure
*/
static SessionJob_t *SessionJob_fromJsonNode(JsonNode *jsonJob) {
SessionJob_t *job = NULL;
if (jsonJob) {
// ReSharper disable once CppDFAMemoryLeak
// Rider flags this calloc as a potential leak, but ownership of the
// returned SessionJob_t is intentionally transferred to the scheduler's
// ScheduledJob_t linked list via prioritize_jobs()/schedule_job(). Jobs
// are released by clear_job_schedules(). In the first-registration path
// where jobs are not scheduled, the caller
// (SessionRegisterResp_fromJson) frees them explicitly via
// SessionRegisterResp_freeJobs(). See the __NEVER_COMPILE_THIS__ block
// in SessionRegisterResp_free() for the full ownership rationale.
job = calloc(1, sizeof(SessionJob_t));
if (!job) {
log_error("%s::%s(%d) : Null pointer dereference - failed to "
"allocate SessionJob_t",
LOG_INF);
return NULL;
}
job->CompletionEndpoint =
json_get_member_string(jsonJob, "CompletionEndpoint");
job->ConfigurationEndpoint =
json_get_member_string(jsonJob, "ConfigurationEndpoint");
job->Cron = json_get_member_string(jsonJob, "Cron");
job->JobId = json_get_member_string(jsonJob, "JobId");
job->JobTypeId = json_get_member_string(jsonJob, "JobTypeId");
job->Schedule = json_get_member_string(jsonJob, "Schedule");
double priorityVal = json_get_member_number(jsonJob, "Priority", 5);
if (priorityVal < INT_MIN || priorityVal > INT_MAX) {
log_error("%s::%s(%d) : Priority value %.0f out of integer range, "
"defaulting to 5",
LOG_INF, priorityVal);
job->Priority = 5;
} else {
job->Priority = (int)priorityVal;
}
}
return job;
} /* SessionJob_fromJsonNode */
/**
* @brief Parse a SessionRegisterResponse from JSON string
*
* @param[in] jsonString JSON string to parse
* @return Pointer to newly allocated SessionRegisterResp_t, or NULL on failure
*/
SessionRegisterResp_t *SessionRegisterResp_fromJson(char *jsonString) {
JsonNode *jsonRoot = NULL;
JsonNode *jsonSession = NULL;
int jobCount = 0;
JsonNode *jsonJobs = NULL;
JsonNode *jsonTmp = NULL;
int current = 0;
JsonNode *jsonParams = NULL;
JsonNode *jsonResult = NULL;
SessionRegisterResp_t *resp = NULL;
resp = calloc(1, sizeof(SessionRegisterResp_t));
if (NULL == resp) {
log_error("%s::%s(%d) : Out of memory allocating Session Response",
LOG_INF);
return NULL;
}
if (jsonString) {
jsonRoot = json_decode(jsonString);
if (jsonRoot) {
jsonSession = json_find_member(jsonRoot, "Session");
if (jsonSession) {
resp->Session.Token =
json_get_member_string(jsonSession, "Token");
resp->Session.AgentId =
json_get_member_string(jsonSession, "AgentId");
resp->Session.Certificate =
json_get_member_string(jsonSession, "Certificate");
resp->Session.ClientMachine =
json_get_member_string(jsonSession, "ClientMachine");
resp->Session.HeartbeatInterval =
json_get_member_number(jsonSession, "HeartbeatInterval", 5);
jsonJobs = json_find_member(jsonSession, "Jobs");
jobCount = json_array_size(jsonJobs);
resp->Session.Jobs_count = jobCount;
resp->Session.Jobs = calloc(jobCount, sizeof(SessionJob_t *));
if (NULL == resp->Session.Jobs) {
log_error("%s::%s(%d) : Out of memory allocating"
" Session.Jobs",
LOG_INF);
if (resp) {
/* Free any allocated memory before returning */
SessionRegisterResp_free(resp);
}
return NULL;
}
current = 0;
json_foreach(jsonTmp, jsonJobs) {
// ReSharper disable once CppDFAMemoryLeak
// False positive: SessionJob_t instances allocated here are
// stored in resp->Session.Jobs[] and ownership is
// intentionally transferred to the scheduler's
// ScheduledJob_t linked list via
// prioritize_jobs()/schedule_job(). They are freed by
// clear_job_schedules(). In the first-registration path
// where jobs are not scheduled, the caller frees them
// explicitly via SessionRegisterResp_freeJobs() before
// calling SessionRegisterResp_free(). See the
// __NEVER_COMPILE_THIS__ block in
// SessionRegisterResp_free() for the full ownership
// rationale.
resp->Session.Jobs[current++] =
SessionJob_fromJsonNode(jsonTmp);
}
jsonParams = json_find_member(jsonSession, "ClientParameters");
if (jsonParams && jsonParams->tag == JSON_OBJECT) {
current = 0;
json_foreach(jsonTmp, jsonParams) { current++; }
resp->Session.ClientParameters =
calloc(current, sizeof(ClientParameter_t *));
if (NULL == resp->Session.ClientParameters) {
log_error("%s::%s(%d) : Out of memory allocating"
" ClientParameters",
LOG_INF);
if (resp) {
/* Free any allocated memory before returning */
/* Note, we may have jobs at this point. */
/* So manually free them first, as the */
/* SessionRegisterResp_free will not do that */
SessionRegisterResp_freeJobs(resp);
SessionRegisterResp_free(resp);
}
return NULL;
}
current = 0;
json_foreach(jsonTmp, jsonParams) {
if (jsonTmp && jsonTmp->tag == JSON_STRING &&
jsonTmp->u.string_) {
// ReSharper disable once CppDFAMemoryLeak
// False positive: ClientParameter_t instances
// allocated here are stored in
// resp->Session.ClientParameters[] and are owned by
// the response struct. They are guaranteed to be
// freed by the ClientParameter_free() loop inside
// SessionRegisterResp_free(), which is called by
// all callers of this function once they are done
// with the response. There are no execution paths
// between this point and the return of resp that
// can cause a leak.
resp->Session.ClientParameters[current++] =
ClientParameter_new(jsonTmp->key,
jsonTmp->u.string_);
}
}
resp->Session.ClientParameters_count = current;
}
}
jsonResult = json_find_member(jsonRoot, "Result");
if (jsonResult) {
resp->Result = AgentApiResult_fromJsonNode(jsonResult);
}
json_delete(jsonRoot);
}
}
return resp;
} /* SessionRegisterResp_fromJson */
/**
* @brief Allocate and initialize a new CommonConfigRequest structure
*
* @return Pointer to newly allocated CommonConfigReq_t, or NULL on failure
*/
CommonConfigReq_t *CommonConfigReq_new(void) {
return calloc(1, sizeof(CommonConfigReq_t));
} /* CommonConfigReq_new */
/**
* @brief Free memory allocated for a CommonConfigRequest structure
*
* @param[in] req Pointer to CommonConfigReq_t to free
* @return None
*/
void CommonConfigReq_free(CommonConfigReq_t *req) {
if (req) {
if (req->JobId) {
free(req->JobId);
req->JobId = NULL;
}
if (req->SessionToken) {
free(req->SessionToken);
req->SessionToken = NULL;
}
free(req);
}
} /* CommonConfigReq_free */
/**
* @brief Convert a CommonConfigRequest to JSON string
*
* @param[in] req Pointer to CommonConfigReq_t to serialize
* @return Newly allocated JSON string, or NULL on failure. Caller must free.
*/
char *CommonConfigReq_toJson(CommonConfigReq_t *req) {
char *jsonString = NULL;
if (req) {
JsonNode *jsonRoot = json_mkobject();
if (req->SessionToken) {
json_append_member(jsonRoot, "SessionToken",
json_mkstring(req->SessionToken));
} else {
json_append_member(jsonRoot, "SessionToken", json_mknull());
}
if (req->JobId) {
json_append_member(jsonRoot, "JobId", json_mkstring(req->JobId));
} else {
json_append_member(jsonRoot, "JobId", json_mknull());
}
jsonString = json_encode(jsonRoot);
json_delete(jsonRoot);
}
return jsonString;
} /* CommonConfigReq_toJson */
/**
* @brief Allocate and initialize a new CommonCompleteRequest structure
*
* @return Pointer to newly allocated CommonCompleteReq_t, or NULL on failure
*/
CommonCompleteReq_t *CommonCompleteReq_new(void) {
return calloc(1, sizeof(CommonCompleteReq_t));
} /* CommonCompleteReq_new */
/**
* @brief Free memory allocated for a CommonCompleteRequest structure
*
* @param[in] req Pointer to CommonCompleteReq_t to free
* @return None
*/
void CommonCompleteReq_free(CommonCompleteReq_t *req) {
if (req) {
if (req->JobId) {
free(req->JobId);
req->JobId = NULL;
}
if (req->SessionToken) {
free(req->SessionToken);
req->SessionToken = NULL;
}
if (req->Message) {
free(req->Message);
req->Message = NULL;
}
free(req);
}
} /* CommonCompleteReq_free */
/**
* @brief Convert a CommonCompleteRequest to JSON string
*
* @param[in] req Pointer to CommonCompleteReq_t to serialize
* @return Newly allocated JSON string, or NULL on failure. Caller must free.
*/
char *CommonCompleteReq_toJson(CommonCompleteReq_t *req) {
char *jsonString = NULL;
if (req) {
JsonNode *jsonRoot = json_mkobject();
json_append_member(jsonRoot, "Status",
json_mknumber((double)req->Status));
json_append_member(jsonRoot, "AuditId",
json_mknumber((double)req->AuditId));
if (req->JobId) {
json_append_member(jsonRoot, "JobId", json_mkstring(req->JobId));
} else {
json_append_member(jsonRoot, "JobId", json_mknull());
}
if (req->Message) {
json_append_member(jsonRoot, "Message",
json_mkstring(req->Message));
} else {
json_append_member(jsonRoot, "Message", json_mknull());
}
if (req->SessionToken) {
json_append_member(jsonRoot, "SessionToken",
json_mkstring(req->SessionToken));
} else {
json_append_member(jsonRoot, "SessionToken", json_mknull());
}
jsonString = json_encode(jsonRoot);
json_delete(jsonRoot);
}
return jsonString;
} /* CommonCompleteReq_toJson */
/**
* @brief Free memory allocated for a CommonCompleteResponse structure
*
* @param[in] resp Pointer to CommonCompleteResp_t to free
* @return None
*/
void CommonCompleteResp_free(CommonCompleteResp_t *resp) {
if (resp) {
AgentApiResult_free(resp->Result);
free(resp);
}
} /* CommonCompleteResp_free */
/**
* @brief Parse a CommonCompleteResponse from JSON string
*
* @param[in] jsonString JSON string to parse
* @return Pointer to newly allocated CommonCompleteResp_t, or NULL on failure
*/
CommonCompleteResp_t *CommonCompleteResp_fromJson(char *jsonString) {
CommonCompleteResp_t *resp = NULL;
if (jsonString) {
JsonNode *jsonRoot = json_decode(jsonString);
if (jsonRoot) {
resp = calloc(1, sizeof(CommonCompleteResp_t));
if (!resp) {
log_error("%s::%s(%d) : Null pointer dereference - failed to "
"allocate CommonCompleteResp_t",
LOG_INF);
json_delete(jsonRoot);
return NULL;
}
JsonNode *jsonResult = json_find_member(jsonRoot, "Result");
if (jsonResult) {
resp->Result = AgentApiResult_fromJsonNode(jsonResult);
}
json_delete(jsonRoot);
}
}
return resp;
} /* CommonCompleteResp_fromJson */
/**
* @brief Free memory allocated for a ManagementConfigResponse structure
*
* @param[in] resp Pointer to ManagementConfigResp_t to free
* @return None
*/
void ManagementConfigResp_free(ManagementConfigResp_t *resp) {
if (resp) {
AgentApiResult_free(resp->Result);
if (resp->Job.Alias) {