2 * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 * @file unix_socket.cpp
18 * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
20 * @brief This file is the implementation file of unix socket
23 #include <dpl/socket/unix_socket.h>
24 #include <dpl/log/log.h>
25 #include <dpl/exception.h>
27 #include <sys/socket.h>
37 UnixSocket::UnixSocket()
40 int UnixSocket::AllocSpecificDescriptor() const
42 LogPedantic("Creating UNIX socket...");
44 // Create new descriptor
45 int newSocket = socket(AF_UNIX, SOCK_STREAM, 0);
47 if (newSocket == -1) {
48 Throw(Exception::CreateFailed);
51 LogPedantic("UNIX socket created");
53 // Return new descriptor
57 std::pair<sockaddr *, socklen_t> UnixSocket::TranslateAddressGenericToSpecific(
58 const Address &address) const
60 // Allocate new socket address structure
61 sockaddr_un *sockAddress =
62 static_cast<sockaddr_un *>(malloc(sizeof(sockaddr_un)));
64 throw std::bad_alloc();
67 memset(sockAddress, 0, sizeof(sockaddr_un));
69 // Copy address properties
70 sockAddress->sun_family = AF_UNIX;
71 strncpy(sockAddress->sun_path, address.GetAddress().c_str(),
72 sizeof(sockAddress->sun_path) - 1);
74 //Prevent buffer overflows
75 sockAddress->sun_path[sizeof(sockAddress->sun_path) - 1] = '\0';
77 // Set proper address length
78 socklen_t sockAddressLength = SUN_LEN(sockAddress);
80 // Return new translated address
81 return std::make_pair(reinterpret_cast<sockaddr *>(sockAddress),
85 Address UnixSocket::TranslateAddressSpecificToGeneric(sockaddr *address,
88 // FIXME: Constrain check ?
89 sockaddr_un *unixAddress = reinterpret_cast<sockaddr_un *>(address);
90 return Address(unixAddress->sun_path);
93 socklen_t UnixSocket::GetSpecificAddressSize() const
95 return static_cast<socklen_t>(sizeof(sockaddr_un));
98 UnixSocket *UnixSocket::AllocAcceptedSpecificSocket() const
100 return new UnixSocket();
103 void UnixSocket::Bind(const Address &address)
105 // Always remove socket file if any
106 unlink(address.GetAddress().c_str());
108 // Call base implementation
109 GenericSocket<UnixSocket>::Bind(address);
111 // Always set proper permissions to the socket file
112 if (chmod(address.GetAddress().c_str(), 0777) < 0) {
114 "Error setting permissions to the socket file. Errno " <<