Merge "Revert "Change MoveTo API()" (for RC29)" into tizen_2.1
[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         const int aul_ret = aul_send_service_result(b);
139
140         result r = GetConvertedResult(aul_ret, "SendResult");
141         if (r == E_INVALID_ARG)
142         {
143                 SysLog(NID_APP, "Converting internal exception to E_MAX_EXCEEDED.");
144                 r = E_MAX_EXCEEDED;
145         }
146         return r;
147 }
148
149
150 bool
151 _Aul::IsRunning(const AppId& appId, const String& exeName)
152 {
153         char slpPackageName[MAX_SLP_PACKAGE_ID] = {0, };
154         bool isRunning = false;
155
156         _PackageManagerImpl* pPackageManagerImpl = _PackageManagerImpl::GetInstance();
157         SysTryReturn(NID_APP, pPackageManagerImpl != null, false, E_INVALID_STATE, "[E_INVALID_STATE] Invalid package instance.");
158
159         pPackageManagerImpl->GetPackageName(appId, &exeName, slpPackageName, MAX_SLP_PACKAGE_ID);
160
161         app_manager_is_running(slpPackageName, &isRunning);
162
163         SysLog(NID_APP, "'%s' %s running now.", slpPackageName, (isRunning == true) ? "is" : "is NOT");
164
165         return isRunning;
166 }
167
168 bool
169 _Aul::IsRunning(const String& packageName)
170 {
171         bool isRunning = false;
172         std::unique_ptr<char[]> pSlpPackageName(_StringConverter::CopyToCharArrayN(packageName));
173
174         app_manager_is_running(pSlpPackageName.get(), &isRunning);
175
176         SysLog(NID_APP, "'%ls' %s running now.", packageName.GetPointer(), (isRunning) ? "is" : "is NOT");
177         return isRunning;
178 }
179
180
181 void
182 _Aul::SetOnAppTerminatedCb(int (* pf_app_dead_handler)(int pid, void* pData), void* pData)
183 {
184         aul_listen_app_dead_signal(pf_app_dead_handler, pData);
185         SysLog(NID_APP, "'app_dead_handler is set.");
186 }
187
188
189 result
190 _Aul::TerminateApplicationByPid(int pid)
191 {
192         int ret_aul = aul_terminate_pid(pid);
193
194         return GetConvertedResult(ret_aul, "TerminateApplicationByPid");
195 }
196
197 static int
198 TerminateApplicationIterFnCb(const aul_app_info* pAppInfo, void* pData)
199 {
200         const char* pStr = static_cast<const char*>(pData);
201
202         if (pStr && strncmp(pStr, pAppInfo->pkg_name, NATIVE_APP_MAX_APPID_LENGTH) == 0)
203         {
204                 SysLog(NID_APP, "%s(%d) is terminated.", pAppInfo->pkg_name, pAppInfo->pid);
205                 int ret_aul = aul_terminate_pid( pAppInfo->pid );
206                 SetLastResult(_Aul::GetConvertedResult(ret_aul, "TerminateApplication"));
207         }
208         return 0;
209 }
210
211 result
212 _Aul::TerminateApplication(const AppId& appId)
213 {
214         SetLastResult(E_OBJ_NOT_FOUND);
215         std::unique_ptr<char[]> pAppId(_StringConverter::CopyToCharArrayN(appId));
216         aul_app_get_running_app_info(TerminateApplicationIterFnCb, static_cast<void*>(pAppId.get()));
217
218         SysLog(NID_APP, "%ls terminated.", appId.GetPointer());
219         return GetLastResult();
220 }
221
222 result
223 _Aul::SetOomAdj(int pid, int adj)
224 {
225         // set oom_adj to -17 for system service
226         result r = E_SUCCESS;
227         char buf[FILENAME_MAX];
228         FILE *fP = NULL;
229
230         snprintf(buf, FILENAME_MAX, "/proc/%d/oom_adj", pid);
231         fP = fopen(buf, "w");
232         SysTryReturnResult(NID_APP, fP != NULL, E_SYSTEM, "oom_adj change failed with %s.", strerror(errno));
233
234         fprintf(fP, "%d", adj);
235         fclose(fP);
236
237         return r;
238 }
239
240 result
241 _Aul::SetPowerOffNotiListener( void (*powerOffCb)(void *pData), void *pData)
242 {
243         int heyFd = heynoti_init();
244         SysTryReturnResult(NID_APP, heyFd >= 0, E_SYSTEM, "heynoti_init failed.");
245
246         int ret = heynoti_subscribe(heyFd, "power_off_start", powerOffCb, pData);
247         SysTryReturnResult(NID_APP, ret >= 0, E_SYSTEM, "heynoti_subscribe failed.");
248
249         ret = heynoti_attach_handler(heyFd);
250         SysTryReturnResult(NID_APP, ret >= 0, E_SYSTEM, "heynoti_attach_handler failed.");
251
252         return E_SUCCESS;
253 }
254
255 int
256 _Aul::GetAppType(const String& category)
257 {
258         int ret = 0;
259
260         HashMapT<String, int> map;
261         map.Construct();
262
263         StringTokenizer strTok(category, L';');
264
265         String token;
266         while (strTok.HasMoreTokens())
267         {
268                 result r = strTok.GetNextToken(token);
269                 if (r == E_SUCCESS)
270                 {
271                         map.Add(token, 0);
272                 }
273         }
274
275         SysLog(NID_APP, "%d category items .", map.GetCount());
276
277         String key;
278
279         for (int i = 0; i < _NUM_CATEGORY; i++)
280         {
281                 bool b = false;
282                 key = _CATEGORY_LIST[i].category;
283                 result r = map.ContainsKey(key, b);
284                 if (r == E_SUCCESS && b)
285                 {
286                         ret |= _CATEGORY_LIST[i].type;
287                 }
288         }
289
290         return ret;
291 }
292
293 bool _Aul::IsInstalled(const AppId& appId)
294 {
295         String packageId;
296         packageId = _PackageManagerImpl::GetPackageIdByAppId(appId);
297
298         return _PackageManagerImpl::GetInstance()->IsPackageInstalled(packageId);
299 }
300
301 result
302 _Aul::_DesktopFile::MakePath(const AppId& appId, char* path, int size)
303 {
304         SysTryReturnResult(NID_APP, path != null, E_INVALID_ARG, "");
305
306         std::unique_ptr<char[]> pAppId(_StringConverter::CopyToCharArrayN(appId));
307         SysTryReturnResult(NID_APP, pAppId != null, E_OUT_OF_MEMORY, "Failed to allocate memory for 'pAppId'");
308
309         snprintf(path, size, _DESKTOP_FILE_PATH_FORMAT, _DESKTOP_FILE_PATH, pAppId.get());
310
311         return E_SUCCESS;
312 }
313
314 result
315 _Aul::_DesktopFile::UpdateService(const AppId& appId, const char* value)
316 {
317         char path[FILENAME_MAX] = {0, };
318         MakePath(appId, path, FILENAME_MAX);
319
320         return UpdateField(path, _X_TIZEN_SVC, value);
321 }
322
323
324 result
325 _Aul::_DesktopFile::RemoveService(const AppId& appId, const char* operationOnlyValue)
326 {
327         char path[FILENAME_MAX] = {0, };
328         MakePath(appId, path, FILENAME_MAX);
329
330         return UpdateField(path, _X_TIZEN_SVC, operationOnlyValue, true);
331 }
332
333 //
334 // Update value of specified field.
335 // currently only "x-slp-svc" field is supported.
336 //
337 #define BUFFER_SIZE 1024
338 result
339 _Aul::_DesktopFile::UpdateField(const char* path, const char* fieldName, const char* value, bool isRemove)
340 {
341         SysTryReturnResult(NID_APP, path != null, E_INVALID_ARG, "path should not be null.");
342         SysTryReturnResult(NID_APP, fieldName != null, E_INVALID_ARG, "fieldName should not be null.");
343         SysTryReturnResult(NID_APP, value != null, E_INVALID_ARG, "value should not be null.");
344
345         FILE* fp = fopen(path, "r+");
346         SysTryReturnResult(NID_APP, fp != null, E_SYSTEM, "falied to open '%s' due to %s", path, strerror(errno));
347
348         char buffer[BUFFER_SIZE] = {0, };
349         bool found = false;
350         int len = 0;
351         int pos = 0;
352         int foundpos = 0;
353         result r = E_SUCCESS;
354         int remains = 0;
355
356         ArrayListT<char*> buffers;
357         buffers.Construct();
358
359         char* pCurrent = null;
360
361         while (fgets(buffer, BUFFER_SIZE, fp) != NULL)
362         {
363                 len = strlen(buffer);
364                 SysTryCatch(NID_APP, len < BUFFER_SIZE, , r = E_INVALID_ARG, "strlen returns invalid value. (%d)", len );
365
366                 if (found)
367                 {
368                         pCurrent = new (std::nothrow) char[len + 1];
369                         SysTryCatch(NID_APP, pCurrent != null, , r = E_OUT_OF_MEMORY, "failed to allocate mem pCurrent");
370
371                         strncpy(pCurrent, buffer, len);
372                         buffers.Add(pCurrent);
373                 }
374                 else
375                 {
376                         if (strncmp(buffer, fieldName, len) == 0)
377                         {
378                                 int fieldNameLen = strlen(fieldName);
379                                 SysTryCatch(NID_APP, len > fieldNameLen, , E_INVALID_ARG, "[E_INVALID_ARG] fieldName(%s)", fieldName);
380
381                                 pCurrent = UpdateServiceValueN(buffer + fieldNameLen, value, isRemove);
382                                 SysTryCatch(NID_APP, pCurrent != null, , r = GetLastResult(), "[%s] UpdateServiceValue failed", GetErrorMessage(GetLastResult()));
383
384                                 buffers.Add(pCurrent);
385
386                                 foundpos = pos;
387                                 found = true;
388                         }
389                 }
390
391                 pos += len;
392         }
393
394         if (found)
395         {
396                 fsetpos(fp, (fpos_t*) &foundpos);
397
398                 remains = buffers.GetCount();   // prevent infinite loop
399                 while (buffers.GetCount() > 0 && remains-- > 0)
400                 {
401                         pCurrent = null;
402                         buffers.GetAt(0, pCurrent);
403                         buffers.RemoveAt(0);
404                         SysTryCatch(NID_APP, pCurrent != null, , r = E_INVALID_STATE, "");
405
406                         fputs(pCurrent, fp);
407                         len = strlen(pCurrent);
408                         pos += len;
409                         delete[] pCurrent;
410                 }
411
412                 int ret = truncate(path, pos);
413                 SysTryLog(NID_APP, ret == 0, "Truncate failure (%s).", strerror(errno));
414         }
415         else
416         {
417                 char svctext[_MAX_TIZEN_SVC_DESC_LEN] = {0, };
418                 snprintf(svctext, _MAX_TIZEN_SVC_DESC_LEN, "%s=%s\n", fieldName, value);
419                 fputs(svctext, fp);
420         }
421         fclose(fp);
422
423         return E_SUCCESS;
424
425 CATCH:
426
427         remains = buffers.GetCount();   // prevent infinite loop
428         while (buffers.GetCount() > 0 && remains-- > 0)
429         {
430                 pCurrent = null;
431                 buffers.GetAt(0, pCurrent);
432                 buffers.RemoveAt(0);
433                 if (pCurrent != null)
434                 {
435                         delete[] pCurrent;
436                 }
437         }
438
439         fclose(fp);
440
441         return r;
442 }
443
444 //
445 //      Tizen service string example
446 //      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
447 //
448 char*
449 _Aul::_DesktopFile::UpdateServiceValueN(char* buffer, const char* newValue, bool isRemove)
450 {
451         SysTryReturn(NID_APP, buffer != null, null, E_INVALID_ARG, "");
452         SysTryReturn(NID_APP, newValue != null, null, E_INVALID_ARG, "");
453
454         SysLog(NID_APP, "current(%s), new(%s), isRemove(%s)", buffer, newValue, (isRemove) ? "true" : "false");
455
456         String buf(buffer);
457         bool found = false;
458
459         const String& servicePattern(L"([A-Za-z&=:/\\.\\-]*);?");
460
461         ArrayList services;
462         String resultString;
463
464         Utility::RegularExpression regex;
465         result r = regex.Construct(servicePattern);
466         SysTryReturn(NID_APP, !IsFailed(r), null, r, "");
467
468         String newOperation;
469         String newUrl;
470         String newMimeType;
471         String newService(newValue);
472
473         if (isRemove == false)
474         {
475                 ParseService(newService, newOperation, newUrl, newMimeType);
476         }
477         else
478         {
479                 newOperation = newValue;
480         }
481
482         services.Construct();
483
484         while (regex.Consume(buf, &services) == true)
485         {
486                 String* pCurrentService = (String*) services.GetAt(1);
487                 services.RemoveAll(false);
488
489                 String operation;
490                 String url;
491                 String mimeType;
492
493                 ParseService(*pCurrentService, operation, url, mimeType);
494
495                 if (operation == newOperation)
496                 {
497                         if (isRemove == true)
498                         {
499                                 SysLog(NID_APP, "opreration '%ls' will be removed", operation.GetPointer());
500                         }
501                         else
502                         {
503                                 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.");
504                                 // replace operation.
505                                 if (found == false) // ( if duplicated operation is already exist, It will be keeped.
506                                 {
507                                         // update value
508                                         AppendServiceValueToString(resultString, newService);
509                                         SysLog(NID_APP, "opreration '%ls;%ls;%ls' will be updated to ;%ls;%ls", operation.GetPointer(), url.GetPointer(), mimeType.GetPointer(), newUrl.GetPointer(), mimeType.GetPointer());
510                                 }
511                         }
512                         found = true;
513                 }
514                 else
515                 {
516                         // add not specified service.
517                         AppendServiceValueToString(resultString, *pCurrentService);
518                 }
519
520                 delete pCurrentService;
521         }
522
523         if (found == false && isRemove == false)
524         {
525                 AppendServiceValueToString(resultString, newService);
526                 SysLog(NID_APP, "opreration '%ls;%ls;%ls' will be added", newOperation.GetPointer(), newUrl.GetPointer(), newMimeType.GetPointer());
527         }
528
529         SysLog(NID_APP, "updated string is '%ls'", resultString.GetPointer());
530         return _StringConverter::CopyToCharArrayN(resultString);
531 }
532
533
534 void
535 _Aul::_DesktopFile::AppendServiceValueToString(String& serviceString, const String& newVaue)
536 {
537         if (serviceString.GetLength() > 0)
538         {
539                 serviceString += ";";
540         }
541
542         serviceString += newVaue;
543 }
544
545
546 result
547 _Aul::_DesktopFile::ParseService(const String& service, String& operation, String& url, String& mimeType)
548 {
549         SysLog(NID_APP, "service(%ls)", service.GetPointer());
550
551         const String& serviceDetailPattern(L"([A-Za-z&=/\\.\\-]*):(.*://[A-Za-z&=/\\.\\-]*|[A-Za-z&=/\\.\\-]*):([A-Za-z&=/\\.\\-]*)");
552
553         Utility::RegularExpression regexDetail;
554         result r = regexDetail.Construct(serviceDetailPattern);
555         SysTryReturn(NID_APP, !IsFailed(r), null, r, "[%s] RegularExpression::Construct(L\"%ls\") failed.", GetErrorMessage(r), serviceDetailPattern.GetPointer());
556
557         ArrayList matchedItems;
558         matchedItems.Construct();
559         regexDetail.Match(service, true, &matchedItems);
560
561         int matchedCount = matchedItems.GetCount();
562         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());
563
564         if (matchedCount > 1)
565         {
566                 operation = *(String*) matchedItems.GetAt(1);
567         }
568
569         if (matchedCount > 2)
570         {
571                 url = *(String*) matchedItems.GetAt(2);
572         }
573
574         if (matchedCount > 3)
575         {
576                 mimeType = *(String*) matchedItems.GetAt(3);
577         }
578
579         SysLog(NID_APP, "matched(%d) : (%ls;%ls;%ls)", matchedItems.GetCount(), operation.GetPointer(), url.GetPointer(), mimeType.GetPointer());
580         matchedItems.RemoveAll(true);
581
582         return E_SUCCESS;
583 }
584
585 } } // Tizen::App