1 /*
2  * Copyright (c) 2020 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *    http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "securec.h"
17 #include "log.h"
18 #include "mem_stat.h"
19 #include "jsonutil.h"
20 #include "base.h"
21 #include "parsedata.h"
22 #include "key_agreement_version.h"
23 
parse_inform_message(const char * payload,enum json_object_data_type data_type)24 void *parse_inform_message(const char *payload, enum json_object_data_type data_type)
25 {
26     struct inform_message_data *inform_msg = (struct inform_message_data *)MALLOC(sizeof(struct inform_message_data));
27     if (inform_msg == NULL) {
28         return NULL;
29     }
30     (void)memset_s(inform_msg, sizeof(*inform_msg), 0, sizeof(*inform_msg));
31     json_handle obj = parse_payload(payload, data_type);
32     if (obj == NULL) {
33         LOGE("Parse Inform Message parse payload failed");
34         goto error;
35     }
36     int32_t error_code = get_json_int(obj, FIELD_ERROR_CODE);
37     if (error_code == -1) {
38         LOGE("Parse Inform Message failed, field is null in errorCode");
39         goto error;
40     }
41     inform_msg->error_code = error_code;
42     free_payload(obj, data_type);
43     return (void *)inform_msg;
44 error:
45     free_payload(obj, data_type);
46     FREE(inform_msg);
47     return NULL;
48 }
49 
free_inform_message(void * obj)50 void free_inform_message(void *obj)
51 {
52     if (obj != NULL) {
53         FREE(obj);
54     }
55 }
56 
make_inform_message(void * data)57 char *make_inform_message(void *data)
58 {
59     struct inform_message_data *inform_msg = data;
60     char *ret_str = (char *)MALLOC(RET_STR_LENGTH);
61     if (ret_str == NULL) {
62         return NULL;
63     }
64     (void)memset_s(ret_str, RET_STR_LENGTH, 0, RET_STR_LENGTH);
65     int32_t code = (int32_t)(inform_msg->error_code);
66     if (snprintf_s(ret_str, RET_STR_LENGTH, RET_STR_LENGTH - 1, "{\"%s\":%d, \"%s\":{\"%s\":%d}}", FIELD_MESSAGE,
67         INFORM_MESSAGE, FIELD_PAYLOAD, FIELD_ERROR_CODE, code) < 0) {
68         LOGE("String generate failed");
69         FREE(ret_str);
70         ret_str = NULL;
71     }
72     return ret_str;
73 }
74