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