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