1 /* stdbuf -- setup the standard streams for a command
2    Copyright (C) 2009-2018 Free Software Foundation, Inc.
3 
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8 
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13 
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <https://www.gnu.org/licenses/>.  */
16 
17 /* Written by Pádraig Brady.  */
18 
19 #include <config.h>
20 #include <stdio.h>
21 #include <getopt.h>
22 #include <sys/types.h>
23 #include <assert.h>
24 
25 #include "system.h"
26 #include "die.h"
27 #include "error.h"
28 #include "filenamecat.h"
29 #include "quote.h"
30 #include "xreadlink.h"
31 #include "xstrtol.h"
32 #include "c-ctype.h"
33 
34 /* The official name of this program (e.g., no 'g' prefix).  */
35 #define PROGRAM_NAME "stdbuf"
36 #define LIB_NAME "libstdbuf.so" /* FIXME: don't hardcode  */
37 
38 #define AUTHORS proper_name ("Padraig Brady")
39 
40 static char *program_path;
41 
42 static struct
43 {
44   size_t size;
45   int optc;
46   char *optarg;
47 } stdbuf[3];
48 
49 static struct option const longopts[] =
50 {
51   {"input", required_argument, NULL, 'i'},
52   {"output", required_argument, NULL, 'o'},
53   {"error", required_argument, NULL, 'e'},
54   {GETOPT_HELP_OPTION_DECL},
55   {GETOPT_VERSION_OPTION_DECL},
56   {NULL, 0, NULL, 0}
57 };
58 
59 /* Set size to the value of STR, interpreted as a decimal integer,
60    optionally multiplied by various values.
61    Return -1 on error, 0 on success.
62 
63    This supports dd BLOCK size suffixes.
64    Note we don't support dd's b=512, c=1, w=2 or 21x512MiB formats.  */
65 static int
parse_size(char const * str,size_t * size)66 parse_size (char const *str, size_t *size)
67 {
68   uintmax_t tmp_size;
69   enum strtol_error e = xstrtoumax (str, NULL, 10, &tmp_size, "EGkKMPTYZ0");
70   if (e == LONGINT_OK && SIZE_MAX < tmp_size)
71     e = LONGINT_OVERFLOW;
72 
73   if (e == LONGINT_OK)
74     {
75       errno = 0;
76       *size = tmp_size;
77       return 0;
78     }
79 
80   errno = (e == LONGINT_OVERFLOW ? EOVERFLOW : errno);
81   return -1;
82 }
83 
84 void
usage(int status)85 usage (int status)
86 {
87   if (status != EXIT_SUCCESS)
88     emit_try_help ();
89   else
90     {
91       printf (_("Usage: %s OPTION... COMMAND\n"), program_name);
92       fputs (_("\
93 Run COMMAND, with modified buffering operations for its standard streams.\n\
94 "), stdout);
95 
96       emit_mandatory_arg_note ();
97 
98       fputs (_("\
99   -i, --input=MODE   adjust standard input stream buffering\n\
100   -o, --output=MODE  adjust standard output stream buffering\n\
101   -e, --error=MODE   adjust standard error stream buffering\n\
102 "), stdout);
103       fputs (HELP_OPTION_DESCRIPTION, stdout);
104       fputs (VERSION_OPTION_DESCRIPTION, stdout);
105       fputs (_("\n\
106 If MODE is 'L' the corresponding stream will be line buffered.\n\
107 This option is invalid with standard input.\n"), stdout);
108       fputs (_("\n\
109 If MODE is '0' the corresponding stream will be unbuffered.\n\
110 "), stdout);
111       fputs (_("\n\
112 Otherwise MODE is a number which may be followed by one of the following:\n\
113 KB 1000, K 1024, MB 1000*1000, M 1024*1024, and so on for G, T, P, E, Z, Y.\n\
114 In this case the corresponding stream will be fully buffered with the buffer\n\
115 size set to MODE bytes.\n\
116 "), stdout);
117       fputs (_("\n\
118 NOTE: If COMMAND adjusts the buffering of its standard streams ('tee' does\n\
119 for example) then that will override corresponding changes by 'stdbuf'.\n\
120 Also some filters (like 'dd' and 'cat' etc.) don't use streams for I/O,\n\
121 and are thus unaffected by 'stdbuf' settings.\n\
122 "), stdout);
123       emit_ancillary_info (PROGRAM_NAME);
124     }
125   exit (status);
126 }
127 
128 /* argv[0] can be anything really, but generally it contains
129    the path to the executable or just a name if it was executed
130    using $PATH. In the latter case to get the path we can:
131    search getenv("PATH"), readlink("/prof/self/exe"), getenv("_"),
132    dladdr(), pstat_getpathname(), etc.  */
133 
134 static void
set_program_path(const char * arg)135 set_program_path (const char *arg)
136 {
137   if (strchr (arg, '/'))        /* Use absolute or relative paths directly.  */
138     {
139       program_path = dir_name (arg);
140     }
141   else
142     {
143       char *path = xreadlink ("/proc/self/exe");
144       if (path)
145         program_path = dir_name (path);
146       else if ((path = getenv ("PATH")))
147         {
148           char *dir;
149           path = xstrdup (path);
150           for (dir = strtok (path, ":"); dir != NULL; dir = strtok (NULL, ":"))
151             {
152               char *candidate = file_name_concat (dir, arg, NULL);
153               if (access (candidate, X_OK) == 0)
154                 {
155                   program_path = dir_name (candidate);
156                   free (candidate);
157                   break;
158                 }
159               free (candidate);
160             }
161         }
162       free (path);
163     }
164 }
165 
166 static int
optc_to_fileno(int c)167 optc_to_fileno (int c)
168 {
169   int ret = -1;
170 
171   switch (c)
172     {
173     case 'e':
174       ret = STDERR_FILENO;
175       break;
176     case 'i':
177       ret = STDIN_FILENO;
178       break;
179     case 'o':
180       ret = STDOUT_FILENO;
181       break;
182     }
183 
184   return ret;
185 }
186 
187 static void
set_LD_PRELOAD(void)188 set_LD_PRELOAD (void)
189 {
190   int ret;
191 #ifdef __APPLE__
192   char const *preload_env = "DYLD_INSERT_LIBRARIES";
193 #else
194   char const *preload_env = "LD_PRELOAD";
195 #endif
196   char *old_libs = getenv (preload_env);
197   char *LD_PRELOAD;
198 
199   /* Note this would auto add the appropriate search path for "libstdbuf.so":
200      gcc stdbuf.c -Wl,-rpath,'$ORIGIN' -Wl,-rpath,$PKGLIBEXECDIR
201      However we want the lookup done for the exec'd command not stdbuf.
202 
203      Since we don't link against libstdbuf.so add it to PKGLIBEXECDIR
204      rather than to LIBDIR.
205 
206      Note we could add "" as the penultimate item in the following list
207      to enable searching for libstdbuf.so in the default system lib paths.
208      However that would not indicate an error if libstdbuf.so was not found.
209      Also while this could support auto selecting the right arch in a multilib
210      environment, what we really want is to auto select based on the arch of the
211      command being run, rather than that of stdbuf itself.  This is currently
212      not supported due to the unusual need for controlling the stdio buffering
213      of programs that are a different architecture to the default on the
214      system (and that of stdbuf itself).  */
215   char const *const search_path[] = {
216     program_path,
217     PKGLIBEXECDIR,
218     NULL
219   };
220 
221   char const *const *path = search_path;
222   char *libstdbuf;
223 
224   while (true)
225     {
226       struct stat sb;
227 
228       if (!**path)              /* system default  */
229         {
230           libstdbuf = xstrdup (LIB_NAME);
231           break;
232         }
233       ret = asprintf (&libstdbuf, "%s/%s", *path, LIB_NAME);
234       if (ret < 0)
235         xalloc_die ();
236       if (stat (libstdbuf, &sb) == 0)   /* file_exists  */
237         break;
238       free (libstdbuf);
239 
240       ++path;
241       if ( ! *path)
242         die (EXIT_CANCELED, 0, _("failed to find %s"), quote (LIB_NAME));
243     }
244 
245   /* FIXME: Do we need to support libstdbuf.dll, c:, '\' separators etc?  */
246 
247   if (old_libs)
248     ret = asprintf (&LD_PRELOAD, "%s=%s:%s", preload_env, old_libs, libstdbuf);
249   else
250     ret = asprintf (&LD_PRELOAD, "%s=%s", preload_env, libstdbuf);
251 
252   if (ret < 0)
253     xalloc_die ();
254 
255   free (libstdbuf);
256 
257   ret = putenv (LD_PRELOAD);
258 #ifdef __APPLE__
259   if (ret == 0)
260     ret = setenv ("DYLD_FORCE_FLAT_NAMESPACE", "y", 1);
261 #endif
262 
263   if (ret != 0)
264     {
265       die (EXIT_CANCELED, errno,
266            _("failed to update the environment with %s"),
267            quote (LD_PRELOAD));
268     }
269 }
270 
271 /* Populate environ with _STDBUF_I=$MODE _STDBUF_O=$MODE _STDBUF_E=$MODE.
272    Return TRUE if any environment variables set.   */
273 
274 static bool
set_libstdbuf_options(void)275 set_libstdbuf_options (void)
276 {
277   bool env_set = false;
278 
279   for (size_t i = 0; i < ARRAY_CARDINALITY (stdbuf); i++)
280     {
281       if (stdbuf[i].optarg)
282         {
283           char *var;
284           int ret;
285 
286           if (*stdbuf[i].optarg == 'L')
287             ret = asprintf (&var, "%s%c=L", "_STDBUF_",
288                             toupper (stdbuf[i].optc));
289           else
290             ret = asprintf (&var, "%s%c=%" PRIuMAX, "_STDBUF_",
291                             toupper (stdbuf[i].optc),
292                             (uintmax_t) stdbuf[i].size);
293           if (ret < 0)
294             xalloc_die ();
295 
296           if (putenv (var) != 0)
297             {
298               die (EXIT_CANCELED, errno,
299                    _("failed to update the environment with %s"),
300                    quote (var));
301             }
302 
303           env_set = true;
304         }
305     }
306 
307   return env_set;
308 }
309 
310 int
main(int argc,char ** argv)311 main (int argc, char **argv)
312 {
313   int c;
314 
315   initialize_main (&argc, &argv);
316   set_program_name (argv[0]);
317   setlocale (LC_ALL, "");
318   bindtextdomain (PACKAGE, LOCALEDIR);
319   textdomain (PACKAGE);
320 
321   initialize_exit_failure (EXIT_CANCELED);
322   atexit (close_stdout);
323 
324   while ((c = getopt_long (argc, argv, "+i:o:e:", longopts, NULL)) != -1)
325     {
326       int opt_fileno;
327 
328       switch (c)
329         {
330         /* Old McDonald had a farm ei...  */
331         case 'e':
332         case 'i':
333         case 'o':
334           opt_fileno = optc_to_fileno (c);
335           assert (0 <= opt_fileno && opt_fileno < ARRAY_CARDINALITY (stdbuf));
336           stdbuf[opt_fileno].optc = c;
337           while (c_isspace (*optarg))
338             optarg++;
339           stdbuf[opt_fileno].optarg = optarg;
340           if (c == 'i' && *optarg == 'L')
341             {
342               /* -oL will be by far the most common use of this utility,
343                  but one could easily think -iL might have the same affect,
344                  so disallow it as it could be confusing.  */
345               error (0, 0, _("line buffering stdin is meaningless"));
346               usage (EXIT_CANCELED);
347             }
348 
349           if (!STREQ (optarg, "L")
350               && parse_size (optarg, &stdbuf[opt_fileno].size) == -1)
351             die (EXIT_CANCELED, errno, _("invalid mode %s"), quote (optarg));
352 
353           break;
354 
355         case_GETOPT_HELP_CHAR;
356 
357         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
358 
359         default:
360           usage (EXIT_CANCELED);
361         }
362     }
363 
364   argv += optind;
365   argc -= optind;
366 
367   /* must specify at least 1 command.  */
368   if (argc < 1)
369     {
370       error (0, 0, _("missing operand"));
371       usage (EXIT_CANCELED);
372     }
373 
374   if (! set_libstdbuf_options ())
375     {
376       error (0, 0, _("you must specify a buffering mode option"));
377       usage (EXIT_CANCELED);
378     }
379 
380   /* Try to preload libstdbuf first from the same path as
381      stdbuf is running from.  */
382   set_program_path (program_name);
383   if (!program_path)
384     program_path = xstrdup (PKGLIBDIR);  /* Need to init to non-NULL.  */
385   set_LD_PRELOAD ();
386   free (program_path);
387 
388   execvp (*argv, argv);
389 
390   int exit_status = errno == ENOENT ? EXIT_ENOENT : EXIT_CANNOT_INVOKE;
391   error (0, errno, _("failed to run command %s"), quote (argv[0]));
392   return exit_status;
393 }
394