aboutsummaryrefslogtreecommitdiff
path: root/shared.c
diff options
context:
space:
mode:
authorLars Hjemli <hjemli@gmail.com>2010-03-22 00:09:43 +0100
committerLars Hjemli <hjemli@gmail.com>2010-03-22 00:09:43 +0100
commitba56a37e863d0f90e3e953047486905cfb959925 (patch)
tree965e2c917f472264de35125eec35c361984eba4f /shared.c
parentff3a3b4e2b7463bb8cb370bdda393e8b3526fcb9 (diff)
downloadcgit-ba56a37e863d0f90e3e953047486905cfb959925.tar.gz
cgit-ba56a37e863d0f90e3e953047486905cfb959925.tar.bz2
Add support for environment variable expansion
This patch teaches cgit to expand environment variables in certain cgitrc option values (cache_root, scan-path, include) plus when finding the location of cgitrc itself. One use case for this feature is virtual hosting - e.g. by setting $CGIT_CONFIG='/etc/cgitrc/$HTTP_HOST' in httpd.conf, all virtual hosts automatically gets their own cgitrc. Signed-off-by: Lars Hjemli <hjemli@gmail.com>
Diffstat (limited to 'shared.c')
-rw-r--r--shared.c71
1 files changed, 71 insertions, 0 deletions
diff --git a/shared.c b/shared.c
index 5f46793..76d26dd 100644
--- a/shared.c
+++ b/shared.c
@@ -423,3 +423,74 @@ int readfile(const char *path, char **buf, size_t *size)
close(fd);
return (*size == st.st_size ? 0 : e);
}
+
+int is_token_char(char c)
+{
+ return isalnum(c) || c == '_';
+}
+
+/* Replace name with getenv(name), return pointer to zero-terminating char
+ */
+char *expand_macro(char *name, int maxlength)
+{
+ char *value;
+ int len;
+
+ len = 0;
+ value = getenv(name);
+ if (value) {
+ len = strlen(value);
+ if (len > maxlength)
+ len = maxlength;
+ strncpy(name, value, len);
+ }
+ return name + len;
+}
+
+#define EXPBUFSIZE (1024 * 8)
+
+/* Replace all tokens prefixed by '$' in the specified text with the
+ * value of the named environment variable.
+ * NB: the return value is a static buffer, i.e. it must be strdup'd
+ * by the caller.
+ */
+char *expand_macros(const char *txt)
+{
+ static char result[EXPBUFSIZE];
+ char *p, *start;
+ int len;
+
+ p = result;
+ start = NULL;
+ while (p < result + EXPBUFSIZE - 1 && txt && *txt) {
+ *p = *txt;
+ if (start) {
+ if (!is_token_char(*txt)) {
+ if (p - start > 0) {
+ *p = '\0';
+ len = result + EXPBUFSIZE - start - 1;
+ p = expand_macro(start, len) - 1;
+ }
+ start = NULL;
+ txt--;
+ }
+ p++;
+ txt++;
+ continue;
+ }
+ if (*txt == '$') {
+ start = p;
+ txt++;
+ continue;
+ }
+ p++;
+ txt++;
+ }
+ *p = '\0';
+ if (start && p - start > 0) {
+ len = result + EXPBUFSIZE - start - 1;
+ p = expand_macro(start, len);
+ *p = '\0';
+ }
+ return result;
+}