1 /*
2  * Copyright (C) 2020 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "chpp/services/loopback.h"
18 
19 #include <stdbool.h>
20 #include <stddef.h>
21 #include <stdint.h>
22 #include <string.h>
23 
24 #include "chpp/app.h"
25 #include "chpp/log.h"
26 #include "chpp/memory.h"
27 #include "chpp/transport.h"
28 
29 /************************************************
30  *  Public Functions
31  ***********************************************/
32 
chppDispatchLoopbackClientRequest(struct ChppAppState * context,uint8_t * buf,size_t len)33 bool chppDispatchLoopbackClientRequest(struct ChppAppState *context,
34                                        uint8_t *buf, size_t len) {
35   uint8_t *response = chppMalloc(len);
36   if (response == NULL) {
37     CHPP_LOG_OOM();
38     chppEnqueueTxErrorDatagram(context->transportContext,
39                                CHPP_TRANSPORT_ERROR_OOM);
40 
41   } else {
42     CHPP_LOGI("Looping back len=%" PRIuSIZE, len);
43 
44     // Copy received datagram
45     memcpy(response, buf, len);
46 
47     // Modify response message type per loopback spec.
48     struct ChppAppHeader *responseHeader = (struct ChppAppHeader *)response;
49     responseHeader->type = CHPP_MESSAGE_TYPE_SERVICE_RESPONSE;
50 
51     // Send out response datagram
52     chppEnqueueTxDatagramOrFail(context->transportContext, response, len);
53   }
54 
55   return true;
56 }
57