home *** CD-ROM | disk | FTP | other *** search
/ PC Online 1999 April / PCO0499.ISO / filesbbs / os2 / apach134.arj / APACH134.ZIP / src / modules / standard / mod_unique_id.c < prev    next >
Encoding:
C/C++ Source or Header  |  1999-01-01  |  15.6 KB  |  401 lines

  1. /* ====================================================================
  2.  * Copyright (c) 1995-1999 The Apache Group.  All rights reserved.
  3.  *
  4.  * Redistribution and use in source and binary forms, with or without
  5.  * modification, are permitted provided that the following conditions
  6.  * are met:
  7.  *
  8.  * 1. Redistributions of source code must retain the above copyright
  9.  *    notice, this list of conditions and the following disclaimer.
  10.  *
  11.  * 2. Redistributions in binary form must reproduce the above copyright
  12.  *    notice, this list of conditions and the following disclaimer in
  13.  *    the documentation and/or other materials provided with the
  14.  *    distribution.
  15.  *
  16.  * 3. All advertising materials mentioning features or use of this
  17.  *    software must display the following acknowledgment:
  18.  *    "This product includes software developed by the Apache Group
  19.  *    for use in the Apache HTTP server project (http://www.apache.org/)."
  20.  *
  21.  * 4. The names "Apache Server" and "Apache Group" must not be used to
  22.  *    endorse or promote products derived from this software without
  23.  *    prior written permission. For written permission, please contact
  24.  *    apache@apache.org.
  25.  *
  26.  * 5. Products derived from this software may not be called "Apache"
  27.  *    nor may "Apache" appear in their names without prior written
  28.  *    permission of the Apache Group.
  29.  *
  30.  * 6. Redistributions of any form whatsoever must retain the following
  31.  *    acknowledgment:
  32.  *    "This product includes software developed by the Apache Group
  33.  *    for use in the Apache HTTP server project (http://www.apache.org/)."
  34.  *
  35.  * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
  36.  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  37.  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  38.  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE APACHE GROUP OR
  39.  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  40.  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  41.  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  42.  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  43.  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  44.  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  45.  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  46.  * OF THE POSSIBILITY OF SUCH DAMAGE.
  47.  * ====================================================================
  48.  *
  49.  * This software consists of voluntary contributions made by many
  50.  * individuals on behalf of the Apache Group and was originally based
  51.  * on public domain software written at the National Center for
  52.  * Supercomputing Applications, University of Illinois, Urbana-Champaign.
  53.  * For more information on the Apache Group and the Apache HTTP server
  54.  * project, please see <http://www.apache.org/>.
  55.  *
  56.  */
  57.  
  58. /*
  59.  * mod_unique_id.c: generate a unique identifier for each request
  60.  *
  61.  * Original author: Dean Gaudet <dgaudet@arctic.org>
  62.  * UUencoding modified by: Alvaro Martinez Echevarria <alvaro@lander.es>
  63.  */
  64.  
  65. #include "httpd.h"
  66. #include "http_config.h"
  67. #include "http_log.h"
  68. #include "multithread.h"
  69.  
  70. #ifdef MULTITHREAD
  71. #error sorry this module does not support multithreaded servers yet
  72. #endif
  73.  
  74. typedef struct {
  75.     unsigned int stamp;
  76.     unsigned int in_addr;
  77.     unsigned int pid;
  78.     unsigned short counter;
  79. } unique_id_rec;
  80.  
  81. /* Comments:
  82.  *
  83.  * We want an identifier which is unique across all hits, everywhere.
  84.  * "everywhere" includes multiple httpd instances on the same machine, or on
  85.  * multiple machines.  Essentially "everywhere" should include all possible
  86.  * httpds across all servers at a particular "site".  We make some assumptions
  87.  * that if the site has a cluster of machines then their time is relatively
  88.  * synchronized.  We also assume that the first address returned by a
  89.  * gethostbyname (gethostname()) is unique across all the machines at the
  90.  * "site".
  91.  *
  92.  * We also further assume that pids fit in 32-bits.  If something uses more
  93.  * than 32-bits, the fix is trivial, but it requires the unrolled uuencoding
  94.  * loop to be extended.  * A similar fix is needed to support multithreaded
  95.  * servers, using a pid/tid combo.
  96.  *
  97.  * Together, the in_addr and pid are assumed to absolutely uniquely identify
  98.  * this one child from all other currently running children on all servers
  99.  * (including this physical server if it is running multiple httpds) from each
  100.  * other.
  101.  *
  102.  * The stamp and counter are used to distinguish all hits for a particular
  103.  * (in_addr,pid) pair.  The stamp is updated using r->request_time,
  104.  * saving cpu cycles.  The counter is never reset, and is used to permit up to
  105.  * 64k requests in a single second by a single child.
  106.  *
  107.  * The 112-bits of unique_id_rec are uuencoded using the alphabet
  108.  * [A-Za-z0-9@-], resulting in 19 bytes of printable characters.  That is then
  109.  * stuffed into the environment variable UNIQUE_ID so that it is available to
  110.  * other modules.  The alphabet choice differs from normal base64 encoding
  111.  * [A-Za-z0-9+/] because + and / are special characters in URLs and we want to
  112.  * make it easy to use UNIQUE_ID in URLs.
  113.  *
  114.  * Note that UNIQUE_ID should be considered an opaque token by other
  115.  * applications.  No attempt should be made to dissect its internal components.
  116.  * It is an abstraction that may change in the future as the needs of this
  117.  * module change.
  118.  *
  119.  * It is highly desirable that identifiers exist for "eternity".  But future
  120.  * needs (such as much faster webservers, moving to 64-bit pids, or moving to a
  121.  * multithreaded server) may dictate a need to change the contents of
  122.  * unique_id_rec.  Such a future implementation should ensure that the first
  123.  * field is still a time_t stamp.  By doing that, it is possible for a site to
  124.  * have a "flag second" in which they stop all of their old-format servers,
  125.  * wait one entire second, and then start all of their new-servers.  This
  126.  * procedure will ensure that the new space of identifiers is completely unique
  127.  * from the old space.  (Since the first four unencoded bytes always differ.)
  128.  */
  129. /*
  130.  * Sun Jun  7 05:43:49 CEST 1998 -- Alvaro
  131.  * More comments:
  132.  * 1) The UUencoding prodecure is now done in a general way, avoiding the problems
  133.  * with sizes and paddings that can arise depending on the architecture. Now the
  134.  * offsets and sizes of the elements of the unique_id_rec structure are calculated
  135.  * in unique_id_global_init; and then used to duplicate the structure without the
  136.  * paddings that might exist. The multithreaded server fix should be now very easy:
  137.  * just add a new "tid" field to the unique_id_rec structure, and increase by one
  138.  * UNIQUE_ID_REC_MAX.
  139.  * 2) unique_id_rec.stamp has been changed from "time_t" to "unsigned int", because
  140.  * its size is 64bits on some platforms (linux/alpha), and this caused problems with
  141.  * htonl/ntohl. Well, this shouldn't be a problem till year 2106.
  142.  */
  143.  
  144. static unsigned global_in_addr;
  145.  
  146. static APACHE_TLS unique_id_rec cur_unique_id;
  147.  
  148. /*
  149.  * Number of elements in the structure unique_id_rec.
  150.  */
  151. #define UNIQUE_ID_REC_MAX 4
  152.  
  153. static unsigned short unique_id_rec_offset[UNIQUE_ID_REC_MAX],
  154.                       unique_id_rec_size[UNIQUE_ID_REC_MAX],
  155.                       unique_id_rec_total_size,
  156.                       unique_id_rec_size_uu;
  157.  
  158. static void unique_id_global_init(server_rec *s, pool *p)
  159. {
  160. #ifndef MAXHOSTNAMELEN
  161. #define MAXHOSTNAMELEN 256
  162. #endif
  163.     char str[MAXHOSTNAMELEN + 1];
  164.     struct hostent *hent;
  165. #ifndef NO_GETTIMEOFDAY
  166.     struct timeval tv;
  167. #endif
  168.  
  169.     /*
  170.      * Calculate the sizes and offsets in cur_unique_id.
  171.      */
  172.     unique_id_rec_offset[0] = XtOffsetOf(unique_id_rec, stamp);
  173.     unique_id_rec_size[0] = sizeof(cur_unique_id.stamp);
  174.     unique_id_rec_offset[1] = XtOffsetOf(unique_id_rec, in_addr);
  175.     unique_id_rec_size[1] = sizeof(cur_unique_id.in_addr);
  176.     unique_id_rec_offset[2] = XtOffsetOf(unique_id_rec, pid);
  177.     unique_id_rec_size[2] = sizeof(cur_unique_id.pid);
  178.     unique_id_rec_offset[3] = XtOffsetOf(unique_id_rec, counter);
  179.     unique_id_rec_size[3] = sizeof(cur_unique_id.counter);
  180.     unique_id_rec_total_size = unique_id_rec_size[0] + unique_id_rec_size[1] +
  181.                                unique_id_rec_size[2] + unique_id_rec_size[3];
  182.  
  183.     /*
  184.      * Calculate the size of the structure when uuencoded.
  185.      */
  186.     unique_id_rec_size_uu = (unique_id_rec_total_size*8+5)/6;
  187.  
  188.     /*
  189.      * Now get the global in_addr.  Note that it is not sufficient to use one
  190.      * of the addresses from the main_server, since those aren't as likely to
  191.      * be unique as the physical address of the machine
  192.      */
  193.     if (gethostname(str, sizeof(str) - 1) != 0) {
  194.         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ALERT, s,
  195.           "gethostname: mod_unique_id requires the hostname of the server");
  196.         exit(1);
  197.     }
  198.     str[sizeof(str) - 1] = '\0';
  199.  
  200.     if ((hent = gethostbyname(str)) == NULL) {
  201.         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ALERT, s,
  202.                     "mod_unique_id: unable to gethostbyname(\"%s\")", str);
  203.         exit(1);
  204.     }
  205.  
  206.     global_in_addr = ((struct in_addr *) hent->h_addr_list[0])->s_addr;
  207.  
  208.     ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, s,
  209.                 "mod_unique_id: using ip addr %s",
  210.                 inet_ntoa(*(struct in_addr *) hent->h_addr_list[0]));
  211.  
  212.     /*
  213.      * If the server is pummelled with restart requests we could possibly end
  214.      * up in a situation where we're starting again during the same second
  215.      * that has been used in previous identifiers.  Avoid that situation.
  216.      * 
  217.      * In truth, for this to actually happen not only would it have to restart
  218.      * in the same second, but it would have to somehow get the same pids as
  219.      * one of the other servers that was running in that second. Which would
  220.      * mean a 64k wraparound on pids ... not very likely at all.
  221.      * 
  222.      * But protecting against it is relatively cheap.  We just sleep into the
  223.      * next second.
  224.      */
  225. #ifdef NO_GETTIMEOFDAY
  226.     sleep(1);
  227. #else
  228.     if (gettimeofday(&tv, NULL) == -1) {
  229.         sleep(1);
  230.     }
  231.     else if (tv.tv_usec) {
  232.         tv.tv_sec = 0;
  233.         tv.tv_usec = 1000000 - tv.tv_usec;
  234.         select(0, NULL, NULL, NULL, &tv);
  235.     }
  236. #endif
  237. }
  238.  
  239. static void unique_id_child_init(server_rec *s, pool *p)
  240. {
  241.     pid_t pid;
  242. #ifndef NO_GETTIMEOFDAY
  243.     struct timeval tv;
  244. #endif
  245.  
  246.     /*
  247.      * Note that we use the pid because it's possible that on the same
  248.      * physical machine there are multiple servers (i.e. using Listen). But
  249.      * it's guaranteed that none of them will share the same pids between
  250.      * children.
  251.      * 
  252.      * XXX: for multithread this needs to use a pid/tid combo and probably
  253.      * needs to be expanded to 32 bits
  254.      */
  255.     pid = getpid();
  256.     cur_unique_id.pid = pid;
  257.  
  258.     /*
  259.      * Test our assumption that the pid is 32-bits.  It's possible that
  260.      * 64-bit machines will declare pid_t to be 64 bits but only use 32
  261.      * of them.  It would have been really nice to test this during
  262.      * global_init ... but oh well.
  263.      */
  264.     if (cur_unique_id.pid != pid) {
  265.         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_CRIT, s,
  266.                     "oh no! pids are greater than 32-bits!  I'm broken!");
  267.     }
  268.  
  269.     cur_unique_id.in_addr = global_in_addr;
  270.  
  271.     /*
  272.      * If we use 0 as the initial counter we have a little less protection
  273.      * against restart problems, and a little less protection against a clock
  274.      * going backwards in time.
  275.      */
  276. #ifndef NO_GETTIMEOFDAY
  277.     if (gettimeofday(&tv, NULL) == -1) {
  278.         cur_unique_id.counter = 0;
  279.     }
  280.     else {
  281.     /* Some systems have very low variance on the low end of their
  282.      * system counter, defend against that.
  283.      */
  284.         cur_unique_id.counter = tv.tv_usec / 10;
  285.     }
  286. #else
  287.     cur_unique_id.counter = 0;
  288. #endif
  289.  
  290.     /*
  291.      * We must always use network ordering for these bytes, so that
  292.      * identifiers are comparable between machines of different byte
  293.      * orderings.  Note in_addr is already in network order.
  294.      */
  295.     cur_unique_id.pid = htonl(cur_unique_id.pid);
  296.     cur_unique_id.counter = htons(cur_unique_id.counter);
  297. }
  298.  
  299. /* NOTE: This is *NOT* the same encoding used by uuencode ... the last two
  300.  * characters should be + and /.  But those two characters have very special
  301.  * meanings in URLs, and we want to make it easy to use identifiers in
  302.  * URLs.  So we replace them with @ and -.
  303.  */
  304. static const char uuencoder[64] = {
  305.     'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
  306.     'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
  307.     'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
  308.     'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
  309.     '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '@', '-',
  310. };
  311.  
  312. static int gen_unique_id(request_rec *r)
  313. {
  314.     char *str;
  315.     /*
  316.      * Buffer padded with two final bytes, used to copy the unique_id_red
  317.      * structure without the internal paddings that it could have.
  318.      */
  319.     struct {
  320.     unique_id_rec foo;
  321.     unsigned char pad[2];
  322.     } paddedbuf;
  323.     unsigned char *x,*y;
  324.     unsigned short counter;
  325.     const char *e;
  326.     int i,j,k;
  327.  
  328.     /* copy the unique_id if this is an internal redirect (we're never
  329.      * actually called for sub requests, so we don't need to test for
  330.      * them) */
  331.     if (r->prev && (e = ap_table_get(r->subprocess_env, "REDIRECT_UNIQUE_ID"))) {
  332.     ap_table_setn(r->subprocess_env, "UNIQUE_ID", e);
  333.     return DECLINED;
  334.     }
  335.  
  336.     cur_unique_id.stamp = htonl((unsigned int)r->request_time);
  337.  
  338.     /* we'll use a temporal buffer to avoid uuencoding the possible internal
  339.      * paddings of the original structure */
  340.     x = (unsigned char *) &paddedbuf;
  341.     y = (unsigned char *) &cur_unique_id;
  342.     k = 0;
  343.     for (i = 0; i < UNIQUE_ID_REC_MAX; i++) {
  344.         y = ((unsigned char *) &cur_unique_id) + unique_id_rec_offset[i];
  345.         for (j = 0; j < unique_id_rec_size[i]; j++, k++) {
  346.             x[k] = y[j];
  347.         }
  348.     }
  349.     /*
  350.      * We reset two more bytes just in case padding is needed for the uuencoding.
  351.      */
  352.     x[k++] = '\0';
  353.     x[k++] = '\0';
  354.     
  355.     /* alloc str and do the uuencoding */
  356.     str = (char *)ap_palloc(r->pool, unique_id_rec_size_uu + 1);
  357.     k = 0;
  358.     for (i = 0; i < unique_id_rec_total_size; i += 3) {
  359.         y = x + i;
  360.         str[k++] = uuencoder[y[0] >> 2];
  361.         str[k++] = uuencoder[((y[0] & 0x03) << 4) | ((y[1] & 0xf0) >> 4)];
  362.         if (k == unique_id_rec_size_uu) break;
  363.         str[k++] = uuencoder[((y[1] & 0x0f) << 2) | ((y[2] & 0xc0) >> 6)];
  364.         if (k == unique_id_rec_size_uu) break;
  365.         str[k++] = uuencoder[y[2] & 0x3f];
  366.     }
  367.     str[k++] = '\0';
  368.  
  369.     /* set the environment variable */
  370.     ap_table_setn(r->subprocess_env, "UNIQUE_ID", str);
  371.  
  372.     /* and increment the identifier for the next call */
  373.     counter = ntohs(cur_unique_id.counter) + 1;
  374.     cur_unique_id.counter = htons(counter);
  375.  
  376.     return DECLINED;
  377. }
  378.  
  379.  
  380. module MODULE_VAR_EXPORT unique_id_module = {
  381.     STANDARD_MODULE_STUFF,
  382.     unique_id_global_init,      /* initializer */
  383.     NULL,                       /* dir config creater */
  384.     NULL,                       /* dir merger --- default is to override */
  385.     NULL,                       /* server config */
  386.     NULL,                       /* merge server configs */
  387.     NULL,                       /* command table */
  388.     NULL,                       /* handlers */
  389.     NULL,                       /* filename translation */
  390.     NULL,                       /* check_user_id */
  391.     NULL,                       /* check auth */
  392.     NULL,                       /* check access */
  393.     NULL,                       /* type_checker */
  394.     NULL,                       /* fixups */
  395.     NULL,                       /* logger */
  396.     NULL,                       /* header parser */
  397.     unique_id_child_init,       /* child_init */
  398.     NULL,                       /* child_exit */
  399.     gen_unique_id               /* post_read_request */
  400. };
  401.