2 * Copyright (c) 2012 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.
18 /* standard library header */
25 /* SLP library header */
29 #include "ServerResource.h"
30 #include "TerminalInterface.h"
31 #include "APDUHelper.h"
32 #include "SignatureHelper.h"
36 #define EXTERN_API __attribute__((visibility("default")))
39 namespace smartcard_service_api
41 unsigned int IntegerHandle::newHandle = 0;
42 set<unsigned int> IntegerHandle::setHandles;
43 PMutex IntegerHandle::mutexLock;
45 unsigned int IntegerHandle::assignHandle()
49 pair<set<unsigned int>::iterator, bool> result;
54 if (newHandle == (unsigned int)-1)
59 result = setHandles.insert(newHandle);
62 while (!result.second);
65 SCARD_DEBUG("assign handle : newHandle [%d]", newHandle);
70 void IntegerHandle::releaseHandle(unsigned int handle)
72 SCARD_DEBUG("will be released : Handle [%d]", handle);
76 setHandles.erase(handle);
80 #define OMAPI_SE_PATH "/usr/lib/se"
82 ServerResource::ServerResource() : mainLoop(NULL)
86 serverIPC = ServerIPC::getInstance();
87 serverDispatcher = ServerDispatcher::getInstance();
95 ServerResource::~ServerResource()
99 ServerResource &ServerResource::getInstance()
101 static ServerResource serverResource;
103 return serverResource;
106 bool ServerResource::createClient(void *ioChannel, int socket, int watchID, int state, int pid)
110 if (getClient(socket) == NULL)
112 ClientInstance *instance = new ClientInstance(ioChannel, socket, watchID, state, pid);
113 if (instance != NULL)
115 mapClients.insert(make_pair(socket, instance));
120 SCARD_DEBUG_ERR("alloc failed");
125 SCARD_DEBUG_ERR("client already exist [%d]", socket);
131 ClientInstance *ServerResource::getClient(int socket)
133 ClientInstance *result = NULL;
134 map<int, ClientInstance *>::iterator item;
136 if ((item = mapClients.find(socket)) != mapClients.end())
138 result = item->second;
144 void ServerResource::setPID(int socket, int pid)
146 map<int, ClientInstance *>::iterator item;
148 if ((item = mapClients.find(socket)) != mapClients.end())
150 if (item->second->getPID() < 0)
151 item->second->setPID(pid);
155 int ServerResource::getClientCount()
157 return (int)mapClients.size();
160 void ServerResource::removeClient(int socket)
162 map<int, ClientInstance *>::iterator item;
164 if ((item = mapClients.find(socket)) != mapClients.end())
166 ServerIPC::getInstance()->releaseClient(item->second->getIOChannel(), item->second->getSocket(), item->second->getWatchID());
169 mapClients.erase(item);
173 SCARD_DEBUG("client removed already [%d]", socket);
177 void ServerResource::removeClients()
179 map<int, ClientInstance *>::iterator item;
181 for (item = mapClients.begin(); item != mapClients.end(); item++)
183 ServerIPC::getInstance()->releaseClient(item->second->getIOChannel(), item->second->getSocket(), item->second->getWatchID());
191 bool ServerResource::createService(int socket, unsigned int context)
194 ClientInstance *instance = NULL;
196 if ((instance = getClient(socket)) != NULL)
198 if ((result = instance->createService(context)) == false)
200 SCARD_DEBUG_ERR("ClientInstance::createService failed [%d] [%d]", socket, context);
205 SCARD_DEBUG_ERR("client doesn't exist [%d]", socket);
211 ServiceInstance *ServerResource::getService(int socket, unsigned int context)
213 ServiceInstance *result = NULL;
214 ClientInstance *instance = NULL;
216 if ((instance = getClient(socket)) != NULL)
218 result = instance->getService(context);
222 SCARD_DEBUG_ERR("client doesn't exist [%d]", socket);
228 void ServerResource::removeService(int socket, unsigned int context)
230 ClientInstance *instance = NULL;
232 if ((instance = getClient(socket)) != NULL)
234 instance->removeService(context);
238 SCARD_DEBUG_ERR("client doesn't exist [%d]", socket);
242 void ServerResource::removeServices(int socket)
244 ClientInstance *instance = NULL;
246 if ((instance = getClient(socket)) != NULL)
248 instance->removeServices();
252 SCARD_DEBUG_ERR("client doesn't exist [%d]", socket);
256 Terminal *ServerResource::getTerminal(unsigned int terminalID)
258 Terminal *result = NULL;
259 map<unsigned int, Terminal *>::iterator item;
261 if ((item = mapTerminals.find(terminalID)) != mapTerminals.end())
263 result = item->second;
267 SCARD_DEBUG_ERR("Terminal doesn't exist [%d]", terminalID);
273 Terminal *ServerResource::getTerminal(const char *name)
275 Terminal *result = NULL;
276 map<unsigned int, Terminal *>::iterator item;
278 for (item = mapTerminals.begin(); item != mapTerminals.end(); item++)
280 if (strncmp(name, item->second->getName(), strlen(name)) == 0)
282 result = item->second;
290 unsigned int ServerResource::createSession(int socket, unsigned int context, unsigned int terminalID, vector<ByteArray> &certHashes, void *caller)
292 unsigned int result = -1;
293 Terminal *temp = NULL;
294 ServiceInstance *instance = NULL;
296 if ((instance = getService(socket, context)) != NULL)
298 if ((temp = getTerminal(terminalID)) != NULL)
300 result = instance->openSession(temp, certHashes, caller);
305 SCARD_DEBUG_ERR("getService doesn't exist : socket [%d], context [%d]", socket, context);
311 ServerSession *ServerResource::getSession(int socket, unsigned int context, unsigned int sessionID)
313 ServerSession *result = NULL;
314 ServiceInstance *instance = NULL;
316 if ((instance = getService(socket, context)) != NULL)
318 result = instance->getSession(sessionID);
322 SCARD_DEBUG_ERR("Session doesn't exist : socket [%d], context [%d], handle [%d]", socket, context, sessionID);
328 unsigned int ServerResource::getChannelCount(int socket, unsigned int context, unsigned int sessionID)
330 unsigned int result = -1;
331 ServiceInstance *instance = NULL;
333 if ((instance = getService(socket, context)) != NULL)
335 result = instance->getChannelCountBySession(sessionID);
339 SCARD_DEBUG_ERR("getService doesn't exist : socket [%d], context [%d]", socket, context);
345 void ServerResource::removeSession(int socket, unsigned int context, unsigned int sessionID)
347 ServiceInstance *instance = NULL;
349 if ((instance = getService(socket, context)) != NULL)
351 instance->closeSession(sessionID);
355 SCARD_DEBUG_ERR("getService doesn't exist : socket [%d], context [%d]", socket, context);
359 bool ServerResource::_isAuthorizedAccess(Terminal *terminal, int pid, ByteArray aid, vector<ByteArray> &hashes)
363 #if 1 /* disable for temporary */
364 char filename[1024] = { 0, };
365 AccessControlList *acList = NULL;
367 /* check exceptional case */
368 SignatureHelper::getProcessName(pid, filename, sizeof(filename));
369 if (strncmp(filename, "ozD3Dw1MZruTDKHWGgYaDib2B2LV4/nfT+8b/g1Vsk8=", sizeof(filename)) != 0)
371 /* request open channel sequence */
372 if ((acList = getAccessControlList(terminal)) != NULL)
375 result = acList->isAuthorizedAccess(aid, hashes);
377 result = acList->isAuthorizedAccess(aid, session->packageCert);
382 SCARD_DEBUG_ERR("acList is null");
391 unsigned int ServerResource::_createChannel(Terminal *terminal, ServiceInstance *service, int channelType, unsigned int sessionID, ByteArray aid)
393 unsigned int result = IntegerHandle::INVALID_HANDLE;
399 if (channelType == 1)
402 command = APDUHelper::generateAPDU(APDUHelper::COMMAND_OPEN_LOGICAL_CHANNEL, 0, ByteArray::EMPTY);
403 rv = terminal->transmitSync(command, response);
405 if (rv == 0 && response.getLength() >= 2)
407 ResponseHelper resp(response);
409 if (resp.getStatus() == 0)
411 channelNum = resp.getDataField()[0];
413 SCARD_DEBUG("channelNum [%d]", channelNum);
417 SCARD_DEBUG_ERR("status word [%d][ %02X %02X ]", resp.getStatus(), resp.getSW1(), resp.getSW2());
424 SCARD_DEBUG_ERR("select apdu is failed, rv [%d], length [%d]", rv, response.getLength());
432 apdu.setCommand(0, APDUCommand::INS_SELECT_FILE, APDUCommand::P1_SELECT_BY_DF_NAME, APDUCommand::P2_SELECT_GET_FCP, aid, 0);
433 apdu.setChannel(1, channelNum);
434 apdu.getBuffer(command);
436 rv = terminal->transmitSync(command, response);
437 if (rv == 0 && response.getLength() >= 2)
439 ResponseHelper resp(response);
441 if (resp.getStatus() == 0)
443 result = service->openChannel(sessionID, channelNum, response);
444 if (result == IntegerHandle::INVALID_HANDLE)
446 SCARD_DEBUG_ERR("channel is null.");
451 SCARD_DEBUG_ERR("status word [%d][ %02X %02X ]", resp.getStatus(), resp.getSW1(), resp.getSW2());
456 SCARD_DEBUG_ERR("select apdu is failed, rv [%d], length [%d]", rv, response.getLength());
462 unsigned int ServerResource::createChannel(int socket, unsigned int context, unsigned int sessionID, int channelType, ByteArray aid)
464 unsigned int result = -1;
465 ServiceInstance *service = NULL;
467 if ((service = getService(socket, context)) != NULL)
469 if (service->isVaildSessionHandle(sessionID) == true)
471 ServerSession *session = NULL;
472 Terminal *terminal = NULL;
474 terminal = service->getTerminal(sessionID);
475 session = service->getSession(sessionID);
476 if (terminal != NULL && session != NULL)
478 if (_isAuthorizedAccess(terminal, service->getParent()->getPID(), aid, service->getParent()->getCertificationHashes()) == true)
480 result = _createChannel(terminal, service, channelType, sessionID, aid);
484 SCARD_DEBUG_ERR("access denied [%d]", sessionID);
489 SCARD_DEBUG_ERR("session is invalid [%d]", sessionID);
494 SCARD_DEBUG_ERR("session is invalid [%d]", sessionID);
499 SCARD_DEBUG_ERR("getService is failed [%d] [%d]", socket, context);
505 Channel *ServerResource::getChannel(int socket, unsigned int context, unsigned int channelID)
507 Channel *result = NULL;
508 ServiceInstance *instance = NULL;
510 if ((instance = getService(socket, context)) != NULL)
512 result = instance->getChannel(channelID);
516 SCARD_DEBUG_ERR("Channel doesn't exist : socket [%d], context [%d], handle [%d]", socket, context, channelID);
522 void ServerResource::removeChannel(int socket, unsigned int context, unsigned int channelID)
524 ServiceInstance *instance = NULL;
526 if ((instance = getService(socket, context)) != NULL)
528 instance->closeChannel(channelID);
532 SCARD_DEBUG_ERR("getService doesn't exist : socket [%d], context [%d]", socket, context);
536 AccessControlList *ServerResource::getAccessControlList(Terminal *terminal)
538 AccessControlList *result = NULL;
539 map<Terminal *, AccessControlList *>::iterator item;
541 if ((item = mapACL.find(terminal)) == mapACL.end())
543 ServerChannel *channel = new ServerChannel(NULL, NULL, 0, terminal);
546 /* load access control */
547 result = new GPSEACL(channel);
550 mapACL.insert(make_pair(terminal, result));
554 SCARD_DEBUG_ERR("alloc failed");
559 SCARD_DEBUG_ERR("alloc failed");
564 result = item->second;
570 Terminal *ServerResource::createInstance(void *library)
572 Terminal *terminal = NULL;
573 terminal_create_instance_fn createInstance = NULL;
575 /* create se instance */
576 createInstance = (terminal_create_instance_fn)dlsym(library, "create_instance");
577 if (createInstance != NULL)
579 terminal = (Terminal *)createInstance();
580 if (terminal != NULL)
582 SCARD_DEBUG("terminal [%p]", terminal);
586 SCARD_DEBUG_ERR("terminal is null");
591 SCARD_DEBUG_ERR("create_instance is null [%d]", errno);
597 bool ServerResource::appendSELibrary(char *library)
599 void *libHandle = NULL;
602 libHandle = dlopen(library, RTLD_LAZY);
603 if (libHandle != NULL)
605 Terminal *terminal = NULL;
607 terminal = createInstance(libHandle);
608 if (terminal != NULL)
610 unsigned int handle = IntegerHandle::assignHandle();
612 mapTerminals.insert(make_pair(handle, terminal));
613 libraries.push_back(libHandle);
615 terminal->setStatusCallback(&ServerResource::terminalCallback);
617 SCARD_DEBUG("register success [%s] [%p] [%s] [%p]", library, libHandle, terminal->getName(), terminal);
623 SCARD_DEBUG_ERR("terminal is null [%s]", library);
630 SCARD_DEBUG_ERR("it is not se file [%s] [%d]", library, errno);
636 int ServerResource::loadSecureElements()
641 struct dirent *entry = NULL;
643 if ((dir = opendir(OMAPI_SE_PATH)) != NULL)
645 while ((entry = readdir(dir)) != NULL)
647 if (strncmp(entry->d_name, ".", 1) != 0 && strncmp(entry->d_name, "..", 2) != 0)
649 char fullPath[1024] = { 0, };
651 /* TODO : need additional name rule :) */
653 /* open each files */
656 snprintf(fullPath, sizeof(fullPath), "%s/%s", OMAPI_SE_PATH, entry->d_name);
658 SCARD_DEBUG("se name [%s]", fullPath);
660 result = appendSELibrary(fullPath);
676 void ServerResource::unloadSecureElements()
679 map<unsigned int, Terminal *>::iterator item;
681 for (item = mapTerminals.begin(); item != mapTerminals.end(); item++)
683 item->second->finalize();
685 IntegerHandle::releaseHandle(item->first);
688 mapTerminals.clear();
690 for (i = 0; i < libraries.size(); i++)
692 if (libraries[i] != NULL)
693 dlclose(libraries[i]);
699 bool ServerResource::isValidReaderHandle(unsigned int reader)
701 return (getTerminal(reader) != NULL);
704 bool ServerResource::isValidSessionHandle(int socket, unsigned int context, unsigned int session)
706 ServiceInstance *instance = NULL;
708 return (((instance = getService(socket, context)) != NULL) && (getService(socket, context)->isVaildSessionHandle(session)));
711 int ServerResource::getReadersInformation(ByteArray &info)
714 unsigned char *buffer = NULL;
715 unsigned int length = 0;
716 unsigned int offset = 0;
717 unsigned int nameLen = 0;
719 if (mapTerminals.size() > 0)
721 map<unsigned int, Terminal *>::iterator item;
723 for (item = mapTerminals.begin(); item != mapTerminals.end(); item++)
725 if (item->second->isSecureElementPresence())
727 length += sizeof(nameLen) + strlen(item->second->getName()) + sizeof(unsigned int);
732 buffer = new unsigned char[length];
735 memset(buffer, 0, length);
737 for (item = mapTerminals.begin(); item != mapTerminals.end(); item++)
739 if (item->second->isSecureElementPresence())
741 nameLen = strlen(item->second->getName());
743 memcpy(buffer + offset, &nameLen, sizeof(nameLen));
744 offset += sizeof(nameLen);
746 memcpy(buffer + offset, item->second->getName(), nameLen);
749 memcpy(buffer + offset, &item->first, sizeof(unsigned int));
750 offset += sizeof(unsigned int);
754 info.setBuffer(buffer, length);
759 SCARD_DEBUG_ERR("alloc failed");
765 SCARD_DEBUG("no secure element");
771 bool ServerResource::sendMessageToAllClients(Message &msg)
774 map<int, ClientInstance *>::iterator item;
776 for (item = mapClients.begin(); item != mapClients.end(); item++)
778 if (item->second->sendMessageToAllServices(item->second->getSocket(), msg) == false)
785 void ServerResource::terminalCallback(void *terminal, int event, int error, void *user_param)
791 case Terminal::NOTIFY_SE_AVAILABLE :
795 SCARD_DEBUG("[NOTIFY_SE_AVAILABLE]");
796 SCARD_DEBUG("terminal [%s], error [%d], user_param [%p]", (char *)terminal, error, user_param);
798 /* send all client to refresh reader */
799 msg.message = msg.MSG_NOTIFY_SE_INSERTED;
800 msg.data.setBuffer((unsigned char *)terminal, strlen((char *)terminal) + 1);
802 ServerResource::getInstance().sendMessageToAllClients(msg);
806 case Terminal::NOTIFY_SE_NOT_AVAILABLE :
810 SCARD_DEBUG("[NOTIFY_SE_NOT_AVAILABLE]");
811 SCARD_DEBUG("terminal [%s], error [%d], user_param [%p]", (char *)terminal, error, user_param);
813 /* send all client to refresh reader */
814 msg.message = msg.MSG_NOTIFY_SE_REMOVED;
815 msg.data.setBuffer((unsigned char *)terminal, strlen((char *)terminal) + 1);
817 ServerResource::getInstance().sendMessageToAllClients(msg);
822 SCARD_DEBUG("terminal [%s], event [%d], error [%d], user_param [%p]", (char *)terminal, event, error, user_param);
829 } /* namespace smartcard_service_api */
831 using namespace smartcard_service_api;
833 EXTERN_API void server_resource_set_main_loop_instance(void *instance)
835 ServerResource::getInstance().setMainLoopInstance(instance);