Fix minor issues
[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)
23     : request_type_(pkgmgr_common::REQ_TYPE_NONE), data_size_(-1) {
24   socket_ = std::unique_ptr<pkgmgr_common::socket::DataSocket>(
25       new (std::nothrow) pkgmgr_common::socket::DataSocket(fd));
26   if (socket_ == nullptr)
27     LOGE("Out of memory");
28 }
29
30 PkgRequest::~PkgRequest() {
31   if (data_ != nullptr)
32     delete[] data_;
33 }
34
35 unsigned char* PkgRequest::GetData() {
36   return data_;
37 }
38
39 int PkgRequest::GetSize() {
40   return data_size_;
41 }
42
43 pid_t PkgRequest::GetSenderPID() {
44   return socket_->GetPID();
45 }
46
47 pkgmgr_common::ReqType PkgRequest::GetRequestType() {
48   return request_type_;
49 }
50
51 bool PkgRequest::ReceiveData() {
52   int ret = socket_->ReceiveData(&request_type_, sizeof(request_type_));
53   if (ret < 0 || request_type_ == pkgmgr_common::REQ_TYPE_NONE) {
54     LOGE("Failed to ReceiveData");
55     return false;
56   }
57   ret = socket_->ReceiveData(&data_size_, sizeof(data_size_));
58   if (ret < 0) {
59     LOGE("Failed to ReceiveData");
60     request_type_ = pkgmgr_common::REQ_TYPE_NONE;
61     return false;
62   }
63   if (data_size_ <= 0) {
64     LOGE("Invalid data");
65     request_type_ = pkgmgr_common::REQ_TYPE_NONE;
66     return false;
67   }
68
69   data_ = new (std::nothrow) unsigned char[data_size_];
70   if (data_ == nullptr) {
71     LOGE("Out of memory");
72     request_type_ = pkgmgr_common::REQ_TYPE_NONE;
73     return false;
74   }
75   ret = socket_->ReceiveData(reinterpret_cast<void*>(data_), data_size_);
76   if (ret < 0) {
77     LOGE("Failed to ReceiveData");
78     delete[] data_;
79     data_ = nullptr;
80     request_type_ = pkgmgr_common::REQ_TYPE_NONE;
81     return false;
82   }
83
84   return true;
85 }
86
87 bool PkgRequest::SendData(unsigned char* data, int size) {
88   if (socket_->SendData(&size, sizeof(size)) < 0)
89     return false;
90
91   return (socket_->SendData(data, size) < 0);
92 }
93
94 }  // namespace pkgmgr_server