Fix the boiler plate codes
[platform/framework/native/appfw.git] / src / app / FApp_Aul.cpp
1 //
2 // Copyright (c) 2012 Samsung Electronics Co., Ltd.
3 //
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
7 //
8 //     http://www.apache.org/licenses/LICENSE-2.0
9 //
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.
15 //
16
17 /**
18  * @file         FApp_Aul.cpp
19  * @brief       This is the implementation for the _Aul.cpp class.
20  */
21 #include <cstdio>
22 #include <cstdlib>
23 #include <new>
24 #include <unistd.h>
25 #include <sys/prctl.h>
26 #include <signal.h>
27 #include <unique_ptr.h>
28
29 #include <aul.h>
30 #include <bundle.h>
31 #include <appsvc/appsvc.h>
32 #include <app_manager.h>
33 #include <heynoti.h>
34
35 #include <FBaseObject.h>
36 #include <FBaseString.h>
37 #include <FBaseUtil.h>
38 #include <FBaseSysLog.h>
39 #include <FBaseColHashMapT.h>
40 #include <FAppPkgPackageInfo.h>
41
42 #include <FBaseRt_Process.h>
43 #include <FBase_StringConverter.h>
44 #include "FAppPkg_PackageManagerImpl.h"
45 #include "FApp_Types.h"
46 #include "FApp_Aul.h"
47 #include "FApp_TemplateUtil.h"
48
49 #ifdef __cplusplus
50 extern "C" {
51 #endif
52 extern int aul_listen_app_dead_signal(int (* func)(int, void*), void* data);
53 #ifdef __cplusplus
54 }
55 #endif
56
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;
62
63 namespace
64 {
65
66 const char _DESKTOP_FILE_PATH[] = "/opt/share/applications";
67 const char _DESKTOP_FILE_PATH_FORMAT[] = "%s/%s.desktop";
68
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;
71
72 const int _MAX_CATEGORY = 12;
73 const int _MAX_PACKAGE_ID_LENGTH = 10;
74
75 // borrowed from app-svc/include/pri_key.h
76 #define APP_SVC_K_RES_VAL       "__APP_SVC_K_RES_VAL__"
77
78 }
79
80 namespace Tizen { namespace App
81 {
82
83 struct _CategoryList
84 {
85         const char category[_MAX_CATEGORY];
86         _AppType type;
87 };
88
89 static const _CategoryList _CATEGORY_LIST[] =
90 {
91         {"home-screen", _APP_TYPE_HOME_APP},
92         {"lock-screen", _APP_TYPE_LOCK_APP},
93         {"ime", _APP_TYPE_IME_APP},
94 };
95
96 static const int _NUM_CATEGORY = sizeof(_CATEGORY_LIST) / sizeof(_CategoryList);
97
98 result
99 _Aul::GetConvertedResult(const int aul_ret, const char* pFunctionName)
100 {
101         result r = E_SUCCESS;
102
103         switch (aul_ret)
104         {
105         case AUL_R_EINVAL:
106                 r = E_INVALID_ARG;
107                 SysLogException(NID_APP, r, "%s : Invalid argument.", pFunctionName);
108                 break;
109
110         case AUL_R_ECOMM:
111                 r = E_SYSTEM;
112                 SysLogException(NID_APP, r, "%s : Internal IPC error.", pFunctionName);
113                 break;
114
115         case AUL_R_ERROR:
116                 r = E_SYSTEM;
117                 SysLogException(NID_APP, r, "%s : General error.", pFunctionName);
118                 break;
119
120         default:
121                 SysLog(NID_APP, "%s : successed.", pFunctionName);
122                 break;
123         }
124
125         return r;
126 }
127
128 result
129 _Aul::SendResult(bundle* b, appsvc_result_val res)
130 {
131         // to skip error handling, of appsvc_send_result, use aul_send_service_result() directly.
132         //int ret = appsvc_send_result(b, res);
133
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);
137
138         int aul_ret = aul_send_service_result(b);
139
140         return GetConvertedResult(aul_ret, "SendResult");
141 }
142
143
144 bool
145 _Aul::IsRunning(const AppId& appId, const String& exeName)
146 {
147         char slpPackageName[MAX_SLP_PACKAGE_ID] = {0, };
148         bool isRunning = false;
149
150         _PackageManagerImpl* pPackageManagerImpl = _PackageManagerImpl::GetInstance();
151         SysTryReturn(NID_APP, pPackageManagerImpl != null, false, E_INVALID_STATE, "[E_INVALID_STATE] Invalid package instance.");
152
153         pPackageManagerImpl->GetPackageName(appId, &exeName, slpPackageName, MAX_SLP_PACKAGE_ID);
154
155         app_manager_is_running(slpPackageName, &isRunning);
156
157         SysLog(NID_APP, "'%s' %s running now.", slpPackageName, (isRunning == true) ? "is" : "is NOT");
158
159         return isRunning;
160 }
161
162 bool
163 _Aul::IsRunning(const String& packageName)
164 {
165         bool isRunning = false;
166         std::unique_ptr<char[]> pSlpPackageName(_StringConverter::CopyToCharArrayN(packageName));
167
168         app_manager_is_running(pSlpPackageName.get(), &isRunning);
169
170         SysLog(NID_APP, "'%ls' %s running now.", packageName.GetPointer(), (isRunning) ? "is" : "is NOT");
171         return isRunning;
172 }
173
174
175 void
176 _Aul::SetOnAppTerminatedCb(int (* pf_app_dead_handler)(int pid, void* pData), void* pData)
177 {
178         aul_listen_app_dead_signal(pf_app_dead_handler, pData);
179         SysLog(NID_APP, "'app_dead_handler is set.");
180 }
181
182
183 result
184 _Aul::TerminateApplicationByPid(int pid)
185 {
186         int ret_aul = aul_terminate_pid(pid);
187
188         return GetConvertedResult(ret_aul, "TerminateApplicationByPid");
189 }
190
191 static int
192 TerminateApplicationIterFnCb(const aul_app_info* pAppInfo, void* pData)
193 {
194         const char* pStr = static_cast<const char*>(pData);
195
196         if (pStr && strncmp(pStr, pAppInfo->pkg_name, NATIVE_APP_MAX_APPID_LENGTH) == 0)
197         {
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"));
201         }
202         return 0;
203 }
204
205 result
206 _Aul::TerminateApplication(const AppId& appId)
207 {
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()));
211
212         SysLog(NID_APP, "%ls terminated.", appId.GetPointer());
213         return GetLastResult();
214 }
215
216 result
217 _Aul::SetOomAdj(int pid, int adj)
218 {
219         // set oom_adj to -17 for system service
220         result r = E_SUCCESS;
221         char buf[FILENAME_MAX];
222         FILE *fP = NULL;
223
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));
227
228         fprintf(fP, "%d", adj);
229         fclose(fP);
230
231         return r;
232 }
233
234 result
235 _Aul::SetPowerOffNotiListener( void (*powerOffCb)(void *pData), void *pData)
236 {
237         int heyFd = heynoti_init();
238         SysTryReturnResult(NID_APP, heyFd >= 0, E_SYSTEM, "heynoti_init failed.");
239
240         int ret = heynoti_subscribe(heyFd, "power_off_start", powerOffCb, pData);
241         SysTryReturnResult(NID_APP, ret >= 0, E_SYSTEM, "heynoti_subscribe failed.");
242
243         ret = heynoti_attach_handler(heyFd);
244         SysTryReturnResult(NID_APP, ret >= 0, E_SYSTEM, "heynoti_attach_handler failed.");
245
246         return E_SUCCESS;
247 }
248
249 int
250 _Aul::GetAppType(const String& category)
251 {
252         int ret = 0;
253
254         HashMapT<String, int> map;
255         map.Construct();
256
257         StringTokenizer strTok(category, L';');
258
259         String token;
260         while (strTok.HasMoreTokens())
261         {
262                 result r = strTok.GetNextToken(token);
263                 if (r == E_SUCCESS)
264                 {
265                         map.Add(token, 0);
266                 }
267         }
268
269         SysLog(NID_APP, "%d category items .", map.GetCount());
270
271         String key;
272
273         for (int i = 0; i < _NUM_CATEGORY; i++)
274         {
275                 bool b = false;
276                 key = _CATEGORY_LIST[i].category;
277                 result r = map.ContainsKey(key, b);
278                 if (r == E_SUCCESS && b)
279                 {
280                         ret |= _CATEGORY_LIST[i].type;
281                 }
282         }
283
284         return ret;
285 }
286
287 bool _Aul::IsInstalled(const AppId& appId)
288 {
289         String packageId;
290         packageId = _PackageManagerImpl::GetPackageIdByAppId(appId);
291
292         return _PackageManagerImpl::GetInstance()->IsPackageInstalled(packageId);
293 }
294
295 result
296 _Aul::_DesktopFile::MakePath(const AppId& appId, char* path, int size)
297 {
298         SysTryReturnResult(NID_APP, path != null, E_INVALID_ARG, "");
299
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'");
302
303         snprintf(path, size, _DESKTOP_FILE_PATH_FORMAT, _DESKTOP_FILE_PATH, pAppId.get());
304
305         return E_SUCCESS;
306 }
307
308 result
309 _Aul::_DesktopFile::UpdateService(const AppId& appId, const char* value)
310 {
311         char path[FILENAME_MAX] = {0, };
312         MakePath(appId, path, FILENAME_MAX);
313
314         return UpdateField(path, _X_TIZEN_SVC, value);
315 }
316
317
318 result
319 _Aul::_DesktopFile::RemoveService(const AppId& appId, const char* operationOnlyValue)
320 {
321         char path[FILENAME_MAX] = {0, };
322         MakePath(appId, path, FILENAME_MAX);
323
324         return UpdateField(path, _X_TIZEN_SVC, operationOnlyValue, true);
325 }
326
327 //
328 // Update value of specified field.
329 // currently only "x-slp-svc" field is supported.
330 //
331 #define BUFFER_SIZE 1024
332 result
333 _Aul::_DesktopFile::UpdateField(const char* path, const char* fieldName, const char* value, bool isRemove)
334 {
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.");
338
339         FILE* fp = fopen(path, "r+");
340         SysTryReturnResult(NID_APP, fp != null, E_SYSTEM, "falied to open '%s' due to %s", path, strerror(errno));
341
342         char buffer[BUFFER_SIZE] = {0, };
343         bool found = false;
344         int len = 0;
345         int pos = 0;
346         int foundpos = 0;
347         result r = E_SUCCESS;
348         int remains = 0;
349
350         ArrayListT<char*> buffers;
351         buffers.Construct();
352
353         char* pCurrent = null;
354
355         while (fgets(buffer, BUFFER_SIZE, fp) != NULL)
356         {
357                 len = strlen(buffer);
358                 SysTryCatch(NID_APP, len < BUFFER_SIZE, , r = E_INVALID_ARG, "strlen returns invalid value. (%d)", len );
359
360                 if (found)
361                 {
362                         pCurrent = new (std::nothrow) char[len + 1];
363                         SysTryCatch(NID_APP, pCurrent != null, , r = E_OUT_OF_MEMORY, "failed to allocate mem pCurrent");
364
365                         strncpy(pCurrent, buffer, len);
366                         buffers.Add(pCurrent);
367                 }
368                 else
369                 {
370                         if (strncmp(buffer, fieldName, len) == 0)
371                         {
372                                 int fieldNameLen = strlen(fieldName);
373                                 SysTryCatch(NID_APP, len > fieldNameLen, , E_INVALID_ARG, "[E_INVALID_ARG] fieldName(%s)", fieldName);
374
375                                 pCurrent = UpdateServiceValueN(buffer + fieldNameLen, value, isRemove);
376                                 SysTryCatch(NID_APP, pCurrent != null, , r = GetLastResult(), "[%s] UpdateServiceValue failed", GetErrorMessage(GetLastResult()));
377
378                                 buffers.Add(pCurrent);
379
380                                 foundpos = pos;
381                                 found = true;
382                         }
383                 }
384
385                 pos += len;
386         }
387
388         if (found)
389         {
390                 fsetpos(fp, (fpos_t*) &foundpos);
391
392                 remains = buffers.GetCount();   // prevent infinite loop
393                 while (buffers.GetCount() > 0 && remains-- > 0)
394                 {
395                         pCurrent = null;
396                         buffers.GetAt(0, pCurrent);
397                         buffers.RemoveAt(0);
398                         SysTryCatch(NID_APP, pCurrent != null, , r = E_INVALID_STATE, "");
399
400                         fputs(pCurrent, fp);
401                         len = strlen(pCurrent);
402                         pos += len;
403                         delete[] pCurrent;
404                 }
405
406                 int ret = truncate(path, pos);
407                 SysTryLog(NID_APP, ret == 0, "Truncate failure (%s).", strerror(errno));
408         }
409         else
410         {
411                 char svctext[_MAX_TIZEN_SVC_DESC_LEN] = {0, };
412                 snprintf(svctext, _MAX_TIZEN_SVC_DESC_LEN, "%s=%s\n", fieldName, value);
413                 fputs(svctext, fp);
414         }
415         fclose(fp);
416
417         return E_SUCCESS;
418
419 CATCH:
420
421         remains = buffers.GetCount();   // prevent infinite loop
422         while (buffers.GetCount() > 0 && remains-- > 0)
423         {
424                 pCurrent = null;
425                 buffers.GetAt(0, pCurrent);
426                 buffers.RemoveAt(0);
427                 if (pCurrent != null)
428                 {
429                         delete[] pCurrent;
430                 }
431         }
432
433         fclose(fp);
434
435         return r;
436 }
437
438 //
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
441 //
442 char*
443 _Aul::_DesktopFile::UpdateServiceValueN(char* buffer, const char* newValue, bool isRemove)
444 {
445         SysTryReturn(NID_APP, buffer != null, null, E_INVALID_ARG, "");
446         SysTryReturn(NID_APP, newValue != null, null, E_INVALID_ARG, "");
447
448         SysLog(NID_APP, "current(%s), new(%s), isRemove(%s)", buffer, newValue, (isRemove) ? "true" : "false");
449
450         String buf(buffer);
451         bool found = false;
452
453         const String& servicePattern(L"([A-Za-z&=:/\\.\\-]*);?");
454
455         ArrayList services;
456         String resultString;
457
458         Utility::RegularExpression regex;
459         result r = regex.Construct(servicePattern);
460         SysTryReturn(NID_APP, !IsFailed(r), null, r, "");
461
462         String newOperation;
463         String newUrl;
464         String newMimeType;
465         String newService(newValue);
466
467         if (isRemove == false)
468         {
469                 ParseService(newService, newOperation, newUrl, newMimeType);
470         }
471         else
472         {
473                 newOperation = newValue;
474         }
475
476         services.Construct();
477
478         while (regex.Consume(buf, &services) == true)
479         {
480                 String* pCurrentService = (String*) services.GetAt(1);
481                 services.RemoveAll(false);
482
483                 String operation;
484                 String url;
485                 String mimeType;
486
487                 ParseService(*pCurrentService, operation, url, mimeType);
488
489                 if (operation == newOperation)
490                 {
491                         if (isRemove == true)
492                         {
493                                 SysLog(NID_APP, "opreration '%ls' will be removed", operation.GetPointer());
494                         }
495                         else
496                         {
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.
500                                 {
501                                         // update value
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());
504                                 }
505                         }
506                         found = true;
507                 }
508                 else
509                 {
510                         // add not specified service.
511                         AppendServiceValueToString(resultString, *pCurrentService);
512                 }
513
514                 delete pCurrentService;
515         }
516
517         if (found == false && isRemove == false)
518         {
519                 AppendServiceValueToString(resultString, newService);
520                 SysLog(NID_APP, "opreration '%ls;%ls;%ls' will be added", newOperation.GetPointer(), newUrl.GetPointer(), newMimeType.GetPointer());
521         }
522
523         SysLog(NID_APP, "updated string is '%ls'", resultString.GetPointer());
524         return _StringConverter::CopyToCharArrayN(resultString);
525 }
526
527
528 void
529 _Aul::_DesktopFile::AppendServiceValueToString(String& serviceString, const String& newVaue)
530 {
531         if (serviceString.GetLength() > 0)
532         {
533                 serviceString += ";";
534         }
535
536         serviceString += newVaue;
537 }
538
539
540 result
541 _Aul::_DesktopFile::ParseService(const String& service, String& operation, String& url, String& mimeType)
542 {
543         SysLog(NID_APP, "service(%ls)", service.GetPointer());
544
545         const String& serviceDetailPattern(L"([A-Za-z&=/\\.\\-]*):(.*://[A-Za-z&=/\\.\\-]*|[A-Za-z&=/\\.\\-]*):([A-Za-z&=/\\.\\-]*)");
546
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());
550
551         ArrayList matchedItems;
552         matchedItems.Construct();
553         regexDetail.Match(service, true, &matchedItems);
554
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());
557
558         if (matchedCount > 1)
559         {
560                 operation = *(String*) matchedItems.GetAt(1);
561         }
562
563         if (matchedCount > 2)
564         {
565                 url = *(String*) matchedItems.GetAt(2);
566         }
567
568         if (matchedCount > 3)
569         {
570                 mimeType = *(String*) matchedItems.GetAt(3);
571         }
572
573         SysLog(NID_APP, "matched(%d) : (%ls;%ls;%ls)", matchedItems.GetCount(), operation.GetPointer(), url.GetPointer(), mimeType.GetPointer());
574         matchedItems.RemoveAll(true);
575
576         return E_SUCCESS;
577 }
578
579 } } // Tizen::App