2 * Generic freedesktop.org support code
4 * Copyright (C) 2006 Mikolaj Zalewski
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 * XDG_UserDirLookup() and helper functions are based on code from:
22 * http://www.freedesktop.org/wiki/Software/xdg-user-dirs
24 * Copyright (c) 2007 Red Hat, inc
26 * From the xdg-user-dirs license:
27 * Permission is hereby granted, free of charge, to any person
28 * obtaining a copy of this software and associated documentation files
29 * (the "Software"), to deal in the Software without restriction,
30 * including without limitation the rights to use, copy, modify, merge,
31 * publish, distribute, sublicense, and/or sell copies of the Software,
32 * and to permit persons to whom the Software is furnished to do so,
33 * subject to the following conditions:
35 * The above copyright notice and this permission notice shall be
36 * included in all copies or substantial portions of the Software.
38 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
39 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
40 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
41 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
42 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
43 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
44 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
49 #include "wine/port.h"
55 #ifdef HAVE_SYS_STAT_H
56 # include <sys/stat.h>
67 #include "wine/debug.h"
68 #include "shell32_main.h"
71 WINE_DEFAULT_DEBUG_CHANNEL(xdg
);
74 * XDG paths implemented using Desktop Base Directory spec version 0.6
75 * (from http://standards.freedesktop.org/basedir-spec/basedir-spec-0.6.html)
78 static CRITICAL_SECTION XDG_PathsLock
;
79 static CRITICAL_SECTION_DEBUG XDG_PathsLock_Debug
=
82 { &XDG_PathsLock_Debug
.ProcessLocksList
,
83 &XDG_PathsLock_Debug
.ProcessLocksList
},
84 0, 0, { (DWORD_PTR
)__FILE__
": XDG_PathsLock"}
86 static CRITICAL_SECTION XDG_PathsLock
= { &XDG_PathsLock_Debug
, -1, 0, 0, 0, 0 };
91 const char *default_value
;
94 static const std_path paths
[] = {
95 {"XDG_DATA_HOME", "$HOME/.local/share"},
96 {"XDG_CONFIG_HOME", "$HOME/.config"},
97 {"XDG_DATA_DIRS", "/usr/local/share:/usr/share"},
98 {"XDG_CONFIG_DIRS", "/etc/xdg"},
99 {"XDG_CACHE_HOME", "$HOME/.cache"}
102 #define PATHS_COUNT (sizeof(paths)/sizeof(paths[0]))
104 /* will be filled with paths as they are computed */
105 static const char *path_values
[PATHS_COUNT
] = {
113 static char *load_path(int path_id
)
115 char *env
= getenv(paths
[path_id
].var_name
);
118 if (env
!= NULL
&& env
[0]=='/')
120 ret
= SHAlloc(strlen(env
)+1);
126 if (memcmp(paths
[path_id
].default_value
, "$HOME", 5)==0)
128 char *home
= getenv("HOME");
131 if (!home
) return NULL
;
132 ret
= SHAlloc(strlen(home
)+strlen(paths
[path_id
].default_value
)-5+1);
133 if (ret
== NULL
) return NULL
;
137 if (len
>0 && ret
[len
-1]=='/')
139 lstrcatA(ret
, paths
[path_id
].default_value
+5);
143 ret
= SHAlloc(strlen(paths
[path_id
].default_value
)+1);
145 lstrcpyA(ret
, paths
[path_id
].default_value
);
149 /******************************************************************************
150 * XDG_GetPath [internal]
152 * Get one of the XDG standard patch. The return value shouldn't be modified nor
153 * freed. A return value of NULL means that the memory is exhausted or the input
156 * For XDG_DATA_HOME, XDG_CONFIG_HOME and XDG_CACHE_HOME the result is a Unix path.
157 * For XDG_DATA_DIRS and XDG_CONFIG_DIRS the result is a colon-separated list of Unix
160 * The paths are guaranteed to start with '/'
162 static const char *XDG_GetPath(int path_id
)
164 if (path_id
>= PATHS_COUNT
|| path_id
< 0)
166 ERR("Invalid path_id %d\n", path_id
);
170 if (path_values
[path_id
] != NULL
)
171 return path_values
[path_id
];
172 EnterCriticalSection(&XDG_PathsLock
);
173 if (path_values
[path_id
] == NULL
)
174 path_values
[path_id
] = load_path(path_id
);
175 LeaveCriticalSection(&XDG_PathsLock
);
176 return path_values
[path_id
];
179 /******************************************************************************
180 * XDG_BuildPath [internal]
182 * Build a string with a subpath of one of the XDG standard paths.
183 * The root can be one of XDG_DATA_HOME, XDG_CONFIG_HOME and XDG_CACHE_HOME.
184 * The subpath is a path relative to that root (it shouldn't start with a slash)
186 * The returned path should be freed with SHFree. A return of NULL means that the
187 * memory is exhausted or the parameters are invalid
189 char *XDG_BuildPath(int root_id
, const char *subpath
)
191 const char *root_path
= XDG_GetPath(root_id
);
195 if (root_id
== XDG_DATA_DIRS
|| root_id
== XDG_CONFIG_DIRS
)
197 ERR("Invalid path id %d\n", root_id
);
201 if (root_path
== NULL
) return NULL
;
202 root_len
= strlen(root_path
);
203 if (root_path
[root_len
-1]=='/') root_len
--;
204 ret_buffer
= SHAlloc(root_len
+1+strlen(subpath
)+1);
205 if (ret_buffer
== NULL
) return NULL
;
206 lstrcpyA(ret_buffer
, root_path
);
207 ret_buffer
[root_len
]='/';
208 lstrcpyA(ret_buffer
+root_len
+1, subpath
);
212 /******************************************************************************
213 * XDG_MakeDirs [internal]
215 * Checks that all the directories on the specified path exists. If some don't exists
216 * they are created with mask 0700 as required by many the freedeskop.org specs.
217 * If the path doesn't end with '/' it is assumed to be a path to a file and the last
218 * segment is not checked
220 * In case of a failure the errno is always set and can be used e.g for debugging
223 * TRUE on success, FALSE on error
225 BOOL
XDG_MakeDirs(const char *path
)
230 char *buffer
= SHAlloc(strlen(path
)+1);
237 lstrcpyA(buffer
, path
);
239 TRACE("(%s)\n", debugstr_a(path
));
242 char *slash
=strchr(buffer
+last_slash
+1, '/');
246 /* cut the string at that position and create the directory if it doesn't exist */
248 TRACE("Checking path %s\n", debugstr_a(buffer
));
249 success
= (stat(buffer
, &tmp
)==0);
250 if (!success
&& errno
==ENOENT
)
253 success
= (mkdir(buffer
, 0700)==0);
257 WARN("Couldn't process directory %s (errno=%d)\n", debugstr_a(buffer
), errno
);
261 last_slash
= slash
-buffer
;
268 * .desktop files functions
272 /******************************************************************************
273 * dskentry_encode [internal]
275 * Escape the characters that can't be present in a desktop entry value like \n, leading
276 * spaces etc. The output parameter may be NULL. Then only the number of characters will
280 * The number of characters after escaping the special characters, including the
283 static int dskentry_encode(const char *value
, char *output
)
285 BOOL only_spc
= TRUE
;
288 for (c
= value
; *c
; c
++)
290 if (only_spc
&& *c
==' ')
302 if (*c
=='\t' || *c
=='\r' || *c
=='\n' || *c
=='\\')
307 if (*c
=='\t') *(output
++) = 't';
308 if (*c
=='\r') *(output
++) = 'r';
309 if (*c
=='\n') *(output
++) = 'n';
310 if (*c
=='\\') *(output
++) = '\\';
328 /******************************************************************************
329 * dskentry_decode [internal]
331 * Unescape the characters that can be escaped according to the desktop entry spec.
332 * The output parameter may be NULL. Then only the number of characters will
336 * The number of characters after unescaping the special characters, including the
339 static int dskentry_decode(const char *value
, int len
, char *output
)
346 if (value
[pos
] == '\\' && pos
<len
-1)
351 case 's': c
= ' '; break;
352 case 'n': c
= '\n'; break;
353 case 't': c
= '\t'; break;
354 case 'r': c
= 'r'; break;
355 case '\\': c
= '\\'; break;
357 /* store both the backslash and the character */
381 /******************************************************************************
382 * url_encode [internal]
384 * URL-encode the given string (i.e. use escape codes like %20). Note that an
385 * URL-encoded string can be used as a value in desktop entry files as all
386 * unsafe characters are escaped.
388 * The output can be NULL. Then only the number of characters will be counted
391 * The number of characters after escaping the special characters, including the
394 static int url_encode(const char *value
, char *output
)
396 static const char unsafechars
[] = "^&`{}|[]'<>\\#%\"+";
397 static const char hexchars
[] = "0123456789ABCDEF";
401 for (c
= value
; *c
; c
++)
403 if (*c
<=0x20 || *c
>=0x7f || strchr(unsafechars
, *c
))
408 *(output
++) = hexchars
[(unsigned char)*c
/ 16];
409 *(output
++) = hexchars
[(unsigned char)*c
% 16];
428 static int decode_url_code(const char *c
)
432 static const char hexchars
[] = "0123456789ABCDEF";
436 p1
= strchr(hexchars
, toupper(*c
));
437 p2
= strchr(hexchars
, toupper(*(c
+1)));
438 if (p1
== NULL
|| p2
== NULL
)
440 v1
= (int)(p1
- hexchars
);
441 v2
= (int)(p2
- hexchars
);
445 /******************************************************************************
446 * url_decode [internal]
448 * URL-decode the given string (i.e. unescape codes like %20). The decoded string
449 * will never be longer than the encoded one. The decoding can be done in place - the
450 * output variable can point to the value buffer.
452 * output should not be NULL
454 static void url_decode(const char *value
, char *output
)
456 const char *c
= value
;
461 int v
= decode_url_code(c
+1);
476 static int escape_value(const char *value
, DWORD dwFlags
, char *output
)
478 if (dwFlags
& XDG_URLENCODE
)
479 return url_encode(value
, output
);
480 return dskentry_encode(value
, output
);
483 /******************************************************************************
484 * XDG_WriteDesktopStringEntry [internal]
486 * Writes a key=value pair into the specified file descriptor.
489 * TRUE on success, else FALSE
491 BOOL
XDG_WriteDesktopStringEntry(int writer
, const char *keyName
, DWORD dwFlags
, const char *value
)
493 int keyLen
= lstrlenA(keyName
);
494 int valueLen
= escape_value(value
, dwFlags
, NULL
);
495 char *string
= SHAlloc(keyLen
+1+valueLen
);
500 lstrcpyA(string
, keyName
);
501 string
[keyLen
] = '=';
502 escape_value(value
, dwFlags
, string
+keyLen
+1);
503 string
[keyLen
+1+valueLen
-1]='\n'; /* -1 because valueLen contains the last NUL character */
504 ret
= (write(writer
, string
, keyLen
+1+valueLen
)!=-1);
515 typedef struct tagPARSED_ENTRY PARSED_ENTRY
;
516 struct tagPARSED_ENTRY
519 PARSED_STRING equals
;
524 typedef struct tagPARSED_GROUP PARSED_GROUP
;
525 struct tagPARSED_GROUP
528 PARSED_ENTRY
*entries
;
533 struct tagXDG_PARSED_FILE
536 PARSED_ENTRY
*head_comments
;
537 PARSED_GROUP
*groups
;
540 static BOOL
parsed_str_eq(const PARSED_STRING
*str1
, const char *str2
)
542 if (strncmp(str1
->str
, str2
, str1
->len
) != 0)
544 if (str2
[str1
->len
] != 0)
549 static void free_entries_list(PARSED_ENTRY
*first
)
560 void XDG_FreeParsedFile(XDG_PARSED_FILE
*parsed
)
562 PARSED_GROUP
*group
, *next
;
565 free_entries_list(parsed
->head_comments
);
567 group
= parsed
->groups
;
571 free_entries_list(group
->entries
);
575 SHFree(parsed
->contents
);
581 #define LINE_COMMENT 3
583 static int parse_line(char *content
, PARSED_ENTRY
*output
, int *outType
)
587 ZeroMemory(output
, sizeof(PARSED_ENTRY
));
588 end
= strchr(content
, '\n');
590 end
= content
+ strlen(content
) - 1;
594 *outType
= LINE_COMMENT
;
595 output
->equals
.str
= content
;
596 output
->equals
.len
= end
- content
;
598 output
->equals
.len
++;
600 else if (*content
== '[')
602 char *last_char
= end
;
604 *outType
= LINE_GROUP
;
606 /* the standard says nothing about skipping white spaces but e.g. KDE accepts such files */
607 while (isspace(*last_char
))
609 if (*last_char
!= ']')
611 output
->name
.str
= content
+ 1;
612 output
->name
.len
= last_char
- (content
+ 1);
616 /* 'name = value' line */
617 char *equal
, *eq_begin
, *eq_end
;
619 *outType
= LINE_ENTRY
;
621 equal
= strchr(content
, '=');
622 if (equal
== NULL
|| equal
> end
)
624 for (eq_begin
= equal
-1; isspace(*eq_begin
) && eq_begin
>= content
; eq_begin
--)
626 for (eq_end
= equal
+1; isspace(*eq_end
) && *eq_end
!= '\n'; eq_end
++)
629 output
->name
.str
= content
;
630 output
->name
.len
= eq_begin
- content
+ 1;
632 output
->equals
.str
= eq_begin
+ 1;
633 output
->equals
.len
= eq_end
- eq_begin
- 1;
635 output
->value
.str
= eq_end
;
636 output
->value
.len
= end
- eq_end
;
641 return end
- content
+ 1;
644 XDG_PARSED_FILE
*XDG_ParseDesktopFile(int fd
)
647 XDG_PARSED_FILE
*parsed
= NULL
;
648 PARSED_ENTRY
**curr_entry
;
649 PARSED_GROUP
**curr_group
;
650 BOOL is_in_group
= FALSE
;
654 if (fstat(fd
, &stats
) == -1) goto failed
;
655 parsed
= SHAlloc(sizeof(XDG_PARSED_FILE
));
656 if (parsed
== NULL
) goto failed
;
657 parsed
->groups
= NULL
;
658 parsed
->head_comments
= NULL
;
659 parsed
->contents
= SHAlloc(stats
.st_size
+1);
660 if (parsed
->contents
== NULL
) goto failed
;
662 curr_entry
= &parsed
->head_comments
;
663 curr_group
= &parsed
->groups
;
665 if (read(fd
, parsed
->contents
, stats
.st_size
) == -1) goto failed
;
666 parsed
->contents
[stats
.st_size
] = 0;
668 while (pos
< stats
.st_size
)
670 PARSED_ENTRY statement
;
673 size
= parse_line(parsed
->contents
+ pos
, &statement
, &type
);
674 if (size
== -1) goto failed
;
683 PARSED_GROUP
*group
= SHAlloc(sizeof(PARSED_GROUP
));
684 if (group
== NULL
) goto failed
;
687 group
->name
= statement
.name
;
688 group
->entries
= NULL
;
691 curr_group
= &group
->next
;
692 curr_entry
= &group
->entries
;
697 if (!is_in_group
) goto failed
;
701 PARSED_ENTRY
*new_stat
= SHAlloc(sizeof(PARSED_ENTRY
));
702 if (new_stat
== NULL
) goto failed
;
703 *new_stat
= statement
;
704 new_stat
->next
= NULL
;
705 *curr_entry
= new_stat
;
706 curr_entry
= &new_stat
->next
;
714 XDG_FreeParsedFile(parsed
);
718 char *XDG_GetStringValue(XDG_PARSED_FILE
*file
, const char *group_name
, const char *value_name
, DWORD dwFlags
)
723 for (group
= file
->groups
; group
; group
= group
->next
)
725 if (!parsed_str_eq(&group
->name
, group_name
))
728 for (entry
= group
->entries
; entry
; entry
= entry
->next
)
729 if (entry
->name
.str
!= NULL
&& parsed_str_eq(&entry
->name
, value_name
))
734 len
= dskentry_decode(entry
->value
.str
, entry
->value
.len
, NULL
);
736 if (ret
== NULL
) return NULL
;
737 dskentry_decode(entry
->value
.str
, entry
->value
.len
, ret
);
738 if (dwFlags
& XDG_URLENCODE
)
739 url_decode(ret
, ret
);
747 /* Get the name of the xdg configuration file.
749 * [in] home_dir - $HOME
750 * [out] config_file - the name of the configuration file
752 static HRESULT
get_xdg_config_file(char * home_dir
, char ** config_file
)
756 config_home
= getenv("XDG_CONFIG_HOME");
757 if (!config_home
|| !config_home
[0])
759 *config_file
= HeapAlloc(GetProcessHeap(), 0, strlen(home_dir
) + strlen("/.config/user-dirs.dirs") + 1);
761 return E_OUTOFMEMORY
;
763 strcpy(*config_file
, home_dir
);
764 strcat(*config_file
, "/.config/user-dirs.dirs");
768 *config_file
= HeapAlloc(GetProcessHeap(), 0, strlen(config_home
) + strlen("/user-dirs.dirs") + 1);
770 return E_OUTOFMEMORY
;
772 strcpy(*config_file
, config_home
);
773 strcat(*config_file
, "/user-dirs.dirs");
778 /* Parse the key in a line in the xdg-user-dir config file.
779 * i.e. XDG_PICTURES_DIR="$HOME/Pictures"
782 * [in] xdg_dirs - array of xdg directories to look for
783 * [in] num_dirs - number of elements in xdg_dirs
784 * [in/out] p_ptr - pointer to where we are in the buffer
785 * Returns the index to xdg_dirs if we find the key, or -1 on error.
787 static int parse_config1(const char * const *xdg_dirs
, const unsigned int num_dirs
, char ** p_ptr
)
793 while (*p
== ' ' || *p
== '\t')
795 if (strncmp(p
, "XDG_", 4))
799 for (i
= 0; i
< num_dirs
; i
++)
801 if (!strncmp(p
, xdg_dirs
[i
], strlen(xdg_dirs
[i
])))
803 p
+= strlen(xdg_dirs
[i
]);
809 if (strncmp(p
, "_DIR", 4))
812 while (*p
== ' ' || *p
== '\t')
817 while (*p
== ' ' || *p
== '\t')
827 /* Parse the value in a line in the xdg-user-dir config file.
828 * i.e. XDG_PICTURES_DIR="$HOME/Pictures"
831 * [in] p - pointer to the buffer
832 * [in] home_dir - $HOME
833 * [out] out_ptr - the directory name
835 static HRESULT
parse_config2(char * p
, const char * home_dir
, char ** out_ptr
)
842 if (!strncmp(p
, "$HOME/", 6))
852 out
= HeapAlloc(GetProcessHeap(), 0, strlen(home_dir
) + strlen(p
) + 2);
854 return E_OUTOFMEMORY
;
856 strcpy(out
, home_dir
);
861 out
= HeapAlloc(GetProcessHeap(), 0, strlen(p
) + 1);
863 return E_OUTOFMEMORY
;
867 d
= out
+ strlen(out
);
868 while (*p
&& *p
!= '"')
870 if ((*p
== '\\') && (*(p
+ 1) != 0))
879 /* Parse part of a line in the xdg-user-dir config file.
880 * i.e. XDG_PICTURES_DIR="$HOME/Pictures"
883 * The calling function is responsible for freeing all elements of out_ptr as
884 * well as out_ptr itself.
886 * [in] xdg_dirs - array of xdg directories to look for
887 * [in] num_dirs - number of elements in xdg_dirs
888 * [out] out_ptr - an array of the xdg directories names
890 HRESULT
XDG_UserDirLookup(const char * const *xdg_dirs
, const unsigned int num_dirs
, char *** out_ptr
)
894 char *home_dir
, *config_file
;
900 *out_ptr
= HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY
, num_dirs
* sizeof(char *));
903 return E_OUTOFMEMORY
;
905 home_dir
= getenv("HOME");
909 goto xdg_user_dir_lookup_error
;
912 hr
= get_xdg_config_file(home_dir
, &config_file
);
914 goto xdg_user_dir_lookup_error
;
916 file
= fopen(config_file
, "r");
917 HeapFree(GetProcessHeap(), 0, config_file
);
921 goto xdg_user_dir_lookup_error
;
924 while (fgets(buffer
, sizeof(buffer
), file
))
929 /* Remove newline at end */
930 len
= strlen(buffer
);
931 if (len
> 0 && buffer
[len
-1] == '\n')
936 idx
= parse_config1(xdg_dirs
, num_dirs
, &p
);
942 /* Parse the value */
943 hr
= parse_config2(p
, home_dir
, &out
[idx
]);
946 if (hr
== E_OUTOFMEMORY
)
949 goto xdg_user_dir_lookup_error
;
957 /* Remove entries for directories that do not exist */
958 for (i
= 0; i
< num_dirs
; i
++)
960 struct stat statFolder
;
964 if (!stat(out
[i
], &statFolder
) && S_ISDIR(statFolder
.st_mode
))
966 HeapFree(GetProcessHeap(), 0, out
[i
]);
970 xdg_user_dir_lookup_error
:
973 for (i
= 0; i
< num_dirs
; i
++) HeapFree(GetProcessHeap(), 0, out
[i
]);
974 HeapFree(GetProcessHeap(), 0, *out_ptr
);