Merge pull request #48 from changyu-choi/server/pkg_request
[platform/core/appfw/pkgmgr-info.git] / src / server / pkg_request.cc
1 /*
2  * Copyright (c) 2021 Samsung Electronics Co., Ltd All Rights Reserved
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 "pkg_request.hh"
18 #include "pkgmgrinfo_debug.h"
19
20 namespace pkgmgr_server {
21
22 PkgRequest::PkgRequest(int fd) : fd_(fd), data_size_(-1) {
23   socket_ = std::unique_ptr<pkgmgr_common::socket::DataSocket>(
24       new (std::nothrow) pkgmgr_common::socket::DataSocket(fd_));
25   if (socket_ == nullptr) LOGE("Out of memory");
26 }
27
28 PkgRequest::~PkgRequest() {
29   if (data_ != nullptr) delete[] data_;
30 }
31
32 unsigned char* PkgRequest::GetData() { return data_; }
33
34 int PkgRequest::GetSize() { return data_size_; }
35
36 bool PkgRequest::ReceiveData() {
37   int ret = socket_->ReceiveData(&data_size_, sizeof(data_size_));
38   if (ret < 0) {
39     LOGE("Failed to ReceiveData");
40     return false;
41   }
42   if (data_size_ < 0) {
43     LOGE("Invalid data");
44     data_size_ = -1;
45     return false;
46   }
47   data_ = new (std::nothrow) unsigned char[data_size_];
48   if (data_ == nullptr) {
49     LOGE("Out of memory");
50     data_size_ = -1;
51     return false;
52   }
53   ret = socket_->ReceiveData((void*)data_, data_size_);
54   if (ret < 0) {
55     LOGE("Failed to ReceiveData");
56     delete[] data_;
57     data_ = nullptr;
58     data_size_ = -1;
59     return false;
60   }
61
62   return true;
63 }
64
65 bool PkgRequest::SendData(unsigned char* data, int size) {
66   return (socket_->SendData(data, size) < 0);
67 }
68
69 }  // namespace pkgmgr_server