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.
19 * @brief This is the implementation for the _Aul.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"
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 // borrowed from app-svc/include/pri_key.h
76 #define APP_SVC_K_RES_VAL "__APP_SVC_K_RES_VAL__"
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);
99 _Aul::GetConvertedResult(const int aul_ret, const char* pFunctionName)
101 result r = E_SUCCESS;
107 SysLogException(NID_APP, r, "%s : Invalid argument.", pFunctionName);
112 SysLogException(NID_APP, r, "%s : Internal IPC error.", pFunctionName);
117 SysLogException(NID_APP, r, "%s : General error.", pFunctionName);
121 SysLog(NID_APP, "%s : successed.", pFunctionName);
129 _Aul::SendResult(bundle* b, appsvc_result_val res)
131 // to skip error handling, of appsvc_send_result, use aul_send_service_result() directly.
132 //int ret = appsvc_send_result(b, res);
134 char tmp[32] = {0, };
135 snprintf(tmp, 32, "%d", static_cast<int>(res));
136 appsvc_add_data(b, APP_SVC_K_RES_VAL, tmp);
138 int aul_ret = aul_send_service_result(b);
140 return GetConvertedResult(aul_ret, "SendResult");
145 _Aul::IsRunning(const AppId& appId, const String& exeName)
147 char slpPackageName[MAX_SLP_PACKAGE_ID] = {0, };
148 bool isRunning = false;
150 _PackageManagerImpl* pPackageManagerImpl = _PackageManagerImpl::GetInstance();
151 SysTryReturn(NID_APP, pPackageManagerImpl != null, false, E_INVALID_STATE, "[E_INVALID_STATE] Invalid package instance.");
153 pPackageManagerImpl->GetPackageName(appId, &exeName, slpPackageName, MAX_SLP_PACKAGE_ID);
155 app_manager_is_running(slpPackageName, &isRunning);
157 SysLog(NID_APP, "'%s' %s running now.", slpPackageName, (isRunning == true) ? "is" : "is NOT");
163 _Aul::IsRunning(const String& packageName)
165 bool isRunning = false;
166 std::unique_ptr<char[]> pSlpPackageName(_StringConverter::CopyToCharArrayN(packageName));
168 app_manager_is_running(pSlpPackageName.get(), &isRunning);
170 SysLog(NID_APP, "'%ls' %s running now.", packageName.GetPointer(), (isRunning) ? "is" : "is NOT");
176 _Aul::SetOnAppTerminatedCb(int (* pf_app_dead_handler)(int pid, void* pData), void* pData)
178 aul_listen_app_dead_signal(pf_app_dead_handler, pData);
179 SysLog(NID_APP, "'app_dead_handler is set.");
184 _Aul::TerminateApplicationByPid(int pid)
186 int ret_aul = aul_terminate_pid(pid);
188 return GetConvertedResult(ret_aul, "TerminateApplicationByPid");
192 TerminateApplicationIterFnCb(const aul_app_info* pAppInfo, void* pData)
194 const char* pStr = static_cast<const char*>(pData);
196 if (pStr && strncmp(pStr, pAppInfo->pkg_name, NATIVE_APP_MAX_APPID_LENGTH) == 0)
198 SysLog(NID_APP, "%s(%d) is terminated.", pAppInfo->pkg_name, pAppInfo->pid);
199 int ret_aul = aul_terminate_pid( pAppInfo->pid );
200 SetLastResult(_Aul::GetConvertedResult(ret_aul, "TerminateApplication"));
206 _Aul::TerminateApplication(const AppId& appId)
208 SetLastResult(E_OBJ_NOT_FOUND);
209 std::unique_ptr<char[]> pAppId(_StringConverter::CopyToCharArrayN(appId));
210 aul_app_get_running_app_info(TerminateApplicationIterFnCb, static_cast<void*>(pAppId.get()));
212 SysLog(NID_APP, "%ls terminated.", appId.GetPointer());
213 return GetLastResult();
217 _Aul::SetOomAdj(int pid, int adj)
219 // set oom_adj to -17 for system service
220 result r = E_SUCCESS;
221 char buf[FILENAME_MAX];
224 snprintf(buf, FILENAME_MAX, "/proc/%d/oom_adj", pid);
225 fP = fopen(buf, "w");
226 SysTryReturnResult(NID_APP, fP != NULL, E_SYSTEM, "oom_adj change failed with %s.", strerror(errno));
228 fprintf(fP, "%d", adj);
235 _Aul::SetPowerOffNotiListener( void (*powerOffCb)(void *pData), void *pData)
237 int heyFd = heynoti_init();
238 SysTryReturnResult(NID_APP, heyFd >= 0, E_SYSTEM, "heynoti_init failed.");
240 int ret = heynoti_subscribe(heyFd, "power_off_start", powerOffCb, pData);
241 SysTryReturnResult(NID_APP, ret >= 0, E_SYSTEM, "heynoti_subscribe failed.");
243 ret = heynoti_attach_handler(heyFd);
244 SysTryReturnResult(NID_APP, ret >= 0, E_SYSTEM, "heynoti_attach_handler failed.");
250 _Aul::GetAppType(const String& category)
254 HashMapT<String, int> map;
257 StringTokenizer strTok(category, L';');
260 while (strTok.HasMoreTokens())
262 result r = strTok.GetNextToken(token);
269 SysLog(NID_APP, "%d category items .", map.GetCount());
273 for (int i = 0; i < _NUM_CATEGORY; i++)
276 key = _CATEGORY_LIST[i].category;
277 result r = map.ContainsKey(key, b);
278 if (r == E_SUCCESS && b)
280 ret |= _CATEGORY_LIST[i].type;
287 bool _Aul::IsInstalled(const AppId& appId)
290 packageId = _PackageManagerImpl::GetPackageIdByAppId(appId);
292 return _PackageManagerImpl::GetInstance()->IsPackageInstalled(packageId);
296 _Aul::_DesktopFile::MakePath(const AppId& appId, char* path, int size)
298 SysTryReturnResult(NID_APP, path != null, E_INVALID_ARG, "");
300 std::unique_ptr<char[]> pAppId(_StringConverter::CopyToCharArrayN(appId));
301 SysTryReturnResult(NID_APP, pAppId != null, E_OUT_OF_MEMORY, "Failed to allocate memory for 'pAppId'");
303 snprintf(path, size, _DESKTOP_FILE_PATH_FORMAT, _DESKTOP_FILE_PATH, pAppId.get());
309 _Aul::_DesktopFile::UpdateService(const AppId& appId, const char* value)
311 char path[FILENAME_MAX] = {0, };
312 MakePath(appId, path, FILENAME_MAX);
314 return UpdateField(path, _X_TIZEN_SVC, value);
319 _Aul::_DesktopFile::RemoveService(const AppId& appId, const char* operationOnlyValue)
321 char path[FILENAME_MAX] = {0, };
322 MakePath(appId, path, FILENAME_MAX);
324 return UpdateField(path, _X_TIZEN_SVC, operationOnlyValue, true);
328 // Update value of specified field.
329 // currently only "x-slp-svc" field is supported.
331 #define BUFFER_SIZE 1024
333 _Aul::_DesktopFile::UpdateField(const char* path, const char* fieldName, const char* value, bool isRemove)
335 SysTryReturnResult(NID_APP, path != null, E_INVALID_ARG, "path should not be null.");
336 SysTryReturnResult(NID_APP, fieldName != null, E_INVALID_ARG, "fieldName should not be null.");
337 SysTryReturnResult(NID_APP, value != null, E_INVALID_ARG, "value should not be null.");
339 FILE* fp = fopen(path, "r+");
340 SysTryReturnResult(NID_APP, fp != null, E_SYSTEM, "falied to open '%s' due to %s", path, strerror(errno));
342 char buffer[BUFFER_SIZE] = {0, };
347 result r = E_SUCCESS;
350 ArrayListT<char*> buffers;
353 char* pCurrent = null;
355 while (fgets(buffer, BUFFER_SIZE, fp) != NULL)
357 len = strlen(buffer);
358 SysTryCatch(NID_APP, len < BUFFER_SIZE, , r = E_INVALID_ARG, "strlen returns invalid value. (%d)", len );
362 pCurrent = new (std::nothrow) char[len + 1];
363 SysTryCatch(NID_APP, pCurrent != null, , r = E_OUT_OF_MEMORY, "failed to allocate mem pCurrent");
365 strncpy(pCurrent, buffer, len);
366 buffers.Add(pCurrent);
370 if (strncmp(buffer, fieldName, len) == 0)
372 int fieldNameLen = strlen(fieldName);
373 SysTryCatch(NID_APP, len > fieldNameLen, , E_INVALID_ARG, "[E_INVALID_ARG] fieldName(%s)", fieldName);
375 pCurrent = UpdateServiceValueN(buffer + fieldNameLen, value, isRemove);
376 SysTryCatch(NID_APP, pCurrent != null, , r = GetLastResult(), "[%s] UpdateServiceValue failed", GetErrorMessage(GetLastResult()));
378 buffers.Add(pCurrent);
390 fsetpos(fp, (fpos_t*) &foundpos);
392 remains = buffers.GetCount(); // prevent infinite loop
393 while (buffers.GetCount() > 0 && remains-- > 0)
396 buffers.GetAt(0, pCurrent);
398 SysTryCatch(NID_APP, pCurrent != null, , r = E_INVALID_STATE, "");
401 len = strlen(pCurrent);
406 int ret = truncate(path, pos);
407 SysTryLog(NID_APP, ret == 0, "Truncate failure (%s).", strerror(errno));
411 char svctext[_MAX_TIZEN_SVC_DESC_LEN] = {0, };
412 snprintf(svctext, _MAX_TIZEN_SVC_DESC_LEN, "%s=%s\n", fieldName, value);
421 remains = buffers.GetCount(); // prevent infinite loop
422 while (buffers.GetCount() > 0 && remains-- > 0)
425 buffers.GetAt(0, pCurrent);
427 if (pCurrent != null)
439 // Tizen service string example
440 // 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
443 _Aul::_DesktopFile::UpdateServiceValueN(char* buffer, const char* newValue, bool isRemove)
445 SysTryReturn(NID_APP, buffer != null, null, E_INVALID_ARG, "");
446 SysTryReturn(NID_APP, newValue != null, null, E_INVALID_ARG, "");
448 SysLog(NID_APP, "current(%s), new(%s), isRemove(%s)", buffer, newValue, (isRemove) ? "true" : "false");
453 const String& servicePattern(L"([A-Za-z&=:/\\.\\-]*);?");
458 Utility::RegularExpression regex;
459 result r = regex.Construct(servicePattern);
460 SysTryReturn(NID_APP, !IsFailed(r), null, r, "");
465 String newService(newValue);
467 if (isRemove == false)
469 ParseService(newService, newOperation, newUrl, newMimeType);
473 newOperation = newValue;
476 services.Construct();
478 while (regex.Consume(buf, &services) == true)
480 String* pCurrentService = (String*) services.GetAt(1);
481 services.RemoveAll(false);
487 ParseService(*pCurrentService, operation, url, mimeType);
489 if (operation == newOperation)
491 if (isRemove == true)
493 SysLog(NID_APP, "opreration '%ls' will be removed", operation.GetPointer());
497 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.");
498 // replace operation.
499 if (found == false) // ( if duplicated operation is already exist, It will be keeped.
502 AppendServiceValueToString(resultString, newService);
503 SysLog(NID_APP, "opreration '%ls;%ls;%ls' will be updated to ;%ls;%ls", operation.GetPointer(), url.GetPointer(), mimeType.GetPointer(), newUrl.GetPointer(), mimeType.GetPointer());
510 // add not specified service.
511 AppendServiceValueToString(resultString, *pCurrentService);
514 delete pCurrentService;
517 if (found == false && isRemove == false)
519 AppendServiceValueToString(resultString, newService);
520 SysLog(NID_APP, "opreration '%ls;%ls;%ls' will be added", newOperation.GetPointer(), newUrl.GetPointer(), newMimeType.GetPointer());
523 SysLog(NID_APP, "updated string is '%ls'", resultString.GetPointer());
524 return _StringConverter::CopyToCharArrayN(resultString);
529 _Aul::_DesktopFile::AppendServiceValueToString(String& serviceString, const String& newVaue)
531 if (serviceString.GetLength() > 0)
533 serviceString += ";";
536 serviceString += newVaue;
541 _Aul::_DesktopFile::ParseService(const String& service, String& operation, String& url, String& mimeType)
543 SysLog(NID_APP, "service(%ls)", service.GetPointer());
545 const String& serviceDetailPattern(L"([A-Za-z&=/\\.\\-]*):(.*://[A-Za-z&=/\\.\\-]*|[A-Za-z&=/\\.\\-]*):([A-Za-z&=/\\.\\-]*)");
547 Utility::RegularExpression regexDetail;
548 result r = regexDetail.Construct(serviceDetailPattern);
549 SysTryReturn(NID_APP, !IsFailed(r), null, r, "[%s] RegularExpression::Construct(L\"%ls\") failed.", GetErrorMessage(r), serviceDetailPattern.GetPointer());
551 ArrayList matchedItems;
552 matchedItems.Construct();
553 regexDetail.Match(service, true, &matchedItems);
555 int matchedCount = matchedItems.GetCount();
556 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());
558 if (matchedCount > 1)
560 operation = *(String*) matchedItems.GetAt(1);
563 if (matchedCount > 2)
565 url = *(String*) matchedItems.GetAt(2);
568 if (matchedCount > 3)
570 mimeType = *(String*) matchedItems.GetAt(3);
573 SysLog(NID_APP, "matched(%d) : (%ls;%ls;%ls)", matchedItems.GetCount(), operation.GetPointer(), url.GetPointer(), mimeType.GetPointer());
574 matchedItems.RemoveAll(true);