home *** CD-ROM | disk | FTP | other *** search
/ Nebula / nebula.bin / Documents / FAQ / Unix / Unix.faq4 < prev    next >
Text File  |  1993-01-27  |  22KB  |  530 lines

  1. Archive-name: unix-faq/part4
  2. Version: $Id: part4,v 1.4 92/03/19 14:07:51 tmatimar Exp $
  3.  
  4. These four articles contain the answers to some Frequently Asked
  5. Questions often seen in comp.unix.questions and comp.unix.shell.
  6. Please don't ask these questions again, they've been answered plenty
  7. of times already - and please don't flame someone just because they may
  8. not have read this particular posting.  Thank you.
  9.  
  10. These articles are divided approximately as follows:
  11.  
  12.       1.*) General questions.
  13.       2.*) Relatively basic questions, likely to be asked by beginners.
  14.       3.*) Intermediate questions.
  15.       4.*) Advanced questions, likely to be asked by people who thought
  16.        they already knew all of the answers.
  17.  
  18. This article includes answers to:
  19.  
  20.       4.1)  How do I read characters from a terminal without requiring the user
  21.               to hit RETURN?
  22.       4.2)  How do I check to see if there are characters to be read without
  23.               actually reading?
  24.       4.3)  How do I find the name of an open file?
  25.       4.4)  How can an executing program determine its own pathname?
  26.       4.5)  How do I use popen() to open a process for reading AND writing?
  27.       4.6)  How do I sleep() in a C program for less than one second?
  28.       4.7)  How can I get setuid shell scripts to work?
  29.       4.8)  How can I find out which user or process has a file open or is using
  30.             a particular file system (so that I can unmount it?)
  31.       4.9)  How do I keep track of people who are fingering me?
  32.       4.10) Is it possible to reconnect a process to a terminal after it has
  33.             been disconnected, e.g. after starting a program in the background
  34.             and logging out?
  35.       4.11) Is it possible to "spy" on a terminal, displaying the output
  36.             that's appearing on it on another terminal?
  37.  
  38.     If you're looking for the answer to, say, question 4.5, and want to skip
  39.     everything else, you can search ahead for the regular expression "^5)".
  40.  
  41. While these are all legitimate questions, they seem to crop up in
  42. comp.unix.questions on an annual basis, usually followed by plenty
  43. of replies (only some of which are correct) and then a period of
  44. griping about how the same questions keep coming up.  You may also like
  45. to read the monthly article "Answers to Frequently Asked Questions"
  46. in the newsgroup "news.announce.newusers", which will tell you what
  47. "UNIX" stands for.
  48.  
  49. With the variety of Unix systems in the world, it's hard to guarantee
  50. that these answers will work everywhere.  Read your local manual pages
  51. before trying anything suggested here.  If you have suggestions or
  52. corrections for any of these answers, please send them to to
  53. tmatimar@nff.ncl.omron.co.jp.
  54.  
  55. 1)  How do I read characters from a terminal without requiring the user
  56.     to hit RETURN?
  57.  
  58.     Check out cbreak mode in BSD, ~ICANON mode in SysV.
  59.  
  60.     If you don't want to tackle setting the terminal parameters
  61.     yourself (using the "ioctl(2)" system call) you can let the stty
  62.     program do the work - but this is slow and inefficient, and you
  63.     should change the code to do it right some time:
  64.  
  65.     #include <stdio.h>
  66.     main()
  67.     {
  68.         int c;
  69.  
  70.         printf("Hit any character to continue\n");
  71.         /*
  72.          * ioctl() would be better here; only lazy
  73.          * programmers do it this way:
  74.          */
  75.         system("/bin/stty cbreak");        /* or "stty raw" */
  76.         c = getchar();
  77.         system("/bin/stty -cbreak");
  78.         printf("Thank you for typing %c.\n", c);
  79.  
  80.         exit(0);
  81.     }
  82.  
  83.     You might like to check out the documentation for the "curses"
  84.     library of portable screen functions.  Often if you're interested
  85.     in single-character I/O like this, you're also interested in doing
  86.     some sort of screen display control, and the curses library
  87.     provides various portable routines for both functions.
  88.  
  89. 2)  How do I check to see if there are characters to be read without
  90.     actually reading?
  91.  
  92.     Certain versions of UNIX provide ways to check whether
  93.     characters are currently available to be read from a file
  94.     descriptor.  In BSD, you can use select(2).  You can also use
  95.     the FIONREAD ioctl (see tty(4)), which returns the number of
  96.     characters waiting to be read, but only works on terminals,
  97.     pipes and sockets.  In System V Release 3, you can use poll(2),
  98.     but that only works on streams.  In Xenix - and therefore
  99.     Unix SysV r3.2 and later - the rdchk() system call reports
  100.     whether a read() call on a given file descriptor will block.
  101.  
  102.     There is no way to check whether characters are available to be
  103.     read from a FILE pointer.  (You could poke around inside stdio data
  104.     structures to see if the input buffer is nonempty, but that wouldn't
  105.     work since you'd have no way of knowing what will happen the next
  106.     time you try to fill the buffer.)
  107.  
  108.     Sometimes people ask this question with the intention of writing
  109.         if (characters available from fd)
  110.             read(fd, buf, sizeof buf);
  111.     in order to get the effect of a nonblocking read.  This is not the
  112.     best way to do this, because it is possible that characters will
  113.     be available when you test for availability, but will no longer
  114.     be available when you call read.  Instead, set the O_NDELAY flag
  115.     (which is also called FNDELAY under BSD) using the F_SETFL option
  116.     of fcntl(2).  Older systems (Version 7, 4.1 BSD) don't have O_NDELAY;
  117.     on these systems the closest you can get to a nonblocking read is
  118.     to use alarm(2) to time out the read.
  119.  
  120. 3)  How do I find the name of an open file?
  121.  
  122.     In general, this is too difficult.  The file descriptor may
  123.     be attached to a pipe or pty, in which case it has no name.
  124.     It may be attached to a file that has been removed.  It may
  125.     have multiple names, due to either hard or symbolic links.
  126.  
  127.     If you really need to do this, and be sure you think long
  128.     and hard about it and have decided that you have no choice,
  129.     you can use find with the -inum and possibly -xdev option,
  130.     or you can use ncheck, or you can recreate the functionality
  131.     of one of these within your program.  Just realize that
  132.     searching a 600 megabyte filesystem for a file that may not
  133.     even exist is going to take some time.
  134.  
  135. 4)  How can an executing program determine its own pathname?
  136.  
  137.     Your program can look at argv[0]; if it begins with a "/",
  138.     it is probably the absolute pathname to your program, otherwise
  139.     your program can look at every directory named in the environment
  140.     variable PATH and try to find the first one that contains an
  141.     executable file whose name matches your program's argv[0]
  142.     (which by convention is the name of the file being executed).
  143.     By concatenating that directory and the value of argv[0] you'd
  144.     probably have the right name.
  145.  
  146.     You can't really be sure though, since it is quite legal for one
  147.     program to exec() another with any value of argv[0] it desires.
  148.     It is merely a convention that new programs are exec'd with the
  149.     executable file name in argv[0].
  150.  
  151.     For instance, purely a hypothetical example:
  152.     
  153.     #include <stdio.h>
  154.     main()
  155.     {
  156.         execl("/usr/games/rogue", "vi Thesis", (char *)NULL);
  157.     }
  158.  
  159.     The executed program thinks its name (its argv[0] value) is
  160.     "vi Thesis".   (Certain other programs might also think that
  161.     the name of the program you're currently running is "vi Thesis",
  162.     but of course this is just a hypothetical example, don't
  163.     try it yourself :-)
  164.  
  165. 5)  How do I use popen() to open a process for reading AND writing?
  166.  
  167.     The problem with trying to pipe both input and output to an arbitrary
  168.     slave process is that deadlock can occur, if both processes are waiting
  169.     for not-yet-generated input at the same time.  Deadlock can be avoided
  170.     only by having BOTH sides follow a strict deadlock-free protocol, but
  171.     since that requires cooperation from the processes it is inappropriate
  172.     for a popen()-like library function.
  173.  
  174.     The 'expect' distribution includes a library of functions that a C
  175.     programmer can call directly.  One of the functions does the
  176.     equivalent of a popen for both reading and writing.  It uses ptys
  177.     rather than pipes, and has no deadlock problem.  It's portable to
  178.     both BSD and SV.  See the next answer for more about 'expect'.
  179.  
  180. 6)  How do I sleep() in a C program for less than one second?
  181.  
  182.     The first thing you need to be aware of is that all you can specify is a
  183.     MINIMUM amount of delay; the actual delay will depend on scheduling
  184.     issues such as system load, and could be arbitrarily large if you're
  185.     unlucky.
  186.  
  187.     There is no standard library function that you can count on in all
  188.     environments for "napping" (the usual name for short sleeps).
  189.     Some environments supply a "usleep(n)" function which suspends
  190.     execution for n microseconds.  If your environment doesn't support
  191.     usleep(), here are a couple of implementations for BSD and
  192.     System V environments.
  193.  
  194.     The following code is adapted from Doug Gwyn's System V emulation
  195.     support for 4BSD and exploits the 4BSD select() system call.
  196.     Doug originally called it 'nap()'; you probably want to call it
  197.     "usleep()";
  198.  
  199.     /*
  200.         usleep -- support routine for 4.2BSD system call emulations
  201.         last edit:    29-Oct-1984    D A Gwyn
  202.     */
  203.  
  204.     extern int    select();
  205.  
  206.     int
  207.     usleep( usec )                /* returns 0 if ok, else -1 */
  208.         long        usec;        /* delay in microseconds */
  209.         {
  210.         static struct            /* `timeval' */
  211.             {
  212.             long    tv_sec;        /* seconds */
  213.             long    tv_usec;    /* microsecs */
  214.             }    delay;        /* _select() timeout */
  215.  
  216.         delay.tv_sec = usec / 1000000L;
  217.         delay.tv_usec = usec % 1000000L;
  218.  
  219.         return select( 0, (long *)0, (long *)0, (long *)0, &delay );
  220.         }
  221.  
  222.     On System V you might do it this way:
  223.  
  224.     /*
  225.     subseconds sleeps for System V - or anything that has poll()
  226.     Don Libes, 4/1/1991
  227.  
  228.     The BSD analog to this function is defined in terms of microseconds
  229.     while poll() is defined in terms of milliseconds.  For compatibility,
  230.     this function provides accuracy "over the long run" by truncating
  231.     actual requests to milliseconds and accumulating microseconds across
  232.     calls with the idea that you are probably calling it in a tight loop,
  233.     and that over the long run, the error will even out.
  234.  
  235.     If you aren't calling it in a tight loop, then you almost certainly
  236.     aren't making microsecond-resolution requests anyway, in which case
  237.     you don't care about microseconds.  And if you did, you wouldn't be
  238.     using UNIX anyway because random system indigestion (i.e., scheduling)
  239.     can make mincemeat out of any timing code.
  240.  
  241.     Returns 0 if successful timeout, -1 if unsuccessful.
  242.  
  243.     */
  244.  
  245.     #include <poll.h>
  246.  
  247.     int
  248.     usleep(usec)
  249.     unsigned int usec;        /* microseconds */
  250.     {
  251.         static subtotal = 0;    /* microseconds */
  252.         int msec;            /* milliseconds */
  253.  
  254.         /* 'foo' is only here because some versions of 5.3 have
  255.          * a bug where the first argument to poll() is checked
  256.          * for a valid memory address even if the second argument is 0.
  257.          */
  258.         struct pollfd foo;
  259.  
  260.         subtotal += usec;
  261.         /* if less then 1 msec request, do nothing but remember it */
  262.         if (subtotal < 1000) return(0);
  263.         msec = subtotal/1000;
  264.         subtotal = subtotal%1000;
  265.         return poll(&foo,(unsigned long)0,msec);
  266.     }
  267.  
  268.     Another possibility for nap()ing on System V, and probably other
  269.     non-BSD Unices is Jon Zeeff's s5nap package, posted to
  270.     comp.sources.misc, volume 4.  It does require a installing
  271.     a device driver, but works flawlessly once installed.
  272.     (Its resolution is limited to the kernel HZ value, since it
  273.     uses the kernel delay() routine.)
  274.  
  275. 7)  How can I get setuid shell scripts to work?
  276.  
  277.     [ This is a long answer, but it's a complicated and frequently-asked
  278.       question.  Thanks to Maarten Litmaath for this answer, and
  279.       for the "indir" program mentioned below. ]
  280.  
  281.     Let us first assume you are on a UNIX variant (e.g. 4.3BSD or SunOS)
  282.     that knows about so-called `executable shell scripts'.  Such a script
  283.     must start with a line like:
  284.  
  285.     #!/bin/sh
  286.  
  287.     The script is called `executable' because just like a real (binary)
  288.     executable it starts with a so-called `magic number' indicating the
  289.     type of the executable.  In our case this number is `#!' and the OS
  290.     takes the rest of the first line as the interpreter for the script,
  291.     possibly followed by 1 initial option like:
  292.  
  293.     #!/bin/sed -f
  294.  
  295.     Suppose this script is called `foo' and is found in /bin,
  296.     then if you type:
  297.  
  298.     foo arg1 arg2 arg3
  299.  
  300.     the OS will rearrange things as though you had typed:
  301.  
  302.     /bin/sed -f /bin/foo arg1 arg2 arg3
  303.  
  304.     There is one difference though: if the setuid permission bit for
  305.     `foo' is set, it will be honored in the first form of the command;
  306.     if you really type the second form, the OS will honor the permission
  307.     bits of /bin/sed, which is not setuid, of course.
  308.  
  309.     ----------
  310.  
  311.     OK, but what if my shell script does NOT start with such a `#!' line
  312.     or my OS does not know about it?
  313.  
  314.     Well, if the shell (or anybody else) tries to execute it, the OS will
  315.     return an error indication, as the file does not start with a valid
  316.     magic number.  Upon receiving this indication the shell ASSUMES the
  317.     file to be a shell script and gives it another try:
  318.  
  319.     /bin/sh shell_script arguments
  320.  
  321.     But we have already seen that a setuid bit on `shell_script' will NOT
  322.     be honored in this case!
  323.  
  324.     ----------
  325.  
  326.     Right, but what about the security risks of setuid shell scripts?
  327.  
  328.     Well, suppose the script is called `/etc/setuid_script', starting
  329.     with:
  330.  
  331.     #!/bin/sh
  332.     
  333.     Now let us see what happens if we issue the following commands:
  334.  
  335.     $ cd /tmp
  336.     $ ln /etc/setuid_script -i
  337.     $ PATH=.
  338.     $ -i
  339.  
  340.     We know the last command will be rearranged to:
  341.  
  342.     /bin/sh -i
  343.  
  344.     But this command will give us an interactive shell, setuid to the
  345.     owner of the script!
  346.     Fortunately this security hole can easily be closed by making the
  347.     first line:
  348.  
  349.     #!/bin/sh -
  350.  
  351.     The `-' signals the end of the option list: the next argument `-i'
  352.     will be taken as the name of the file to read commands from, just
  353.     like it should!
  354.  
  355.     ---------
  356.  
  357.     There are more serious problems though:
  358.  
  359.     $ cd /tmp
  360.     $ ln /etc/setuid_script temp
  361.     $ nice -20 temp &
  362.     $ mv my_script temp
  363.  
  364.     The third command will be rearranged to:
  365.  
  366.     nice -20 /bin/sh - temp
  367.  
  368.     As this command runs so slowly, the fourth command might be able to
  369.     replace the original `temp' with `my_script' BEFORE `temp' is opened
  370.     by the shell!
  371.     There are 4 ways to fix this security hole:
  372.  
  373.     1)  let the OS start setuid scripts in a different, secure way
  374.         - System V R4 and 4.4BSD use the /dev/fd driver to pass the
  375.         interpreter a file descriptor for the script
  376.  
  377.     2)  let the script be interpreted indirectly, through a frontend
  378.         that makes sure everything is all right before starting the
  379.         real interpreter - if you use the `indir' program from
  380.         comp.sources.unix the setuid script will look like this:
  381.  
  382.         #!/bin/indir -u
  383.         #?/bin/sh /etc/setuid_script
  384.  
  385.     3)  make a `binary wrapper': a real executable that is setuid and
  386.         whose only task is to execute the interpreter with the name of
  387.         the script as an argument
  388.  
  389.     4)  make a general `setuid script server' that tries to locate the
  390.         requested `service' in a database of valid scripts and upon
  391.         success will start the right interpreter with the right
  392.         arguments.
  393.  
  394.     ---------
  395.  
  396.     Now that we have made sure the right file gets interpreted, are there
  397.     any risks left?
  398.  
  399.     Certainly!  For shell scripts you must not forget to set the PATH
  400.     variable to a safe path explicitly.  Can you figure out why?
  401.     Also there is the IFS variable that might cause trouble if not set
  402.     properly.  Other environment variables might turn out to compromise
  403.     security as well, e.g. SHELL...
  404.     Furthermore you must make sure the commands in the script do not
  405.     allow interactive shell escapes!
  406.     Then there is the umask which may have been set to something
  407.     strange...
  408.  
  409.     Etcetera.  You should realise that a setuid script `inherits' all the
  410.     bugs and security risks of the commands that it calls!
  411.  
  412.     All in all we get the impression setuid shell scripts are quite a
  413.     risky business!  You may be better off writing a C program instead!
  414.  
  415. 8)  How can I find out which user or process has a file open or is using
  416.     a particular file system (so that I can unmount it?)
  417.  
  418.     Use fuser (system V), fstat (BSD), ofiles (public domain) or
  419.     pff (public domain).  These programs will tell you various things
  420.     about processes using particular files.
  421.  
  422.     A port of the 4.3 BSD fstat to Dynix, SunOS and Ultrix
  423.     can be found in archives of comp.sources.unix, volume 18.
  424.  
  425.     pff is part of the kstuff package, and works on quite a few systems.
  426.     Instructions for obtaining kstuff are provided in question 3.10.
  427.  
  428. 9)  How do I keep track of people who are fingering me?
  429.  
  430.     Generally, you can't find out the userid of someone who is
  431.     fingering you from a remote machine.  You may be able to
  432.     find out which machine the remote request is coming from.
  433.     One possibility, if your system supports it and assuming
  434.     the finger daemon doesn't object, is to make your .plan file a
  435.     "named pipe" instead of a plain file.  (Use 'mknod' to do this.)
  436.  
  437.     You can then start up a program that will open your .plan file for
  438.     writing; the open will block until some other process (namely
  439.     fingerd) opens the .plan for reading.  Now you can whatever you
  440.     want through this pipe, which lets you show different .plan
  441.     information every time someone fingers you.
  442.  
  443.     Of course, this may not work at all if your system doesn't
  444.     support named pipes or if your local fingerd insists
  445.     on having plain .plan files.
  446.  
  447.     Your program can also take the opportunity to look at the output of
  448.     "netstat" and spot where an incoming finger connection is coming
  449.     from, but this won't get you the remote user.
  450.  
  451.     Getting the remote userid would require that the remote site be
  452.     running an identity service such as RFC 931.  There are now three
  453.     RFC 931 implementations for popular BSD machines, and several
  454.     applications (such as the wuarchive ftpd) supporting the server.
  455.     For more information join the rfc931-users mailing list,
  456.     rfc931-users-request@kramden.acf.nyu.edu.
  457.  
  458. 10) Is it possible to reconnect a process to a terminal after it has
  459.     been disconnected, e.g. after starting a program in the background
  460.     and logging out?
  461.  
  462.     Most variants of Unix do not support "detaching" and "attaching"
  463.     processes, as operating systems such as VMS and Multics support.
  464.     However, there are two freely redistributable packages which can
  465.     be used to start processes in such a way that they can be later
  466.     reattached to a terminal.
  467.  
  468.     The first is "screen," which is described in the comp.sources.unix
  469.     archives as "Screen, multiple windows on a CRT" (see the "screen-3.2"
  470.     package in comp.sources.misc, volume 28.)  This package will run
  471.     on at least BSD, System V r3.2 and SCO UNIX.
  472.  
  473.     The second is "pty," which is described in the comp.sources.unix
  474.     archives as a package to "Run a program under a pty session" (see
  475.     "pty" in volume 23).  pty is designed for use under BSD-like system
  476.     only.
  477.  
  478.     Neither of these packages is retroactive, i.e. you must have
  479.     started a process under screen or pty in order to be able to
  480.     detach and reattach it.
  481.  
  482. 11) Is it possible to "spy" on a terminal, displaying the output
  483.     that's appearing on it on another terminal?
  484.  
  485.     There are a few different ways you can do this, although none
  486.     of them is perfect:
  487.  
  488.     * kibitz allows two (or more) people to interact with a shell (or
  489.       any arbitary program).  Uses include:
  490.  
  491.     - watching or aiding another person's terminal session;
  492.     - recording a conversation while retaining the ability to
  493.       scroll backwards, save the conversation, or even edit it
  494.       while in progress;
  495.     - teaming up on games, document editing, or other cooperative
  496.       tasks where each person has strengths and weakness that
  497.       complement one another.
  498.  
  499.       kibitz comes as part of the expect distribution.  See question 3.9.
  500.  
  501.       kibitz requires permission from the person to be spyed upon.  To
  502.       spy without permission requires less pleasant approaches:
  503.  
  504.     * You can write a program that grovels through Kernel structures
  505.       and watches the output buffer for the terminal in question,
  506.       displaying characters as they are output.  This, obviously, is
  507.       not something that should be attempted by anyone who does not
  508.       have experience working with the Unix kernel.  Furthermore,
  509.       whatever method you come up with will probably be quite
  510.       non-portable.
  511.  
  512.     * If you want to do this to a particular hard-wired terminal all
  513.       the time (e.g. if you want operators to be able to check the
  514.       console terminal of a machine from other machines), you can
  515.       actually splice a monitor into the cable for the terminal.  For
  516.       example, plug the monitor output into another machine's serial
  517.       port, and run a program on that port that stores its input
  518.       somewhere and then transmits it out *another* port, this one
  519.       really going to the physical terminal.  If you do this, you have
  520.       to make sure that any output from the terminal is transmitted
  521.       back over the wire, although if you splice only into the
  522.       computer->terminal wires, this isn't much of a problem.  This is
  523.       not something that should be attempted by anyone who is not very
  524.       familiar with terminal wiring and such.
  525. -- 
  526. Ted Timar - tmatimar@nff.ncl.omron.co.jp
  527. Omron Corporation, Shimokaiinji, Nagaokakyo-city, Kyoto 617,  Japan
  528.  
  529.  
  530.