2 * Copyright (c) 2012, 2013 Samsung Electronics Co., Ltd.
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 /* standard library header */
24 /* SLP library header */
28 #include "ServerResource.h"
29 #include "TerminalInterface.h"
30 #include "APDUHelper.h"
31 #include "SignatureHelper.h"
34 #include "ServerGDBus.h"
35 #include "smartcard-daemon.h"
38 #define EXTERN_API __attribute__((visibility("default")))
43 namespace smartcard_service_api
45 unsigned int IntegerHandle::newHandle = 0;
46 set<unsigned int> IntegerHandle::setHandles;
47 PMutex IntegerHandle::mutexLock;
49 unsigned int IntegerHandle::assignHandle()
53 pair<set<unsigned int>::iterator, bool> result;
58 if (newHandle == (unsigned int)-1)
63 result = setHandles.insert(newHandle);
66 while (!result.second);
69 _DBG("assign handle : newHandle [%d]", newHandle);
74 void IntegerHandle::releaseHandle(unsigned int handle)
76 _DBG("will be released : Handle [%d]", handle);
80 setHandles.erase(handle);
84 #define OMAPI_SE_PATH "/usr/lib/se"
86 ServerResource::ServerResource() : seLoaded(false)
92 ServerResource::~ServerResource()
96 ServerResource &ServerResource::getInstance()
98 static ServerResource serverResource;
100 return serverResource;
103 bool ServerResource::createClient(const char *name, pid_t pid)
107 if (getClient(name) == NULL)
109 ClientInstance *instance = new ClientInstance(name, pid);
110 if (instance != NULL)
112 mapClients.insert(make_pair(name, instance));
117 _ERR("alloc failed");
122 _ERR("client already exist, name [%s]", name);
128 ClientInstance *ServerResource::getClient(const char *name)
130 ClientInstance *result = NULL;
131 map<string, ClientInstance *>::iterator item;
133 if ((item = mapClients.find(name)) != mapClients.end())
135 result = item->second;
141 void ServerResource::removeClient(const char *name)
143 map<string, ClientInstance *>::iterator item;
145 if ((item = mapClients.find(name)) != mapClients.end())
148 mapClients.erase(item);
152 _DBG("client removed already, name [%s]", name);
156 void ServerResource::removeClients()
158 map<string, ClientInstance *>::iterator item;
160 for (item = mapClients.begin(); item != mapClients.end(); item++)
168 int ServerResource::getClientCount() const
170 return (int)mapClients.size();
173 ServiceInstance *ServerResource::createService(const char *name)
175 ServiceInstance *result = NULL;
176 ClientInstance *instance = NULL;
178 if ((instance = getClient(name)) != NULL)
180 if ((result = instance->createService()) == NULL)
182 _ERR("ClientInstance::createService failed [%d]", name);
187 _ERR("client doesn't exist, name [%s]", name);
193 ServiceInstance *ServerResource::getService(const char *name, unsigned int handle)
195 ServiceInstance *result = NULL;
196 ClientInstance *instance = NULL;
198 if ((instance = getClient(name)) != NULL)
200 result = instance->getService(handle);
204 _ERR("client doesn't exist, name [%s]", name);
210 void ServerResource::removeService(const char *name, unsigned int handle)
212 ClientInstance *instance = NULL;
214 if ((instance = getClient(name)) != NULL)
216 instance->removeService(handle);
217 if (instance->getServiceCounts() == 0) {
219 /* remove client instance */
225 _ERR("client doesn't exist, name [%s]", name);
229 void ServerResource::removeServices(const char *name)
231 ClientInstance *instance = NULL;
233 if ((instance = getClient(name)) != NULL)
235 instance->removeServices();
237 /* remove client instance */
242 _ERR("client doesn't exist, name [%s]", name);
246 unsigned int ServerResource::createSession(const char *name, unsigned int handle, unsigned int readerID, vector<ByteArray> &certHashes, void *caller)
248 unsigned int result = -1;
249 Terminal *temp = NULL;
250 ServiceInstance *instance = NULL;
252 if ((instance = getService(name, handle)) != NULL)
254 if ((temp = getTerminalByReaderID(readerID)) != NULL)
256 result = instance->openSession(temp, certHashes, caller);
261 _ERR("getService doesn't exist : name [%s], handle [%d]", name, handle);
267 ServerSession *ServerResource::getSession(const char *name, unsigned int handle, unsigned int sessionID)
269 ServerSession *result = NULL;
270 ServiceInstance *instance = NULL;
272 if ((instance = getService(name, handle)) != NULL)
274 result = instance->getSession(sessionID);
278 _ERR("Session doesn't exist : name [%s], handle [%d], handle [%d]", name, handle, sessionID);
284 bool ServerResource::isValidSessionHandle(const char *name, unsigned int handle, unsigned int session)
286 ServiceInstance *instance = NULL;
288 return (((instance = getService(name, handle)) != NULL) && (instance->isVaildSessionHandle(session)));
291 unsigned int ServerResource::getChannelCount(const char *name, unsigned int handle, unsigned int sessionID)
293 unsigned int result = -1;
294 ServiceInstance *instance = NULL;
296 if ((instance = getService(name, handle)) != NULL)
298 result = instance->getChannelCountBySession(sessionID);
302 _ERR("getService doesn't exist : name [%s], handle [%d]", name, handle);
308 void ServerResource::removeSession(const char *name, unsigned int handle, unsigned int sessionID)
310 ServiceInstance *instance = NULL;
312 if ((instance = getService(name, handle)) != NULL)
314 instance->closeSession(sessionID);
318 _ERR("getService doesn't exist : name [%s], handle [%d]", name, handle);
322 unsigned int ServerResource::createChannel(const char *name, unsigned int handle, unsigned int sessionID, int channelType, ByteArray aid)
323 throw(ExceptionBase &)
325 unsigned int result = -1;
326 ServiceInstance *service = NULL;
328 if ((service = getService(name, handle)) != NULL)
330 if (service->isVaildSessionHandle(sessionID) == true)
332 ServerSession *session = NULL;
333 Terminal *terminal = NULL;
335 terminal = service->getTerminal(sessionID);
336 session = service->getSession(sessionID);
337 if (terminal != NULL && session != NULL)
339 if (terminal->open() == true) {
340 result = _createChannel(terminal, service, channelType, sessionID, aid);
341 if (result == IntegerHandle::INVALID_HANDLE)
343 _ERR("create channel failed [%d]", sessionID);
348 _ERR("terminal open failed");
349 throw ExceptionBase(SCARD_ERROR_UNAVAILABLE);
354 _ERR("session is invalid [%d]", sessionID);
355 throw ExceptionBase(SCARD_ERROR_UNAVAILABLE);
360 _ERR("session is invalid [%d]", sessionID);
361 throw ExceptionBase(SCARD_ERROR_ILLEGAL_STATE);
366 _ERR("getService is failed, name [%s], handle [%d]", name, handle);
367 throw ExceptionBase(SCARD_ERROR_UNAVAILABLE);
373 Channel *ServerResource::getChannel(const char *name, unsigned int handle, unsigned int channelID)
375 Channel *result = NULL;
376 ServiceInstance *instance = NULL;
378 if ((instance = getService(name, handle)) != NULL)
380 result = instance->getChannel(channelID);
384 _ERR("Channel doesn't exist : name [%s], handle [%d], handle [%d]", name, handle, channelID);
390 void ServerResource::removeChannel(const char *name, unsigned int handle, unsigned int channelID)
392 ServiceInstance *instance = NULL;
394 if ((instance = getService(name, handle)) != NULL)
396 ServerChannel *channel;
397 Terminal *terminal = NULL;
399 channel = instance->getChannel(channelID);
400 if (channel != NULL) {
401 terminal = channel->getTerminal();
404 instance->closeChannel(channelID);
406 if (terminal != NULL) {
412 _ERR("getService doesn't exist : name [%s], handle [%d]", name, handle);
416 Terminal *ServerResource::getTerminal(unsigned int terminalID)
418 Terminal *result = NULL;
419 map<unsigned int, Terminal *>::iterator item;
421 if ((item = mapTerminals.find(terminalID)) != mapTerminals.end())
423 result = item->second;
427 _ERR("Terminal doesn't exist [%d]", terminalID);
433 const Terminal *ServerResource::getTerminal(unsigned int terminalID) const
435 const Terminal *result = NULL;
436 map<unsigned int, Terminal *>::const_iterator item;
438 if ((item = mapTerminals.find(terminalID)) != mapTerminals.end())
440 result = item->second;
444 _ERR("Terminal doesn't exist [%d]", terminalID);
450 Terminal *ServerResource::getTerminal(const char *name)
452 Terminal *result = NULL;
453 map<unsigned int, Terminal *>::iterator item;
455 for (item = mapTerminals.begin(); item != mapTerminals.end(); item++)
457 if (strncmp(name, item->second->getName(), strlen(name)) == 0)
459 result = item->second;
467 Terminal *ServerResource::getTerminalByReaderID(unsigned int readerID)
469 Terminal *result = NULL;
470 map<unsigned int, unsigned int>::iterator item;
472 if ((item = mapReaders.find(readerID)) != mapReaders.end())
474 result = getTerminal(item->second);
478 _ERR("Terminal doesn't exist, reader ID [%d]", readerID);
484 const Terminal *ServerResource::getTerminalByReaderID(unsigned int readerID) const
486 const Terminal *result = NULL;
487 map<unsigned int, unsigned int>::const_iterator item;
489 if ((item = mapReaders.find(readerID)) != mapReaders.end())
491 result = getTerminal(item->second);
495 _ERR("Terminal doesn't exist, reader ID [%d]", readerID);
501 unsigned int ServerResource::getTerminalID(const char *name) const
503 unsigned int result = IntegerHandle::INVALID_HANDLE;
504 map<unsigned int, Terminal *>::const_iterator item;
506 for (item = mapTerminals.begin();
507 item != mapTerminals.end(); item++)
509 if (strncmp(name, item->second->getName(),
512 result = item->first;
520 bool ServerResource::_isAuthorizedAccess(ServerChannel *channel,
521 const ByteArray &aid, const vector<ByteArray> &hashes)
524 AccessControlList *acList = NULL;
526 /* request open channel sequence */
527 if ((acList = getAccessControlList(channel)) == NULL)
529 /* load access control defined by Global Platform */
530 GPACE *acl = new GPACE();
535 ret = acl->loadACL(channel);
536 if (ret >= SCARD_ERROR_OK)
539 addAccessControlList(channel, acList);
543 _ERR("unknown error, 0x%x", -ret);
549 _ERR("alloc failed");
554 acList->loadACL(channel);
559 result = acList->isAuthorizedAccess(aid, hashes);
565 int ServerResource::_openLogicalChannel(Terminal *terminal)
573 command = APDUHelper::generateAPDU(APDUHelper::COMMAND_OPEN_LOGICAL_CHANNEL, 0, ByteArray::EMPTY);
574 rv = terminal->transmitSync(command, response);
575 if (rv == 0 && response.size() >= 2)
577 ResponseHelper resp(response);
579 if (resp.getStatus() >= 0)
581 result = resp.getDataField()[0];
585 result = resp.getStatus();
590 _ERR("transmitSync failed, rv [%d], length [%d]", rv, response.size());
596 int ServerResource::_closeLogicalChannel(Terminal *terminal, int channelNum)
598 int result = SCARD_ERROR_UNKNOWN;
604 command = APDUHelper::generateAPDU(APDUHelper::COMMAND_CLOSE_LOGICAL_CHANNEL, channelNum, ByteArray::EMPTY);
605 rv = terminal->transmitSync(command, response);
606 if (rv == 0 && response.size() >= 2)
608 ResponseHelper resp(response);
610 if (resp.getStatus() >= 0)
612 _DBG("channel closed [%d]", channelNum);
613 result = SCARD_ERROR_OK;
617 _ERR("status word [ %02X %02X ]", resp.getSW1(), resp.getSW2());
622 _ERR("select apdu is failed, rv [%d], length [%d]", rv, response.size());
628 unsigned int ServerResource::_createChannel(Terminal *terminal,
629 ServiceInstance *service, int channelType,
630 unsigned int sessionID, const ByteArray &aid)
631 throw(ExceptionBase &)
633 unsigned int result = IntegerHandle::INVALID_HANDLE;
635 ServerChannel *channel = NULL;
637 /* open logical channel */
638 if (channelType == 1)
640 channelNum = _openLogicalChannel(terminal);
643 _DBG("channelNum [%d]", channelNum);
647 _ERR("_openLogicalChannel failed [%d]", channelNum);
648 throw ExceptionBase(SCARD_ERROR_NOT_ENOUGH_RESOURCE);
652 /* create channel instance */
653 result = service->openChannel(sessionID, channelNum, ByteArray::EMPTY);
654 if (result == IntegerHandle::INVALID_HANDLE)
656 _ERR("channel is null.");
658 /* close logical channel */
661 _closeLogicalChannel(terminal, channelNum);
663 throw ExceptionBase(SCARD_ERROR_OUT_OF_MEMORY);
666 channel = service->getChannel(result);
669 if (_isAuthorizedAccess(channel, aid,
670 service->getParent()->getCertificationHashes()) == true)
675 if (aid == PKCS15::PKCS15_AID)
677 PKCS15 pkcs15(channel);
679 rv = pkcs15.select();
680 if (rv >= SCARD_ERROR_OK)
682 /* remove privilege mode */
683 channel->unsetPrivilegeMode();
684 channel->setSelectResponse(pkcs15.getSelectResponse());
688 _ERR("select failed, [%x]", -rv);
690 service->closeChannel(result);
691 throw ExceptionBase(SCARD_ERROR_IO_FAILED);
696 FileObject file(channel);
698 rv = file.select(aid);
699 if (rv >= SCARD_ERROR_OK)
701 /* remove privilege mode */
702 channel->unsetPrivilegeMode();
703 channel->setSelectResponse(file.getSelectResponse());
707 _ERR("select failed [%x]", -rv);
709 service->closeChannel(result);
710 throw ExceptionBase(SCARD_ERROR_IO_FAILED);
716 _ERR("unauthorized access");
718 service->closeChannel(result);
719 throw ExceptionBase(SCARD_ERROR_SECURITY_NOT_ALLOWED);
725 void ServerResource::addAccessControlList(Terminal *terminal, AccessControlList *acl)
727 map<Terminal *, AccessControlList *>::iterator item;
729 if ((item = mapACL.find(terminal)) == mapACL.end())
731 mapACL.insert(make_pair(terminal, acl));
739 void ServerResource::addAccessControlList(ServerChannel *channel, AccessControlList *acl)
741 map<Terminal *, AccessControlList *>::iterator item;
743 if ((item = mapACL.find(channel->getTerminal())) == mapACL.end())
745 mapACL.insert(make_pair(channel->getTerminal(), acl));
753 AccessControlList *ServerResource::getAccessControlList(Terminal *terminal)
755 AccessControlList *result = NULL;
756 map<Terminal *, AccessControlList *>::iterator item;
758 if ((item = mapACL.find(terminal)) != mapACL.end())
760 result = item->second;
766 AccessControlList *ServerResource::getAccessControlList(ServerChannel *channel)
768 AccessControlList *result = NULL;
769 map<Terminal *, AccessControlList *>::iterator item;
771 if ((item = mapACL.find(channel->getTerminal())) != mapACL.end())
773 result = item->second;
779 Terminal *ServerResource::createInstance(void *library)
781 Terminal *terminal = NULL;
782 terminal_create_instance_fn createInstance = NULL;
784 /* create se instance */
785 createInstance = (terminal_create_instance_fn)dlsym(library, "create_instance");
786 if (createInstance != NULL)
788 terminal = (Terminal *)createInstance();
789 if (terminal != NULL)
791 _DBG("terminal [%p]", terminal);
795 _ERR("terminal is null");
800 _ERR("create_instance is null [%d]", errno);
806 bool ServerResource::appendSELibrary(char *library)
808 void *libHandle = NULL;
811 libHandle = dlopen(library, RTLD_LAZY);
812 if (libHandle != NULL)
814 Terminal *terminal = NULL;
816 terminal = createInstance(libHandle);
817 if (terminal != NULL)
819 unsigned int handle = IntegerHandle::assignHandle();
821 mapTerminals.insert(make_pair(handle, terminal));
822 libraries.push_back(libHandle);
824 terminal->setStatusCallback(&ServerResource::terminalCallback);
826 _DBG("register success [%s] [%p] [%s] [%p]", library, libHandle, terminal->getName(), terminal);
828 if (terminal->isSecureElementPresence() == true)
830 createReader(handle);
837 _ERR("terminal is null [%s]", library);
844 _ERR("it is not se file [%s] [%d]", library, errno);
850 int ServerResource::loadSecureElements()
854 if (seLoaded == false)
857 struct dirent *entry;
859 if ((dir = opendir(OMAPI_SE_PATH)) != NULL)
861 while ((entry = readdir(dir)) != NULL)
863 if (strncmp(entry->d_name, ".", 1) != 0 &&
864 strncmp(entry->d_name, "..", 2) != 0)
868 /* TODO : need additional name rule :) */
870 /* append each files */
871 snprintf(fullPath, sizeof(fullPath),
872 "%s/%s", OMAPI_SE_PATH, entry->d_name);
874 result = appendSELibrary(fullPath);
891 void ServerResource::unloadSecureElements()
893 if (seLoaded == true)
896 map<unsigned int, Terminal *>::iterator item;
898 for (item = mapTerminals.begin(); item != mapTerminals.end(); item++)
900 item->second->finalize();
902 IntegerHandle::releaseHandle(item->first);
905 mapTerminals.clear();
907 for (i = 0; i < libraries.size(); i++)
909 if (libraries[i] != NULL)
910 dlclose(libraries[i]);
919 bool ServerResource::isValidReaderHandle(unsigned int reader) const
921 return (getTerminalByReaderID(reader) != NULL);
924 void ServerResource::getReaders(vector<pair<unsigned int, string> > &readers) const
926 const Terminal *terminal;
927 map<unsigned int, unsigned int>::const_iterator item;
931 for (item = mapReaders.begin(); item != mapReaders.end(); item++)
933 if (item->second != IntegerHandle::INVALID_HANDLE)
935 terminal = getTerminal(item->second);
936 if (terminal != NULL && terminal->isSecureElementPresence() == true)
938 readers.push_back(make_pair(item->first, terminal->getName()));
944 int ServerResource::getReadersInformation(ByteArray &info) const
947 unsigned char *buffer = NULL;
948 unsigned int length = 0;
949 unsigned int offset = 0;
950 unsigned int nameLen = 0;
952 if (mapReaders.size() > 0)
954 const Terminal *terminal = NULL;
955 map<unsigned int, unsigned int>::const_iterator item;
957 for (item = mapReaders.begin(); item != mapReaders.end(); item++)
959 if (item->second != IntegerHandle::INVALID_HANDLE)
961 terminal = getTerminal(item->second);
962 if (terminal != NULL)
964 if (terminal->isSecureElementPresence())
966 length += sizeof(nameLen) + strlen(terminal->getName()) + sizeof(unsigned int);
973 buffer = new unsigned char[length];
976 memset(buffer, 0, length);
978 for (item = mapReaders.begin(); item != mapReaders.end(); item++)
980 if (item->second != IntegerHandle::INVALID_HANDLE)
982 terminal = getTerminal(item->second);
983 if (terminal != NULL)
985 if (terminal->isSecureElementPresence())
987 nameLen = strlen(terminal->getName());
989 memcpy(buffer + offset, &nameLen, sizeof(nameLen));
990 offset += sizeof(nameLen);
992 memcpy(buffer + offset, terminal->getName(), nameLen);
995 memcpy(buffer + offset, &item->first, sizeof(unsigned int));
996 offset += sizeof(unsigned int);
1002 info.assign(buffer, length);
1007 _ERR("alloc failed");
1013 _INFO("no secure element");
1019 void ServerResource::terminalCallback(const void *terminal, int event,
1020 int error, void *user_param)
1022 _DBG("terminal [%s], event [%d], error [%d], user_param [%p]", (char *)terminal, event, error, user_param);
1026 case Terminal::NOTIFY_SE_AVAILABLE :
1028 ServerResource &instance = ServerResource::getInstance();
1029 unsigned int terminalID = IntegerHandle::INVALID_HANDLE;
1031 _INFO("[NOTIFY_SE_AVAILABLE]");
1033 terminalID = instance.getTerminalID((char *)terminal);
1034 if (terminalID != IntegerHandle::INVALID_HANDLE)
1036 unsigned int readerID = instance.createReader(terminalID);
1038 ServerGDBus::getInstance().emitReaderInserted(readerID, (const char *)terminal);
1043 case Terminal::NOTIFY_SE_NOT_AVAILABLE :
1045 ServerResource &instance = ServerResource::getInstance();
1046 unsigned int readerID = IntegerHandle::INVALID_HANDLE;
1048 _INFO("[NOTIFY_SE_NOT_AVAILABLE]");
1050 readerID = instance.getReaderID((char *)terminal);
1052 ServerGDBus::getInstance().emitReaderRemoved(
1053 readerID, (const char *)terminal);
1055 instance.removeReader(readerID);
1060 _DBG("terminal [%s], event [%d], error [%d], user_param [%p]", (char *)terminal, event, error, user_param);
1065 unsigned int ServerResource::createReader(unsigned int terminalID)
1067 unsigned int result = -1;
1069 result = IntegerHandle::assignHandle();
1071 mapReaders.insert(make_pair(result, terminalID));
1076 unsigned int ServerResource::getReaderID(const char *name) const
1078 unsigned int result = IntegerHandle::INVALID_HANDLE,
1079 terminalID = IntegerHandle::INVALID_HANDLE;
1081 terminalID = getTerminalID(name);
1082 if (terminalID != IntegerHandle::INVALID_HANDLE)
1084 map<unsigned int, unsigned int>::const_iterator item;
1086 for (item = mapReaders.begin();
1087 item != mapReaders.end(); item++)
1089 if (item->second == terminalID)
1091 result = item->first;
1100 void ServerResource::removeReader(unsigned int readerID)
1102 map<unsigned int, unsigned int>::iterator item;
1104 if ((item = mapReaders.find(readerID)) != mapReaders.end())
1106 item->second = IntegerHandle::INVALID_HANDLE;
1110 bool ServerResource::isAuthorizedNFCAccess(Terminal *terminal,
1111 const ByteArray &aid, const vector<ByteArray> &hashes)
1113 bool result = false;
1115 if (terminal == NULL) {
1119 int num = _openLogicalChannel(terminal);
1121 /* create channel instance */
1122 ServerChannel *channel = new ServerChannel(NULL, NULL, num, terminal);
1123 if (channel != NULL) {
1124 AccessControlList *acl = getAccessControlList(channel);
1127 /* load access control defined by Global Platform */
1132 ret = acl->loadACL(channel);
1133 if (ret >= SCARD_ERROR_OK) {
1134 addAccessControlList(channel, acl);
1136 _ERR("unknown error, 0x%x", -ret);
1142 _ERR("alloc failed");
1145 acl->updateACL(channel);
1149 result = acl->isAuthorizedNFCAccess(aid, hashes);
1151 _ERR("acl is null");
1156 _ERR("alloc failed");
1159 _ERR("_openLogicalChannel failed");
1165 void ServerResource::finish()
1167 if (getClientCount() == 0) {
1168 _INFO("no client connected. terminate server");
1170 smartcard_daemon_exit();
1173 } /* namespace smartcard_service_api */