Reimplement security-manager mockup.
[platform/core/security/key-manager.git] / src / manager / main / socket-2-id.cpp
1 /*
2  *  Copyright (c) 2000 - 2015 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  * @file       socket-2-id.cpp
18  * @author     Bartlomiej Grzelewski (b.grzelewski@samsung.com)
19  * @version    1.0
20  */
21 #include <sys/smack.h>
22 #include <sys/types.h>
23 #include <sys/socket.h>
24
25 #include <dpl/log/log.h>
26 #include <protocols.h>
27 #include <socket-2-id.h>
28
29 namespace CKM {
30
31 namespace {
32
33 int assignToString(std::vector<char> &vec, socklen_t len, std::string &res) {
34     if (vec.size() <= len)
35         return -1;
36
37     vec[len] = 0;            // old implementation getsockopt returns cstring without 0
38     if (vec[len-1] == 0) {
39         --len;               // new implementation of getsockopt returns cstring size+1
40     }
41
42     res.assign(vec.data(), len);
43     return 0;
44 }
45
46 } // namespace anonymous
47
48 int Socket2Id::getCredentialsFromSocket(int sock, std::string &res)  {
49     std::vector<char> result(SMACK_LABEL_LEN+1);
50     socklen_t length = SMACK_LABEL_LEN;
51
52     if (0 == getsockopt(sock, SOL_SOCKET, SO_PEERSEC, result.data(), &length)) {
53         return assignToString(result, length, res);
54     }
55
56     if (errno != ERANGE) {
57         LogError("getsockopt failed");
58         return -1;
59     }
60
61     result.resize(length+1);
62
63     if (0 > getsockopt(sock, SOL_SOCKET, SO_PEERSEC, result.data(), &length)) {
64         LogError("getsockopt failed with errno: " << errno);
65         return -1;
66     }
67
68     return assignToString(result, length, res);
69 }
70
71 void Socket2Id::resetCache() {
72     m_stringMap.clear();
73 }
74
75 } // namespace CKM
76