1 
2 #define _GNU_SOURCE
3 
4 #include <stdio.h>
5 #include <string.h>
6 #include <stdlib.h>
7 #include <unistd.h>
8 #include <sys/wait.h>
9 
10 #include "meh.h"
11 
imagemagick_open(FILE * f)12 struct image *imagemagick_open(FILE *f){
13 	int tmpfd[2];
14 	if(pipe(tmpfd)){
15 		perror("pipe");
16 		exit(EXIT_FAILURE);
17 	}
18 
19 	int pid;
20 	if(!(pid = fork())){
21 		close(tmpfd[0]);
22 		int origfd = fileno(f);
23 		if(lseek(origfd, 0, SEEK_SET) != 0){
24 			perror("lseek");
25 			exit(EXIT_FAILURE);
26 		}
27 
28 		char *argv[6];
29 
30 		argv[0] = "convert";
31 		argv[1] = "-depth";
32 		argv[2] = "255";
33 		if((asprintf(&argv[3], "fd:%i", origfd) < 0) || (asprintf(&argv[4], "ppm:fd:%i", tmpfd[1]) < 0)){
34 			fprintf(stderr, "Out of memory");
35 			exit(EXIT_FAILURE);
36 		}
37 		argv[5] = NULL;
38 
39 #ifdef NDEBUG
40 		/* STFU OMFG */
41 		FILE *unused __attribute__((unused));
42 		unused = freopen("/dev/null", "w", stdout);
43 		unused = freopen("/dev/null", "w", stderr);
44 #endif
45 
46 		execvp(argv[0], argv);
47 
48 		perror("exec");
49 		exit(EXIT_FAILURE);
50 	}else{
51 		close(tmpfd[1]);
52 		FILE *ftmp;
53 		if(!(ftmp = fdopen(tmpfd[0], "rb"))){
54 			perror("fopen");
55 			exit(EXIT_FAILURE);
56 		}
57 		struct image *img = netpbm.open(ftmp);
58 		if(!img)
59 			return NULL;
60 		fclose(f);
61 		return img;
62 	}
63 }
64 
65 struct imageformat imagemagick = {
66 	imagemagick_open,
67 	NULL,
68 	NULL,
69 	NULL
70 };
71 
72