tizen 2.3 release
[framework/appfw/debug-launchpad.git] / src / fileutils.c
1 /*
2  *  debug-launchpad
3  *
4  * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
5  *
6  * Contact: Jungmin Cho <chivalry.cho@samsung.com>, Gwangho Hwang <gwang.hwang@samsung.com>
7  *
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  *
20  */
21
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <unistd.h>
26 #include <sys/stat.h>
27 #include <limits.h>
28 #include <fcntl.h>
29
30 static int recurse(const char *path, mode_t mode, int (*fn)(const char *,mode_t, int)) {
31     struct stat st;
32     char dir[PATH_MAX];
33
34     if (path == NULL) {
35         return -1;
36     }
37     if (lstat (path, &st) == -1) {
38         return -1;
39     }
40     if (strrchr(path, '/') != NULL) {
41         int n = strlen(path)-strlen(strrchr(path, '/'));
42         if (n >= PATH_MAX) {
43             return -1;
44         }
45         strncpy(dir, path, n);
46         dir[n] = '\0';
47         fn(dir, mode,1);
48         return 0;
49     }
50     return -1;
51 }
52
53 int dlp_chmod(const char *path, mode_t mode, int recursive) {
54 #ifdef HAVE_WIN32_PROC
55     fprintf(stderr, "error: dlp_chmod not implemented on Win32 (%s)\n", path);
56     return -1;
57 #else
58     int fd;
59     struct stat lstat_info;
60     struct stat fstat_info;
61
62     if (lstat (path, &lstat_info) == -1)
63         return -1;
64
65     fd = open(path, O_WRONLY, S_IRWXU);
66     if(fd == -1)
67         return -1;
68
69     if (fstat (fd, &fstat_info) == -1)
70     {
71         close(fd);
72         return -1;
73     }
74
75     // this complex check is required because of 'chmod' security issue.
76     // otherwise hacker can change other file's permission by using race condition and symbolic link.
77     if(lstat_info.st_mode == fstat_info.st_mode &&
78        lstat_info.st_ino == fstat_info.st_ino &&
79        lstat_info.st_dev == fstat_info.st_dev){
80         if (fchmod (fd, mode) == -1) {
81             close(fd);
82             return -1;
83         }
84     }
85
86     close(fd);
87
88     if (recursive) {
89         return recurse(path, mode, dlp_chmod);
90     }
91     return 0;
92 #endif
93 }