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>
32 #include <app_manager.h>
35 #include <FBaseObject.h>
36 #include <FBaseString.h>
37 #include <FBaseUtil.h>
38 #include <FBaseSysLog.h>
39 #include <FBaseColHashMapT.h>
40 #include <FAppPkgPackageInfo.h>
42 #include <FBaseRt_Process.h>
43 #include <FBase_StringConverter.h>
44 #include "FAppPkg_PackageManagerImpl.h"
45 #include "FApp_Types.h"
46 #include "FApp_AulServer.h"
47 #include "FApp_TemplateUtil.h"
52 extern int aul_listen_app_dead_signal(int (* func)(int, void*), void* data);
57 using namespace Tizen::App::Package;
58 using namespace Tizen::Base;
59 using namespace Tizen::Base::Collection;
60 using namespace Tizen::Base::Runtime;
61 using namespace Tizen::Base::Utility;
66 const char _DESKTOP_FILE_PATH[] = "/opt/share/applications";
67 const char _DESKTOP_FILE_PATH_FORMAT[] = "%s/%s.desktop";
69 const char _X_TIZEN_SVC[] = "x-tizen-svc"; //X-TIZEN-SVC=[operation1] | [URI1] | [MIME1] ; [operation2] | [URI2] | [MIME2]
70 const int _MAX_TIZEN_SVC_DESC_LEN = 1024;
72 const int _MAX_CATEGORY = 12;
73 const int _MAX_PACKAGE_ID_LENGTH = 10;
75 const char _APP_PATH_FORMAT[] = "/opt/usr/apps/0000000000/bin/%ls";
76 const char _APP_PATH_FORMAT2[] = "/opt/apps/0000000000/bin/%ls";
77 const char PATH_ROOT[] = "/opt/usr/apps/";
78 const char PATH_ROOT2[] = "/opt/apps/";
82 namespace Tizen { namespace App
87 const char category[_MAX_CATEGORY];
91 static const _CategoryList _CATEGORY_LIST[] =
93 {"home-screen", _APP_TYPE_HOME_APP},
94 {"lock-screen", _APP_TYPE_LOCK_APP},
95 {"ime", _APP_TYPE_IME_APP},
98 static const int _NUM_CATEGORY = sizeof(_CATEGORY_LIST) / sizeof(_CategoryList);
102 _AulServer::SendResult(bundle* b, appsvc_result_val res)
104 result r = E_SUCCESS;
106 int ret = appsvc_send_result(b, res);
112 SysLogException(NID_APP, r, "Invalid result bundle.");
117 SysLogException(NID_APP, r, "Internal IPC error.");
122 SysLogException(NID_APP, r, "General error.");
129 SysLog(NID_APP, "SendResult() ok");
136 _AulServer::IsRunning(const AppId& appId, const String& exeName)
138 char slpPackageName[MAX_SLP_PACKAGE_ID] = {0, };
139 bool isRunning = false;
141 _PackageManagerImpl* pPackageManagerImpl = _PackageManagerImpl::GetInstance();
142 SysTryReturn(NID_APP, pPackageManagerImpl != null, false, E_INVALID_STATE, "[E_INVALID_STATE] Invalid package instance.");
144 pPackageManagerImpl->GetPackageName(appId, &exeName, slpPackageName, MAX_SLP_PACKAGE_ID);
146 app_manager_is_running(slpPackageName, &isRunning);
148 SysLog(NID_APP, "'%s' %s running now.", slpPackageName, (isRunning == true) ? "is" : "is NOT");
154 _AulServer::IsRunning(const String& packageName)
156 bool isRunning = false;
157 std::unique_ptr<char[]> pSlpPackageName(_StringConverter::CopyToCharArrayN(packageName));
159 app_manager_is_running(pSlpPackageName.get(), &isRunning);
161 SysLog(NID_APP, "'%ls' %s running now.", packageName.GetPointer(), (isRunning) ? "is" : "is NOT");
167 _AulServer::SetOnAppTerminatedCb(int (* pf_app_dead_handler)(int pid, void* pData), void* pData)
169 aul_listen_app_dead_signal(pf_app_dead_handler, pData);
170 SysLog(NID_APP, "'app_dead_handler is set.");
175 _AulServer::TerminateApplicationByPid(int pid)
177 int ret_aul = aul_terminate_pid(pid);
178 result r = E_SUCCESS;
184 SysLogException(NID_APP, r, "invaild pid.\n");
189 SysLogException(NID_APP, r, "internal AUL IPC error.\n");
194 SysLogException(NID_APP, r, "general error.\n");
198 SysLog(NID_APP, "'%d' is terminated.", pid);
206 _AulServer::SetOomAdj(int pid, int adj)
208 // set oom_adj to -17 for system service
209 result r = E_SUCCESS;
210 char buf[FILENAME_MAX];
213 snprintf(buf, FILENAME_MAX, "/proc/%d/oom_adj", pid);
214 fP = fopen(buf, "w");
215 SysTryReturnResult(NID_APP, fP != NULL, E_SYSTEM, "oom_adj change failed with %s.", strerror(errno));
217 fprintf(fP, "%d", adj);
224 _AulServer::SetPowerOffNotiListener( void (*powerOffCb)(void *pData), void *pData)
226 int heyFd = heynoti_init();
227 SysTryReturnResult(NID_APP, heyFd >= 0, E_SYSTEM, "heynoti_init failed.");
229 int ret = heynoti_subscribe(heyFd, "power_off_start", powerOffCb, pData);
230 SysTryReturnResult(NID_APP, ret >= 0, E_SYSTEM, "heynoti_subscribe failed.");
232 ret = heynoti_attach_handler(heyFd);
233 SysTryReturnResult(NID_APP, ret >= 0, E_SYSTEM, "heynoti_attach_handler failed.");
239 _AulServer::GetAppType(const String& category)
243 HashMapT<String, int> map;
246 StringTokenizer strTok(category, L';');
249 while (strTok.HasMoreTokens())
251 result r = strTok.GetNextToken(token);
258 SysLog(NID_APP, "%d category items .", map.GetCount());
262 for (int i = 0; i < _NUM_CATEGORY; i++)
265 key = _CATEGORY_LIST[i].category;
266 result r = map.ContainsKey(key, b);
267 if (r == E_SUCCESS && b)
269 ret |= _CATEGORY_LIST[i].type;
276 bool _AulServer::IsInstalled(const AppId& appId)
279 packageId = _PackageManagerImpl::GetPackageIdByAppId(appId);
281 return _PackageManagerImpl::GetInstance()->IsPackageInstalled(packageId);
284 int _AulServer::CreateProcess(const AppId& appId)
286 SysTryReturn(NID_APP, appId.GetLength() > 10 && appId[10] == L'.', -1, E_INVALID_ARG, "[E_INVALID_ARG] Wrong appId %ls.", appId.GetPointer());
296 char path[FILENAME_MAX];
297 memset(path, '\0', FILENAME_MAX);
300 snprintf(path, FILENAME_MAX, _APP_PATH_FORMAT2, appId.GetPointer() + 11);
302 int ret = wcstombs(path + strlen(PATH_ROOT2), appId.GetPointer(), 10);
305 SysLogException(NID_APP, E_SYSTEM, "Launching service (%ls)(%s) failed with [%s].", appId.GetPointer(), path, strerror(errno));
309 snprintf(path, FILENAME_MAX, _APP_PATH_FORMAT2, appId.GetPointer() + 11);
311 int ret = wcstombs(path + strlen(PATH_ROOT2), appId.GetPointer(), 10);
314 SysLogException(NID_APP, E_SYSTEM, "Launching service (%ls)(%s) failed with [%s].", appId.GetPointer(), path, strerror(errno));
318 if (euidaccess(path, R_OK) != 0)
320 snprintf(path, FILENAME_MAX, _APP_PATH_FORMAT, appId.GetPointer() + 11);
322 ret = wcstombs(path + strlen(PATH_ROOT), appId.GetPointer(), 10);
325 SysLogException(NID_APP, E_SYSTEM, "Launching service (%ls)(%s) failed with [%s].", appId.GetPointer(), path, strerror(errno));
331 SysLog(NID_APP, "Launching %s.", path);
333 int currentPid = getpid();
335 SetOomAdj(currentPid, -17); // set oom_adj to -17 for system service
337 prctl(PR_SET_PDEATHSIG, SIGTERM);
339 setpgid(currentPid, currentPid);
341 ret = execl(path, path, static_cast<char*>(NULL));
344 SysLogException(NID_APP, E_SYSTEM, "Launching service (%ls)(%s) failed with [%s].", appId.GetPointer(), path, strerror(errno));
354 _AulServer::_DesktopFile::MakePath(const AppId& appId, const String* pExeName, char* path, int size)
356 SysTryReturnResult(NID_APP, path != null, E_INVALID_ARG, "");
358 char packageName[MAX_SLP_PACKAGE_ID] = {0, };
359 result r = E_SUCCESS;
360 _PackageManagerImpl* pPackageManagerImpl = _PackageManagerImpl::GetInstance();
361 SysTryReturnResult(NID_APP, pPackageManagerImpl, E_INVALID_STATE, "Invalid package manager instance.");
363 r = pPackageManagerImpl->GetPackageName(appId, pExeName, packageName, MAX_SLP_PACKAGE_ID);
364 SysTryReturn(NID_APP, !IsFailed(r), r, r, "%s", GetErrorMessage(r));
366 snprintf(path, size, _DESKTOP_FILE_PATH_FORMAT, _DESKTOP_FILE_PATH, packageName);
372 _AulServer::_DesktopFile::UpdateService(const AppId& appId, const char* value)
374 char path[FILENAME_MAX] = {0, };
375 MakePath(appId, null, path, FILENAME_MAX);
377 return UpdateField(path, _X_TIZEN_SVC, value);
382 _AulServer::_DesktopFile::RemoveService(const AppId& appId, const char* operationOnlyValue)
384 char path[FILENAME_MAX] = {0, };
385 MakePath(appId, null, path, FILENAME_MAX);
387 return UpdateField(path, _X_TIZEN_SVC, operationOnlyValue, true);
392 // Update value of specified field.
393 // currently only "x-slp-svc" field is supported.
395 #define BUFFER_SIZE 1024
397 _AulServer::_DesktopFile::UpdateField(const char* path, const char* fieldName, const char* value, bool isRemove)
399 SysTryReturnResult(NID_APP, path != null, E_INVALID_ARG, "path should not be null.");
400 SysTryReturnResult(NID_APP, fieldName != null, E_INVALID_ARG, "fieldName should not be null.");
401 SysTryReturnResult(NID_APP, value != null, E_INVALID_ARG, "value should not be null.");
403 FILE* fp = fopen(path, "r+");
404 SysTryReturnResult(NID_APP, fp != null, E_SYSTEM, "falied to open '%s' due to %s", path, strerror(errno));
406 char buffer[BUFFER_SIZE] = {0, };
411 result r = E_SUCCESS;
414 ArrayListT<char*> buffers;
417 char* pCurrent = null;
419 while (fgets(buffer, BUFFER_SIZE, fp) != NULL)
421 len = strlen(buffer);
422 SysTryCatch(NID_APP, len < BUFFER_SIZE, , r = E_INVALID_ARG, "strlen returns invalid value. (%d)", len );
426 pCurrent = new (std::nothrow) char[len + 1];
427 SysTryCatch(NID_APP, pCurrent != null, , r = E_OUT_OF_MEMORY, "failed to allocate mem pCurrent");
429 strncpy(pCurrent, buffer, len);
430 buffers.Add(pCurrent);
434 if (strncmp(buffer, fieldName, len) == 0)
436 int fieldNameLen = strlen(fieldName);
437 SysTryCatch(NID_APP, len > fieldNameLen, , E_INVALID_ARG, "[E_INVALID_ARG] fieldName(%s)", fieldName);
439 pCurrent = UpdateServiceValueN(buffer + fieldNameLen, value, isRemove);
440 SysTryCatch(NID_APP, pCurrent != null, , r = GetLastResult(), "[%s] UpdateServiceValue failed", GetErrorMessage(GetLastResult()));
442 buffers.Add(pCurrent);
454 fsetpos(fp, (fpos_t*) &foundpos);
456 remains = buffers.GetCount(); // prevent infinite loop
457 while (buffers.GetCount() > 0 && remains-- > 0)
460 buffers.GetAt(0, pCurrent);
462 SysTryCatch(NID_APP, pCurrent != null, , r = E_INVALID_STATE, "");
465 len = strlen(pCurrent);
470 int ret = truncate(path, pos);
471 SysTryLog(NID_APP, ret == 0, "Truncate failure (%s).", strerror(errno));
475 char svctext[_MAX_TIZEN_SVC_DESC_LEN] = {0, };
476 snprintf(svctext, _MAX_TIZEN_SVC_DESC_LEN, "%s=%s\n", fieldName, value);
485 remains = buffers.GetCount(); // prevent infinite loop
486 while (buffers.GetCount() > 0 && remains-- > 0)
489 buffers.GetAt(0, pCurrent);
491 if (pCurrent != null)
503 // Tizen service string example
504 // 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
507 _AulServer::_DesktopFile::UpdateServiceValueN(char* buffer, const char* newValue, bool isRemove)
509 SysTryReturn(NID_APP, buffer != null, null, E_INVALID_ARG, "");
510 SysTryReturn(NID_APP, newValue != null, null, E_INVALID_ARG, "");
512 SysLog(NID_APP, "current(%s), new(%s), isRemove(%s)", buffer, newValue, (isRemove) ? "true" : "false");
517 const String& servicePattern(L"([A-Za-z&=:/\\.\\-]*);?");
522 Utility::RegularExpression regex;
523 result r = regex.Construct(servicePattern);
524 SysTryReturn(NID_APP, !IsFailed(r), null, r, "");
529 String newService(newValue);
531 if (isRemove == false)
533 ParseService(newService, newOperation, newUrl, newMimeType);
537 newOperation = newValue;
540 services.Construct();
542 while (regex.Consume(buf, &services) == true)
544 String* pCurrentService = (String*) services.GetAt(1);
545 services.RemoveAll(false);
551 ParseService(*pCurrentService, operation, url, mimeType);
553 if (operation == newOperation)
555 if (isRemove == true)
557 SysLog(NID_APP, "opreration '%ls' will be removed", operation.GetPointer());
561 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.");
562 // replace operation.
563 if (found == false) // ( if duplicated operation is already exist, It will be keeped.
566 AppendServiceValueToString(resultString, newService);
567 SysLog(NID_APP, "opreration '%ls;%ls;%ls' will be updated to ;%ls;%ls", operation.GetPointer(), url.GetPointer(), mimeType.GetPointer(), newUrl.GetPointer(), mimeType.GetPointer());
574 // add not specified service.
575 AppendServiceValueToString(resultString, *pCurrentService);
578 delete pCurrentService;
581 if (found == false && isRemove == false)
583 AppendServiceValueToString(resultString, newService);
584 SysLog(NID_APP, "opreration '%ls;%ls;%ls' will be added", newOperation.GetPointer(), newUrl.GetPointer(), newMimeType.GetPointer());
587 SysLog(NID_APP, "updated string is '%ls'", resultString.GetPointer());
588 return _StringConverter::CopyToCharArrayN(resultString);
593 _AulServer::_DesktopFile::AppendServiceValueToString(String& serviceString, const String& newVaue)
595 if (serviceString.GetLength() > 0)
597 serviceString += ";";
600 serviceString += newVaue;
605 _AulServer::_DesktopFile::ParseService(const String& service, String& operation, String& url, String& mimeType)
607 SysLog(NID_APP, "service(%ls)", service.GetPointer());
609 const String& serviceDetailPattern(L"([A-Za-z&=/\\.\\-]*):(.*://[A-Za-z&=/\\.\\-]*|[A-Za-z&=/\\.\\-]*):([A-Za-z&=/\\.\\-]*)");
611 Utility::RegularExpression regexDetail;
612 result r = regexDetail.Construct(serviceDetailPattern);
613 SysTryReturn(NID_APP, !IsFailed(r), null, r, "[%s] RegularExpression::Construct(L\"%ls\") failed.", GetErrorMessage(r), serviceDetailPattern.GetPointer());
615 ArrayList matchedItems;
616 matchedItems.Construct();
617 regexDetail.Match(service, true, &matchedItems);
619 int matchedCount = matchedItems.GetCount();
620 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());
622 if (matchedCount > 1)
624 operation = *(String*) matchedItems.GetAt(1);
627 if (matchedCount > 2)
629 url = *(String*) matchedItems.GetAt(2);
632 if (matchedCount > 3)
634 mimeType = *(String*) matchedItems.GetAt(3);
637 SysLog(NID_APP, "matched(%d) : (%ls;%ls;%ls)", matchedItems.GetCount(), operation.GetPointer(), url.GetPointer(), mimeType.GetPointer());
638 matchedItems.RemoveAll(true);