Reimplement security-manager mockup.
[platform/core/security/key-manager.git] / src / manager / main / socket-2-id-wrapper.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-wrapper.cpp
18  * @author     Bartlomiej Grzelewski (b.grzelewski@samsung.com)
19  * @version    1.0
20  */
21 #include <string>
22
23 #include <security-manager.h>
24
25 #include <dpl/log/log.h>
26 #include <protocols.h>
27 #include <socket-2-id.h>
28
29 namespace CKM {
30
31 int Socket2Id::getPkgIdFromSmack(const std::string &smack, std::string &pkgId) {
32     // TODO
33     // Conversion from smack label to pkgId should be done
34     // by security-manager. Current version of security-manager
35     // does not support this feature yet.
36
37     static const std::string SMACK_PREFIX_APPID  = "User::App::";
38
39     if (smack.empty()) {
40         LogError("Smack is empty. Connection will be rejected");
41         return -1;
42     }
43
44     if (smack.compare(0, SMACK_PREFIX_APPID.size(), SMACK_PREFIX_APPID)) {
45         pkgId = "/" + smack;
46         LogDebug("Smack: " << smack << " Was translated to owner id: " << pkgId);
47         return 0;
48     }
49
50     std::string appId = smack.substr(SMACK_PREFIX_APPID.size(), std::string::npos);
51
52     char *pkg = nullptr;
53
54     if (0 > security_manager_get_app_pkgid(&pkg, appId.c_str())) {
55         LogError("Error in security_manager_get_app_pkgid");
56         return -1;
57     }
58
59     if (!pkg) {
60         LogError("PkgId could not be NULL");
61         return -1;
62     }
63
64     pkgId = pkg;
65     free(pkg);
66     LogDebug("Smack: " << smack << " Was translated to owner id: " << pkgId);
67     return 0;
68 }
69
70 int Socket2Id::translate(int sock, std::string &result) {
71     std::string smack;
72
73     if (0 > getCredentialsFromSocket(sock, smack)) {
74         return -1;
75     }
76
77     StringMap::iterator it = m_stringMap.find(smack);
78
79     if (it != m_stringMap.end()) {
80         result = it->second;
81         return 0;
82     }
83
84     std::string pkgId;
85     if (0 > getPkgIdFromSmack(smack, pkgId)) {
86         return -1;
87     }
88
89     result = pkgId;
90     m_stringMap.emplace(std::move(smack), std::move(pkgId));
91     return 0;
92 }
93
94 } // namespace CKM
95