2 // Copyright (c) 2012 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.
18 * @file FApp_AulServer.cpp
19 * @brief This is the implementation for the _AulServer.cpp class.
25 #include <sys/prctl.h>
27 #include <unique_ptr.h>
31 #include <appsvc/appsvc.h>
33 #include <FBaseObject.h>
34 #include <FBaseString.h>
35 #include <FBaseUtil.h>
36 #include <FBaseSysLog.h>
37 #include <FBaseColHashMapT.h>
38 #include <FAppPkgPackageInfo.h>
40 #include <FBaseRt_Process.h>
41 #include <FBase_StringConverter.h>
42 #include "FAppPkg_PackageManagerImpl.h"
43 #include "FApp_Types.h"
44 #include "FApp_AulServer.h"
45 #include "FApp_TemplateUtil.h"
50 extern int aul_listen_app_dead_signal(int (* func)(int, void*), void* data);
55 using namespace Tizen::App::Package;
56 using namespace Tizen::Base;
57 using namespace Tizen::Base::Collection;
58 using namespace Tizen::Base::Runtime;
59 using namespace Tizen::Base::Utility;
64 const char _DESKTOP_FILE_PATH[] = "/opt/share/applications";
65 const char _DESKTOP_FILE_PATH_FORMAT[] = "%s/%s.desktop";
67 const char _X_TIZEN_SVC[] = "x-tizen-svc"; //X-TIZEN-SVC=[operation1] | [URI1] | [MIME1] ; [operation2] | [URI2] | [MIME2]
68 const int _MAX_TIZEN_SVC_DESC_LEN = 1024;
70 const int _MAX_CATEGORY = 12;
71 const int _MAX_PACKAGE_ID_LENGTH = 10;
73 const char _APP_PATH_FORMAT[] = "/opt/usr/apps/0000000000/bin/%ls";
74 const char _APP_PATH_FORMAT2[] = "/opt/apps/0000000000/bin/%ls";
75 const char PATH_ROOT[] = "/opt/usr/apps/";
76 const char PATH_ROOT2[] = "/opt/apps/";
80 namespace Tizen { namespace App
85 const char category[_MAX_CATEGORY];
89 static const _CategoryList _CATEGORY_LIST[] =
91 {"home-screen", _APP_TYPE_HOME_APP},
92 {"lock-screen", _APP_TYPE_LOCK_APP},
93 {"ime", _APP_TYPE_IME_APP},
96 static const int _NUM_CATEGORY = sizeof(_CATEGORY_LIST) / sizeof(_CategoryList);
100 _AulServer::SendResult(bundle* b, appsvc_result_val res)
102 result r = E_SUCCESS;
104 int ret = appsvc_send_result(b, res);
110 SysLogException(NID_APP, r, "Invalid result bundle.");
115 SysLogException(NID_APP, r, "Internal IPC error.");
120 SysLogException(NID_APP, r, "General error.");
127 SysLog(NID_APP, "SendResult() ok");
134 _AulServer::IsRunning(const AppId& appId, const String& exeName)
136 char slpPackageName[MAX_SLP_PACKAGE_ID] = {0, };
138 _PackageManagerImpl* pPackageManagerImpl = _PackageManagerImpl::GetInstance();
139 SysTryReturn(NID_APP, pPackageManagerImpl != null, false, E_INVALID_STATE, "[E_INVALID_STATE] Invalid package instance.");
141 pPackageManagerImpl->GetPackageName(appId, &exeName, slpPackageName, MAX_SLP_PACKAGE_ID);
143 const bool isRunning = (aul_app_is_running(slpPackageName) > 0);
145 SysLog(NID_APP, "'%s' %s running now.", slpPackageName, (isRunning) ? "is" : "is NOT");
151 _AulServer::IsRunning(const String& packageName)
153 std::unique_ptr<char[]> pPackageId(_StringConverter::CopyToCharArrayN(packageName));
155 const bool isRunning = (aul_app_is_running(pPackageId.get()) > 0);
157 SysLog(NID_APP, "'%ls' %s running now.", packageName.GetPointer(), (isRunning) ? "is" : "is NOT");
163 _AulServer::SetOnAppTerminatedCb(int (* pf_app_dead_handler)(int pid, void* pData), void* pData)
165 aul_listen_app_dead_signal(pf_app_dead_handler, pData);
166 SysLog(NID_APP, "'app_dead_handler is set.");
171 _AulServer::TerminateApplicationByPid(int pid)
173 int ret_aul = aul_subapp_terminate_request_pid(pid);
174 result r = E_SUCCESS;
180 SysLogException(NID_APP, r, "invaild pid.\n");
185 SysLogException(NID_APP, r, "internal AUL IPC error.\n");
190 SysLogException(NID_APP, r, "general error.\n");
194 SysLog(NID_APP, "'%d' is terminated.", pid);
202 _AulServer::SetOomAdj(int pid, int adj)
204 // set oom_adj to -17 for system service
205 result r = E_SUCCESS;
206 char buf[FILENAME_MAX];
209 snprintf(buf, FILENAME_MAX, "/proc/%d/oom_adj", pid);
210 fP = fopen(buf, "w");
211 SysTryReturnResult(NID_APP, fP != NULL, E_SYSTEM, "oom_adj change failed with %s.", strerror(errno));
213 fprintf(fP, "%d", adj);
220 _AulServer::GetAppType(const String& category)
224 HashMapT<String, int> map;
227 StringTokenizer strTok(category, L';');
230 while (strTok.HasMoreTokens())
232 result r = strTok.GetNextToken(token);
239 SysLog(NID_APP, "%d category items .", map.GetCount());
243 for (int i = 0; i < _NUM_CATEGORY; i++)
246 key = _CATEGORY_LIST[i].category;
247 result r = map.ContainsKey(key, b);
248 if (r == E_SUCCESS && b)
250 ret |= _CATEGORY_LIST[i].type;
257 bool _AulServer::IsInstalled(const AppId& appId)
260 packageId = _PackageManagerImpl::GetPackageIdByAppId(appId);
262 return _PackageManagerImpl::GetInstance()->IsPackageInstalled(packageId);
265 int _AulServer::CreateProcess(const AppId& appId)
267 SysTryReturn(NID_APP, appId.GetLength() > 10 && appId[10] == L'.', -1, E_INVALID_ARG, "[E_INVALID_ARG] Wrong appId %ls.", appId.GetPointer());
277 char path[FILENAME_MAX];
278 memset(path, '\0', FILENAME_MAX);
281 snprintf(path, FILENAME_MAX, _APP_PATH_FORMAT2, appId.GetPointer() + 11);
283 int ret = wcstombs(path + strlen(PATH_ROOT2), appId.GetPointer(), 10);
286 SysLogException(NID_APP, E_SYSTEM, "Launching service (%ls)(%s) failed with [%s].", appId.GetPointer(), path, strerror(errno));
290 snprintf(path, FILENAME_MAX, _APP_PATH_FORMAT2, appId.GetPointer() + 11);
292 int ret = wcstombs(path + strlen(PATH_ROOT2), appId.GetPointer(), 10);
295 SysLogException(NID_APP, E_SYSTEM, "Launching service (%ls)(%s) failed with [%s].", appId.GetPointer(), path, strerror(errno));
299 if (euidaccess(path, R_OK) != 0)
301 snprintf(path, FILENAME_MAX, _APP_PATH_FORMAT, appId.GetPointer() + 11);
303 ret = wcstombs(path + strlen(PATH_ROOT), appId.GetPointer(), 10);
306 SysLogException(NID_APP, E_SYSTEM, "Launching service (%ls)(%s) failed with [%s].", appId.GetPointer(), path, strerror(errno));
312 SysLog(NID_APP, "Launching %s.", path);
314 int currentPid = getpid();
316 //SetOomAdj(currentPid, -17); // set oom_adj to -17 for system service
318 prctl(PR_SET_PDEATHSIG, SIGTERM);
320 setpgid(currentPid, currentPid);
322 ret = execl(path, path, static_cast<char*>(NULL));
325 SysLogException(NID_APP, E_SYSTEM, "Launching service (%ls)(%s) failed with [%s].", appId.GetPointer(), path, strerror(errno));
335 _AulServer::IsUserPreferredAppForAppControlResolution(const AppId& appId)
337 std::unique_ptr<char[]> pAppId(_StringConverter::CopyToCharArrayN(appId));
339 int ret = appsvc_is_defapp(pAppId.get());
340 SysTryReturn(NID_APP, ret == 1, false, E_SUCCESS,"%ls is not an UserPreferredAppForAppControlResolution. ret(%d)", appId.GetPointer(), ret);
342 SysLog(NID_APP, "%ls is an UserPreferredAppForAppControlResolution.", appId.GetPointer());
347 _AulServer::ClearUserPreferenceForAppControlResolution(const AppId& appId)
349 std::unique_ptr<char[]> pAppId(_StringConverter::CopyToCharArrayN(appId));
351 int ret_aul = appsvc_unset_defapp(pAppId.get());
352 SysTryReturnResult(NID_APP, ret_aul == APPSVC_RET_OK, E_SYSTEM, "Fail to clear UserPreferredAppForAppControlResolution of %ls. ret_aul(%d)", appId.GetPointer(), ret_aul);
354 SysLog(NID_APP, "Succeed to clear UserPreferredAppForAppControlResolution of %ls.", appId.GetPointer());
359 _AulServer::_DesktopFile::MakePath(const AppId& appId, const String* pExeName, char* path, int size)
361 SysTryReturnResult(NID_APP, path != null, E_INVALID_ARG, "");
363 char packageName[MAX_SLP_PACKAGE_ID] = {0, };
364 result r = E_SUCCESS;
365 _PackageManagerImpl* pPackageManagerImpl = _PackageManagerImpl::GetInstance();
366 SysTryReturnResult(NID_APP, pPackageManagerImpl, E_INVALID_STATE, "Invalid package manager instance.");
368 r = pPackageManagerImpl->GetPackageName(appId, pExeName, packageName, MAX_SLP_PACKAGE_ID);
369 SysTryReturn(NID_APP, !IsFailed(r), r, r, "%s", GetErrorMessage(r));
371 snprintf(path, size, _DESKTOP_FILE_PATH_FORMAT, _DESKTOP_FILE_PATH, packageName);
377 _AulServer::_DesktopFile::UpdateService(const AppId& appId, const char* value)
379 char path[FILENAME_MAX] = {0, };
380 MakePath(appId, null, path, FILENAME_MAX);
382 return UpdateField(path, _X_TIZEN_SVC, value);
387 _AulServer::_DesktopFile::RemoveService(const AppId& appId, const char* operationOnlyValue)
389 char path[FILENAME_MAX] = {0, };
390 MakePath(appId, null, path, FILENAME_MAX);
392 return UpdateField(path, _X_TIZEN_SVC, operationOnlyValue, true);
397 // Update value of specified field.
398 // currently only "x-slp-svc" field is supported.
400 #define BUFFER_SIZE 1024
402 _AulServer::_DesktopFile::UpdateField(const char* path, const char* fieldName, const char* value, bool isRemove)
404 SysTryReturnResult(NID_APP, path != null, E_INVALID_ARG, "path should not be null.");
405 SysTryReturnResult(NID_APP, fieldName != null, E_INVALID_ARG, "fieldName should not be null.");
406 SysTryReturnResult(NID_APP, value != null, E_INVALID_ARG, "value should not be null.");
408 FILE* fp = fopen(path, "r+");
409 SysTryReturnResult(NID_APP, fp != null, E_SYSTEM, "falied to open '%s' due to %s", path, strerror(errno));
411 char buffer[BUFFER_SIZE] = {0, };
416 result r = E_SUCCESS;
419 ArrayListT<char*> buffers;
422 char* pCurrent = null;
424 while (fgets(buffer, BUFFER_SIZE, fp) != NULL)
426 len = strlen(buffer);
427 SysTryCatch(NID_APP, len < BUFFER_SIZE, , r = E_INVALID_ARG, "strlen returns invalid value. (%d)", len );
431 pCurrent = new (std::nothrow) char[len + 1];
432 SysTryCatch(NID_APP, pCurrent != null, , r = E_OUT_OF_MEMORY, "failed to allocate mem pCurrent");
434 strncpy(pCurrent, buffer, len);
435 buffers.Add(pCurrent);
439 if (strncmp(buffer, fieldName, len) == 0)
441 int fieldNameLen = strlen(fieldName);
442 SysTryCatch(NID_APP, len > fieldNameLen, , E_INVALID_ARG, "[E_INVALID_ARG] fieldName(%s)", fieldName);
444 pCurrent = UpdateServiceValueN(buffer + fieldNameLen, value, isRemove);
445 SysTryCatch(NID_APP, pCurrent != null, , r = GetLastResult(), "[%s] UpdateServiceValue failed", GetErrorMessage(GetLastResult()));
447 buffers.Add(pCurrent);
459 fsetpos(fp, (fpos_t*) &foundpos);
461 remains = buffers.GetCount(); // prevent infinite loop
462 while (buffers.GetCount() > 0 && remains-- > 0)
465 buffers.GetAt(0, pCurrent);
467 SysTryCatch(NID_APP, pCurrent != null, , r = E_INVALID_STATE, "");
470 len = strlen(pCurrent);
475 int ret = truncate(path, pos);
476 SysTryLog(NID_APP, ret == 0, "Truncate failure (%s).", strerror(errno));
480 char svctext[_MAX_TIZEN_SVC_DESC_LEN] = {0, };
481 snprintf(svctext, _MAX_TIZEN_SVC_DESC_LEN, "%s=%s\n", fieldName, value);
490 remains = buffers.GetCount(); // prevent infinite loop
491 while (buffers.GetCount() > 0 && remains-- > 0)
494 buffers.GetAt(0, pCurrent);
496 if (pCurrent != null)
508 // Tizen service string example
509 // X-TIZEN-SVC= http://tizen.org/appcontrol/operation/pick|NULL|image/jpge; http://tizen.org/appcontrol/operation/pick|NULL|video/mp4; http://tizen.org/appcontrol/operation/pick|NULL|NULL; http://tizen.org/appcontrol/operation/pview|NULL|NULL
512 _AulServer::_DesktopFile::UpdateServiceValueN(char* buffer, const char* newValue, bool isRemove)
514 SysTryReturn(NID_APP, buffer != null, null, E_INVALID_ARG, "");
515 SysTryReturn(NID_APP, newValue != null, null, E_INVALID_ARG, "");
517 SysLog(NID_APP, "current(%s), new(%s), isRemove(%s)", buffer, newValue, (isRemove) ? "true" : "false");
522 const String& servicePattern(L"([A-Za-z&=:/\\.\\-]*);?");
527 Utility::RegularExpression regex;
528 result r = regex.Construct(servicePattern);
529 SysTryReturn(NID_APP, !IsFailed(r), null, r, "");
534 String newService(newValue);
536 if (isRemove == false)
538 ParseService(newService, newOperation, newUrl, newMimeType);
542 newOperation = newValue;
545 services.Construct();
547 while (regex.Consume(buf, &services) == true)
549 String* pCurrentService = (String*) services.GetAt(1);
550 services.RemoveAll(false);
556 ParseService(*pCurrentService, operation, url, mimeType);
558 if (operation == newOperation)
560 if (isRemove == true)
562 SysLog(NID_APP, "opreration '%ls' will be removed", operation.GetPointer());
566 SysAssertf(found == false, "It's assumed that service doesn't have duplicated operation in tizen desktop file. But it isn't, so now we have to check this case.");
567 // replace operation.
568 if (found == false) // ( if duplicated operation is already exist, It will be keeped.
571 AppendServiceValueToString(resultString, newService);
572 SysLog(NID_APP, "opreration '%ls;%ls;%ls' will be updated to ;%ls;%ls", operation.GetPointer(), url.GetPointer(), mimeType.GetPointer(), newUrl.GetPointer(), mimeType.GetPointer());
579 // add not specified service.
580 AppendServiceValueToString(resultString, *pCurrentService);
583 delete pCurrentService;
586 if (found == false && isRemove == false)
588 AppendServiceValueToString(resultString, newService);
589 SysLog(NID_APP, "opreration '%ls;%ls;%ls' will be added", newOperation.GetPointer(), newUrl.GetPointer(), newMimeType.GetPointer());
592 SysLog(NID_APP, "updated string is '%ls'", resultString.GetPointer());
593 return _StringConverter::CopyToCharArrayN(resultString);
598 _AulServer::_DesktopFile::AppendServiceValueToString(String& serviceString, const String& newVaue)
600 if (serviceString.GetLength() > 0)
602 serviceString += ";";
605 serviceString += newVaue;
610 _AulServer::_DesktopFile::ParseService(const String& service, String& operation, String& url, String& mimeType)
612 SysLog(NID_APP, "service(%ls)", service.GetPointer());
614 const String& serviceDetailPattern(L"([A-Za-z&=/\\.\\-]*):(.*://[A-Za-z&=/\\.\\-]*|[A-Za-z&=/\\.\\-]*):([A-Za-z&=/\\.\\-]*)");
616 Utility::RegularExpression regexDetail;
617 result r = regexDetail.Construct(serviceDetailPattern);
618 SysTryReturn(NID_APP, !IsFailed(r), null, r, "[%s] RegularExpression::Construct(L\"%ls\") failed.", GetErrorMessage(r), serviceDetailPattern.GetPointer());
620 ArrayList matchedItems;
621 matchedItems.Construct();
622 regexDetail.Match(service, true, &matchedItems);
624 int matchedCount = matchedItems.GetCount();
625 SysTryLog(NID_APP, matchedCount == 4, "It's assumed that x-slp-svc value always have operation:url:mime in tizen desktop file. But it isn't or our parser is invalid. so now we have to check this case. %d", matchedItems.GetCount());
627 if (matchedCount > 1)
629 operation = *(String*) matchedItems.GetAt(1);
632 if (matchedCount > 2)
634 url = *(String*) matchedItems.GetAt(2);
637 if (matchedCount > 3)
639 mimeType = *(String*) matchedItems.GetAt(3);
642 SysLog(NID_APP, "matched(%d) : (%ls;%ls;%ls)", matchedItems.GetCount(), operation.GetPointer(), url.GetPointer(), mimeType.GetPointer());
643 matchedItems.RemoveAll(true);