masqmail-0.2
view src/peopen.c @ 28:71605f542ecc
flattened conditional nesting
author | meillo@marmaro.de |
---|---|
date | Thu, 06 May 2010 11:52:34 +0200 |
parents | f671821d8222 |
children | 7cdd30429cc9 |
line source
1 /* This a snippet I found in sourceforge. I just changed the identing
2 style to my own and deleted the main function. */
4 #include <errno.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <unistd.h>
8 #include <string.h>
9 #include <sys/types.h>
10 #include <sysexits.h>
12 #include "peopen.h"
13 #include "masqmail.h"
15 static void
16 destroy_argv(char **arr)
17 {
18 char *p = arr[0];
19 int i = 0;
21 while (p) {
22 free(p);
23 p = arr[i++];
24 }
25 free(arr);
26 }
28 static char**
29 create_argv(const char *cmd, int count)
30 {
31 char buf[strlen(cmd) + 1];
32 char **arr, *q;
33 const char *p;
34 int i = 0;
36 arr = (char **) g_malloc(sizeof(char *) * count);
38 p = cmd;
39 while (*p && i < (count - 1)) {
40 while (*p && isspace(*p))
41 p++;
42 q = buf;
43 while (*p && !isspace(*p))
44 *q++ = *p++;
45 *q = '\0';
46 arr[i++] = strdup(buf);
47 while (*p && isspace(*p))
48 p++;
49 }
50 arr[i] = NULL;
52 return arr;
53 }
55 FILE*
56 peidopen(const char *command, const char *type, char *const envp[], int *ret_pid, uid_t uid, gid_t gid)
57 {
58 enum { Read, Write } mode;
59 int pipe_fd[2];
60 pid_t pid;
62 if (command == NULL || type == NULL) {
63 errno = EINVAL;
64 return NULL;
65 }
67 if (strcmp(type, "r")) {
68 if (strcmp(type, "w")) {
69 errno = EINVAL;
70 return NULL;
71 } else
72 mode = Write;
73 } else
74 mode = Read;
76 if (pipe(pipe_fd) == -1)
77 return NULL;
79 switch (pid = fork()) {
80 case 0: /* child thread */
82 {
83 int i, max_fd = sysconf(_SC_OPEN_MAX);
85 if (max_fd <= 0)
86 max_fd = 64;
87 for (i = 0; i < max_fd; i++)
88 if ((i != pipe_fd[0]) && (i != pipe_fd[1]))
89 close(i);
90 }
91 if (close(pipe_fd[mode == Read ? 0 : 1]) != -1 &&
92 dup2(pipe_fd[mode == Read ? 1 : 0],
93 mode == Read ? STDOUT_FILENO : STDIN_FILENO) != -1) {
94 // char *argv [] = { "/bin/sh", "-c", (char*) command, NULL };
95 char **argv = create_argv(command, 10);
96 int ret;
98 if (uid != (uid_t) - 1) {
99 if ((ret = seteuid(0)) != 0) {
100 exit(EX_NOPERM);
101 }
102 }
103 if (gid != (gid_t) - 1) {
104 if ((ret = setgid(gid)) != 0) {
105 exit(EX_NOPERM);
106 }
107 }
108 if (uid != (uid_t) - 1) {
109 if ((ret = setuid(uid)) != 0) {
110 exit(EX_NOPERM);
111 }
112 }
113 execve(*argv, argv, envp);
114 }
116 _exit(errno);
118 default: /* parent thread */
119 *ret_pid = pid;
120 close(pipe_fd[mode == Read ? 1 : 0]);
121 return fdopen(pipe_fd[mode == Read ? 0 : 1], type);
123 case -1:
124 close(pipe_fd[0]);
125 close(pipe_fd[1]);
126 return NULL;
127 }
128 }
130 FILE*
131 peopen(const char *command, const char *type, char *const envp[], int *ret_pid)
132 {
133 return peidopen(command, type, envp, ret_pid, -1, -1);
134 }