-
Notifications
You must be signed in to change notification settings - Fork 0
/
dirReader.c
343 lines (273 loc) · 9.14 KB
/
dirReader.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h> // directory abstraction (DIR struct)
#include <errno.h>
// #include <math.h>
#include <sys/types.h> // types and stat for open
#include <sys/stat.h> // stat means status
// #include <fcntl.h>
#include <sys/wait.h> // waitpid
#include "dirReader.h"
/*
API functions:
1. read definitive directory contents and save to file
2. take in typerBuffer content and fuzzy filter
the contents of said file, return as string or
save to new file. --> see fzfTest
3. if saving to file, a function to read it and return
a string to driver file
*/
/*
Questions:
1. Should this file handle the file descriptors?
Pipe obviously it must handle itself, but what
about passing a file descriptor of the storage
files that must be handled?
I currently lean towards having this file handle
the files entirely itself. The driver file should
only concern itself with getting the string results.
2. I actually don't need to save to a file. But should I?
I don't know the size that the output will be
(the size of their directory, that is), so this
shouldn't be statically allocated
(or I can statically allocate max space).
So dynamically allocate (ew) or save to a file.
I think saving to file and reading with `cat file`
to stdout will be easier.
Remote code execution? Filter takes things quite
literally into its search bar. Most dangerous thing
would be to delete user's file. Don't think that
can happen, but I'm not a security professional.
3. Should driver file know the name of the file(s)?
Can't decide.
*/
// FILENAME_MAX defined as 4096 in stdio. This is... too much.
// https://stackoverflow.com/questions/3437404/min-and-max-in-c
// C doesn't have min and max by default. Forgot that detail.
// #define max(a,b) \
// ({ \
// __typeof__ (a) _a = (a); \
// __typeof__ (b) _b = (b); \
// _a > _b ? _a : _b; \
// })
// #define min(a,b) \
// ({ \
// __typeof__ (a) _a = (a); \
// __typeof__ (b) _b = (b); \
// _a < _b ? _a : _b; \
})
// int dirview_readdir();
// int dirview_filterdir(const char *);
// #define FILE_NAME_LEN 256
// #define DIRENT_NAME_LEN 256
// #define FILTER_LEN 128
// #define DIR_TEXT_NAME ("./dircontents.txt")
// #define DIR_TEXT_NAME_FILTERED ("./dircontentsfilt.txt")
// assume for now, save to file called "dir"
// assume local position for now `./`
int dirview_readdir()
{
DIR *d = opendir("./");
if (d == NULL)
{
return -1;
}
struct dirent *dir;
char thisFileName[FILE_NAME_LEN]; // max length name we could print
memset(thisFileName, 0, FILE_NAME_LEN * sizeof(char));
// O_TRUNC shortens file
// int fd = open("dircontents.txt", O_RDWR | O_CLOEXEC | O_CREAT | O_TRUNC, S_IRWXU);
FILE *f = fopen(DIR_TEXT_NAME, "w");
// can use temp file, but it closes upon fclose
// may write different chain where these functions are passed a FILE stream
// this is probably better than using system calls and cat. Just read and write from stream instead.
// FILE *f = tmpfile(); // opens in read-write
if (f == NULL)
{
perror("dir text file open failed");
}
while ( (dir = readdir(d)) != NULL )
{
size_t len = strnlen(dir->d_name, DIRENT_NAME_LEN); // see dirent definition, 256 bytes
// question: copying over len will ignore \0. Consider implications.
size_t numToCopy = len < FILE_NAME_LEN ? len : FILE_NAME_LEN;
memcpy(thisFileName, dir->d_name, numToCopy * sizeof(char)); // note: memcpy when fields non-overlapping, see man page
// 1. use open (a system call). Maybe slower, maybe not portable
// write(fd, thisFileName, numToCopy);
// write(fd, "\n", 1);
// 2a. FILE write, know how many chars to write
fwrite(thisFileName, sizeof(char), numToCopy, f);
fwrite("\n", sizeof(char), 1, f);
// 2b. use print f, but have to zero out memory each time
// fprintf(f, "%s\n", thisFileName);
// memset(thisFileName, 0, FILE_NAME_LEN);
}
// fwrite("\0", sizeof(char), 1, f);
closedir(d);
fclose(f);
// close(fd);
return EXIT_SUCCESS;
}
int dirview_filterdir(char *filter)
{
errno = 0;
int fd_read_write[2] = {0, 0};
int p = pipe(fd_read_write);
if (p == -1)
{
perror("pipe failed");
_exit(EXIT_FAILURE);
}
pid_t pid = fork();
if (pid == -1)
{
perror("fork failed");
_exit(EXIT_FAILURE);
}
if (pid == 0) // child
{
// close read-end
// alter write-end to be STDOUT file number (dup2)
// close write-end of pipe
// exec
// child runs this command, prints contents of file,
// sent to stdout
// replace with system-agnostic method?
char *args[] = {"cat", DIR_TEXT_NAME, NULL};
p = close(fd_read_write[0]);
if (p == -1)
{
perror("child pipe read close failed");
_exit(EXIT_FAILURE);
}
p = dup2(fd_read_write[1], STDOUT_FILENO);
if (p == -1)
{
perror("child dup2 on pipe write end failed");
_exit(EXIT_FAILURE);
}
p = close(fd_read_write[1]);
if (p == -1)
{
perror("child pipe write end close failed");
_exit(EXIT_FAILURE);
}
p = execvp(args[0], args);
// only here if exec failed
perror("child exec did not run");
_exit(EXIT_FAILURE);
}
else // parent
{
// close write-end
// alter read-end to be STDIN file number (dup2)
// close read-end of pipe
// exec
// Wait for child to finish their sending first,
// so I don't read empty
p = close(fd_read_write[1]);
if (p == -1)
{
perror("parent write end pipe closed failed");
}
p = dup2(fd_read_write[0], STDIN_FILENO);
if (p == -1)
{
perror("parent dup2 on read end failed");
}
p = close(fd_read_write[0]);
if (p == -1)
{
perror("parent read end pipe close failed");
}
int status = 0;
// int wstatus = 0;
// waitpid(pid, &status, WIFEXITED(wstatus));
wait(&status);
char filterBuf[FILTER_LEN];
memset(filterBuf, 0, FILTER_LEN * sizeof(char));
// can't use quotes around it, i.e. "--filter=\"%s\""
// Good and bad. BASH is the one usually being helpful with quotes, but
// running exec isn't doing bash.
// However, exec doesn't care if there are spaces in the arguments,
// the arguments are already parsed and split!! So it will
// still assume it is part of the current argument (filter).
snprintf(filterBuf, FILTER_LEN, "--filter=%s", filter);
char *args[] = {"fzf", filterBuf, NULL};
pid_t pid2 = fork();
if (pid2 == 0)
{
FILE *filterOutFile = fopen(DIR_TEXT_NAME_FILTERED, "w+");
int fd = fileno(filterOutFile);
// don't need pipe! Pipe seems just for communication across processes
dup2(fd, STDOUT_FILENO);
close(fd);
fclose(filterOutFile);
execvp(args[0], args);
_exit(EXIT_FAILURE);
}
else
{
status = 0;
// wstatus = 0;
// waitpid(pid2, &status, WIFEXITED(wstatus));
wait(&status);
}
}
return EXIT_SUCCESS;
}
// https://stackoverflow.com/questions/174531/how-to-read-the-content-of-a-file-to-a-string-in-c
// getdelim function, pass NULL buffer.
/**
* @brief Given a file named in DIR_TEXT_NAME_FILTERED,
* read it and return it as a malloc'd string.
*
* @warning Free returned string after use.
*
* @return char* Single string representing the filtered
* contents of the current directory.
*/
char *dirview_readfilter()
{
FILE *filterFile = fopen(DIR_TEXT_NAME_FILTERED, "r");
char *buffer = NULL;
size_t len = 0;
ssize_t bytes_read = getdelim(
&buffer,
&len,
'\0',
filterFile
);
fclose(filterFile);
// printf("bytes read: %zd\n", bytes_read);
if (bytes_read == -1)
{
// it still mallocs something even if there's nothing
free(buffer);
buffer = malloc(sizeof(char) * 1);
buffer[0] = '\0';
}
return buffer;
}
#ifndef DIRVIEW_LINKED
// remove main
int main(int argc, char *argv[])
{
/* code */
dirview_readdir();
dirview_filterdir(argv[1]);
char *buf = dirview_readfilter();
// printf("%p\n", buf);
printf("Here are the results:\n%s\n", buf);
// for (int i = 0; *(buf+i) != '\0'; ++i)
// {
// // putc(*(buf+i), stdout);
// printf("_%d_", *(buf+i));
// }
// printf("%s---\n", *buf);
free(buf);
return 0;
}
#endif