1/* 2 * Copyright (c) 2021 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 <array> 17 18#include "dgram_socket_server.h" 19 20namespace OHOS { 21namespace HiviewDFX { 22int DgramSocketServer::RecvPacket(std::vector<char>& buffer, struct ucred *cred) 23{ 24 uint16_t packetLen = 0; 25 if (auto status = Recv(&packetLen, sizeof(packetLen)); status < 0) { 26 return status; 27 } 28 if (packetLen > maxPacketLength) { 29 Recv(&packetLen, sizeof(packetLen), 0); // skip too long packet 30 return 0; 31 } 32 33 std::array<char, CMSG_SPACE(sizeof(struct ucred))> control = {0}; 34 35 struct msghdr msgh = {0}; 36 int ret = 0; 37 if (cred != nullptr) { 38 struct iovec iov; 39 iov.iov_base = buffer.data(); 40 iov.iov_len = packetLen; 41 msgh.msg_iov = &iov; 42 msgh.msg_iovlen = 1; 43 44 msgh.msg_control = control.data(); 45 msgh.msg_controllen = control.size(); 46 47 msgh.msg_name = nullptr; 48 msgh.msg_namelen = 0; 49 msgh.msg_flags = 0; 50 51 ret = RecvMsg(&msgh); 52 } else { 53 ret = Recv(buffer.data(), packetLen, 0); 54 } 55 56 if (ret <= 0) { 57 return ret; 58 } else if (cred != nullptr) { 59 struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msgh); 60 struct ucred *receivedUcred = (struct ucred*)CMSG_DATA(cmsg); 61 if (receivedUcred == nullptr) { 62 return 0; 63 } 64 *cred = *receivedUcred; 65 } 66 buffer[ret - 1] = 0; 67 68 return ret; 69} 70} // namespace HiviewDFX 71} // namespace OHOS 72