updated on Thu Jan 26 00:18:00 UTC 2012
[aur-mirror.git] / finit-arc / helpers.c
blobe7e2412e468fdd11220ec181dd2c12c148680e17
2 #include <string.h>
3 #include <limits.h>
4 #include <stdlib.h>
5 #include <sys/stat.h>
6 #include <sys/types.h>
7 #include <fcntl.h>
8 #include <unistd.h>
9 #include <sys/ioctl.h>
10 #include <sys/socket.h>
11 #include <net/if.h>
12 #include <netinet/in.h>
13 #include <arpa/inet.h>
15 #ifdef BUILTIN_RUNPARTS
16 #include <dirent.h>
17 #include <stdarg.h>
18 #include <sys/wait.h>
19 #endif
21 #include <grp.h>
23 #include "helpers.h"
26 * Helpers to replace system() calls
29 int makepath(char *p)
31 char *x, path[PATH_MAX];
32 int ret;
34 x = path;
36 do {
37 do { *x++ = *p++; } while (*p && *p != '/');
38 *x = 0;
39 ret = mkdir(path, 0777);
40 } while (*p && (*p != '/' || *(p + 1))); /* ignore trailing slash */
42 return ret;
45 #define BUF_SIZE 4096
47 void copyfile(char *src, char *dst, int size)
49 char buffer[BUF_SIZE];
50 int s, d, n;
52 /* Size == 0 means copy entire file */
53 if (size == 0)
54 size = INT_MAX;
56 if ((s = open(src, O_RDONLY)) >= 0) {
57 if ((d = open(dst, O_WRONLY | O_CREAT, 0644)) >= 0) {
58 do {
59 int csize = size > BUF_SIZE ? BUF_SIZE : size;
61 if ((n = read(s, buffer, csize)) > 0)
62 write(d, buffer, n);
63 size -= csize;
64 } while (size > 0 && n == BUF_SIZE);
65 close(d);
67 close(s);
71 #ifdef BUILTIN_RUNPARTS
73 #define NUM_SCRIPTS 128 /* ought to be enough for anyone */
74 #define NUM_ARGS 16
76 static int cmp(const void *s1, const void *s2)
78 return strcmp(*(char **)s1, *(char **)s2);
81 int run_parts(char *dir, ...)
83 DIR *d;
84 struct dirent *e;
85 struct stat st;
86 char *ent[NUM_SCRIPTS];
87 int i, num = 0, argnum = 1;
88 char *args[NUM_ARGS];
89 va_list ap;
91 if (chdir(dir))
92 return -1;
94 if ((d = opendir(dir)) == NULL)
95 return -1;
97 va_start(ap, dir);
98 while (argnum < NUM_ARGS && (args[argnum++] = va_arg(ap, char *)));
99 va_end(ap);
101 while ((e = readdir(d))) {
102 if (e->d_type == DT_REG && stat(e->d_name, &st) == 0) {
103 if (st.st_mode & S_IXUSR) {
104 ent[num++] = strdup(e->d_name);
105 if (num >= NUM_SCRIPTS)
106 break;
111 closedir(d);
113 if (num == 0)
114 return 0;
116 qsort(ent, num, sizeof(char *), cmp);
118 for (i = 0; i < num; i++) {
119 args[0] = ent[i];
120 if (!fork()) {
121 execv(ent[i], args);
122 exit(0);
124 wait(NULL);
125 free(ent[i]);
128 return 0;
131 int getgroup(char *s)
133 struct group *grp;
135 if ((grp = getgrnam(s)) == NULL)
136 return -1;
138 return grp->gr_gid;
141 #endif