Support path beginning without / for OSP compatible application
[platform/framework/native/appfw.git] / src / io / FIo_FileImpl.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        FIo_FileImpl.cpp
20  * @brief       This is the implementation file for %_FileImpl class.
21  */
22
23 #include <stdlib.h>
24 #include <unistd.h>
25 #include <string.h>
26 #include <sys/stat.h>
27 #include <sys/types.h>
28 #include <sys/mount.h>
29 #include <limits.h>
30 #include <errno.h>
31 #include <new>
32 #include <unique_ptr.h>
33 #include <fcntl.h>
34
35 #include <FBaseSysLog.h>
36 #include <FAppPkgPackageInfo.h>
37 #include <FIoDirectory.h>
38 #include <FIoFile.h>
39 #include <FAppApp.h>
40 #include <FSysEnvironment.h>
41
42 #include <FBase_StringConverter.h>
43 #include <FApp_AppInfo.h>
44 #include <FAppPkg_PackageInfoImpl.h>
45 #include <FSys_EnvironmentImpl.h>
46 #include <FBase_NativeError.h>
47
48 #include "FIo_FileImpl.h"
49 #include "FIo_NormalFile.h"
50 #include "FIo_DirectoryImpl.h"
51 #include "FIo_SecureFile.h"
52 #include "FIo_SecureIoUtil.h"
53 #include "FIo_IFileCore.h"
54 #include "FIo_FileUtil.h"
55 #include "FIo_FileLockImpl.h"
56
57 using namespace std;
58 using namespace Tizen::Base;
59 using namespace Tizen::App;
60 using namespace Tizen::System;
61
62 namespace Tizen { namespace Io
63 {
64
65 static const int _MAX_PATH_LENGTH = 128;
66 static const int _APP_UID = 5000;
67 static const size_t _MAX_FILE_OPENMODE_LENGTH = 3;
68 static const char _INTERNAL_MOUNT_FLAG[] = "/tmp/osp-compat/mount/internal";
69 static const char _EXTERNAL_MOUNT_FLAG[] = "/tmp/osp-compat/mount/external";
70
71 struct _OspDir
72 {
73         char path[_MAX_PATH_LENGTH];
74         mode_t mode;
75         bool appPrivilege; // false: root privilege
76 };
77
78 struct _LinkDir
79 {
80         char srcPath[_MAX_PATH_LENGTH];
81         char destPath[_MAX_PATH_LENGTH];
82 };
83
84 struct _PathInfo
85 {
86     char destPath[_MAX_PATH_LENGTH];
87 };
88
89 _FileImpl::_FileImpl(void)
90         : __pCore(null)
91         , __read(false)
92         , __write(false)
93         , __truncate(false)
94         , __append(false)
95         , __pFileLockImpl(null)
96 {
97 }
98
99 _FileImpl::~_FileImpl(void)
100 {
101         delete __pCore;
102         if (__pFileLockImpl != null)
103         {
104                 __pFileLockImpl->__pFileImpl = null;
105         }
106 }
107
108 _FileImpl::_FileImpl(const _FileImpl& fileImpl)
109         : __pCore(null)
110         , __read(false)
111         , __write(false)
112         , __truncate(false)
113         , __append(false)
114 {
115         SysAssertf(false, "_FileImpl class does not support copy constructor.\n");
116 }
117
118 _FileImpl&
119 _FileImpl::operator =(const _FileImpl& fileImpl)
120 {
121         SysAssertf(false, "_FileImpl class does not support '=' operator.\n");
122
123         if (&fileImpl == this)
124         {
125                 return *this;
126         }
127
128         return *this;
129 }
130
131 bool
132 _FileImpl::VerifyFileOpenMode(const char* pOpenMode)
133 {
134         if (pOpenMode == null)
135         {
136                 SysLog(NID_IO, "[E_INVALID_ARG] The specified openMode is null.");
137                 return false;
138         }
139
140         if (strlen(pOpenMode) > _MAX_FILE_OPENMODE_LENGTH)
141         {
142                 SysLog(NID_IO, "[E_INVALID_ARG] The specified openMode (%s) is invalid.", pOpenMode);
143                 return false;
144         }
145
146         switch (pOpenMode[0])
147         {
148         case 'r':
149                 __read = true;
150                 break;
151         case 'w':
152                 __write = true;
153                 __truncate = true;
154                 break;
155         case 'a':
156                 __write = true;
157                 __append = true;
158                 break;
159         default:
160                 SysLog(NID_IO, "[E_INVALID_ARG] The specified openMode (%s) is invalid.", pOpenMode);
161                 return false;
162         }
163
164         switch (pOpenMode[1])
165         {
166         case '\0':
167                 break;
168         case '+':
169                 if (pOpenMode[2] == '\0' || pOpenMode[2] == 'b')
170                 {
171                         __read = true;
172                         __write = true;
173                         break;
174                 }
175                 else
176                 {
177                         SysLog(NID_IO, "[E_INVALID_ARG] The specified openMode (%s) is invalid.", pOpenMode);
178                         return false;
179                 }
180         case 'b':
181                 if (pOpenMode[2] == '\0')
182                 {
183                         break;
184                 }
185                 else if (pOpenMode[2] == '+')
186                 {
187                         __read = true;
188                         __write = true;
189                         break;
190                 }
191                 else
192                 {
193                         SysLog(NID_IO, "[E_INVALID_ARG] The specified openMode (%s) is invalid.", pOpenMode);
194                         return false;
195                 }
196         default:
197                 SysLog(NID_IO, "[E_INVALID_ARG] The specified openMode (%s) is invalid.", pOpenMode);
198                 return false;
199         }
200
201         return true;
202 }
203
204 result
205 _FileImpl::Construct(const String& filePath, const String& openMode, bool createParentDirsToo, const ByteBuffer* pSecretKey)
206 {
207         SysAssertf(__pCore == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class\n");
208         result r = E_SUCCESS;
209
210         if (openMode.Contains(L'r') == true)
211         {
212                 SysTryReturnResult(NID_IO, !createParentDirsToo, E_INVALID_ARG,
213                                 "The specified createParentDirsToo cannot be used without file creation mode.");
214         }
215
216         if (createParentDirsToo == true)
217         {
218                 String dirPath;
219                 int position = 0;
220
221                 r = filePath.LastIndexOf(L'/', filePath.GetLength() - 1, position);
222                 SysTryReturnResult(NID_IO, r != E_OBJ_NOT_FOUND, E_INVALID_ARG, "The specified filePath is invalid.");
223                 SysTryReturnResult(NID_IO, !(position == 0), E_INVALID_ARG, "The specified filePath is invalid.");
224
225                 r = filePath.SubString(0, position, dirPath);
226                 SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to extract dir path.", GetErrorMessage(r));
227
228                 r = Directory::Create(dirPath, true);
229                 if (IsFailed(r))
230                 {
231                         if (r == E_FILE_ALREADY_EXIST)
232                         {
233                                 r = E_SUCCESS;
234                         }
235                         else
236                         {
237                                 SysPropagate(NID_IO, r);
238                                 return r;
239                         }
240                 }
241         }
242
243         unique_ptr<char[]> pOpenMode(_StringConverter::CopyToCharArrayN(openMode));
244         SysTryReturnResult(NID_IO, pOpenMode != null, E_OUT_OF_MEMORY, "The memory is insufficient.");
245
246         return Construct(filePath, pOpenMode.get(), pSecretKey);
247 }
248
249 result
250 _FileImpl::Construct(const String& filePath, const char* pOpenMode, const ByteBuffer* pSecretKey)
251 {
252         SysAssertf(__pCore == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class\n");
253         result r = E_SUCCESS;
254
255         bool isValidOpenMode = VerifyFileOpenMode(pOpenMode);
256         SysTryReturnResult(NID_IO, isValidOpenMode == true, E_INVALID_ARG, "The specified openMode is invalid. (%s)", pOpenMode);
257
258         SysTryReturnResult(NID_IO, VerifyFilePathCompatibility(filePath, _AppInfo::IsOspCompat()) == true,
259                         E_INVALID_ARG, " [%ls] is not compatible.", filePath.GetPointer());
260
261         if (!__truncate && IsFileExist(filePath))
262         {
263                 r = _SecureIoUtil::CheckSecureFileHeader(filePath, pSecretKey);
264                 if (r == E_END_OF_FILE)
265                 {
266                         r = E_IO; //for security error
267                 }
268                 SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r));
269         }
270
271         if (pSecretKey == null)
272         {
273                 unique_ptr<_NormalFile> pNormalFile(new (std::nothrow) _NormalFile());
274                 SysTryReturnResult(NID_IO, pNormalFile, E_OUT_OF_MEMORY, "The memory is insufficient.");
275
276                 r = pNormalFile->Construct(filePath, pOpenMode);
277                 SysTryReturn(NID_IO, !IsFailed(r), r , r, "[%s] Propagated.", GetErrorMessage(r));
278                 __pCore = pNormalFile.release();
279         }
280         else
281         {
282                 unique_ptr<_SecureFile> pSecureFile(new (std::nothrow) _SecureFile(__read, __write, __truncate, __append));
283                 SysTryReturnResult(NID_IO, pSecureFile, E_OUT_OF_MEMORY, "The memory is insufficient.");
284
285                 r = pSecureFile->Construct(filePath, pOpenMode, pSecretKey);
286                 SysTryReturn(NID_IO, !IsFailed(r), r , r, "[%s] Propagated.", GetErrorMessage(r));
287                 __pCore = pSecureFile.release();
288         }
289
290         return E_SUCCESS;
291 }
292
293 result
294 _FileImpl::ReadN(char** buffer, int& length)
295 {
296         result r = E_SUCCESS;
297         if (__pCore != null)
298         {
299                 _NormalFile* pNormalFile = dynamic_cast< _NormalFile* > (__pCore);
300                 if (pNormalFile != null)
301                 {
302                         r = pNormalFile->ReadN(buffer, length);
303                 }
304         }
305         else
306         {
307                 r = E_INVALID_OPERATION;
308         }
309
310         return r;
311 }
312
313 result
314 _FileImpl::Read(ByteBuffer& buffer)
315 {
316         SysAssertf(__pCore != null, "Not yet constructed. Construct() should be called before use.\n");
317         SysTryReturnResult(NID_IO, __read == true, E_ILLEGAL_ACCESS, "File is not opened for reading.");
318         return __pCore->Read(buffer);
319 }
320
321 int
322 _FileImpl::Read(void* buffer, int length)
323 {
324         SysAssertf(__pCore != null, "Not yet constructed. Construct() should be called before use.\n");
325         SysTryReturn(NID_IO, __read == true, 0, E_ILLEGAL_ACCESS, "[E_ILLEGAL_ACCESS] File is not opened for reading.");
326         return __pCore->Read(buffer, length);
327 }
328
329 result
330 _FileImpl::Read(String& buffer)
331 {
332         SysAssertf(__pCore != null, "Not yet constructed. Construct() should be called before use.\n");
333         SysTryReturnResult(NID_IO, __read == true, E_ILLEGAL_ACCESS, "File is not opened for reading.");
334         return __pCore->Read(buffer);
335 }
336
337 result
338 _FileImpl::Write(const ByteBuffer& buffer)
339 {
340         SysAssertf(__pCore != null, "Not yet constructed. Construct() should be called before use.\n");
341         SysTryReturnResult(NID_IO, __write == true, E_ILLEGAL_ACCESS, "File is not opened for writing.");
342         return __pCore->Write(buffer);
343 }
344
345 result
346 _FileImpl::Write(const void* buffer, int length)
347 {
348         SysAssertf(__pCore != null, "Not yet constructed. Construct() should be called before use.\n");
349         SysTryReturnResult(NID_IO, __write == true, E_ILLEGAL_ACCESS, "File is not opened for writing.");
350         return __pCore->Write(buffer, length);
351 }
352
353 result
354 _FileImpl::Write(const String& buffer)
355 {
356         SysAssertf(__pCore != null, "Not yet constructed. Construct() should be called before use.\n");
357         SysTryReturnResult(NID_IO, __write == true, E_ILLEGAL_ACCESS, "File is not opened for writing.");
358         return __pCore->Write(buffer);
359 }
360
361 result
362 _FileImpl::Flush(void)
363 {
364         SysAssertf(__pCore != null, "Not yet constructed. Construct() should be called before use.\n");
365         return __pCore->Flush();
366 }
367
368 int
369 _FileImpl::Tell(void) const
370 {
371         SysTryReturnResult(NID_IO, __pCore != null, -1, "File is not constructed! Construct destined file first! ");
372         return __pCore->Tell();
373 }
374
375 result
376 _FileImpl::Seek(FileSeekPosition position, long offset)
377 {
378         SysAssertf(__pCore != null, "Not yet constructed. Construct() should be called before use.\n");
379         return __pCore->Seek(position, offset);
380 }
381
382 result
383 _FileImpl::Truncate(int length)
384 {
385         SysAssertf(__pCore != null, "Not yet constructed. Construct() should be called before use.\n");
386         SysTryReturnResult(NID_IO, __write == true, E_ILLEGAL_ACCESS, "File is not opened for writing.");
387         return __pCore->Truncate(length);
388 }
389
390 String
391 _FileImpl::GetName(void) const
392 {
393         SysAssertf(__pCore != null, "Not yet constructed. Construct() should be called before use.\n");
394         return __pCore->GetName();
395 }
396
397 FILE*
398 _FileImpl::GetFilePointer(void) const
399 {
400         SysAssertf(__pCore != null, "Not yet constructed. Construct() should be called before use.\n");
401         return __pCore->GetFilePointer();
402 }
403
404 FileLock*
405 _FileImpl::LockN(FileLockType lockType)
406 {
407         SysAssertf(__pCore != null, "Not yet constructed. Construct() should be called before use.\n");
408         return LockN(lockType, FILE_LOCK_MODE_BLOCKING, 0, 0);
409 }
410
411 FileLock*
412 _FileImpl::LockN(FileLockType lockType, int offset, int length)
413 {
414         SysAssertf(__pCore != null, "Not yet constructed. Construct() should be called before use.\n");
415         return LockN(lockType, FILE_LOCK_MODE_BLOCKING, offset, length);
416 }
417
418 FileLock*
419 _FileImpl::TryToLockN(FileLockType lockType)
420 {
421         SysAssertf(__pCore != null, "Not yet constructed. Construct() should be called before use.\n");
422         return LockN(lockType, FILE_LOCK_MODE_NON_BLOCKING, 0, 0);
423 }
424
425 FileLock*
426 _FileImpl::TryToLockN(FileLockType lockType, int offset, int length)
427 {
428         SysAssertf(__pCore != null, "Not yet constructed. Construct() should be called before use.\n");
429         return LockN(lockType, FILE_LOCK_MODE_NON_BLOCKING, offset, length);
430 }
431
432 FileLock*
433 _FileImpl::LockN(FileLockType lockType, _FileLockMode lockMode, int offset, int length)
434 {
435         SysAssertf(__pCore != null, "Not yet constructed. Construct() should be called before use.\n");
436         SysTryReturn(NID_IO, offset >= 0, null, E_INVALID_ARG, "[E_INVALID_ARG] The specified offset is negative.");
437         SysTryReturn(NID_IO, length >= 0, null, E_INVALID_ARG, "[E_INVALID_ARG] The specified length is negative.");
438
439         struct flock lock;
440         switch (lockType)
441         {
442         case FILE_LOCK_SHARED:
443                 SysTryReturn(NID_IO, __read == true, null, E_INVALID_OPERATION, "[E_INVALID_OPERATION] File is not opened for reading.");
444                 lock.l_type = F_RDLCK;
445                 break;
446         case FILE_LOCK_EXCLUSIVE:
447                 SysTryReturn(NID_IO, __write == true, null, E_INVALID_OPERATION, "[E_INVALID_OPERATION] File is not opened for writing.");
448                 lock.l_type = F_WRLCK;
449                 break;
450         default:
451                 SysLogException(NID_IO, E_INVALID_ARG, "[E_INVALID_ARG] The specified lock type is invalid.");
452                 return null;
453         }
454
455         int fd = fileno(this->GetFilePointer());
456         int lockCommand = -1;
457         int ret = -1;
458         switch (lockMode)
459         {
460         case FILE_LOCK_MODE_BLOCKING:
461                 lockCommand = F_SETLKW;
462                 break;
463         case FILE_LOCK_MODE_NON_BLOCKING:
464         {
465                 lockCommand = F_SETLK;
466                 break;
467         }
468         default:
469                 SysLogException(NID_IO, E_INVALID_ARG, "[E_INVALID_ARG] The specified lock mode is invalid.");
470                 return null;
471         }
472
473         lock.l_whence = SEEK_SET;
474         lock.l_start = offset;
475         lock.l_len = length;
476         lock.l_pid = getpid();
477
478         ret = fcntl(fd, lockCommand, &lock);
479         if (ret != 0)
480         {
481                 result r = E_SUCCESS;
482                 switch (errno)
483                 {
484                 case ENOLCK:
485                         r = E_MAX_EXCEEDED;
486                         break;
487                 case EDEADLK:
488                 {
489                         if (lockMode == FILE_LOCK_MODE_BLOCKING)
490                         {
491                                 r = E_WOULD_DEADLOCK;
492                         }
493                         else
494                         {
495                                 r = E_SYSTEM;
496                         }
497                         break;
498                 }
499                 case EAGAIN:
500                         // fall through
501                 case EACCES:
502                         if (lockMode == FILE_LOCK_MODE_NON_BLOCKING)
503                         {
504                                 r = E_OBJECT_LOCKED;
505                                 break;
506                         }
507                         // else fall through
508                 case EFAULT:
509                         // fall through
510                 case EBADF:
511                         r = E_SYSTEM;
512                         break;
513                 default:
514                         r = _NativeError::ConvertNativeErrorToResult(errno, true);
515                         break;
516                 }
517
518                 SysLogException(NID_IO, r, "[%s] Aquiring file lock of type (%d) is failed, errno: %d (%s)", GetErrorMessage(r), lockType, errno, strerror(errno));
519                 return null;
520         }
521
522         unique_ptr<FileLock> pFileLock(_FileLockImpl::CreateFileLockInstanceN(this, lockType, lock.l_start, lock.l_len, lock.l_pid));
523         SysTryReturn(NID_IO, pFileLock != null, null, GetLastResult(), "[%s] Propagating to caller....", GetErrorMessage(GetLastResult()));
524         __pFileLockImpl = _FileLockImpl::GetInstance(*pFileLock);
525         SetLastResult(E_SUCCESS);
526         return pFileLock.release();
527 }
528
529 result
530 _FileImpl::Remove(const String& filePath)
531 {
532         SysTryReturnResult(NID_IO, VerifyFilePathCompatibility(filePath, _AppInfo::IsOspCompat()) == true,
533                                           E_INVALID_ARG, " [%ls] is not compatible.", filePath.GetPointer());
534         return _FileUtil::Remove(filePath);
535 }
536
537 result
538 _FileImpl::Move(const String& oldFilePath, const String& newFilePath)
539 {
540         SysTryReturnResult(NID_IO, VerifyFilePathCompatibility(oldFilePath, _AppInfo::IsOspCompat()) == true,
541                                           E_INVALID_ARG, " [%ls] is not compatible.", oldFilePath.GetPointer());
542
543         SysTryReturnResult(NID_IO, VerifyFilePathCompatibility(newFilePath, _AppInfo::IsOspCompat()) == true,
544                                           E_INVALID_ARG, " [%ls] is not compatible.", newFilePath.GetPointer());
545         return _FileUtil::Move(oldFilePath, newFilePath);
546 }
547
548 result
549 _FileImpl::Copy(const String& srcFilePath, const String& destFilePath, bool failIfExist)
550 {
551         SysTryReturnResult(NID_IO, VerifyFilePathCompatibility(srcFilePath, _AppInfo::IsOspCompat()) == true,
552                                           E_INVALID_ARG, " [%ls] is not compatible.", srcFilePath.GetPointer());
553
554         SysTryReturnResult(NID_IO, VerifyFilePathCompatibility(destFilePath, _AppInfo::IsOspCompat()) == true,
555                                           E_INVALID_ARG, " [%ls] is not compatible.", destFilePath.GetPointer());
556         return _FileUtil::Copy(srcFilePath, destFilePath, failIfExist);
557 }
558
559 result
560 _FileImpl::GetAttributes(const String& filePath, FileAttributes& attribute)
561 {
562         SysTryReturnResult(NID_IO, VerifyFilePathCompatibility(filePath, _AppInfo::IsOspCompat()) == true,
563                                           E_INVALID_ARG, " [%ls] is not compatible.", filePath.GetPointer());
564         return _FileUtil::GetAttributes(filePath, attribute);
565 }
566
567 String
568 _FileImpl::GetFileName(const String& filePath)
569 {
570         return _FileUtil::GetFileName(filePath);
571 }
572
573 String
574 _FileImpl::GetFileExtension(const String& filePath)
575 {
576         return _FileUtil::GetFileExtension(filePath);
577 }
578
579 bool
580 _FileImpl::IsFileExist(const String& filePath)
581 {
582         SysTryReturn(NID_IO, VerifyFilePathCompatibility(filePath, _AppInfo::IsOspCompat()) == true,
583                         false, E_INVALID_ARG, "[E_INVALID_ARG] The specified filePath (%ls) is invalid.", filePath.GetPointer());
584
585         return _FileUtil::IsFileExist(filePath);
586 }
587
588 result
589 _FileImpl::ConvertToSecureFile(const String& plainFilePath, const String& secureFilePath,
590                                                            const ByteBuffer& key)
591 {
592         return _FileUtil::ConvertToSecureFile(plainFilePath, secureFilePath, &key);
593 }
594
595 bool
596 _FileImpl::IsAppPath(const String& filePath)
597 {
598         SysTryReturn(NID_IO, VerifyFilePathCompatibility(filePath, _AppInfo::IsOspCompat()) == true,
599                         false, E_INVALID_ARG, "[E_INVALID_ARG] The specified filePath (%ls) is invalid.", filePath.GetPointer());
600
601         return _FileUtil::IsAppPath(filePath);
602 }
603
604 bool
605 _FileImpl::IsMediaPath(const String& filePath)
606 {
607         SysTryReturn(NID_IO, VerifyFilePathCompatibility(filePath, _AppInfo::IsOspCompat()) == true,
608                         false, E_INVALID_ARG, "[E_INVALID_ARG] The specified filePath (%ls) is invalid.", filePath.GetPointer());
609
610         return _FileUtil::IsMediaPath(filePath);
611 }
612
613 bool
614 _FileImpl::IsSystemPath(const String& filePath)
615 {
616         SysTryReturn(NID_IO, VerifyFilePathCompatibility(filePath, _AppInfo::IsOspCompat()) == true,
617                         false, E_INVALID_ARG, "[E_INVALID_ARG] The specified filePath (%ls) is invalid.", filePath.GetPointer());
618
619         return _FileUtil::IsSystemPath(filePath);
620 }
621
622 bool
623 _FileImpl::VerifyFilePath(const String& filePath, _FilePathType pathType)
624 {
625         return _FileUtil::VerifyFilePath(filePath, pathType);
626 }
627
628 bool
629 _FileImpl::CleanDirectories(const String& appRootPath, const String& pkgId)
630 {
631         char removeCmd[PATH_MAX] = {0, };
632         int ret = 0;
633
634         String ospSharePkgIdPath = _EnvironmentImpl::GetOspCompatSharedPath();
635         ospSharePkgIdPath.Append(L"share/");
636         ospSharePkgIdPath.Append(pkgId);
637
638         String ospShare2PkgIdPath = _EnvironmentImpl::GetOspCompatSharedPath();
639         ospShare2PkgIdPath.Append(L"share2/");
640         ospShare2PkgIdPath.Append(pkgId);
641
642 #if 0
643         r = Directory::Remove(ospSharePkgIdPath, true);
644         SysTryReturn(NID_IO, !IsFailed(r), false, E_SYSTEM, "[%s] Failed to remove directory (%ls)",
645                         GetErrorMessage(r), ospSharePkgIdPath.GetPointer());
646
647         r = Directory::Remove(ospShare2PkgIdPath, true);
648         SysTryReturn(NID_IO, !IsFailed(r), false, E_SYSTEM, "[%s] Failed to remove directory (%ls)",
649                         GetErrorMessage(r), ospShare2PkgIdPath.GetPointer());
650 #else
651         sprintf(removeCmd, "rm -rf %ls", ospSharePkgIdPath.GetPointer());
652         ret = system(removeCmd);
653         SysTryReturn(NID_IO, ret != -1, false, E_SYSTEM, "Failed to remove directory (%ls)",
654                         ospSharePkgIdPath.GetPointer());
655
656         memset(removeCmd, 0, PATH_MAX);
657
658         sprintf(removeCmd, "rm -rf %ls", ospShare2PkgIdPath.GetPointer());
659         ret = system(removeCmd);
660         SysTryReturn(NID_IO, ret != -1, false, E_SYSTEM, "Failed to remove directory (%ls)",
661                         ospShare2PkgIdPath.GetPointer());
662 #endif
663
664         return true;
665 }
666
667 // This method is called by package installer backend.
668 bool
669 _FileImpl::PrepareDataCaging(const String& appRootPath, const String& pkgId)
670 {
671         int index = 0;
672         char* pCwd = null;
673         bool internalInstalled = true;
674         result r = E_SUCCESS;
675
676         SysSecureLog(NID_IO, "[data_caging] PrepareDataCaging() was called by installer backend, appRootPath: %ls, packageId: %ls",
677                         appRootPath.GetPointer(), pkgId.GetPointer());
678
679         if (CleanDirectories(appRootPath, pkgId) == false)
680         {
681                 SysLog(NID_IO, "CleanDirectories() failed.");
682                 return false;
683         }
684
685         pCwd = get_current_dir_name();
686         SysTryCatch(NID_IO, pCwd != null, r = E_SYSTEM, E_SYSTEM,
687                            "[E_SYSTEM] get_current_dir_name() was failed, errno: %d (%s).", errno, strerror(errno));
688
689         // Check whether package is installed on internal storage or not
690         r = appRootPath.IndexOf("/opt/storage/sdcard", 0, index);
691         if (r == E_SUCCESS)
692         {
693                 internalInstalled = false;
694         }
695         else
696         {
697                 internalInstalled = true;
698         }
699
700         umask(0000);
701
702         if (internalInstalled == true)
703         {
704                 unique_ptr<char[]> pAppRootPath(_StringConverter::CopyToCharArrayN(appRootPath));
705                 SysTryCatch(NID_IO, pAppRootPath != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] The memory is insufficient.");
706
707                 SysTryCatch(NID_IO, chdir(pAppRootPath.get()) == 0, r = E_SYSTEM, E_SYSTEM,
708                                 "[E_SYSTEM] chdir() was failed (%s), path: %s", strerror(errno), pAppRootPath.get());
709
710                 SysTryCatch(NID_IO, CreateOspInternalDirectories(appRootPath, pkgId) == true, r = E_SYSTEM, E_SYSTEM,
711                                 "[E_SYSTEM] fail to create OSP Internal directories");
712         }
713         else
714         {
715                 String appExRootPath(appRootPath);
716
717                 int ret = 0;
718
719                 appExRootPath.Append(pkgId);
720                 unique_ptr<char[]> pAppExRootPath(_StringConverter::CopyToCharArrayN(appExRootPath));
721                 SysTryCatch(NID_IO, pAppExRootPath != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] The memory is insufficient.");
722
723                 ret = mkdir(pAppExRootPath.get(), 0705);
724                 if (ret == -1 && errno != 17) // EEXIST
725                 {
726                         SysLog(NID_IO, "mkdir() failed (%s), path: %s, mode: 0%o",
727                                                 strerror(errno), pAppExRootPath.get(), 0705);
728                         goto CATCH;
729                 }
730
731                 SysTryCatch(NID_IO, chdir(pAppExRootPath.get()) == 0, r = E_SYSTEM, E_SYSTEM,
732                                 "[E_SYSTEM] chdir() was failed (%s), path: %s", strerror(errno), pAppExRootPath.get());
733                 SysTryCatch(NID_IO, CreateOspExternalDirectories(pkgId) == true, r = E_SYSTEM, E_SYSTEM,
734                                 "[E_SYSTEM] fail to create OSP External directories");
735         }
736
737         SysTryCatch(NID_IO, CreateSlpDirectories() == true, r = E_SYSTEM, E_SYSTEM,
738                         "[E_SYSTEM] fail to create SLP directories");
739         SysTryCatch(NID_IO, CreateSymbolicLink() == true, r = E_SYSTEM, E_SYSTEM,
740                         "[E_SYSTEM] Fail to create symbolic link.");
741         SysTryCatch(NID_IO, chdir(pCwd) == 0, r = E_SYSTEM, E_SYSTEM,
742                         "[E_SYSTEM] chdir() was failed (%s), path: %s", strerror(errno), pCwd);
743
744         r = E_SUCCESS;
745         SysLog(NID_IO, "[data_caging] PrepareDataCaging() succeeded.");
746
747         // fall thru
748 CATCH:
749         if (pCwd != null)
750         {
751                 free(pCwd);
752         }
753
754         umask(0022);
755
756         if (IsFailed(r))
757         {
758                 SysLog(NID_IO, "[data_caging] PrepareDataCaging() failed.");
759                 return false;
760         }
761
762         return true;
763 }
764
765 bool
766 _FileImpl::FinalizeDataCaging(const String& appRootPath) // for 2.0 app
767 {
768         static const struct _PathInfo mountPath[] =
769         {
770                 //{ "./bin" },
771                 //{ "./boot" },
772                 //{ "./cache" },
773                 { "./csa" },
774                 { "./dev/pts" },
775                 { "./dev/shm" },
776                 { "./dev" },
777                 { "./etc" },
778                 { "./lib" },
779                 //{ "./lost+found" },
780                 { "./media" },
781                 { "./mnt" },
782                 { "./opt/usr" },
783                 { "./opt/var/kdb/db" },
784                 { "./opt/storage/sdcard" },
785                 { "./opt" },
786                 //{ "./packaging" },
787                 { "./proc" },
788                 { "./sbin" },
789                 { "./smack" },
790                 { "./srv" },
791                 { "./sys/kernel/debug" },
792                 { "./sys" },
793                 { "./tmp" },
794                 { "./usr" },
795                 { "./var/run" },
796                 { "./var" },
797
798                 { "./data/Share" },
799                 { "./data/Share2" },
800                 { "./Share" },
801                 { "./Share2" },
802                 //{ "./Clipboard" },
803                 //{ "./NPKI" },
804                 //{ "./System" },
805                 //{ "./Tmp" },
806                 { "./Media" },
807
808                 { "./Storagecard/Media" },
809         { "./ShareExt" },
810         { "./Share2Ext" },
811         { "./HomeExt/Share" },
812         { "./HomeExt/Share2" },
813         { "./HomeExt" }
814         };
815
816         unique_ptr< char[] > pAppRootPath(_StringConverter::CopyToCharArrayN(appRootPath));
817         SysTryReturn(NID_IO, pAppRootPath != null, false, E_OUT_OF_MEMORY,
818                         "[E_OUT_OF_MEMORY] The memory is insufficient.");
819
820         SysTryReturn(NID_IO, chdir(pAppRootPath.get()) == 0, false, E_SYSTEM,
821                         "[E_SYSTEM] chdir() failed (%d, %s), path: %ls", errno, strerror(errno), appRootPath.GetPointer());
822
823         for (int i = 0; i < sizeof(mountPath) / sizeof(struct _PathInfo); ++i)
824         {
825                 int ret = umount2(mountPath[i].destPath, MNT_DETACH);
826                 SysTryLog(NID_IO, ret == 0, "umount2() errno: %d (%s)", errno, strerror(errno));
827                 SysTryReturn(NID_IO, ret == 0 || errno == EINVAL || errno == ENOENT, false, E_SYSTEM,
828                                 "[E_SYSTEM] umount2() failed (%d, %s), path: %s", errno, strerror(errno), mountPath[i].destPath);
829         }
830
831         char* pkgId = strrchr(pAppRootPath.get(), '/');
832         char mountFlag[_MAX_PATH_LENGTH] = { 0, };
833         sprintf(mountFlag, "%s/%s", _INTERNAL_MOUNT_FLAG, ++pkgId);
834         int res = unlink(mountFlag);
835         if (res == -1 && errno != ENOENT)
836         {
837                 SysLogException(NID_IO, E_SYSTEM, "[E_SYSTEM] Failed to remove mount flag (%s), errno: %d (%s)",
838                                 mountFlag, errno, strerror(errno));
839                 return false;
840         }
841
842         memset(mountFlag, 0, _MAX_PATH_LENGTH);
843         sprintf(mountFlag, "%s/%s", _EXTERNAL_MOUNT_FLAG, pkgId);
844         res = unlink(mountFlag);
845         if (res == -1 && errno != ENOENT)
846         {
847                 SysLogException(NID_IO, E_SYSTEM, "[E_SYSTEM] Failed to remove mount flag (%s), errno: %d (%s)",
848                                 mountFlag, errno, strerror(errno));
849                 return false;
850         }
851
852         SysLog(NID_IO, "[data_caging] FinalizeDataCaging() succeeded, appRootPath: %ls", appRootPath.GetPointer());
853         return true;
854 }
855
856 int
857 _FileImpl::GetAvailableUid(void)
858 {
859         return _APP_UID;
860 }
861
862 bool
863 _FileImpl::CreateOspApplicationDirectories(const String& appRootPath, const String& pkgId) // for 2.0 app
864 {
865 #if 0
866         struct _OspDir appSubDir[] =
867         {
868                 //{ "./shared\0",                       0755, false },
869                 //{ "./shared/data\0",          0755, true },
870                 //{ "./shared/res\0",           0755, false },
871                 //{ "./shared/trusted\0",       0755, true },
872                 //{ "./cache\0", 0700, true }
873         };
874         int uid = -1;
875         int ret = 0;
876         unsigned int i = 0;
877         result r = E_SUCCESS;
878 #endif
879
880         SysTryReturn(NID_IO, CleanDirectories(appRootPath, pkgId) == true, false, E_SYSTEM,
881                         "[E_SYSTEM] Failed to clean directories for 2.0 application compatibility.");
882
883 #if 0
884         unique_ptr<char[]> pAppRootPath(_StringConverter::CopyToCharArrayN(appRootPath));
885         SysTryReturn(NID_IO, pAppRootPath != null, false, E_SYSTEM, "[E_SYSTEM] The memory is insufficient.");
886
887         SysTryReturn(NID_IO, chdir(pAppRootPath.get()) == 0, false, E_SYSTEM,
888                         "[E_SYSTEM] chdir() failed (%d, %s), path: %s", errno, strerror(errno), pAppRootPath.get());
889
890         uid = GetAvailableUid();
891
892         umask(0000);
893
894         for (i = 0; i < sizeof(appSubDir) / sizeof(struct _OspDir); ++i)
895         {
896                 ret = mkdir(appSubDir[i].path, appSubDir[i].mode);
897                 if (ret == -1 && errno != 17) // EEXIST
898                 {
899                         SysLog(NID_IO, "[E_SYSTEM] mkdir() failed (%d, %s), path: %s, mode: 0%o",
900                                         errno, strerror(errno), appSubDir[i].path, appSubDir[i].mode);
901                         goto CATCH;
902                 }
903
904                 if (appSubDir[i].appPrivilege)
905                 {
906                         ret = chown(appSubDir[i].path, uid, uid);
907                         SysTryCatch(NID_IO, ret == 0, , E_SYSTEM,
908                                         "[E_SYSTEM] chown() failed (%d, %s), path: %s, uid: %d",
909                                         errno, strerror(errno), appSubDir[i].path, uid);
910                 }
911         }
912
913         umask(0022);
914
915         SysLog(NID_IO, "_FileImpl::CreateOspApplicationDirectories() succeeded.");
916         return true;
917
918 CATCH:
919         umask(0022);
920
921         return false;
922 #else
923         return true;
924 #endif
925
926 }
927
928 bool
929 _FileImpl::CreateOspInternalDirectories(const String& appRootPath, const String& pkgId) // for 2.0 app
930 {
931         unsigned int i = 0;
932         int ret = 0;
933         int uid = -1;
934         struct _OspDir appSubDir[] =
935         {
936 //              { "./data",                     0700, true },   // It is created by installer.
937                 { "./shared",           0755, false },
938                 { "./data/Share",       0000, true },   // mount from /opt/usr/share/.osp-compat/share/{pkgId}
939                 { "./data/Share2",      0000, true },   // mount from /opt/usr/share/.osp-compat/share2/{pkgId}
940                 { "./Share",            0000, false },  // mount from /opt/usr/share/.osp-compat/share
941                 { "./Share2",           0000, false },  // mount from /opt/usr/share/.osp-compat/share2
942 //              { "./Clipboard",        0000, false },
943 //              { "./NPKI",                     0000, false },
944 //              { "./System",           0000, false },
945 //              { "./Tmp",                      0000, false },
946                 { "./Media",            0000, false },  // mount from /opt/usr/media
947                 { "./Storagecard",      0705, false },
948                 { "./Storagecard/Media", 0000, false }, // mount from /opt/storage/sdcard
949         };
950 #if 1
951         struct _OspDir mediaDir[] =
952         {
953                 { "/opt/usr/media/Images", 0777, false },
954                 { "/opt/usr/media/Sounds", 0777, false },
955                 { "/opt/usr/media/Videos", 0777, false },
956                 //{ "/opt/usr/media/Themes", 0777, false },
957                 { "/opt/usr/media/Others", 0777, false }
958         };
959 #endif
960         String ospCompatSharedPath = _EnvironmentImpl::GetOspCompatSharedPath();
961         String ospShareAppIdPath(L"share/");
962         String ospShare2AppIdPath(L"share2/");
963         result r = E_SUCCESS;
964
965         r = ospShareAppIdPath.Insert(ospCompatSharedPath, 0);
966         SysTryReturn(NID_IO, !IsFailed(r), false, E_SYSTEM,
967                         "[E_SYSTEM] String::Insert() failed. (error: %s)", GetErrorMessage(r));
968
969         r = ospShare2AppIdPath.Insert(ospCompatSharedPath, 0);
970         SysTryReturn(NID_IO, !IsFailed(r), false, E_SYSTEM,
971                         "[E_SYSTEM] String::Insert() failed. (error: %s)", GetErrorMessage(r));
972
973         uid = GetAvailableUid();
974
975         for (i = 0; i < sizeof(appSubDir) / sizeof(struct _OspDir); i++)
976         {
977                 ret = mkdir(appSubDir[i].path, appSubDir[i].mode);
978                 if (ret == -1 && errno != 17) // EEXIST
979                 {
980                         SysLog(NID_IO, "mkdir() failed (%s), path: %s, mode: 0%o",
981                                                 strerror(errno), appSubDir[i].path, appSubDir[i].mode);
982                         return false;
983                 }
984                 if (appSubDir[i].appPrivilege)
985                 {
986                         ret = chown(appSubDir[i].path, uid, uid);
987                         if (ret == -1)
988                         {
989                                 SysLog(NID_IO, "chown() failed (%s), path: %s, uid: %d",
990                                                         strerror(errno), appSubDir[i].path, uid);
991                                 return false;
992                         }
993                 }
994         }
995
996         ospShareAppIdPath.Append(pkgId);
997         unique_ptr<char[]> pOspShareAppIdPath(_StringConverter::CopyToCharArrayN(ospShareAppIdPath));
998         SysTryReturn(NID_IO, pOspShareAppIdPath != null, false, E_SYSTEM, "[E_SYSTEM] The memory is insufficient.");
999         ret = mkdir(pOspShareAppIdPath.get(), 0705);
1000         if (ret == -1 && errno != 17) // EEXIST
1001         {
1002                 SysLog(NID_IO, "mkdir() failed (%s), path: %s, mode: 0%o",
1003                                         strerror(errno), pOspShareAppIdPath.get(), 0705);
1004                 return false;
1005         }
1006         ret = chown(pOspShareAppIdPath.get(), uid, uid);
1007         if (ret == -1)
1008         {
1009                 SysLog(NID_IO, "chown() failed (%s), path: %s, uid: %d",
1010                                         strerror(errno), pOspShareAppIdPath.get(), uid);
1011                 return false;
1012         }
1013
1014         ospShare2AppIdPath.Append(pkgId);
1015         unique_ptr<char[]> pOspShare2AppIdPath(_StringConverter::CopyToCharArrayN(ospShare2AppIdPath));
1016         SysTryReturn(NID_IO, pOspShare2AppIdPath != null, false, E_SYSTEM, "[E_SYSTEM] The memory is insufficient.");
1017         ret = mkdir(pOspShare2AppIdPath.get(), 0705);    // TODO: change to 0770
1018         if (ret == -1 && errno != 17) // EEXIST
1019         {
1020                 SysLog(NID_IO, "mkdir() failed (%s), path: %s, mode: 0%o",
1021                                         strerror(errno), pOspShare2AppIdPath.get(), 0705);
1022                 return false;
1023         }
1024         ret = chown(pOspShare2AppIdPath.get(), uid, uid);
1025         if (ret == -1)
1026         {
1027                 SysLog(NID_IO, "chown() failed (%s), path: %s, uid: %d",
1028                                         strerror(errno), pOspShare2AppIdPath.get(), uid);
1029                 return false;
1030         }
1031
1032 #if 1
1033         for (i = 0; i < sizeof(mediaDir) / sizeof(struct _OspDir); ++i)
1034         {
1035                 ret = mkdir(mediaDir[i].path, mediaDir[i].mode);
1036                 if (ret == -1 && errno != 17) // EEXIST
1037                 {
1038                         SysLog(NID_IO, "mkdir() failed (%s), path: %s, mode: 0%o",
1039                                         strerror(errno), mediaDir[i].path, mediaDir[i].mode);
1040                         return false;
1041                 }
1042                 ret = chown(mediaDir[i].path, 5000, 5000);
1043                 SysTryReturn(NID_IO, ret == 0, false, E_SYSTEM,
1044                                 "[E_SYSTEM] chown() failed (%d, %s), path: %s, uid: 5000, gid: 5000",
1045                                 errno, strerror(errno), mediaDir[i].path);
1046         }
1047 #endif
1048
1049         // XXX: OSP compatible application's data packed in shared/data, shared/trusted directory of SDK
1050         // cannot be delivered.
1051 #if 0
1052         if (access("./shared/data", F_OK) == 0)
1053         {
1054                 char copyCmd[256] = { 0, };
1055                 sprintf(copyCmd, "cp -rf ./shared/data/* /opt/usr/share/.osp-compat/share/%ls/", pkgId.GetPointer());
1056                 ret = system(copyCmd);
1057                 SysTryReturn(NID_IO, ret != -1, false, E_SYSTEM, "Failed to copy command (%s)", copyCmd);
1058
1059                 SysTryReturn(NID_IO, system("rm -rf ./shared/data") != -1, false, E_SYSTEM,
1060                         "[E_SYSTEM] rmdir() failed, path: ./shared/data");
1061
1062                 char chownCmd[256] = { 0, };
1063                 sprintf(chownCmd, "chown -R 5000:5000 /opt/usr/share/.osp-compat/share/%ls/", pkgId.GetPointer());
1064                 SysTryReturn(NID_IO, system(chownCmd) != -1, false, E_SYSTEM, "[E_SYSTEM] chown() failed");
1065         }
1066 #endif
1067         String appSharedDataPath(appRootPath);
1068         appSharedDataPath.Append(L"/shared/data");
1069
1070         String appSharedTrustedPath(appRootPath);
1071         appSharedTrustedPath.Append(L"/shared/trusted");
1072
1073         SysTryReturn(NID_IO, Directory::Remove(appSharedDataPath, true) == E_SUCCESS, false, E_SYSTEM,
1074                         "[E_SYSTEM] Failed to remove path (%ls)", appSharedDataPath.GetPointer());
1075         SysTryReturn(NID_IO, Directory::Remove(appSharedTrustedPath, true) == E_SUCCESS, false, E_SYSTEM,
1076                         "[E_SYSTEM] Failed to remove path (%ls)", appSharedTrustedPath.GetPointer());
1077
1078         ret = symlink(pOspShareAppIdPath.get(), "./shared/data");
1079         SysTryReturn(NID_IO, ret == 0, false, E_SYSTEM,
1080                         "[E_SYSTEM] symlink() failed, errno: %d (%s), link: ./shared/data -> %s",
1081                         errno, strerror(errno), pOspShareAppIdPath.get());
1082         ret = symlink(pOspShare2AppIdPath.get(), "./shared/trusted");
1083         SysTryReturn(NID_IO, ret == 0, false, E_SYSTEM,
1084                         "[E_SYSTEM] symlink() failed, errno: %d (%s), link: ./shared/trusted -> %s",
1085                         errno, strerror(errno), pOspShare2AppIdPath.get());
1086
1087         return true;
1088 }
1089
1090 // TODO: Need to test this method.
1091 bool
1092 _FileImpl::CreateOspExternalDirectories(const String& pkgId)
1093 {
1094         unsigned int i = 0;
1095         int ret = 0;
1096         int uid = -1;
1097         struct _OspDir appSubDir[] = { // virtual path
1098 //              { "./data", 0700, true },
1099                 { "./System", 0000, false },                // mount from /opt/apps/com.samsung.osp/system
1100                 { "./Storagecard", 0705, false },
1101                 { "./Storagecard/Media", 0000, false }          // mount from /opt/storage/sdcard
1102         };
1103 #if 0
1104         struct _OspDir mediaDir[] = { // physical path
1105                 { "/opt/usr/media/Images", 0777, false },
1106                 { "/opt/usr/media/Sounds", 0777, false },
1107                 { "/opt/usr/media/Videos", 0777, false },
1108                 //{ "/opt/usr/media/Themes", 0777, false },
1109                 { "/opt/usr/media/Others", 0777, false }
1110         };
1111 #endif
1112
1113         for (i = 0; i < sizeof(appSubDir) / sizeof(struct _OspDir); i++)
1114         {
1115                 ret = mkdir(appSubDir[i].path, appSubDir[i].mode);
1116                 if (ret == -1 && errno != 17) // EEXIST
1117                 {
1118                         SysLog(NID_IO, "mkdir() failed (%s), path: %s, mode: 0%o",
1119                                                 strerror(errno), appSubDir[i].path, appSubDir[i].mode);
1120                         return false;
1121                 }
1122                 if (appSubDir[i].appPrivilege)
1123                 {
1124                         ret = chown(appSubDir[i].path, uid, uid);
1125                         if (ret == -1)
1126                         {
1127                                 SysLog(NID_IO, "chown() failed (%s), path: %s, uid: %d",
1128                                                         strerror(errno), appSubDir[i].path, uid);
1129                                 return false;
1130                         }
1131                 }
1132         }
1133
1134 #if 0
1135         for (i = 0; i < sizeof(mediaDir) / sizeof(struct _OspDir); i++)
1136         {
1137                 ret = mkdir(mediaDir[i].path, mediaDir[i].mode);
1138                 if (ret == -1 && errno != 17) // EEXIST
1139                 {
1140                         SysLog(NID_IO, "mkdir() failed (%s), path: %s, mode: 0%o",
1141                                                 strerror(errno), mediaDir[i].path, mediaDir[i].mode);
1142                         return false;
1143                 }
1144         }
1145 #endif
1146
1147         return true;
1148 }
1149
1150 bool
1151 _FileImpl::CreateSlpDirectories(void)
1152 {
1153         unsigned int i = 0;
1154         int ret = 0;
1155         struct _OspDir slpDir[] = { // virtual path
1156                 //{ "./bin", 0000, false },     // mount from /bin
1157                 //{ "./boot", 0000,     false },
1158                 //{ "./cache", 0000, false },
1159                 { "./csa", 0000, false },
1160                 { "./dev", 0000, false },
1161                 { "./etc", 0000, false },
1162                 { "./lib", 0000, false },
1163                 //{ "./lost+found",     0000, false },
1164                 { "./media", 0000, false },
1165                 { "./mnt", 0000, false },
1166                 { "./opt", 0000, false },
1167                 //{ "./packaging", 0000, false },
1168                 { "./proc", 0000, false },
1169                 { "./sbin", 0000, false },
1170                 { "./smack", 0000, false },
1171                 { "./srv", 0000, false },
1172                 { "./sys", 0000, false },
1173                 { "./tmp", 0000, false },
1174                 { "./usr", 0000, false },
1175                 { "./var", 0000, false }
1176         };
1177
1178         for (i = 0; i < sizeof(slpDir) / sizeof(struct _OspDir); i++)
1179         {
1180                 ret = mkdir(slpDir[i].path, slpDir[i].mode);
1181                 if (ret == -1 && errno != 17) // EEXIST
1182                 {
1183                         SysLog(NID_IO, "mkdir() failed (%s), path: %s, mode: 0%o",
1184                                                 strerror(errno), slpDir[i].path, slpDir[i].mode);
1185                         return false;
1186                 }
1187         }
1188
1189         return true;
1190 }
1191
1192 bool
1193 _FileImpl::CreateSymbolicLink(void)
1194 {
1195         struct _LinkDir linkDirList[] = {
1196                 { "/opt/home",          "./home" },
1197                 { "/opt/home/root",     "./root" },
1198                 { "/mnt/mmc",           "./sdcard" }
1199         };
1200
1201         for (unsigned int i = 0; i < sizeof(linkDirList) / sizeof(struct _LinkDir); ++i)
1202         {
1203                 int ret = symlink(linkDirList[i].srcPath, linkDirList[i].destPath);
1204                 if (ret == -1 && errno != 17) // EEXIST
1205                 {
1206                         SysLog(NID_IO, "Failed to create symbolic link, errno: %d (%s), src path: %s, dest path: %s",
1207                                         strerror(errno), linkDirList[i].srcPath, linkDirList[i].destPath);
1208                         return false;
1209                 }
1210         }
1211
1212         return true;
1213 }
1214
1215 bool
1216 _FileImpl::VerifyFilePathCompatibility(const String& filePath, bool ospCompat)
1217 {
1218         if (ospCompat == true)
1219         {
1220                 if (filePath[0] != L'/')
1221                 {
1222                         return false;
1223                 }
1224         }
1225         int length = filePath.GetLength();
1226         if (length > 0)
1227         {
1228                 return true;
1229         }
1230         return false;
1231 }
1232
1233 _FileImpl*
1234 _FileImpl::GetInstance(File& file)
1235 {
1236         return file.__pFileImpl;
1237 }
1238
1239 const _FileImpl*
1240 _FileImpl::GetInstance(const File& file)
1241 {
1242         return file.__pFileImpl;
1243 }
1244
1245 result
1246 _FileImpl::ConvertVirtualToPhysicalPath(const String& virtualPath, String& physicalPath) // for 2.0 app
1247 {
1248         SysTryReturnResult(NID_IO, VerifyFilePathCompatibility(virtualPath, _AppInfo::IsOspCompat()) == true,
1249                         E_INVALID_ARG, "[E_INVALID_ARG] %ls is not compatible.", virtualPath.GetPointer());
1250
1251         const wchar_t* virtualPathPrefix[] =
1252         {
1253                 L"/Home/Share2",
1254                 L"/Home/Share",
1255                 L"/Home",
1256                 L"/Res",
1257                 L"/Share2",
1258                 L"/Share/AppControl",
1259                 L"/Share",
1260                 //L"/HomeExt",
1261                 //L"/ShareExt",
1262                 //L"/Share2Ext",
1263                 //L"/NPKI",
1264                 L"/Media",
1265                 L"/Storagecard/Media",
1266                 //L"/Storagecard/NPKI",
1267         };
1268         result r = E_SUCCESS;
1269         int count = sizeof(virtualPathPrefix)/sizeof(wchar_t*);
1270         int i = 0;
1271
1272         for (i = 0; i < count; i++)
1273         {
1274                 SysLog(NID_IO, "[V2P] i: %d, path: %ls", i, virtualPathPrefix[i]);
1275                 if (virtualPath.StartsWith(virtualPathPrefix[i], 0) == true)
1276                 {
1277                         break;
1278                 }
1279         }
1280         SysTryReturnResult(NID_IO, i != count, E_INVALID_ARG, "The path (%ls) is not matched.",
1281                         virtualPath.GetPointer());
1282
1283         int prefixLen = String(virtualPathPrefix[i]).GetLength();
1284         if (virtualPath.GetLength() > prefixLen)
1285         {
1286                 wchar_t ch = '\0';
1287
1288                 r = virtualPath.GetCharAt(prefixLen, ch);
1289                 SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] The path (%ls) is not matched.",
1290                                 GetErrorMessage(r), virtualPath.GetPointer());
1291
1292                 if (ch != L'/')
1293                 {
1294                         physicalPath.Clear();
1295                         SysLog(NID_IO, "[E_INVALID_ARG] The path (%ls) is not matched.",
1296                                         virtualPath.GetPointer());
1297
1298                         return E_INVALID_ARG;
1299                 }
1300         }
1301
1302         String subPath;
1303         virtualPath.SubString(wcslen(virtualPathPrefix[i]), subPath);
1304
1305         Tizen::App::App* pApp = Tizen::App::App::GetInstance();
1306         SysTryReturnResult(NID_IO, pApp != null, E_OUT_OF_MEMORY, "The memory is insufficient.");
1307         String homePath = pApp->GetAppRootPath();
1308         String ospCompatSharedPath = _EnvironmentImpl::GetOspCompatSharedPath();
1309
1310         switch (i)
1311         {
1312         case 0:
1313                 physicalPath = homePath + L"data/Share2";
1314                 break;
1315         case 1:
1316                 physicalPath = homePath + L"data/Share";
1317                 break;
1318         case 2:
1319                 physicalPath = homePath + L"data";
1320                 break;
1321         case 3:
1322                 physicalPath = homePath + L"res";
1323                 break;
1324         case 4:
1325                 physicalPath = ospCompatSharedPath + L"share2";
1326                 break;
1327         case 5:
1328                 physicalPath = ospCompatSharedPath + L"share/AppControl";
1329                 break;
1330         case 6:
1331                 physicalPath = ospCompatSharedPath + L"share";
1332                 break;
1333         case 7:
1334                 physicalPath = Tizen::System::Environment::GetMediaPath();
1335                 break;
1336         case 8:
1337                 physicalPath = Tizen::System::Environment::GetExternalStoragePath() + L"Media";
1338                 break;
1339         default:
1340                 SysLog(NID_IO, "[E_INVALID_ARG] The path (%ls) is not matched.",
1341                                 virtualPath.GetPointer());
1342                 return E_INVALID_ARG;
1343         }
1344
1345         if (subPath.IsEmpty() == false)
1346         {
1347                 physicalPath.Append(subPath);
1348         }
1349
1350         return r;
1351 }
1352
1353 result
1354 _FileImpl::ConvertPhysicalToVirtualPath(const String& physicalPath, String& virtualPath) // for 2.0 app
1355 {
1356         result r = E_SUCCESS;
1357         const wchar_t* homeSubDir[] = {
1358                 L"/data/Share2",
1359                 L"/data/Share",
1360                 L"/data",
1361                 L"/res",
1362         };
1363         const wchar_t* ospHomeSubDir[] = {
1364                 L"/share2",
1365                 L"/share/AppControl",
1366                 L"/share",
1367         };
1368         String subPath;
1369         int homeSubDirCount = sizeof(homeSubDir)/sizeof(wchar_t*);
1370         int ospHomeSubDirCount = sizeof(ospHomeSubDir)/sizeof(wchar_t*);
1371         int baseDirLen = 0;
1372         int i = 0;
1373
1374         SysLog(NID_IO, "[P2V] physicalPath: %ls", physicalPath.GetPointer());
1375
1376         Tizen::App::App* pApp = Tizen::App::App::GetInstance();
1377         SysTryReturnResult(NID_IO, pApp != null, E_OUT_OF_MEMORY, "The memory is insufficient.");
1378         String homePath = pApp->GetAppRootPath();
1379         homePath.SetLength(homePath.GetLength() - 1);
1380
1381         String ospCompatSharedPath = _EnvironmentImpl::GetOspCompatSharedPath();
1382         ospCompatSharedPath.SetLength(ospCompatSharedPath.GetLength() - 1);
1383
1384         String mediaPath = Tizen::System::Environment::GetMediaPath();
1385         mediaPath.SetLength(mediaPath.GetLength() - 1);
1386
1387         String externalPath = Tizen::System::Environment::GetExternalStoragePath();
1388         externalPath.SetLength(externalPath.GetLength() - 1);
1389
1390         if (physicalPath.StartsWith(homePath, 0) == true)
1391         {
1392                 physicalPath.SubString(homePath.GetLength(), subPath);
1393
1394                 for (i = 0; i < homeSubDirCount; i++)
1395                 {
1396                         SysLog(NID_IO, "[P2V] i: %d, path: %ls", i, homeSubDir[i]);
1397                         if (subPath.StartsWith(homeSubDir[i], 0) == true)
1398                         {
1399                                 break;
1400                         }
1401                 }
1402                 SysTryReturnResult(NID_IO, i != homeSubDirCount, E_INVALID_ARG, "The path (%ls) is not matched.",
1403                                 physicalPath.GetPointer());
1404
1405                 baseDirLen = homePath.GetLength() + String(homeSubDir[i]).GetLength();
1406
1407                 switch (i)
1408                 {
1409                 case 0:
1410                         virtualPath = L"/Home/Share2";
1411                         break;
1412                 case 1:
1413                         virtualPath = L"/Home/Share";
1414                         break;
1415                 case 2:
1416                         virtualPath = L"/Home";
1417                         break;
1418                 case 3:
1419                         virtualPath = L"/Res";
1420                         break;
1421                 default:
1422                         break;
1423                 }
1424
1425         }
1426         else if (physicalPath.StartsWith(ospCompatSharedPath, 0) == true)
1427         {
1428                 physicalPath.SubString(ospCompatSharedPath.GetLength(), subPath);
1429
1430                 for (i = 0; i < ospHomeSubDirCount; i++)
1431                 {
1432                         SysLog(NID_IO, "[P2V] i: %d, path: %ls", i, ospHomeSubDir[i]);
1433                         if (subPath.StartsWith(ospHomeSubDir[i], 0) == true)
1434                         {
1435                                 break;
1436                         }
1437                 }
1438                 SysTryReturnResult(NID_IO, i != ospHomeSubDirCount, E_INVALID_ARG, "The path (%ls) is not matched.",
1439                                 physicalPath.GetPointer());
1440
1441                 baseDirLen = ospCompatSharedPath.GetLength() + String(ospHomeSubDir[i]).GetLength();
1442
1443                 switch (i)
1444                 {
1445                 case 0:
1446                         virtualPath = L"/Share2";
1447                         break;
1448                 case 1:
1449                         virtualPath = L"/Share/AppControl";
1450                         break;
1451                 case 2:
1452                         virtualPath = L"/Share";
1453                         break;
1454                 default:
1455                         break;
1456                 }
1457         }
1458         else if (physicalPath.StartsWith(mediaPath, 0) == true)
1459         {
1460                 SysLog(NID_IO, "[P2V] media");
1461                 virtualPath = L"/Media";
1462                 baseDirLen = mediaPath.GetLength();
1463         }
1464         else if (physicalPath.StartsWith(externalPath, 0) == true)
1465         {
1466                 SysLog(NID_IO, "[P2V] external media");
1467                 virtualPath = L"/Storagecard/Media";
1468                 baseDirLen = externalPath.GetLength();
1469         }
1470         else
1471         {
1472                 SysLog(NID_IO, "[E_INVALID_ARG] The path (%ls) is not matched.",
1473                                 physicalPath.GetPointer());
1474
1475                 return E_INVALID_ARG;
1476         }
1477
1478         if (physicalPath.GetLength() > baseDirLen)
1479         {
1480                 wchar_t ch = '\0';
1481
1482                 r = physicalPath.GetCharAt(baseDirLen, ch);
1483                 SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] The path (%ls) is not matched.",
1484                                 GetErrorMessage(r), physicalPath.GetPointer());
1485
1486                 if (ch != L'/')
1487                 {
1488                         virtualPath.Clear();
1489                         SysLog(NID_IO, "[E_INVALID_ARG] The path (%ls) is not matched.",
1490                                         physicalPath.GetPointer());
1491
1492                         return E_INVALID_ARG;
1493                 }
1494         }
1495
1496         subPath.Clear();
1497         physicalPath.SubString(baseDirLen, subPath);
1498
1499         if (subPath.IsEmpty() == false)
1500         {
1501                 virtualPath.Append(subPath);
1502         }
1503
1504         return r;
1505 }
1506
1507 }} // Tizen::Io