From: Amos Jeffries Date: Fri, 10 Oct 2008 08:02:53 +0000 (+1300) Subject: SourceFormat: Main reformat push X-Git-Tag: SQUID_3_2_0_1~1420 X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=26ac04309f51d4be5c9fa41ea3da88688024d9db;p=thirdparty%2Fsquid.git SourceFormat: Main reformat push This revision formats all .h .c .cc .cci files according to the code format chosen for Squid-3 releases in future. Due to outstanding patches which are not easily adapted a few files have been omitted from this particular format push: src/comm.cc src/client_side.cc src/client_side.h src/errorpage.cc src/fde.h src/ftp.cc src/http.cc src/HttpRequest.cc src/pconn.cc src/pconn.h src/ICAP/ICAPModXact.cc src/ICAP/ICAPModXact.h src/ICAP/ICAPOptions.cc src/ICAP/ICAPServiceRep.cc src/ICAP/ICAPServiceRep.h src/ICAP/ICAPXaction.cc src/ICAP/ICAPXaction.h src/Server.cc src/Server.h src/structs.h --- diff --git a/.bzrignore b/.bzrignore index 73d0265407..105a014dd2 100644 --- a/.bzrignore +++ b/.bzrignore @@ -66,6 +66,7 @@ stamp-h1 tags test-suite/Makefile testHeaders +testHeaders.c tmp tools/Makefile tools/cachemgr.cgi diff --git a/contrib/rredir.c b/contrib/rredir.c index 2490256cb9..b9961fd37e 100644 --- a/contrib/rredir.c +++ b/contrib/rredir.c @@ -6,31 +6,31 @@ * Subject: Save 15% on your bandwidth... * Date: 12 Sep 1996 21:21:55 GMT * =========================================================================== - * + * * I have downloaded the multi-megabyte files from Netscape and Microsoft * that our users like to download from every mirror in the world, * defeating the usual caching. - * + * * I put these files in a separate directory and installed a basic * redirector for Squid that checks if the file (so hostname and pathname * are disregarded) is present in this directory. - * + * * After a few days of testing (the redirector looks very stable) it looks * like this is saving us approx. 15% on our cache flow. Also, our own WWW * server has become more popular than ever :) - * + * * I'm sure this code will be useful to others too, so I've attached it at * the end of this message. Improvements, extensions etc. are welcome. - * + * * I'm going on holidays now, so I won't be able to respond to e-mail * quickly. - * + * * Enjoy, Richard. */ /* * rredir - redirect to local directory - * + * * version 0.1, 7 sep 1996 * - initial version (Richard Huveneers ) */ @@ -53,49 +53,49 @@ main() /* make standard output line buffered */ if (setvbuf(stdout, NULL, _IOLBF, 0) != 0) - return 1; + return 1; /* speed up the access() calls below */ if (chdir(ACCESS_LOCAL_DIR) == -1) - return 1; + return 1; /* scan standard input */ while (fgets(buf, BUFFER_SIZE, stdin) != NULL) { - /* check for too long urls */ - if (strchr(buf, '\n') == NULL) { - tlu = 1; - continue; - } - if (tlu) - goto dont_redirect; + /* check for too long urls */ + if (strchr(buf, '\n') == NULL) { + tlu = 1; + continue; + } + if (tlu) + goto dont_redirect; - /* determine end of url */ - if ((s = strchr(buf, ' ')) == NULL) - goto dont_redirect; - *s = '\0'; + /* determine end of url */ + if ((s = strchr(buf, ' ')) == NULL) + goto dont_redirect; + *s = '\0'; - /* determine first character of filename */ - if ((s = strrchr(buf, '/')) == NULL) - goto dont_redirect; - s++; + /* determine first character of filename */ + if ((s = strrchr(buf, '/')) == NULL) + goto dont_redirect; + s++; - /* security: do not redirect to hidden files, the current - * directory or the parent directory */ - if (*s == '.' || *s == '\0') - goto dont_redirect; + /* security: do not redirect to hidden files, the current + * directory or the parent directory */ + if (*s == '.' || *s == '\0') + goto dont_redirect; - /* map filename to lower case */ - for (t = s; *t != '\0'; t++) - *t = (char) tolower((int) *t); + /* map filename to lower case */ + for (t = s; *t != '\0'; t++) + *t = (char) tolower((int) *t); - /* check for a local copy of this file */ - if (access(s, R_OK) == 0) { - (void) printf("%s/%s\n", REDIRECT_TO_URL, s); - continue; - } - dont_redirect: - tlu = 0; - (void) printf("\n"); + /* check for a local copy of this file */ + if (access(s, R_OK) == 0) { + (void) printf("%s/%s\n", REDIRECT_TO_URL, s); + continue; + } +dont_redirect: + tlu = 0; + (void) printf("\n"); } return 0; diff --git a/helpers/basic_auth/LDAP/squid_ldap_auth.c b/helpers/basic_auth/LDAP/squid_ldap_auth.c index d221304d86..ad3d2e47df 100644 --- a/helpers/basic_auth/LDAP/squid_ldap_auth.c +++ b/helpers/basic_auth/LDAP/squid_ldap_auth.c @@ -1,32 +1,32 @@ /* * squid_ldap_auth: authentication via ldap for squid proxy server - * + * * Authors: * Henrik Nordstrom * hno@squid-cache.org * - * Glen Newton + * Glen Newton * glen.newton@nrc.ca - * Advanced Services + * Advanced Services * CISTI * National Research Council * * with contributions from others mentioned in the Changes section below - * + * * Usage: squid_ldap_auth -b basedn [-s searchscope] * [-f searchfilter] [-D binddn -w bindpasswd] * [-u attr] [-h host] [-p port] [-P] [-R] [ldap_server_name[:port]] ... - * + * * Dependencies: You need to get the OpenLDAP libraries * from http://www.openldap.org or another compatible LDAP C-API * implementation. * * If you want to make a TLS enabled connection you will also need the * OpenSSL libraries linked into openldap. See http://www.openssl.org/ - * - * License: squid_ldap_auth is free software; you can redistribute it - * and/or modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2, + * + * License: squid_ldap_auth is free software; you can redistribute it + * and/or modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2, * or (at your option) any later version. * * Changes: @@ -56,7 +56,7 @@ * - Added support for ldap URI via the -H option * (requires OpenLDAP) * 2001-12-12: Michael Cunningham - * - Added TLS support and partial ldap version 3 support. + * - Added TLS support and partial ldap version 3 support. * 2001-10-04: Henrik Nordstrom * - Be consistent with the other helpers in how * spaces are managed. If there is space characters @@ -176,7 +176,7 @@ squid_ldap_set_aliasderef(LDAP * ld, int deref) static void squid_ldap_set_referrals(LDAP * ld, int referrals) { - int *value = referrals ? LDAP_OPT_ON : LDAP_OPT_OFF; + int *value = referrals ? LDAP_OPT_ON :LDAP_OPT_OFF; ldap_set_option(ld, LDAP_OPT_REFERRALS, value); } static void @@ -218,9 +218,9 @@ static void squid_ldap_set_referrals(LDAP * ld, int referrals) { if (referrals) - ld->ld_options |= ~LDAP_OPT_REFERRALS; + ld->ld_options |= ~LDAP_OPT_REFERRALS; else - ld->ld_options &= ~LDAP_OPT_REFERRALS; + ld->ld_options &= ~LDAP_OPT_REFERRALS; } static void squid_ldap_set_timelimit(LDAP * ld, int timelimit) @@ -252,58 +252,58 @@ open_ldap_connection(const char *ldapServer, int port) LDAP *ld = NULL; #if HAS_URI_SUPPORT if (strstr(ldapServer, "://") != NULL) { - int rc = ldap_initialize(&ld, ldapServer); - if (rc != LDAP_SUCCESS) { - fprintf(stderr, "\nUnable to connect to LDAPURI:%s\n", ldapServer); - exit(1); - } + int rc = ldap_initialize(&ld, ldapServer); + if (rc != LDAP_SUCCESS) { + fprintf(stderr, "\nUnable to connect to LDAPURI:%s\n", ldapServer); + exit(1); + } } else #endif #if NETSCAPE_SSL - if (sslpath) { - if (!sslinit && (ldapssl_client_init(sslpath, NULL) != LDAP_SUCCESS)) { - fprintf(stderr, "\nUnable to initialise SSL with cert path %s\n", - sslpath); - exit(1); - } else { - sslinit++; - } - if ((ld = ldapssl_init(ldapServer, port, 1)) == NULL) { - fprintf(stderr, "\nUnable to connect to SSL LDAP server: %s port:%d\n", - ldapServer, port); - exit(1); - } - } else + if (sslpath) { + if (!sslinit && (ldapssl_client_init(sslpath, NULL) != LDAP_SUCCESS)) { + fprintf(stderr, "\nUnable to initialise SSL with cert path %s\n", + sslpath); + exit(1); + } else { + sslinit++; + } + if ((ld = ldapssl_init(ldapServer, port, 1)) == NULL) { + fprintf(stderr, "\nUnable to connect to SSL LDAP server: %s port:%d\n", + ldapServer, port); + exit(1); + } + } else #endif - if ((ld = ldap_init(ldapServer, port)) == NULL) { - fprintf(stderr, "\nUnable to connect to LDAP server:%s port:%d\n", - ldapServer, port); - exit(1); - } + if ((ld = ldap_init(ldapServer, port)) == NULL) { + fprintf(stderr, "\nUnable to connect to LDAP server:%s port:%d\n", + ldapServer, port); + exit(1); + } if (connect_timeout) - squid_ldap_set_connect_timeout(ld, connect_timeout); + squid_ldap_set_connect_timeout(ld, connect_timeout); #ifdef LDAP_VERSION3 if (version == -1) { - version = LDAP_VERSION2; + version = LDAP_VERSION2; } if (ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &version) != LDAP_SUCCESS) { - fprintf(stderr, "Could not set LDAP_OPT_PROTOCOL_VERSION %d\n", - version); - exit(1); + fprintf(stderr, "Could not set LDAP_OPT_PROTOCOL_VERSION %d\n", + version); + exit(1); } if (use_tls) { #ifdef LDAP_OPT_X_TLS - if (version != LDAP_VERSION3) { - fprintf(stderr, "TLS requires LDAP version 3\n"); - exit(1); - } else if (ldap_start_tls_s(ld, NULL, NULL) != LDAP_SUCCESS) { - fprintf(stderr, "Could not Activate TLS connection\n"); - exit(1); - } + if (version != LDAP_VERSION3) { + fprintf(stderr, "TLS requires LDAP version 3\n"); + exit(1); + } else if (ldap_start_tls_s(ld, NULL, NULL) != LDAP_SUCCESS) { + fprintf(stderr, "Could not Activate TLS connection\n"); + exit(1); + } #else - fprintf(stderr, "TLS not supported with your LDAP library\n"); - exit(1); + fprintf(stderr, "TLS not supported with your LDAP library\n"); + exit(1); #endif } #endif @@ -321,21 +321,21 @@ validUsername(const char *user) /* Leading whitespace? */ if (xisspace(p[0])) - return 0; + return 0; while (p[0] && p[1]) { - if (xisspace(p[0])) { - /* More than one consequitive space? */ - if (xisspace(p[1])) - return 0; - /* or odd space type character used? */ - if (p[0] != ' ') - return 0; - } - p++; + if (xisspace(p[0])) { + /* More than one consequitive space? */ + if (xisspace(p[1])) + return 0; + /* or odd space type character used? */ + if (p[0] != ' ') + return 0; + } + p++; } /* Trailing whitespace? */ if (xisspace(p[0])) - return 0; + return 0; return 1; } @@ -352,255 +352,255 @@ main(int argc, char **argv) setbuf(stdout, NULL); while (argc > 1 && argv[1][0] == '-') { - const char *value = ""; - char option = argv[1][1]; - switch (option) { - case 'P': - case 'R': - case 'z': - case 'Z': - case 'd': - case 'O': - break; - default: - if (strlen(argv[1]) > 2) { - value = argv[1] + 2; - } else if (argc > 2) { - value = argv[2]; - argv++; - argc--; - } else - value = ""; - break; - } - argv++; - argc--; - switch (option) { - case 'H': + const char *value = ""; + char option = argv[1][1]; + switch (option) { + case 'P': + case 'R': + case 'z': + case 'Z': + case 'd': + case 'O': + break; + default: + if (strlen(argv[1]) > 2) { + value = argv[1] + 2; + } else if (argc > 2) { + value = argv[2]; + argv++; + argc--; + } else + value = ""; + break; + } + argv++; + argc--; + switch (option) { + case 'H': #if !HAS_URI_SUPPORT - fprintf(stderr, "ERROR: Your LDAP library does not have URI support\n"); - exit(1); + fprintf(stderr, "ERROR: Your LDAP library does not have URI support\n"); + exit(1); #endif - /* Fall thru to -h */ - case 'h': - if (ldapServer) { - int len = strlen(ldapServer) + 1 + strlen(value) + 1; - char *newhost = malloc(len); - snprintf(newhost, len, "%s %s", ldapServer, value); - free(ldapServer); - ldapServer = newhost; - } else { - ldapServer = strdup(value); - } - break; - case 'b': - basedn = value; - break; - case 'f': - searchfilter = value; - break; - case 'u': - userattr = value; - break; - case 'U': - passwdattr = value; - break; - case 's': - if (strcmp(value, "base") == 0) - searchscope = LDAP_SCOPE_BASE; - else if (strcmp(value, "one") == 0) - searchscope = LDAP_SCOPE_ONELEVEL; - else if (strcmp(value, "sub") == 0) - searchscope = LDAP_SCOPE_SUBTREE; - else { - fprintf(stderr, PROGRAM_NAME ": ERROR: Unknown search scope '%s'\n", value); - exit(1); - } - break; - case 'E': + /* Fall thru to -h */ + case 'h': + if (ldapServer) { + int len = strlen(ldapServer) + 1 + strlen(value) + 1; + char *newhost = malloc(len); + snprintf(newhost, len, "%s %s", ldapServer, value); + free(ldapServer); + ldapServer = newhost; + } else { + ldapServer = strdup(value); + } + break; + case 'b': + basedn = value; + break; + case 'f': + searchfilter = value; + break; + case 'u': + userattr = value; + break; + case 'U': + passwdattr = value; + break; + case 's': + if (strcmp(value, "base") == 0) + searchscope = LDAP_SCOPE_BASE; + else if (strcmp(value, "one") == 0) + searchscope = LDAP_SCOPE_ONELEVEL; + else if (strcmp(value, "sub") == 0) + searchscope = LDAP_SCOPE_SUBTREE; + else { + fprintf(stderr, PROGRAM_NAME ": ERROR: Unknown search scope '%s'\n", value); + exit(1); + } + break; + case 'E': #if defined(NETSCAPE_SSL) - sslpath = value; - if (port == LDAP_PORT) - port = LDAPS_PORT; + sslpath = value; + if (port == LDAP_PORT) + port = LDAPS_PORT; #else - fprintf(stderr, PROGRAM_NAME " ERROR: -E unsupported with this LDAP library\n"); - exit(1); + fprintf(stderr, PROGRAM_NAME " ERROR: -E unsupported with this LDAP library\n"); + exit(1); #endif - break; - case 'c': - connect_timeout = atoi(value); - break; - case 't': - timelimit = atoi(value); - break; - case 'a': - if (strcmp(value, "never") == 0) - aliasderef = LDAP_DEREF_NEVER; - else if (strcmp(value, "always") == 0) - aliasderef = LDAP_DEREF_ALWAYS; - else if (strcmp(value, "search") == 0) - aliasderef = LDAP_DEREF_SEARCHING; - else if (strcmp(value, "find") == 0) - aliasderef = LDAP_DEREF_FINDING; - else { - fprintf(stderr, PROGRAM_NAME ": ERROR: Unknown alias dereference method '%s'\n", value); - exit(1); - } - break; - case 'D': - binddn = value; - break; - case 'w': - bindpasswd = value; - break; - case 'W': - readSecret(value); - break; - case 'P': - persistent = !persistent; - break; - case 'O': - bind_once = !bind_once; - break; - case 'p': - port = atoi(value); - break; - case 'R': - noreferrals = !noreferrals; - break; + break; + case 'c': + connect_timeout = atoi(value); + break; + case 't': + timelimit = atoi(value); + break; + case 'a': + if (strcmp(value, "never") == 0) + aliasderef = LDAP_DEREF_NEVER; + else if (strcmp(value, "always") == 0) + aliasderef = LDAP_DEREF_ALWAYS; + else if (strcmp(value, "search") == 0) + aliasderef = LDAP_DEREF_SEARCHING; + else if (strcmp(value, "find") == 0) + aliasderef = LDAP_DEREF_FINDING; + else { + fprintf(stderr, PROGRAM_NAME ": ERROR: Unknown alias dereference method '%s'\n", value); + exit(1); + } + break; + case 'D': + binddn = value; + break; + case 'w': + bindpasswd = value; + break; + case 'W': + readSecret(value); + break; + case 'P': + persistent = !persistent; + break; + case 'O': + bind_once = !bind_once; + break; + case 'p': + port = atoi(value); + break; + case 'R': + noreferrals = !noreferrals; + break; #ifdef LDAP_VERSION3 - case 'v': - switch (atoi(value)) { - case 2: - version = LDAP_VERSION2; - break; - case 3: - version = LDAP_VERSION3; - break; - default: - fprintf(stderr, "Protocol version should be 2 or 3\n"); - exit(1); - } - break; - case 'Z': - if (version == LDAP_VERSION2) { - fprintf(stderr, "TLS (-Z) is incompatible with version %d\n", - version); - exit(1); - } - version = LDAP_VERSION3; - use_tls = 1; - break; + case 'v': + switch (atoi(value)) { + case 2: + version = LDAP_VERSION2; + break; + case 3: + version = LDAP_VERSION3; + break; + default: + fprintf(stderr, "Protocol version should be 2 or 3\n"); + exit(1); + } + break; + case 'Z': + if (version == LDAP_VERSION2) { + fprintf(stderr, "TLS (-Z) is incompatible with version %d\n", + version); + exit(1); + } + version = LDAP_VERSION3; + use_tls = 1; + break; #endif - case 'd': - debug++; - break; - default: - fprintf(stderr, PROGRAM_NAME ": ERROR: Unknown command line option '%c'\n", option); - exit(1); - } + case 'd': + debug++; + break; + default: + fprintf(stderr, PROGRAM_NAME ": ERROR: Unknown command line option '%c'\n", option); + exit(1); + } } while (argc > 1) { - char *value = argv[1]; - if (ldapServer) { - int len = strlen(ldapServer) + 1 + strlen(value) + 1; - char *newhost = malloc(len); - snprintf(newhost, len, "%s %s", ldapServer, value); - free(ldapServer); - ldapServer = newhost; - } else { - ldapServer = strdup(value); - } - argc--; - argv++; + char *value = argv[1]; + if (ldapServer) { + int len = strlen(ldapServer) + 1 + strlen(value) + 1; + char *newhost = malloc(len); + snprintf(newhost, len, "%s %s", ldapServer, value); + free(ldapServer); + ldapServer = newhost; + } else { + ldapServer = strdup(value); + } + argc--; + argv++; } if (!ldapServer) - ldapServer = strdup("localhost"); + ldapServer = strdup("localhost"); if (!basedn) { - fprintf(stderr, "Usage: " PROGRAM_NAME " -b basedn [options] [ldap_server_name[:port]]...\n\n"); - fprintf(stderr, "\t-b basedn (REQUIRED)\tbase dn under which to search\n"); - fprintf(stderr, "\t-f filter\t\tsearch filter to locate user DN\n"); - fprintf(stderr, "\t-u userattr\t\tusername DN attribute\n"); - fprintf(stderr, "\t-s base|one|sub\t\tsearch scope\n"); - fprintf(stderr, "\t-D binddn\t\tDN to bind as to perform searches\n"); - fprintf(stderr, "\t-w bindpasswd\t\tpassword for binddn\n"); - fprintf(stderr, "\t-W secretfile\t\tread password for binddn from file secretfile\n"); + fprintf(stderr, "Usage: " PROGRAM_NAME " -b basedn [options] [ldap_server_name[:port]]...\n\n"); + fprintf(stderr, "\t-b basedn (REQUIRED)\tbase dn under which to search\n"); + fprintf(stderr, "\t-f filter\t\tsearch filter to locate user DN\n"); + fprintf(stderr, "\t-u userattr\t\tusername DN attribute\n"); + fprintf(stderr, "\t-s base|one|sub\t\tsearch scope\n"); + fprintf(stderr, "\t-D binddn\t\tDN to bind as to perform searches\n"); + fprintf(stderr, "\t-w bindpasswd\t\tpassword for binddn\n"); + fprintf(stderr, "\t-W secretfile\t\tread password for binddn from file secretfile\n"); #if HAS_URI_SUPPORT - fprintf(stderr, "\t-H URI\t\t\tLDAPURI (defaults to ldap://localhost)\n"); + fprintf(stderr, "\t-H URI\t\t\tLDAPURI (defaults to ldap://localhost)\n"); #endif - fprintf(stderr, "\t-h server\t\tLDAP server (defaults to localhost)\n"); - fprintf(stderr, "\t-p port\t\t\tLDAP server port\n"); - fprintf(stderr, "\t-P\t\t\tpersistent LDAP connection\n"); + fprintf(stderr, "\t-h server\t\tLDAP server (defaults to localhost)\n"); + fprintf(stderr, "\t-p port\t\t\tLDAP server port\n"); + fprintf(stderr, "\t-P\t\t\tpersistent LDAP connection\n"); #if defined(NETSCAPE_SSL) - fprintf(stderr, "\t-E sslcertpath\t\tenable LDAP over SSL\n"); + fprintf(stderr, "\t-E sslcertpath\t\tenable LDAP over SSL\n"); #endif - fprintf(stderr, "\t-c timeout\t\tconnect timeout\n"); - fprintf(stderr, "\t-t timelimit\t\tsearch time limit\n"); - fprintf(stderr, "\t-R\t\t\tdo not follow referrals\n"); - fprintf(stderr, "\t-a never|always|search|find\n\t\t\t\twhen to dereference aliases\n"); + fprintf(stderr, "\t-c timeout\t\tconnect timeout\n"); + fprintf(stderr, "\t-t timelimit\t\tsearch time limit\n"); + fprintf(stderr, "\t-R\t\t\tdo not follow referrals\n"); + fprintf(stderr, "\t-a never|always|search|find\n\t\t\t\twhen to dereference aliases\n"); #ifdef LDAP_VERSION3 - fprintf(stderr, "\t-v 2|3\t\t\tLDAP version\n"); - fprintf(stderr, "\t-Z\t\t\tTLS encrypt the LDAP connection, requires LDAP version 3\n"); + fprintf(stderr, "\t-v 2|3\t\t\tLDAP version\n"); + fprintf(stderr, "\t-Z\t\t\tTLS encrypt the LDAP connection, requires LDAP version 3\n"); #endif - fprintf(stderr, "\n"); - fprintf(stderr, "\tIf no search filter is specified, then the dn =user,basedn\n\twill be used (same as specifying a search filter of '=',\n\tbut quicker as as there is no need to search for the user DN)\n\n"); - fprintf(stderr, "\tIf you need to bind as a user to perform searches then use the\n\t-D binddn -w bindpasswd or -D binddn -W secretfile options\n\n"); - exit(1); + fprintf(stderr, "\n"); + fprintf(stderr, "\tIf no search filter is specified, then the dn =user,basedn\n\twill be used (same as specifying a search filter of '=',\n\tbut quicker as as there is no need to search for the user DN)\n\n"); + fprintf(stderr, "\tIf you need to bind as a user to perform searches then use the\n\t-D binddn -w bindpasswd or -D binddn -W secretfile options\n\n"); + exit(1); } -/* On Windows ldap_start_tls_s is available starting from Windows XP, - * so we need to bind at run-time with the function entry point - */ + /* On Windows ldap_start_tls_s is available starting from Windows XP, + * so we need to bind at run-time with the function entry point + */ #ifdef _SQUID_MSWIN_ if (use_tls) { - HMODULE WLDAP32Handle; + HMODULE WLDAP32Handle; - WLDAP32Handle = GetModuleHandle("wldap32"); - if ((Win32_ldap_start_tls_s = (PFldap_start_tls_s) GetProcAddress(WLDAP32Handle, LDAP_START_TLS_S)) == NULL) { - fprintf(stderr, PROGRAM_NAME ": ERROR: TLS (-Z) not supported on this platform.\n"); - exit(1); - } + WLDAP32Handle = GetModuleHandle("wldap32"); + if ((Win32_ldap_start_tls_s = (PFldap_start_tls_s) GetProcAddress(WLDAP32Handle, LDAP_START_TLS_S)) == NULL) { + fprintf(stderr, PROGRAM_NAME ": ERROR: TLS (-Z) not supported on this platform.\n"); + exit(1); + } } #endif while (fgets(buf, sizeof(buf), stdin) != NULL) { - user = strtok(buf, " \r\n"); - passwd = strtok(NULL, "\r\n"); - - if (!user || !passwd || !passwd[0]) { - printf("ERR\n"); - continue; - } - rfc1738_unescape(user); - rfc1738_unescape(passwd); - if (!validUsername(user)) { - printf("ERR No such user\n"); - continue; - } - tryagain = (ld != NULL); - recover: - if (ld == NULL && persistent) - ld = open_ldap_connection(ldapServer, port); - if (checkLDAP(ld, user, passwd, ldapServer, port) != 0) { - if (tryagain && squid_ldap_errno(ld) != LDAP_INVALID_CREDENTIALS) { - tryagain = 0; - ldap_unbind(ld); - ld = NULL; - goto recover; - } - printf("ERR %s\n", ldap_err2string(squid_ldap_errno(ld))); - } else { - printf("OK\n"); - } - if (ld && (squid_ldap_errno(ld) != LDAP_SUCCESS && squid_ldap_errno(ld) != LDAP_INVALID_CREDENTIALS)) { - ldap_unbind(ld); - ld = NULL; - } + user = strtok(buf, " \r\n"); + passwd = strtok(NULL, "\r\n"); + + if (!user || !passwd || !passwd[0]) { + printf("ERR\n"); + continue; + } + rfc1738_unescape(user); + rfc1738_unescape(passwd); + if (!validUsername(user)) { + printf("ERR No such user\n"); + continue; + } + tryagain = (ld != NULL); +recover: + if (ld == NULL && persistent) + ld = open_ldap_connection(ldapServer, port); + if (checkLDAP(ld, user, passwd, ldapServer, port) != 0) { + if (tryagain && squid_ldap_errno(ld) != LDAP_INVALID_CREDENTIALS) { + tryagain = 0; + ldap_unbind(ld); + ld = NULL; + goto recover; + } + printf("ERR %s\n", ldap_err2string(squid_ldap_errno(ld))); + } else { + printf("OK\n"); + } + if (ld && (squid_ldap_errno(ld) != LDAP_SUCCESS && squid_ldap_errno(ld) != LDAP_INVALID_CREDENTIALS)) { + ldap_unbind(ld); + ld = NULL; + } } if (ld) - ldap_unbind(ld); + ldap_unbind(ld); return 0; } @@ -609,24 +609,24 @@ ldap_escape_value(char *escaped, int size, const char *src) { int n = 0; while (size > 4 && *src) { - switch (*src) { - case '*': - case '(': - case ')': - case '\\': - n += 3; - size -= 3; - if (size > 0) { - *escaped++ = '\\'; - snprintf(escaped, 3, "%02x", (unsigned char) *src++); - escaped += 2; - } - break; - default: - *escaped++ = *src++; - n++; - size--; - } + switch (*src) { + case '*': + case '(': + case ')': + case '\\': + n += 3; + size -= 3; + if (size > 0) { + *escaped++ = '\\'; + snprintf(escaped, 3, "%02x", (unsigned char) *src++); + escaped += 2; + } + break; + default: + *escaped++ = *src++; + n++; + size--; + } } *escaped = '\0'; return n; @@ -643,110 +643,109 @@ checkLDAP(LDAP * persistent_ld, const char *userid, const char *password, const LDAP *bind_ld = NULL; if (!*password) { - /* LDAP can't bind with a blank password. Seen as "anonymous" - * and always granted access - */ - if (debug) - fprintf(stderr, "Blank password given\n"); - return 1; + /* LDAP can't bind with a blank password. Seen as "anonymous" + * and always granted access + */ + if (debug) + fprintf(stderr, "Blank password given\n"); + return 1; } if (searchfilter) { - char filter[16384]; - char escaped_login[1024]; - LDAPMessage *res = NULL; - LDAPMessage *entry; - char *searchattr[] = - {(char *)LDAP_NO_ATTRS, NULL}; - char *userdn; - int rc; - LDAP *search_ld = persistent_ld; - - if (!search_ld) - search_ld = open_ldap_connection(ldapServer, port); - - ldap_escape_value(escaped_login, sizeof(escaped_login), userid); - if (binddn) { - rc = ldap_simple_bind_s(search_ld, binddn, bindpasswd); - if (rc != LDAP_SUCCESS) { - fprintf(stderr, PROGRAM_NAME ": WARNING, could not bind to binddn '%s'\n", ldap_err2string(rc)); - ret = 1; - goto search_done; - } - } - snprintf(filter, sizeof(filter), searchfilter, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login); - if (debug) - fprintf(stderr, "user filter '%s', searchbase '%s'\n", filter, basedn); - rc = ldap_search_s(search_ld, basedn, searchscope, filter, searchattr, 1, &res); - if (rc != LDAP_SUCCESS) { - if (noreferrals && rc == LDAP_PARTIAL_RESULTS) { - /* Everything is fine. This is expected when referrals - * are disabled. - */ - if (debug) - fprintf(stderr, "noreferrals && rc == LDAP_PARTIAL_RESULTS\n"); - } else { - fprintf(stderr, PROGRAM_NAME ": WARNING, LDAP search error '%s'\n", ldap_err2string(rc)); + char filter[16384]; + char escaped_login[1024]; + LDAPMessage *res = NULL; + LDAPMessage *entry; + char *searchattr[] = {(char *)LDAP_NO_ATTRS, NULL}; + char *userdn; + int rc; + LDAP *search_ld = persistent_ld; + + if (!search_ld) + search_ld = open_ldap_connection(ldapServer, port); + + ldap_escape_value(escaped_login, sizeof(escaped_login), userid); + if (binddn) { + rc = ldap_simple_bind_s(search_ld, binddn, bindpasswd); + if (rc != LDAP_SUCCESS) { + fprintf(stderr, PROGRAM_NAME ": WARNING, could not bind to binddn '%s'\n", ldap_err2string(rc)); + ret = 1; + goto search_done; + } + } + snprintf(filter, sizeof(filter), searchfilter, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login); + if (debug) + fprintf(stderr, "user filter '%s', searchbase '%s'\n", filter, basedn); + rc = ldap_search_s(search_ld, basedn, searchscope, filter, searchattr, 1, &res); + if (rc != LDAP_SUCCESS) { + if (noreferrals && rc == LDAP_PARTIAL_RESULTS) { + /* Everything is fine. This is expected when referrals + * are disabled. + */ + if (debug) + fprintf(stderr, "noreferrals && rc == LDAP_PARTIAL_RESULTS\n"); + } else { + fprintf(stderr, PROGRAM_NAME ": WARNING, LDAP search error '%s'\n", ldap_err2string(rc)); #if defined(NETSCAPE_SSL) - if (sslpath && ((rc == LDAP_SERVER_DOWN) || (rc == LDAP_CONNECT_ERROR))) { - int sslerr = PORT_GetError(); - fprintf(stderr, PROGRAM_NAME ": WARNING, SSL error %d (%s)\n", sslerr, ldapssl_err2string(sslerr)); - } + if (sslpath && ((rc == LDAP_SERVER_DOWN) || (rc == LDAP_CONNECT_ERROR))) { + int sslerr = PORT_GetError(); + fprintf(stderr, PROGRAM_NAME ": WARNING, SSL error %d (%s)\n", sslerr, ldapssl_err2string(sslerr)); + } #endif - ret = 1; - goto search_done; - } - } - entry = ldap_first_entry(search_ld, res); - if (!entry) { - if (debug) - fprintf(stderr, "Ldap search returned nothing\n"); - ret = 1; - goto search_done; - } - userdn = ldap_get_dn(search_ld, entry); - if (!userdn) { - fprintf(stderr, PROGRAM_NAME ": ERROR, could not get user DN for '%s'\n", userid); - ret = 1; - goto search_done; - } - snprintf(dn, sizeof(dn), "%s", userdn); - squid_ldap_memfree(userdn); - - if (ret == 0 && (!binddn || !bind_once || passwdattr)) { - /* Reuse the search connection for comparing the user password attribute */ - bind_ld = search_ld; - search_ld = NULL; - } - search_done: - if (res) { - ldap_msgfree(res); - res = NULL; - } - if (search_ld && search_ld != persistent_ld) { - ldap_unbind(search_ld); - search_ld = NULL; - } - if (ret != 0) - return ret; + ret = 1; + goto search_done; + } + } + entry = ldap_first_entry(search_ld, res); + if (!entry) { + if (debug) + fprintf(stderr, "Ldap search returned nothing\n"); + ret = 1; + goto search_done; + } + userdn = ldap_get_dn(search_ld, entry); + if (!userdn) { + fprintf(stderr, PROGRAM_NAME ": ERROR, could not get user DN for '%s'\n", userid); + ret = 1; + goto search_done; + } + snprintf(dn, sizeof(dn), "%s", userdn); + squid_ldap_memfree(userdn); + + if (ret == 0 && (!binddn || !bind_once || passwdattr)) { + /* Reuse the search connection for comparing the user password attribute */ + bind_ld = search_ld; + search_ld = NULL; + } +search_done: + if (res) { + ldap_msgfree(res); + res = NULL; + } + if (search_ld && search_ld != persistent_ld) { + ldap_unbind(search_ld); + search_ld = NULL; + } + if (ret != 0) + return ret; } else { - snprintf(dn, sizeof(dn), "%s=%s,%s", userattr, userid, basedn); + snprintf(dn, sizeof(dn), "%s=%s,%s", userattr, userid, basedn); } if (debug) - fprintf(stderr, "attempting to authenticate user '%s'\n", dn); + fprintf(stderr, "attempting to authenticate user '%s'\n", dn); if (!bind_ld && !bind_once) - bind_ld = persistent_ld; + bind_ld = persistent_ld; if (!bind_ld) - bind_ld = open_ldap_connection(ldapServer, port); + bind_ld = open_ldap_connection(ldapServer, port); if (passwdattr) { - if (ldap_compare_s(bind_ld, dn, passwdattr, password) != LDAP_COMPARE_TRUE) { - ret = 1; - } + if (ldap_compare_s(bind_ld, dn, passwdattr, password) != LDAP_COMPARE_TRUE) { + ret = 1; + } } else if (ldap_simple_bind_s(bind_ld, dn, password) != LDAP_SUCCESS) - ret = 1; + ret = 1; if (bind_ld != persistent_ld) { - ldap_unbind(bind_ld); - bind_ld = NULL; + ldap_unbind(bind_ld); + bind_ld = NULL; } return ret; } @@ -760,24 +759,24 @@ readSecret(const char *filename) char *passwd = NULL; if (!(f = fopen(filename, "r"))) { - fprintf(stderr, PROGRAM_NAME " ERROR: Can not read secret file %s\n", filename); - return 1; + fprintf(stderr, PROGRAM_NAME " ERROR: Can not read secret file %s\n", filename); + return 1; } if (!fgets(buf, sizeof(buf) - 1, f)) { - fprintf(stderr, PROGRAM_NAME " ERROR: Secret file %s is empty\n", filename); - fclose(f); - return 1; + fprintf(stderr, PROGRAM_NAME " ERROR: Secret file %s is empty\n", filename); + fclose(f); + return 1; } /* strip whitespaces on end */ if ((e = strrchr(buf, '\n'))) - *e = 0; + *e = 0; if ((e = strrchr(buf, '\r'))) - *e = 0; + *e = 0; passwd = (char *) calloc(sizeof(char), strlen(buf) + 1); if (!passwd) { - fprintf(stderr, PROGRAM_NAME " ERROR: can not allocate memory\n"); - exit(1); + fprintf(stderr, PROGRAM_NAME " ERROR: can not allocate memory\n"); + exit(1); } strcpy(passwd, buf); bindpasswd = passwd; diff --git a/helpers/basic_auth/MSNT/allowusers.c b/helpers/basic_auth/MSNT/allowusers.c index c161dd527e..d16f75f56c 100644 --- a/helpers/basic_auth/MSNT/allowusers.c +++ b/helpers/basic_auth/MSNT/allowusers.c @@ -3,7 +3,7 @@ * allowusers.c * (C) 2000 Antonino Iannella, Stellar-X Pty Ltd * Released under GPL, see COPYING-2.0 for details. - * + * * These routines are to allow users attempting to use the proxy which * have been explicitly allowed by the system administrator. * The code originated from denyusers.c. @@ -27,13 +27,13 @@ int Read_allowusers(void) { if (!init) { - memset(&AllowUsers, '\0', sizeof(AllowUsers)); - init = 1; + memset(&AllowUsers, '\0', sizeof(AllowUsers)); + init = 1; } if (*Allowuserpath) - return Read_usersfile(Allowuserpath, &AllowUsers); + return Read_usersfile(Allowuserpath, &AllowUsers); else - return 0; + return 0; } int diff --git a/helpers/basic_auth/MSNT/byteorder.h b/helpers/basic_auth/MSNT/byteorder.h index 1856df9392..b901f20d8f 100644 --- a/helpers/basic_auth/MSNT/byteorder.h +++ b/helpers/basic_auth/MSNT/byteorder.h @@ -1,19 +1,19 @@ -/* +/* * Unix SMB/Netbios implementation. * Version 1.9. * SMB Byte handling * Copyright (C) Andrew Tridgell 1992-1995 - * + * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -23,13 +23,13 @@ #define _BYTEORDER_H_ /* - * This file implements macros for machine independent short and + * This file implements macros for machine independent short and * int manipulation */ #undef CAREFUL_ALIGNMENT -/* we know that the 386 can handle misalignment and has the "right" +/* we know that the 386 can handle misalignment and has the "right" * byteorder */ #ifdef __i386__ #define CAREFUL_ALIGNMENT 0 @@ -62,7 +62,7 @@ typedef unsigned int uint32; * alignment errors */ /* * WARNING: This section is dependent on the length of int16 and int32 - * being correct + * being correct */ #define SVAL(buf,pos) (*(uint16 *)((char *)(buf) + (pos))) #define IVAL(buf,pos) (*(uint32 *)((char *)(buf) + (pos))) diff --git a/helpers/basic_auth/MSNT/confload.c b/helpers/basic_auth/MSNT/confload.c index d30af41138..e04365ed70 100644 --- a/helpers/basic_auth/MSNT/confload.c +++ b/helpers/basic_auth/MSNT/confload.c @@ -3,10 +3,10 @@ * confload.c * (C) 2000 Antonino Iannella, Stellar-X Pty Ltd * Released under GPL, see COPYING-2.0 for details. - * + * * These routines load the msntauth configuration file. * It stores the servers to query, sets the denied and - * allowed user files, and provides the + * allowed user files, and provides the * authenticating function. */ @@ -73,17 +73,17 @@ OpenConfigFile(void) /* Open file */ if ((ConfigFile = fopen(CONFIGFILE, "r")) == NULL) { - syslog(LOG_ERR, "OpenConfigFile: Failed to open %s.", CONFIGFILE); - syslog(LOG_ERR, "%s", strerror(errno)); - return 1; + syslog(LOG_ERR, "OpenConfigFile: Failed to open %s.", CONFIGFILE); + syslog(LOG_ERR, "%s", strerror(errno)); + return 1; } /* Read in, one line at a time */ while (!feof(ConfigFile)) { - Confbuf[0] = '\0'; - if (NULL == fgets(Confbuf, 2048, ConfigFile)) - break; - Confbuf[2048] = '\0'; - ProcessLine(Confbuf); + Confbuf[0] = '\0'; + if (NULL == fgets(Confbuf, 2048, ConfigFile)) + break; + Confbuf[2048] = '\0'; + ProcessLine(Confbuf); } /* @@ -92,8 +92,8 @@ OpenConfigFile(void) * not set in the confugration file. */ if (Serversqueried == 0) { - syslog(LOG_ERR, "OpenConfigFile: No servers set in %s. At least one is needed.", CONFIGFILE); - return 1; + syslog(LOG_ERR, "OpenConfigFile: No servers set in %s. At least one is needed.", CONFIGFILE); + return 1; } fclose(ConfigFile); return 0; @@ -111,59 +111,59 @@ ProcessLine(char *Linebuf) /* Ignore empty lines */ if (strlen(Linebuf) == 0) - return; + return; /* Break up on whitespaces */ if ((Directive = strtok(Linebuf, " \t\n")) == NULL) - return; + return; /* Check for a comment line. If found, stop . */ if (Directive[0] == '#') - return; + return; /* Check for server line. Check for 3 parameters. */ if (strcasecmp(Directive, "server") == 0) { - Param1 = strtok(NULL, " \t\n"); - if (NULL == Param1) { - syslog(LOG_ERR, "ProcessLine: 'server' missing PDC parameter."); - return; - } - Param2 = strtok(NULL, " \t\n"); - if (NULL == Param2) { - syslog(LOG_ERR, "ProcessLine: 'server' missing BDC parameter."); - return; - } - Param3 = strtok(NULL, " \t\n"); - if (NULL == Param3) { - syslog(LOG_ERR, "ProcessLine: 'server' missing domain parameter."); - return; - } - AddServer(Param1, Param2, Param3); - return; + Param1 = strtok(NULL, " \t\n"); + if (NULL == Param1) { + syslog(LOG_ERR, "ProcessLine: 'server' missing PDC parameter."); + return; + } + Param2 = strtok(NULL, " \t\n"); + if (NULL == Param2) { + syslog(LOG_ERR, "ProcessLine: 'server' missing BDC parameter."); + return; + } + Param3 = strtok(NULL, " \t\n"); + if (NULL == Param3) { + syslog(LOG_ERR, "ProcessLine: 'server' missing domain parameter."); + return; + } + AddServer(Param1, Param2, Param3); + return; } /* Check for denyusers line */ if (strcasecmp(Directive, "denyusers") == 0) { - Param1 = strtok(NULL, " \t\n"); - - if (NULL == Param1) { - syslog(LOG_ERR, "ProcessLine: A 'denyusers' line needs a filename parameter."); - return; - } - memset(Denyuserpath, '\0', MAXPATHLEN); - strncpy(Denyuserpath, Param1, MAXPATHLEN - 1); - return; + Param1 = strtok(NULL, " \t\n"); + + if (NULL == Param1) { + syslog(LOG_ERR, "ProcessLine: A 'denyusers' line needs a filename parameter."); + return; + } + memset(Denyuserpath, '\0', MAXPATHLEN); + strncpy(Denyuserpath, Param1, MAXPATHLEN - 1); + return; } /* Check for allowusers line */ if (strcasecmp(Directive, "allowusers") == 0) { - Param1 = strtok(NULL, " \t\n"); - - if (NULL == Param1) { - syslog(LOG_ERR, "ProcessLine: An 'allowusers' line needs a filename parameter."); - return; - } - memset(Allowuserpath, '\0', MAXPATHLEN); - strncpy(Allowuserpath, Param1, MAXPATHLEN - 1); - return; + Param1 = strtok(NULL, " \t\n"); + + if (NULL == Param1) { + syslog(LOG_ERR, "ProcessLine: An 'allowusers' line needs a filename parameter."); + return; + } + memset(Allowuserpath, '\0', MAXPATHLEN); + strncpy(Allowuserpath, Param1, MAXPATHLEN - 1); + return; } /* Reports error for unknown line */ syslog(LOG_ERR, "ProcessLine: Ignoring '%s' line.", Directive); @@ -180,19 +180,19 @@ void AddServer(char *ParamPDC, char *ParamBDC, char *ParamDomain) { if (Serversqueried == MAXSERVERS) { - syslog(LOG_ERR, "AddServer: Ignoring '%s' server line; " - "too many servers.", ParamPDC); - return; + syslog(LOG_ERR, "AddServer: Ignoring '%s' server line; " + "too many servers.", ParamPDC); + return; } if (gethostbyname(ParamPDC) == NULL) { - syslog(LOG_ERR, "AddServer: Ignoring host '%s'. " - "Cannot resolve its address.", ParamPDC); - return; + syslog(LOG_ERR, "AddServer: Ignoring host '%s'. " + "Cannot resolve its address.", ParamPDC); + return; } if (gethostbyname(ParamBDC) == NULL) { - syslog(LOG_USER | LOG_ERR, "AddServer: Ignoring host '%s'. " - "Cannot resolve its address.", ParamBDC); - return; + syslog(LOG_USER | LOG_ERR, "AddServer: Ignoring host '%s'. " + "Cannot resolve its address.", ParamBDC); + return; } /* NOTE: ServerArray is zeroed in OpenConfigFile() */ assert(Serversqueried < MAXSERVERS); @@ -213,8 +213,8 @@ QueryServers(char *username, char *password) { int i; for (i = 0; i < Serversqueried; i++) { - if (0 == QueryServerForUser(i, username, password)) - return 0; + if (0 == QueryServerForUser(i, username, password)) + return 0; } return 1; } @@ -236,30 +236,30 @@ QueryServerForUser(int x, char *username, char *password) int result = 1; result = Valid_User(username, password, ServerArray[x].pdc, - ServerArray[x].bdc, ServerArray[x].domain); + ServerArray[x].bdc, ServerArray[x].domain); switch (result) { /* Write any helpful syslog messages */ case 0: - break; + break; case 1: - syslog(LOG_AUTHPRIV | LOG_INFO, "Server error when checking %s.", - username); - break; + syslog(LOG_AUTHPRIV | LOG_INFO, "Server error when checking %s.", + username); + break; case 2: - syslog(LOG_AUTHPRIV | LOG_INFO, "Protocol error when checking %s.", - username); - break; + syslog(LOG_AUTHPRIV | LOG_INFO, "Protocol error when checking %s.", + username); + break; case 3: - syslog(LOG_AUTHPRIV | LOG_INFO, "Authentication failed for %s.", - username); - break; + syslog(LOG_AUTHPRIV | LOG_INFO, "Authentication failed for %s.", + username); + break; } return result; } /* Valid_User return codes - - * + * * 0 - User authenticated successfully. * 1 - Server error. * 2 - Protocol error. diff --git a/helpers/basic_auth/MSNT/denyusers.c b/helpers/basic_auth/MSNT/denyusers.c index fd44f2f3a6..1f91860fc1 100644 --- a/helpers/basic_auth/MSNT/denyusers.c +++ b/helpers/basic_auth/MSNT/denyusers.c @@ -3,7 +3,7 @@ * denyusers.c * (C) 2000 Antonino Iannella, Stellar-X Pty Ltd * Released under GPL, see COPYING-2.0 for details. - * + * * These routines are to block users attempting to use the proxy which * have been explicitly denied by the system administrator. * Routines at the bottom also use the allowed user functions. @@ -28,13 +28,13 @@ int Read_denyusers(void) { if (!init) { - memset(&DenyUsers, '\0', sizeof(DenyUsers)); - init = 1; + memset(&DenyUsers, '\0', sizeof(DenyUsers)); + init = 1; } if (*Denyuserpath) - return Read_usersfile(Denyuserpath, &DenyUsers); + return Read_usersfile(Denyuserpath, &DenyUsers); else - return 0; + return 0; } static void @@ -54,11 +54,11 @@ Check_ifuserdenied(char *ConnectingUser) { /* If user string is empty, deny */ if (ConnectingUser[0] == '\0') - return 1; + return 1; /* If denied user list is empty, allow */ if (DenyUsers.Inuse == 0) - return 0; + return 0; return Check_userlist(&DenyUsers, ConnectingUser); } @@ -73,10 +73,10 @@ int Check_user(char *ConnectingUser) { if (Check_ifuserdenied(ConnectingUser) == 1) - return 1; + return 1; if (Check_ifuserallowed(ConnectingUser) == 0) - return 1; + return 1; return 0; } @@ -110,9 +110,9 @@ Checktimer() /* If timeout has expired, check the denied user file, else return */ if (difftime(Currenttime, Lasttime) < 60) - return; + return; else { - Check_forchange(-1); - Lasttime = Currenttime; + Check_forchange(-1); + Lasttime = Currenttime; } } diff --git a/helpers/basic_auth/MSNT/md4.c b/helpers/basic_auth/MSNT/md4.c index b9793cd62d..5eaa0e019b 100644 --- a/helpers/basic_auth/MSNT/md4.c +++ b/helpers/basic_auth/MSNT/md4.c @@ -1,19 +1,19 @@ -/* +/* * Unix SMB/Netbios implementation. * Version 1.9. * a implementation of MD4 designed for use in the SMB authentication protocol * Copyright (C) Andrew Tridgell 1997 - * + * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -22,8 +22,8 @@ #include #include "md4.h" -/* NOTE: This code makes no attempt to be fast! - * +/* NOTE: This code makes no attempt to be fast! + * * It assumes that a int is at least 32 bits long */ @@ -69,7 +69,7 @@ mdfour64(uint32 * M) uint32 X[16]; for (j = 0; j < 16; j++) - X[j] = M[j]; + X[j] = M[j]; AA = A; BB = B; @@ -138,7 +138,7 @@ mdfour64(uint32 * M) D &= 0xFFFFFFFF; for (j = 0; j < 16; j++) - X[j] = 0; + X[j] = 0; } static void @@ -147,8 +147,8 @@ copy64(uint32 * M, unsigned char *in) int i; for (i = 0; i < 16; i++) - M[i] = (in[i * 4 + 3] << 24) | (in[i * 4 + 2] << 16) | - (in[i * 4 + 1] << 8) | (in[i * 4 + 0] << 0); + M[i] = (in[i * 4 + 3] << 24) | (in[i * 4 + 2] << 16) | + (in[i * 4 + 1] << 8) | (in[i * 4 + 0] << 0); } static void @@ -175,31 +175,31 @@ mdfour(unsigned char *out, unsigned char *in, int n) D = 0x10325476; while (n > 64) { - copy64(M, in); - mdfour64(M); - in += 64; - n -= 64; + copy64(M, in); + mdfour64(M); + in += 64; + n -= 64; } for (i = 0; i < 128; i++) - buf[i] = 0; + buf[i] = 0; memcpy(buf, in, n); buf[n] = 0x80; if (n <= 55) { - copy4(buf + 56, b); - copy64(M, buf); - mdfour64(M); + copy4(buf + 56, b); + copy64(M, buf); + mdfour64(M); } else { - copy4(buf + 120, b); - copy64(M, buf); - mdfour64(M); - copy64(M, buf + 64); - mdfour64(M); + copy4(buf + 120, b); + copy64(M, buf); + mdfour64(M); + copy64(M, buf + 64); + mdfour64(M); } for (i = 0; i < 128; i++) - buf[i] = 0; + buf[i] = 0; copy64(M, buf); copy4(out, A); diff --git a/helpers/basic_auth/MSNT/msntauth.c b/helpers/basic_auth/MSNT/msntauth.c index 38dd410757..ea72f2fca8 100644 --- a/helpers/basic_auth/MSNT/msntauth.c +++ b/helpers/basic_auth/MSNT/msntauth.c @@ -3,29 +3,29 @@ * MSNT - Microsoft Windows NT domain squid authenticator module * Version 2.0 by Stellar-X Pty Ltd, Antonino Iannella * Sun Sep 2 14:39:53 CST 2001 - * + * * Modified to act as a Squid authenticator module. * Removed all Pike stuff. * Returns OK for a successful authentication, or ERR upon error. - * + * * Uses code from - * Andrew Tridgell 1997 * Richard Sharpe 1996 * Bill Welliver 1999 * Duane Wessels 2000 (wessels@squid-cache.org) - * + * * Released under GNU Public License - * + * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -62,7 +62,7 @@ main(int argc, char **argv) /* Read configuration file. Abort wildly if error. */ if (OpenConfigFile() == 1) - return 1; + return 1; /* * Read denied and allowed user files. @@ -71,11 +71,11 @@ main(int argc, char **argv) * The msntauth process should then be killed. */ if ((Read_denyusers() == 1) || (Read_allowusers() == 1)) { - while (1) { - memset(wstr, '\0', sizeof(wstr)); - fgets(wstr, 255, stdin); - puts("ERR"); - } + while (1) { + memset(wstr, '\0', sizeof(wstr)); + fgets(wstr, 255, stdin); + puts("ERR"); + } } /* * Make Check_forchange() the handle for HUP signals. @@ -86,57 +86,57 @@ main(int argc, char **argv) signal(SIGHUP, Check_forchange); while (1) { - int n; - /* Read whole line from standard input. Terminate on break. */ - memset(wstr, '\0', sizeof(wstr)); - if (fgets(wstr, 255, stdin) == NULL) - break; - /* ignore this line if we didn't get the end-of-line marker */ - if (NULL == strchr(wstr, '\n')) { - err = 1; - continue; - } - if (err) { - syslog(LOG_WARNING, "oversized message"); - goto error; - } + int n; + /* Read whole line from standard input. Terminate on break. */ + memset(wstr, '\0', sizeof(wstr)); + if (fgets(wstr, 255, stdin) == NULL) + break; + /* ignore this line if we didn't get the end-of-line marker */ + if (NULL == strchr(wstr, '\n')) { + err = 1; + continue; + } + if (err) { + syslog(LOG_WARNING, "oversized message"); + goto error; + } - /* - * extract username and password. - * XXX is sscanf() safe? - */ - username[0] = '\0'; - password[0] = '\0'; - n = sscanf(wstr, "%s %[^\n]", username, password); - if (2 != n) { - puts("ERR"); - continue; - } - /* Check for invalid or blank entries */ - if ((username[0] == '\0') || (password[0] == '\0')) { - puts("ERR"); - continue; - } - Checktimer(); /* Check if the user lists have changed */ + /* + * extract username and password. + * XXX is sscanf() safe? + */ + username[0] = '\0'; + password[0] = '\0'; + n = sscanf(wstr, "%s %[^\n]", username, password); + if (2 != n) { + puts("ERR"); + continue; + } + /* Check for invalid or blank entries */ + if ((username[0] == '\0') || (password[0] == '\0')) { + puts("ERR"); + continue; + } + Checktimer(); /* Check if the user lists have changed */ - rfc1738_unescape(username); - rfc1738_unescape(password); + rfc1738_unescape(username); + rfc1738_unescape(password); - /* - * Check if user is explicitly denied or allowed. - * If user passes both checks, they can be authenticated. - */ - if (Check_user(username) == 1) { - syslog(LOG_INFO, "'%s' denied", username); - puts("ERR"); - } else if (QueryServers(username, password) == 0) - puts("OK"); - else { - syslog(LOG_INFO, "'%s' login failed", username); + /* + * Check if user is explicitly denied or allowed. + * If user passes both checks, they can be authenticated. + */ + if (Check_user(username) == 1) { + syslog(LOG_INFO, "'%s' denied", username); + puts("ERR"); + } else if (QueryServers(username, password) == 0) + puts("OK"); + else { + syslog(LOG_INFO, "'%s' login failed", username); error: - puts("ERR"); - } - err = 0; + puts("ERR"); + } + err = 0; } return 0; diff --git a/helpers/basic_auth/MSNT/rfcnb-common.h b/helpers/basic_auth/MSNT/rfcnb-common.h index fab20c4f6e..45c223b5f4 100644 --- a/helpers/basic_auth/MSNT/rfcnb-common.h +++ b/helpers/basic_auth/MSNT/rfcnb-common.h @@ -1,10 +1,10 @@ /* UNIX RFCNB (RFC1001/RFC1002) NetBIOS implementation - * + * * Version 1.0 * RFCNB Common Structures etc Defines - * + * * Copyright (C) Richard Sharpe 1996 - * + * */ /* @@ -12,12 +12,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. diff --git a/helpers/basic_auth/MSNT/rfcnb-error.h b/helpers/basic_auth/MSNT/rfcnb-error.h index 77ca769ec2..60d36b555c 100644 --- a/helpers/basic_auth/MSNT/rfcnb-error.h +++ b/helpers/basic_auth/MSNT/rfcnb-error.h @@ -1,10 +1,10 @@ /* UNIX RFCNB (RFC1001/RFC1002) NetBIOS implementation - * + * * Version 1.0 * RFCNB Error Response Defines - * + * * Copyright (C) Richard Sharpe 1996 - * + * */ /* @@ -12,12 +12,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. diff --git a/helpers/basic_auth/MSNT/rfcnb-io.c b/helpers/basic_auth/MSNT/rfcnb-io.c index 53c5be5c9e..939b13d85e 100644 --- a/helpers/basic_auth/MSNT/rfcnb-io.c +++ b/helpers/basic_auth/MSNT/rfcnb-io.c @@ -1,10 +1,10 @@ /* UNIX RFCNB (RFC1001/RFC1002) NEtBIOS implementation - * + * * Version 1.0 * RFCNB IO Routines ... - * + * * Copyright (C) Richard Sharpe 1996 - * + * */ /* @@ -12,12 +12,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -56,7 +56,7 @@ RFCNB_Set_Timeout(int seconds) int x; RFCNB_Timeout = seconds; if (RFCNB_Timeout <= 0) - return 0; + return 0; #ifdef SA_RESTART sa.sa_handler = rfcnb_alarm; sa.sa_flags = 0; @@ -67,8 +67,8 @@ RFCNB_Set_Timeout(int seconds) signal(SIGALRM, rfcnb_alarm); #endif if (x < 0) { - syslog(LOG_ERR, "%s:%d: signal/sigaction: %s", __FILE__, __LINE__, strerror(errno)); - return -1; + syslog(LOG_ERR, "%s:%d: signal/sigaction: %s", __FILE__, __LINE__, strerror(errno)); + return -1; } return 0; } @@ -98,22 +98,22 @@ RFCNB_Discard_Rest(struct RFCNB_Con *con, int len) while (rest > 0) { - this_read = (rest > sizeof(temp) ? sizeof(temp) : rest); + this_read = (rest > sizeof(temp) ? sizeof(temp) : rest); - bytes_read = read(con->fd, temp, this_read); + bytes_read = read(con->fd, temp, this_read); - if (bytes_read <= 0) { /* Error so return */ + if (bytes_read <= 0) { /* Error so return */ - if (bytes_read < 0) - RFCNB_errno = RFCNBE_BadRead; - else - RFCNB_errno = RFCNBE_ConGone; + if (bytes_read < 0) + RFCNB_errno = RFCNBE_BadRead; + else + RFCNB_errno = RFCNBE_ConGone; - RFCNB_saved_errno = errno; - return (RFCNBE_Bad); + RFCNB_saved_errno = errno; + return (RFCNBE_Bad); - } - rest = rest - bytes_read; + } + rest = rest - bytes_read; } @@ -123,11 +123,11 @@ RFCNB_Discard_Rest(struct RFCNB_Con *con, int len) /* Send an RFCNB packet to the connection. - * - * We just send each of the blocks linked together ... - * - * If we can, try to send it as one iovec ... - * + * + * We just send each of the blocks linked together ... + * + * If we can, try to send it as one iovec ... + * */ int @@ -147,23 +147,23 @@ RFCNB_Put_Pkt(struct RFCNB_Con *con, struct RFCNB_Pkt *pkt, int len) while ((pkt_ptr != NULL) & (i < 10)) { /* Watch that magic number! */ - this_len = pkt_ptr->len; - this_data = pkt_ptr->data; - if ((tot_sent + this_len) > len) - this_len = len - tot_sent; /* Adjust so we don't send too much */ + this_len = pkt_ptr->len; + this_data = pkt_ptr->data; + if ((tot_sent + this_len) > len) + this_len = len - tot_sent; /* Adjust so we don't send too much */ - /* Now plug into the iovec ... */ + /* Now plug into the iovec ... */ - io_list[i].iov_len = this_len; - io_list[i].iov_base = this_data; - i++; + io_list[i].iov_len = this_len; + io_list[i].iov_base = this_data; + i++; - tot_sent += this_len; + tot_sent += this_len; - if (tot_sent == len) - break; /* Let's not send too much */ + if (tot_sent == len) + break; /* Let's not send too much */ - pkt_ptr = pkt_ptr->next; + pkt_ptr = pkt_ptr->next; } @@ -174,29 +174,29 @@ RFCNB_Put_Pkt(struct RFCNB_Con *con, struct RFCNB_Pkt *pkt, int len) /* Set up an alarm if timeouts are set ... */ if (RFCNB_Timeout > 0) - alarm(RFCNB_Timeout); + alarm(RFCNB_Timeout); if ((len_sent = writev(con->fd, io_list, i)) < 0) { /* An error */ - con->rfc_errno = errno; - if (errno == EINTR) /* We were interrupted ... */ - RFCNB_errno = RFCNBE_Timeout; - else - RFCNB_errno = RFCNBE_BadWrite; - RFCNB_saved_errno = errno; - return (RFCNBE_Bad); + con->rfc_errno = errno; + if (errno == EINTR) /* We were interrupted ... */ + RFCNB_errno = RFCNBE_Timeout; + else + RFCNB_errno = RFCNBE_BadWrite; + RFCNB_saved_errno = errno; + return (RFCNBE_Bad); } if (len_sent < tot_sent) { /* Less than we wanted */ - if (errno == EINTR) /* We were interrupted */ - RFCNB_errno = RFCNBE_Timeout; - else - RFCNB_errno = RFCNBE_BadWrite; - RFCNB_saved_errno = errno; - return (RFCNBE_Bad); + if (errno == EINTR) /* We were interrupted */ + RFCNB_errno = RFCNBE_Timeout; + else + RFCNB_errno = RFCNBE_BadWrite; + RFCNB_saved_errno = errno; + return (RFCNBE_Bad); } if (RFCNB_Timeout > 0) - alarm(0); /* Reset that sucker */ + alarm(0); /* Reset that sucker */ #ifdef RFCNB_DEBUG @@ -209,11 +209,11 @@ RFCNB_Put_Pkt(struct RFCNB_Con *con, struct RFCNB_Pkt *pkt, int len) } -/* Read an RFCNB packet off the connection. - * +/* Read an RFCNB packet off the connection. + * * We read the first 4 bytes, that tells us the length, then read the - * rest. We should implement a timeout, but we don't just yet - * + * rest. We should implement a timeout, but we don't just yet + * */ @@ -231,58 +231,58 @@ RFCNB_Get_Pkt(struct RFCNB_Con *con, struct RFCNB_Pkt *pkt, int len) if (len < RFCNB_Pkt_Hdr_Len) { /* What a bozo */ #ifdef RFCNB_DEBUG - fprintf(stderr, "Trying to read less than a packet:"); - perror(""); + fprintf(stderr, "Trying to read less than a packet:"); + perror(""); #endif - RFCNB_errno = RFCNBE_BadParam; - return (RFCNBE_Bad); + RFCNB_errno = RFCNBE_BadParam; + return (RFCNBE_Bad); } /* We discard keep alives here ... */ if (RFCNB_Timeout > 0) - alarm(RFCNB_Timeout); + alarm(RFCNB_Timeout); while (seen_keep_alive) { - if ((read_len = read(con->fd, hdr, sizeof(hdr))) < 0) { /* Problems */ + if ((read_len = read(con->fd, hdr, sizeof(hdr))) < 0) { /* Problems */ #ifdef RFCNB_DEBUG - fprintf(stderr, "Reading the packet, we got:"); - perror(""); + fprintf(stderr, "Reading the packet, we got:"); + perror(""); #endif - if (errno == EINTR) - RFCNB_errno = RFCNBE_Timeout; - else - RFCNB_errno = RFCNBE_BadRead; - RFCNB_saved_errno = errno; - return (RFCNBE_Bad); + if (errno == EINTR) + RFCNB_errno = RFCNBE_Timeout; + else + RFCNB_errno = RFCNBE_BadRead; + RFCNB_saved_errno = errno; + return (RFCNBE_Bad); - } - /* Now we check out what we got */ + } + /* Now we check out what we got */ - if (read_len == 0) { /* Connection closed, send back eof? */ + if (read_len == 0) { /* Connection closed, send back eof? */ #ifdef RFCNB_DEBUG - fprintf(stderr, "Connection closed reading\n"); + fprintf(stderr, "Connection closed reading\n"); #endif - if (errno == EINTR) - RFCNB_errno = RFCNBE_Timeout; - else - RFCNB_errno = RFCNBE_ConGone; - RFCNB_saved_errno = errno; - return (RFCNBE_Bad); + if (errno == EINTR) + RFCNB_errno = RFCNBE_Timeout; + else + RFCNB_errno = RFCNBE_ConGone; + RFCNB_saved_errno = errno; + return (RFCNBE_Bad); - } - if (RFCNB_Pkt_Type(hdr) == RFCNB_SESSION_KEEP_ALIVE) { + } + if (RFCNB_Pkt_Type(hdr) == RFCNB_SESSION_KEEP_ALIVE) { #ifdef RFCNB_DEBUG - fprintf(stderr, "RFCNB KEEP ALIVE received\n"); + fprintf(stderr, "RFCNB KEEP ALIVE received\n"); #endif - } else { - seen_keep_alive = FALSE; - } + } else { + seen_keep_alive = FALSE; + } } @@ -290,15 +290,15 @@ RFCNB_Get_Pkt(struct RFCNB_Con *con, struct RFCNB_Pkt *pkt, int len) if (read_len < sizeof(hdr)) { /* We got a small packet */ - /* Now we need to copy the hdr portion we got into the supplied packet */ + /* Now we need to copy the hdr portion we got into the supplied packet */ - memcpy(pkt->data, hdr, read_len); /*Copy data */ + memcpy(pkt->data, hdr, read_len); /*Copy data */ #ifdef RFCNB_DEBUG - RFCNB_Print_Pkt(stderr, "rcvd", pkt, read_len); + RFCNB_Print_Pkt(stderr, "rcvd", pkt, read_len); #endif - return (read_len); + return (read_len); } /* Now, if we got at least a hdr size, alloc space for rest, if we need it */ @@ -318,65 +318,65 @@ RFCNB_Get_Pkt(struct RFCNB_Con *con, struct RFCNB_Pkt *pkt, int len) /* use an iovec ... */ if (len < pkt_len) /* Only get as much as we have space for */ - more = len - RFCNB_Pkt_Hdr_Len; + more = len - RFCNB_Pkt_Hdr_Len; else - more = pkt_len; + more = pkt_len; this_time = 0; /* We read for each fragment ... */ if (pkt->len == read_len) { /* If this frag was exact size */ - pkt_frag = pkt->next; /* Stick next lot in next frag */ - offset = 0; /* then we start at 0 in next */ + pkt_frag = pkt->next; /* Stick next lot in next frag */ + offset = 0; /* then we start at 0 in next */ } else { - pkt_frag = pkt; /* Otherwise use rest of this frag */ - offset = RFCNB_Pkt_Hdr_Len; /* Otherwise skip the header */ + pkt_frag = pkt; /* Otherwise use rest of this frag */ + offset = RFCNB_Pkt_Hdr_Len; /* Otherwise skip the header */ } frag_len = pkt_frag->len; if (more <= frag_len) /* If len left to get less than frag space */ - this_len = more; /* Get the rest ... */ + this_len = more; /* Get the rest ... */ else - this_len = frag_len - offset; + this_len = frag_len - offset; while (more > 0) { - if ((this_time = read(con->fd, (pkt_frag->data) + offset, this_len)) <= 0) { /* Problems */ + if ((this_time = read(con->fd, (pkt_frag->data) + offset, this_len)) <= 0) { /* Problems */ - if (errno == EINTR) { + if (errno == EINTR) { - RFCNB_errno = RFCNB_Timeout; + RFCNB_errno = RFCNB_Timeout; - } else { - if (this_time < 0) - RFCNB_errno = RFCNBE_BadRead; - else - RFCNB_errno = RFCNBE_ConGone; - } + } else { + if (this_time < 0) + RFCNB_errno = RFCNBE_BadRead; + else + RFCNB_errno = RFCNBE_ConGone; + } - RFCNB_saved_errno = errno; - return (RFCNBE_Bad); + RFCNB_saved_errno = errno; + return (RFCNBE_Bad); - } + } #ifdef RFCNB_DEBUG - fprintf(stderr, "Frag_Len = %i, this_time = %i, this_len = %i, more = %i\n", frag_len, - this_time, this_len, more); + fprintf(stderr, "Frag_Len = %i, this_time = %i, this_len = %i, more = %i\n", frag_len, + this_time, this_len, more); #endif - read_len = read_len + this_time; /* How much have we read ... */ + read_len = read_len + this_time; /* How much have we read ... */ - /* Now set up the next part */ + /* Now set up the next part */ - if (pkt_frag->next == NULL) - break; /* That's it here */ + if (pkt_frag->next == NULL) + break; /* That's it here */ - pkt_frag = pkt_frag->next; - this_len = pkt_frag->len; - offset = 0; + pkt_frag = pkt_frag->next; + this_len = pkt_frag->len; + offset = 0; - more = more - this_time; + more = more - this_time; } @@ -387,11 +387,11 @@ RFCNB_Get_Pkt(struct RFCNB_Con *con, struct RFCNB_Pkt *pkt, int len) if (read_len < (pkt_len + sizeof(hdr))) { /* Discard the rest */ - return (RFCNB_Discard_Rest(con, (pkt_len + sizeof(hdr)) - read_len)); + return (RFCNB_Discard_Rest(con, (pkt_len + sizeof(hdr)) - read_len)); } if (RFCNB_Timeout > 0) - alarm(0); /* Reset that sucker */ + alarm(0); /* Reset that sucker */ return (read_len + sizeof(RFCNB_Hdr)); } diff --git a/helpers/basic_auth/MSNT/rfcnb-io.h b/helpers/basic_auth/MSNT/rfcnb-io.h index 267d12f854..6b54e86e05 100644 --- a/helpers/basic_auth/MSNT/rfcnb-io.h +++ b/helpers/basic_auth/MSNT/rfcnb-io.h @@ -1,10 +1,10 @@ /* UNIX RFCNB (RFC1001/RFC1002) NetBIOS implementation - * + * * Version 1.0 * RFCNB IO Routines Defines - * + * * Copyright (C) Richard Sharpe 1996 - * + * */ /* @@ -12,12 +12,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. diff --git a/helpers/basic_auth/MSNT/rfcnb-priv.h b/helpers/basic_auth/MSNT/rfcnb-priv.h index 1e906b3bdd..d847b3c877 100644 --- a/helpers/basic_auth/MSNT/rfcnb-priv.h +++ b/helpers/basic_auth/MSNT/rfcnb-priv.h @@ -1,10 +1,10 @@ /* UNIX RFCNB (RFC1001/RFC1002) NetBIOS implementation - * + * * Version 1.0 * RFCNB Defines - * + * * Copyright (C) Richard Sharpe 1996 - * + * */ /* @@ -12,12 +12,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -73,8 +73,8 @@ typedef struct RFCNB_Con { } RFCNB_Con; typedef char RFCNB_Hdr[4]; /* The header is 4 bytes long with */ - /* char[0] as the type, char[1] the */ - /* flags, and char[2..3] the length */ +/* char[0] as the type, char[1] the */ +/* flags, and char[2..3] the length */ /* Macros to extract things from the header. These are for portability * between architecture types where we are worried about byte order */ @@ -107,13 +107,13 @@ typedef char RFCNB_Hdr[4]; /* The header is 4 bytes long with */ #define RFCNB_Pkt_Type(p) (CVAL(p, RFCNB_Pkt_Type_Offset)) /*typedef struct RFCNB_Hdr { - * + * * unsigned char type; * unsigned char flags; * int16 len; - * + * * } RFCNB_Hdr; - * + * * typedef struct RFCNB_Sess_Pkt { * unsigned char type; * unsigned char flags; @@ -123,21 +123,21 @@ typedef char RFCNB_Hdr[4]; /* The header is 4 bytes long with */ * unsigned char n2_len; * char calling_name[33]; * } RFCNB_Sess_Pkt; - * - * + * + * * typedef struct RFCNB_Nack_Pkt { - * + * * struct RFCNB_Hdr hdr; * unsigned char error; - * + * * } RFCNB_Nack_Pkt; - * + * * typedef struct RFCNB_Retarget_Pkt { - * + * * struct RFCNB_Hdr hdr; * int dest_ip; * unsigned char port; - * + * * } RFCNB_Redir_Pkt; */ /* Static variables */ diff --git a/helpers/basic_auth/MSNT/rfcnb-util.c b/helpers/basic_auth/MSNT/rfcnb-util.c index 8517c6ec1e..83ce111349 100644 --- a/helpers/basic_auth/MSNT/rfcnb-util.c +++ b/helpers/basic_auth/MSNT/rfcnb-util.c @@ -1,10 +1,10 @@ /* UNIX RFCNB (RFC1001/RFC1002) NetBIOS implementation - * + * * Version 1.0 * RFCNB Utility Routines ... - * + * * Copyright (C) Richard Sharpe 1996 - * + * */ /* @@ -12,12 +12,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -36,8 +36,7 @@ #include #include -const char *RFCNB_Error_Strings[] = -{ +const char *RFCNB_Error_Strings[] = { "RFCNBE_OK: Routine completed successfully.", "RFCNBE_NoSpace: No space available for a malloc call.", @@ -77,20 +76,20 @@ RFCNB_CvtPad_Name(char *name1, char *name2) for (i = 0; i < 16; i++) { - if (i >= len) { + if (i >= len) { - c1 = 'C'; - c2 = 'A'; /* CA is a space */ + c1 = 'C'; + c2 = 'A'; /* CA is a space */ - } else { + } else { - c = name1[i]; - c1 = (char) ((int) c / 16 + (int) 'A'); - c2 = (char) ((int) c % 16 + (int) 'A'); - } + c = name1[i]; + c1 = (char) ((int) c / 16 + (int) 'A'); + c2 = (char) ((int) c % 16 + (int) 'A'); + } - name2[i * 2] = c1; - name2[i * 2 + 1] = c2; + name2[i * 2] = c1; + name2[i * 2 + 1] = c2; } @@ -101,10 +100,10 @@ RFCNB_CvtPad_Name(char *name1, char *name2) /* Converts an Ascii NB Name (16 chars) to an RFCNB Name (32 chars) * Uses the encoding in RFC1001. Each nibble of byte is added to 'A' * to produce the next byte in the name. - * - * This routine assumes that AName is 16 bytes long and that NBName has - * space for 32 chars, so be careful ... - * + * + * This routine assumes that AName is 16 bytes long and that NBName has + * space for 32 chars, so be careful ... + * */ void @@ -115,13 +114,13 @@ RFCNB_AName_To_NBName(char *AName, char *NBName) for (i = 0; i < 16; i++) { - c = AName[i]; + c = AName[i]; - c1 = (char) ((c >> 4) + 'A'); - c2 = (char) ((c & 0xF) + 'A'); + c1 = (char) ((c >> 4) + 'A'); + c2 = (char) ((c & 0xF) + 'A'); - NBName[i * 2] = c1; - NBName[i * 2 + 1] = c2; + NBName[i * 2] = c1; + NBName[i * 2 + 1] = c2; } NBName[32] = 0; /* Put in a null */ @@ -138,12 +137,12 @@ RFCNB_NBName_To_AName(char *NBName, char *AName) for (i = 0; i < 16; i++) { - c1 = NBName[i * 2]; - c2 = NBName[i * 2 + 1]; + c1 = NBName[i * 2]; + c2 = NBName[i * 2 + 1]; - c = (char) (((int) c1 - (int) 'A') * 16 + ((int) c2 - (int) 'A')); + c = (char) (((int) c1 - (int) 'A') * 16 + ((int) c2 - (int) 'A')); - AName[i] = c; + AName[i] = c; } @@ -169,27 +168,27 @@ RFCNB_Print_Hex(FILE * fd, struct RFCNB_Pkt *pkt, int Offset, int Len) while (pkt_ptr != NULL) { - for (i = 0; - i < ((Len > (pkt_ptr->len) ? pkt_ptr->len : Len) - Offset); - i++) { + for (i = 0; + i < ((Len > (pkt_ptr->len) ? pkt_ptr->len : Len) - Offset); + i++) { - c = pkt_ptr->data[i + Offset]; - c1 = Hex_List[c >> 4]; - c2 = Hex_List[c & 0xF]; + c = pkt_ptr->data[i + Offset]; + c1 = Hex_List[c >> 4]; + c2 = Hex_List[c & 0xF]; - outbuf1[j++] = c1; - outbuf1[j++] = c2; + outbuf1[j++] = c1; + outbuf1[j++] = c2; - if (j == 32) { /* Print and reset */ - outbuf1[j] = 0; - fprintf(fd, " %s\n", outbuf1); - j = 0; - } - } + if (j == 32) { /* Print and reset */ + outbuf1[j] = 0; + fprintf(fd, " %s\n", outbuf1); + j = 0; + } + } - Offset = 0; - Len = Len - pkt_ptr->len; /* Reduce amount by this much */ - pkt_ptr = pkt_ptr->next; + Offset = 0; + Len = Len - pkt_ptr->len; /* Reduce amount by this much */ + pkt_ptr = pkt_ptr->next; } @@ -197,8 +196,8 @@ RFCNB_Print_Hex(FILE * fd, struct RFCNB_Pkt *pkt, int Offset, int Len) if (j > 0) { - outbuf1[j] = 0; - fprintf(fd, " %s\n", outbuf1); + outbuf1[j] = 0; + fprintf(fd, " %s\n", outbuf1); } fprintf(fd, "\n"); @@ -209,26 +208,25 @@ RFCNB_Print_Hex(FILE * fd, struct RFCNB_Pkt *pkt, int Offset, int Len) /* Get a packet of size n */ struct RFCNB_Pkt * -RFCNB_Alloc_Pkt(int n) -{ + RFCNB_Alloc_Pkt(int n) { RFCNB_Pkt *pkt; if ((pkt = malloc(sizeof(struct RFCNB_Pkt))) == NULL) { - RFCNB_errno = RFCNBE_NoSpace; - RFCNB_saved_errno = errno; - return (NULL); + RFCNB_errno = RFCNBE_NoSpace; + RFCNB_saved_errno = errno; + return (NULL); } pkt->next = NULL; pkt->len = n; if (n == 0) - return (pkt); + return (pkt); if ((pkt->data = malloc(n)) == NULL) { - RFCNB_errno = RFCNBE_NoSpace; - RFCNB_saved_errno = errno; - free(pkt); - return (NULL); + RFCNB_errno = RFCNBE_NoSpace; + RFCNB_saved_errno = errno; + free(pkt); + return (NULL); } return (pkt); @@ -243,14 +241,14 @@ RFCNB_Free_Pkt(struct RFCNB_Pkt *pkt) while (pkt != NULL) { - pkt_next = pkt->next; + pkt_next = pkt->next; - if (pkt->data != NULL) - free(pkt->data); + if (pkt->data != NULL) + free(pkt->data); - free(pkt); + free(pkt); - pkt = pkt_next; + pkt = pkt_next; } @@ -273,70 +271,70 @@ RFCNB_Print_Pkt(FILE * fd, char *dirn, struct RFCNB_Pkt *pkt, int len) case RFCNB_SESSION_MESSAGE: - fprintf(fd, "SESSION MESSAGE: Length = %i\n", RFCNB_Pkt_Len(pkt->data)); - RFCNB_Print_Hex(fd, pkt, RFCNB_Pkt_Hdr_Len, + fprintf(fd, "SESSION MESSAGE: Length = %i\n", RFCNB_Pkt_Len(pkt->data)); + RFCNB_Print_Hex(fd, pkt, RFCNB_Pkt_Hdr_Len, #ifdef RFCNB_PRINT_DATA - RFCNB_Pkt_Len(pkt->data) - RFCNB_Pkt_Hdr_Len); + RFCNB_Pkt_Len(pkt->data) - RFCNB_Pkt_Hdr_Len); #else - 40); + 40); #endif - if (Prot_Print_Routine != 0) { /* Print the rest of the packet */ + if (Prot_Print_Routine != 0) { /* Print the rest of the packet */ - Prot_Print_Routine(fd, strcmp(dirn, "sent"), pkt, RFCNB_Pkt_Hdr_Len, - RFCNB_Pkt_Len(pkt->data) - RFCNB_Pkt_Hdr_Len); + Prot_Print_Routine(fd, strcmp(dirn, "sent"), pkt, RFCNB_Pkt_Hdr_Len, + RFCNB_Pkt_Len(pkt->data) - RFCNB_Pkt_Hdr_Len); - } - break; + } + break; case RFCNB_SESSION_REQUEST: - fprintf(fd, "SESSION REQUEST: Length = %i\n", - RFCNB_Pkt_Len(pkt->data)); - RFCNB_NBName_To_AName((char *) (pkt->data + RFCNB_Pkt_Called_Offset), lname); - fprintf(fd, " Called Name: %s\n", lname); - RFCNB_NBName_To_AName((char *) (pkt->data + RFCNB_Pkt_Calling_Offset), lname); - fprintf(fd, " Calling Name: %s\n", lname); + fprintf(fd, "SESSION REQUEST: Length = %i\n", + RFCNB_Pkt_Len(pkt->data)); + RFCNB_NBName_To_AName((char *) (pkt->data + RFCNB_Pkt_Called_Offset), lname); + fprintf(fd, " Called Name: %s\n", lname); + RFCNB_NBName_To_AName((char *) (pkt->data + RFCNB_Pkt_Calling_Offset), lname); + fprintf(fd, " Calling Name: %s\n", lname); - break; + break; case RFCNB_SESSION_ACK: - fprintf(fd, "RFCNB SESSION ACK: Length = %i\n", - RFCNB_Pkt_Len(pkt->data)); + fprintf(fd, "RFCNB SESSION ACK: Length = %i\n", + RFCNB_Pkt_Len(pkt->data)); - break; + break; case RFCNB_SESSION_REJ: - fprintf(fd, "RFCNB SESSION REJECT: Length = %i\n", - RFCNB_Pkt_Len(pkt->data)); + fprintf(fd, "RFCNB SESSION REJECT: Length = %i\n", + RFCNB_Pkt_Len(pkt->data)); - if (RFCNB_Pkt_Len(pkt->data) < 1) { - fprintf(fd, " Protocol Error, short Reject packet!\n"); - } else { - fprintf(fd, " Error = %x\n", CVAL(pkt->data, RFCNB_Pkt_Error_Offset)); - } + if (RFCNB_Pkt_Len(pkt->data) < 1) { + fprintf(fd, " Protocol Error, short Reject packet!\n"); + } else { + fprintf(fd, " Error = %x\n", CVAL(pkt->data, RFCNB_Pkt_Error_Offset)); + } - break; + break; case RFCNB_SESSION_RETARGET: - fprintf(fd, "RFCNB SESSION RETARGET: Length = %i\n", - RFCNB_Pkt_Len(pkt->data)); + fprintf(fd, "RFCNB SESSION RETARGET: Length = %i\n", + RFCNB_Pkt_Len(pkt->data)); - /* Print out the IP address etc and the port? */ + /* Print out the IP address etc and the port? */ - break; + break; case RFCNB_SESSION_KEEP_ALIVE: - fprintf(fd, "RFCNB SESSION KEEP ALIVE: Length = %i\n", - RFCNB_Pkt_Len(pkt->data)); - break; + fprintf(fd, "RFCNB SESSION KEEP ALIVE: Length = %i\n", + RFCNB_Pkt_Len(pkt->data)); + break; default: - break; + break; } } @@ -354,20 +352,20 @@ RFCNB_Name_To_IP(char *host, struct in_addr *Dest_IP) if ((addr = inet_addr(host)) == INADDR_NONE) { /* Oh well, a good try :-) */ - /* Now try a name look up with gethostbyname */ + /* Now try a name look up with gethostbyname */ - if ((hp = gethostbyname(host)) == NULL) { /* Not in DNS */ + if ((hp = gethostbyname(host)) == NULL) { /* Not in DNS */ - /* Try NetBIOS name lookup, how the hell do we do that? */ - RFCNB_errno = RFCNBE_BadName; /* Is this right? */ - RFCNB_saved_errno = errno; - return (RFCNBE_Bad); + /* Try NetBIOS name lookup, how the hell do we do that? */ + RFCNB_errno = RFCNBE_BadName; /* Is this right? */ + RFCNB_saved_errno = errno; + return (RFCNBE_Bad); - } else { /* We got a name */ + } else { /* We got a name */ Dest_IP->s_addr = (*((struct in_addr*)hp->h_addr_list[0])).s_addr; - } + } } else { /* It was an IP address */ - Dest_IP->s_addr = addr; + Dest_IP->s_addr = addr; } return 0; @@ -401,9 +399,9 @@ RFCNB_IP_Connect(struct in_addr Dest_IP, int port) if ((fd = socket(PF_INET, SOCK_STREAM, 0)) < 0) { /* Handle the error */ - RFCNB_errno = RFCNBE_BadSocket; - RFCNB_saved_errno = errno; - return (RFCNBE_Bad); + RFCNB_errno = RFCNBE_BadSocket; + RFCNB_saved_errno = errno; + return (RFCNBE_Bad); } memset((char *) &Socket, 0, sizeof(Socket)); memcpy((char *) &Socket.sin_addr, (char *) &Dest_IP, sizeof(Dest_IP)); @@ -415,27 +413,27 @@ RFCNB_IP_Connect(struct in_addr Dest_IP, int port) if (connect(fd, (struct sockaddr *) &Socket, sizeof(Socket)) < 0) { /* Error */ - close(fd); - RFCNB_errno = RFCNBE_ConnectFailed; - RFCNB_saved_errno = errno; - return (RFCNBE_Bad); + close(fd); + RFCNB_errno = RFCNBE_ConnectFailed; + RFCNB_saved_errno = errno; + return (RFCNBE_Bad); } return (fd); } -/* handle the details of establishing the RFCNB session with remote - * end - * +/* handle the details of establishing the RFCNB session with remote + * end + * */ int RFCNB_Session_Req(struct RFCNB_Con *con, - char *Called_Name, - char *Calling_Name, - BOOL * redirect, - struct in_addr *Dest_IP, - int *port) + char *Called_Name, + char *Calling_Name, + BOOL * redirect, + struct in_addr *Dest_IP, + int *port) { char *sess_pkt; @@ -451,7 +449,7 @@ RFCNB_Session_Req(struct RFCNB_Con *con, if (pkt == NULL) { - return (RFCNBE_Bad); /* Leave the error that RFCNB_Alloc_Pkt gives) */ + return (RFCNBE_Bad); /* Leave the error that RFCNB_Alloc_Pkt gives) */ } sess_pkt = pkt->data; /* Get pointer to packet proper */ @@ -474,7 +472,7 @@ RFCNB_Session_Req(struct RFCNB_Con *con, if ((len = RFCNB_Put_Pkt(con, pkt, RFCNB_Pkt_Sess_Len)) < 0) { - return (RFCNBE_Bad); /* Should be able to write that lot ... */ + return (RFCNBE_Bad); /* Should be able to write that lot ... */ } #ifdef RFCNB_DEBUG @@ -489,7 +487,7 @@ RFCNB_Session_Req(struct RFCNB_Con *con, if ((len = RFCNB_Get_Pkt(con, &res_pkt, sizeof(resp))) < 0) { - return (RFCNBE_Bad); + return (RFCNBE_Bad); } /* Now analyze the packet ... */ @@ -498,52 +496,52 @@ RFCNB_Session_Req(struct RFCNB_Con *con, case RFCNB_SESSION_REJ: /* Didnt like us ... too bad */ - /* Why did we get rejected ? */ - - switch (CVAL(resp, RFCNB_Pkt_Error_Offset)) { - - case 0x80: - RFCNB_errno = RFCNBE_CallRejNLOCN; - break; - case 0x81: - RFCNB_errno = RFCNBE_CallRejNLFCN; - break; - case 0x82: - RFCNB_errno = RFCNBE_CallRejCNNP; - break; - case 0x83: - RFCNB_errno = RFCNBE_CallRejInfRes; - break; - case 0x8F: - RFCNB_errno = RFCNBE_CallRejUnSpec; - break; - default: - RFCNB_errno = RFCNBE_ProtErr; - break; - } - - return (RFCNBE_Bad); - break; + /* Why did we get rejected ? */ + + switch (CVAL(resp, RFCNB_Pkt_Error_Offset)) { + + case 0x80: + RFCNB_errno = RFCNBE_CallRejNLOCN; + break; + case 0x81: + RFCNB_errno = RFCNBE_CallRejNLFCN; + break; + case 0x82: + RFCNB_errno = RFCNBE_CallRejCNNP; + break; + case 0x83: + RFCNB_errno = RFCNBE_CallRejInfRes; + break; + case 0x8F: + RFCNB_errno = RFCNBE_CallRejUnSpec; + break; + default: + RFCNB_errno = RFCNBE_ProtErr; + break; + } + + return (RFCNBE_Bad); + break; case RFCNB_SESSION_ACK: /* Got what we wanted ... */ - return (0); - break; + return (0); + break; case RFCNB_SESSION_RETARGET: /* Go elsewhere */ - *redirect = TRUE; /* Copy port and ip addr */ + *redirect = TRUE; /* Copy port and ip addr */ - memcpy(Dest_IP, (resp + RFCNB_Pkt_IP_Offset), sizeof(struct in_addr)); - *port = SVAL(resp, RFCNB_Pkt_Port_Offset); + memcpy(Dest_IP, (resp + RFCNB_Pkt_IP_Offset), sizeof(struct in_addr)); + *port = SVAL(resp, RFCNB_Pkt_Port_Offset); - return (0); - break; + return (0); + break; default: /* A protocol error */ - RFCNB_errno = RFCNBE_ProtErr; - return (RFCNBE_Bad); - break; + RFCNB_errno = RFCNBE_ProtErr; + return (RFCNBE_Bad); + break; } } diff --git a/helpers/basic_auth/MSNT/rfcnb-util.h b/helpers/basic_auth/MSNT/rfcnb-util.h index e19330d4be..e6de08390c 100644 --- a/helpers/basic_auth/MSNT/rfcnb-util.h +++ b/helpers/basic_auth/MSNT/rfcnb-util.h @@ -1,10 +1,10 @@ /* UNIX RFCNB (RFC1001/RFC1002) NetBIOS implementation - * + * * Version 1.0 * RFCNB Utility Defines - * + * * Copyright (C) Richard Sharpe 1996 - * + * */ /* @@ -12,12 +12,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -42,10 +42,10 @@ int RFCNB_Close(int socket); int RFCNB_IP_Connect(struct in_addr Dest_IP, int port); int RFCNB_Session_Req(RFCNB_Con * con, - char *Called_Name, - char *Calling_Name, - BOOL * redirect, - struct in_addr *Dest_IP, - int *port); + char *Called_Name, + char *Calling_Name, + BOOL * redirect, + struct in_addr *Dest_IP, + int *port); void RFCNB_Free_Pkt(struct RFCNB_Pkt *pkt); diff --git a/helpers/basic_auth/MSNT/rfcnb.h b/helpers/basic_auth/MSNT/rfcnb.h index 112ac648da..b1baa0b008 100644 --- a/helpers/basic_auth/MSNT/rfcnb.h +++ b/helpers/basic_auth/MSNT/rfcnb.h @@ -1,10 +1,10 @@ /* UNIX RFCNB (RFC1001/RFC1002) NetBIOS implementation - * + * * Version 1.0 * RFCNB Defines - * + * * Copyright (C) Richard Sharpe 1996 - * + * */ /* @@ -12,12 +12,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -37,7 +37,7 @@ struct RFCNB_Con; void *RFCNB_Call(char *Called_Name, char *Calling_Name, char *Called_Address, - int port); + int port); int RFCNB_Send(struct RFCNB_Con *Con_Handle, struct RFCNB_Pkt *Data, int Length); diff --git a/helpers/basic_auth/MSNT/session.c b/helpers/basic_auth/MSNT/session.c index 66e9b6c3e9..fc2a95141c 100644 --- a/helpers/basic_auth/MSNT/session.c +++ b/helpers/basic_auth/MSNT/session.c @@ -1,10 +1,10 @@ /* UNIX RFCNB (RFC1001/RFC1002) NetBIOS implementation - * + * * Version 1.0 * Session Routines ... - * + * * Copyright (C) Richard Sharpe 1996 - * + * */ /* @@ -12,12 +12,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -47,13 +47,13 @@ void (*Prot_Print_Routine) () = NULL; /* Pointer to print routine */ /* Set up a session with a remote name. We are passed Called_Name as a * string which we convert to a NetBIOS name, ie space terminated, up to * 16 characters only if we need to. If Called_Address is not empty, then - * we use it to connect to the remote end, but put in Called_Name ... Called + * we use it to connect to the remote end, but put in Called_Name ... Called * Address can be a DNS based name, or a TCP/IP address ... */ void * RFCNB_Call(char *Called_Name, char *Calling_Name, char *Called_Address, - int port) + int port) { struct RFCNB_Con *con; struct in_addr Dest_IP; @@ -65,15 +65,15 @@ RFCNB_Call(char *Called_Name, char *Calling_Name, char *Called_Address, /* Now, we really should look up the port in /etc/services ... */ if (port == 0) - port = RFCNB_Default_Port; + port = RFCNB_Default_Port; /* Create a connection structure first */ if ((con = (struct RFCNB_Con *) malloc(sizeof(struct RFCNB_Con))) == NULL) { /* Error in size */ - RFCNB_errno = RFCNBE_NoSpace; - RFCNB_saved_errno = errno; - return (NULL); + RFCNB_errno = RFCNBE_NoSpace; + RFCNB_saved_errno = errno; + return (NULL); } con->fd = -0; /* no descriptor yet */ @@ -86,13 +86,13 @@ RFCNB_Call(char *Called_Name, char *Calling_Name, char *Called_Address, Service_Address = Called_Name; if (strcmp(Called_Address, "") != 0) { /* If the Called Address = "" */ - Service_Address = Called_Address; + Service_Address = Called_Address; } if ((errno = RFCNB_Name_To_IP(Service_Address, &Dest_IP)) < 0) { /* Error */ - /* No need to modify RFCNB_errno as it was done by RFCNB_Name_To_IP */ + /* No need to modify RFCNB_errno as it was done by RFCNB_Name_To_IP */ free(con); - return (NULL); + return (NULL); } /* Now connect to the remote end */ @@ -101,76 +101,76 @@ RFCNB_Call(char *Called_Name, char *Calling_Name, char *Called_Address, while (redirect) { /* Connect and get session info etc */ - redirect = FALSE; /* Assume all OK */ + redirect = FALSE; /* Assume all OK */ - /* Build the redirect info. First one is first addr called */ - /* And tack it onto the list of addresses we called */ + /* Build the redirect info. First one is first addr called */ + /* And tack it onto the list of addresses we called */ - if ((redir_addr = (struct redirect_addr *) malloc(sizeof(struct redirect_addr))) == NULL) { /* Could not get space */ + if ((redir_addr = (struct redirect_addr *) malloc(sizeof(struct redirect_addr))) == NULL) { /* Could not get space */ - RFCNB_errno = RFCNBE_NoSpace; - RFCNB_saved_errno = errno; + RFCNB_errno = RFCNBE_NoSpace; + RFCNB_saved_errno = errno; free(con); - return (NULL); + return (NULL); - } - memcpy((char *) &(redir_addr->ip_addr), (char *) &Dest_IP, sizeof(Dest_IP)); - redir_addr->port = port; - redir_addr->next = NULL; + } + memcpy((char *) &(redir_addr->ip_addr), (char *) &Dest_IP, sizeof(Dest_IP)); + redir_addr->port = port; + redir_addr->next = NULL; - if (con->redirect_list == NULL) { /* Stick on head */ + if (con->redirect_list == NULL) { /* Stick on head */ - con->redirect_list = con->last_addr = redir_addr; + con->redirect_list = con->last_addr = redir_addr; - } else { + } else { - con->last_addr->next = redir_addr; - con->last_addr = redir_addr; + con->last_addr->next = redir_addr; + con->last_addr = redir_addr; - } + } - /* Now, make that connection */ + /* Now, make that connection */ - if ((Client = RFCNB_IP_Connect(Dest_IP, port)) < 0) { /* Error */ + if ((Client = RFCNB_IP_Connect(Dest_IP, port)) < 0) { /* Error */ - /* No need to modify RFCNB_errno as it was done by RFCNB_IP_Connect */ + /* No need to modify RFCNB_errno as it was done by RFCNB_IP_Connect */ free(con); - return (NULL); + return (NULL); - } - con->fd = Client; + } + con->fd = Client; - /* Now send and handle the RFCNB session request */ - /* If we get a redirect, we will comeback with redirect true - * and a new IP address in DEST_IP */ + /* Now send and handle the RFCNB session request */ + /* If we get a redirect, we will comeback with redirect true + * and a new IP address in DEST_IP */ - if ((errno = RFCNB_Session_Req(con, - Called_Name, - Calling_Name, - &redirect, &Dest_IP, &port)) < 0) { + if ((errno = RFCNB_Session_Req(con, + Called_Name, + Calling_Name, + &redirect, &Dest_IP, &port)) < 0) { - /* No need to modify RFCNB_errno as it was done by RFCNB_Session.. */ - RFCNB_Close(con->fd); /* Close it */ + /* No need to modify RFCNB_errno as it was done by RFCNB_Session.. */ + RFCNB_Close(con->fd); /* Close it */ free(con); - return (NULL); + return (NULL); - } - if (redirect) { + } + if (redirect) { - /* We have to close the connection, and then try again */ + /* We have to close the connection, and then try again */ - (con->redirects)++; + (con->redirects)++; - RFCNB_Close(con->fd); /* Close it */ + RFCNB_Close(con->fd); /* Close it */ - } + } } return (con); } -/* We send a packet to the other end ... for the moment, we treat the +/* We send a packet to the other end ... for the moment, we treat the * data as a series of pointers to blocks of data ... we should check the * length ... */ @@ -187,9 +187,9 @@ RFCNB_Send(struct RFCNB_Con *Con_Handle, struct RFCNB_Pkt *udata, int Length) if (pkt == NULL) { - RFCNB_errno = RFCNBE_NoSpace; - RFCNB_saved_errno = errno; - return (RFCNBE_Bad); + RFCNB_errno = RFCNBE_NoSpace; + RFCNB_saved_errno = errno; + return (RFCNBE_Bad); } pkt->next = udata; /* The user data we want to send */ @@ -209,9 +209,9 @@ RFCNB_Send(struct RFCNB_Con *Con_Handle, struct RFCNB_Pkt *udata, int Length) if ((len = RFCNB_Put_Pkt(Con_Handle, pkt, Length + RFCNB_Pkt_Hdr_Len)) < 0) { - /* No need to change RFCNB_errno as it was done by put_pkt ... */ + /* No need to change RFCNB_errno as it was done by put_pkt ... */ - return (RFCNBE_Bad); /* Should be able to write that lot ... */ + return (RFCNBE_Bad); /* Should be able to write that lot ... */ } /* Now we have sent that lot, let's get rid of the RFCNB Header and return */ @@ -224,7 +224,7 @@ RFCNB_Send(struct RFCNB_Con *Con_Handle, struct RFCNB_Pkt *udata, int Length) } -/* We pick up a message from the internet ... We have to worry about +/* We pick up a message from the internet ... We have to worry about * non-message packets ... */ int @@ -235,9 +235,9 @@ RFCNB_Recv(struct RFCNB_Con *con_Handle, struct RFCNB_Pkt *Data, int Length) if (con_Handle == NULL) { - RFCNB_errno = RFCNBE_BadHandle; - RFCNB_saved_errno = errno; - return (RFCNBE_Bad); + RFCNB_errno = RFCNBE_BadHandle; + RFCNB_saved_errno = errno; + return (RFCNBE_Bad); } /* Now get a packet from below. We allocate a header first */ @@ -248,9 +248,9 @@ RFCNB_Recv(struct RFCNB_Con *con_Handle, struct RFCNB_Pkt *Data, int Length) if (pkt == NULL) { - RFCNB_errno = RFCNBE_NoSpace; - RFCNB_saved_errno = errno; - return (RFCNBE_Bad); + RFCNB_errno = RFCNBE_NoSpace; + RFCNB_saved_errno = errno; + return (RFCNBE_Bad); } pkt->next = Data; /* Plug in the data portion */ @@ -258,10 +258,10 @@ RFCNB_Recv(struct RFCNB_Con *con_Handle, struct RFCNB_Pkt *Data, int Length) if ((ret_len = RFCNB_Get_Pkt(con_Handle, pkt, Length + RFCNB_Pkt_Hdr_Len)) < 0) { #ifdef RFCNB_DEBUG - fprintf(stderr, "Bad packet return in RFCNB_Recv... \n"); + fprintf(stderr, "Bad packet return in RFCNB_Recv... \n"); #endif - return (RFCNBE_Bad); + return (RFCNBE_Bad); } /* We should check that we go a message and not a keep alive */ @@ -282,8 +282,8 @@ RFCNB_Hangup(struct RFCNB_Con *con_Handle) { if (con_Handle != NULL) { - RFCNB_Close(con_Handle->fd); /* Could this fail? */ - free(con_Handle); + RFCNB_Close(con_Handle->fd); /* Could this fail? */ + free(con_Handle); } return 0; @@ -297,10 +297,10 @@ void RFCNB_Get_Error(char *buffer, int buf_len) { if (RFCNB_saved_errno <= 0) { - snprintf(buffer, (buf_len-1) ,"%s", RFCNB_Error_Strings[RFCNB_errno]); + snprintf(buffer, (buf_len-1) ,"%s", RFCNB_Error_Strings[RFCNB_errno]); } else { - snprintf(buffer, (buf_len-1), "%s\n\terrno:%s", RFCNB_Error_Strings[RFCNB_errno], - strerror(RFCNB_saved_errno)); + snprintf(buffer, (buf_len-1), "%s\n\terrno:%s", RFCNB_Error_Strings[RFCNB_errno], + strerror(RFCNB_saved_errno)); } } diff --git a/helpers/basic_auth/MSNT/smbdes.c b/helpers/basic_auth/MSNT/smbdes.c index b933cc3d11..c2d0255ddf 100644 --- a/helpers/basic_auth/MSNT/smbdes.c +++ b/helpers/basic_auth/MSNT/smbdes.c @@ -1,43 +1,43 @@ -/* +/* * Unix SMB/Netbios implementation. * Version 1.9. - * - * a partial implementation of DES designed for use in the + * + * a partial implementation of DES designed for use in the * SMB authentication protocol - * + * * Copyright (C) Andrew Tridgell 1997 - * + * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ -/* NOTES: - * +/* NOTES: + * * This code makes no attempt to be fast! In fact, it is a very - * slow implementation - * + * slow implementation + * * This code is NOT a complete DES implementation. It implements only * the minimum necessary for SMB authentication, as used by all SMB * products (including every copy of Microsoft Windows95 ever sold) - * + * * In particular, it can only do a unchained forward DES pass. This * means it is not possible to use this code for encryption/decryption * of data, instead it is only useful as a "hash" algorithm. - * + * * There is no entry point into this code that allows normal DES operation. - * + * * I believe this means that this code does not come under ITAR * regulations but this is NOT a legal opinion. If you are concerned * about the applicability of ITAR regulations to this code then you @@ -47,127 +47,126 @@ #include "smbdes.h" -static int perm1[56] = -{57, 49, 41, 33, 25, 17, 9, - 1, 58, 50, 42, 34, 26, 18, - 10, 2, 59, 51, 43, 35, 27, - 19, 11, 3, 60, 52, 44, 36, - 63, 55, 47, 39, 31, 23, 15, - 7, 62, 54, 46, 38, 30, 22, - 14, 6, 61, 53, 45, 37, 29, - 21, 13, 5, 28, 20, 12, 4}; - -static int perm2[48] = -{14, 17, 11, 24, 1, 5, - 3, 28, 15, 6, 21, 10, - 23, 19, 12, 4, 26, 8, - 16, 7, 27, 20, 13, 2, - 41, 52, 31, 37, 47, 55, - 30, 40, 51, 45, 33, 48, - 44, 49, 39, 56, 34, 53, - 46, 42, 50, 36, 29, 32}; - -static int perm3[64] = -{58, 50, 42, 34, 26, 18, 10, 2, - 60, 52, 44, 36, 28, 20, 12, 4, - 62, 54, 46, 38, 30, 22, 14, 6, - 64, 56, 48, 40, 32, 24, 16, 8, - 57, 49, 41, 33, 25, 17, 9, 1, - 59, 51, 43, 35, 27, 19, 11, 3, - 61, 53, 45, 37, 29, 21, 13, 5, - 63, 55, 47, 39, 31, 23, 15, 7}; - -static int perm4[48] = -{32, 1, 2, 3, 4, 5, - 4, 5, 6, 7, 8, 9, - 8, 9, 10, 11, 12, 13, - 12, 13, 14, 15, 16, 17, - 16, 17, 18, 19, 20, 21, - 20, 21, 22, 23, 24, 25, - 24, 25, 26, 27, 28, 29, - 28, 29, 30, 31, 32, 1}; - -static int perm5[32] = -{16, 7, 20, 21, - 29, 12, 28, 17, - 1, 15, 23, 26, - 5, 18, 31, 10, - 2, 8, 24, 14, - 32, 27, 3, 9, - 19, 13, 30, 6, - 22, 11, 4, 25}; - - -static int perm6[64] = -{40, 8, 48, 16, 56, 24, 64, 32, - 39, 7, 47, 15, 55, 23, 63, 31, - 38, 6, 46, 14, 54, 22, 62, 30, - 37, 5, 45, 13, 53, 21, 61, 29, - 36, 4, 44, 12, 52, 20, 60, 28, - 35, 3, 43, 11, 51, 19, 59, 27, - 34, 2, 42, 10, 50, 18, 58, 26, - 33, 1, 41, 9, 49, 17, 57, 25}; - - -static int sc[16] = -{1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1}; - -static int sbox[8][4][16] = -{ +static int perm1[56] = {57, 49, 41, 33, 25, 17, 9, + 1, 58, 50, 42, 34, 26, 18, + 10, 2, 59, 51, 43, 35, 27, + 19, 11, 3, 60, 52, 44, 36, + 63, 55, 47, 39, 31, 23, 15, + 7, 62, 54, 46, 38, 30, 22, + 14, 6, 61, 53, 45, 37, 29, + 21, 13, 5, 28, 20, 12, 4 + }; + +static int perm2[48] = {14, 17, 11, 24, 1, 5, + 3, 28, 15, 6, 21, 10, + 23, 19, 12, 4, 26, 8, + 16, 7, 27, 20, 13, 2, + 41, 52, 31, 37, 47, 55, + 30, 40, 51, 45, 33, 48, + 44, 49, 39, 56, 34, 53, + 46, 42, 50, 36, 29, 32 + }; + +static int perm3[64] = {58, 50, 42, 34, 26, 18, 10, 2, + 60, 52, 44, 36, 28, 20, 12, 4, + 62, 54, 46, 38, 30, 22, 14, 6, + 64, 56, 48, 40, 32, 24, 16, 8, + 57, 49, 41, 33, 25, 17, 9, 1, + 59, 51, 43, 35, 27, 19, 11, 3, + 61, 53, 45, 37, 29, 21, 13, 5, + 63, 55, 47, 39, 31, 23, 15, 7 + }; + +static int perm4[48] = {32, 1, 2, 3, 4, 5, + 4, 5, 6, 7, 8, 9, + 8, 9, 10, 11, 12, 13, + 12, 13, 14, 15, 16, 17, + 16, 17, 18, 19, 20, 21, + 20, 21, 22, 23, 24, 25, + 24, 25, 26, 27, 28, 29, + 28, 29, 30, 31, 32, 1 + }; + +static int perm5[32] = {16, 7, 20, 21, + 29, 12, 28, 17, + 1, 15, 23, 26, + 5, 18, 31, 10, + 2, 8, 24, 14, + 32, 27, 3, 9, + 19, 13, 30, 6, + 22, 11, 4, 25 + }; + + +static int perm6[64] = {40, 8, 48, 16, 56, 24, 64, 32, + 39, 7, 47, 15, 55, 23, 63, 31, + 38, 6, 46, 14, 54, 22, 62, 30, + 37, 5, 45, 13, 53, 21, 61, 29, + 36, 4, 44, 12, 52, 20, 60, 28, + 35, 3, 43, 11, 51, 19, 59, 27, + 34, 2, 42, 10, 50, 18, 58, 26, + 33, 1, 41, 9, 49, 17, 57, 25 + }; + + +static int sc[16] = {1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1}; + +static int sbox[8][4][16] = { { - {14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7}, - {0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8}, - {4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0}, - {15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13}}, + {14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7}, + {0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8}, + {4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0}, + {15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13}}, { - {15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10}, - {3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5}, - {0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15}, - {13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9}}, + {15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10}, + {3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5}, + {0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15}, + {13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9}}, { - {10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8}, - {13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1}, - {13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7}, - {1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12}}, + {10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8}, + {13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1}, + {13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7}, + {1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12}}, { - {7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15}, - {13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9}, - {10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4}, - {3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14}}, + {7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15}, + {13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9}, + {10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4}, + {3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14}}, { - {2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9}, - {14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6}, - {4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14}, - {11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3}}, + {2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9}, + {14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6}, + {4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14}, + {11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3}}, { - {12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11}, - {10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8}, - {9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6}, - {4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13}}, + {12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11}, + {10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8}, + {9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6}, + {4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13}}, { - {4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1}, - {13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6}, - {1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2}, - {6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12}}, + {4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1}, + {13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6}, + {1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2}, + {6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12}}, { - {13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7}, - {1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2}, - {7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8}, - {2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11}}}; + {13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7}, + {1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2}, + {7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8}, + {2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11}} +}; static void permute(char *out, char *in, int *p, int n) { int i; for (i = 0; i < n; i++) - out[i] = in[p[i] - 1]; + out[i] = in[p[i] - 1]; } static void @@ -176,18 +175,18 @@ lshift(char *d, int count, int n) char out[64]; int i; for (i = 0; i < n; i++) - out[i] = d[(i + count) % n]; + out[i] = d[(i + count) % n]; for (i = 0; i < n; i++) - d[i] = out[i]; + d[i] = out[i]; } static void concat(char *out, char *in1, char *in2, int l1, int l2) { while (l1--) - *out++ = *in1++; + *out++ = *in1++; while (l2--) - *out++ = *in2++; + *out++ = *in2++; } static void @@ -195,7 +194,7 @@ xor(char *out, char *in1, char *in2, int n) { int i; for (i = 0; i < n; i++) - out[i] = in1[i] ^ in2[i]; + out[i] = in1[i] ^ in2[i]; } static void @@ -214,63 +213,63 @@ dohash(char *out, char *in, char *key) permute(pk1, key, perm1, 56); for (i = 0; i < 28; i++) - c[i] = pk1[i]; + c[i] = pk1[i]; for (i = 0; i < 28; i++) - d[i] = pk1[i + 28]; + d[i] = pk1[i + 28]; for (i = 0; i < 16; i++) { - lshift(c, sc[i], 28); - lshift(d, sc[i], 28); + lshift(c, sc[i], 28); + lshift(d, sc[i], 28); - concat(cd, c, d, 28, 28); - permute(ki[i], cd, perm2, 48); + concat(cd, c, d, 28, 28); + permute(ki[i], cd, perm2, 48); } permute(pd1, in, perm3, 64); for (j = 0; j < 32; j++) { - l[j] = pd1[j]; - r[j] = pd1[j + 32]; + l[j] = pd1[j]; + r[j] = pd1[j + 32]; } for (i = 0; i < 16; i++) { - char er[48]; - char erk[48]; - char b[8][6]; - char cb[32]; - char pcb[32]; - char r2[32]; + char er[48]; + char erk[48]; + char b[8][6]; + char cb[32]; + char pcb[32]; + char r2[32]; - permute(er, r, perm4, 48); + permute(er, r, perm4, 48); - xor(erk, er, ki[i], 48); + xor(erk, er, ki[i], 48); - for (j = 0; j < 8; j++) - for (k = 0; k < 6; k++) - b[j][k] = erk[j * 6 + k]; + for (j = 0; j < 8; j++) + for (k = 0; k < 6; k++) + b[j][k] = erk[j * 6 + k]; - for (j = 0; j < 8; j++) { - int m, n; - m = (b[j][0] << 1) | b[j][5]; + for (j = 0; j < 8; j++) { + int m, n; + m = (b[j][0] << 1) | b[j][5]; - n = (b[j][1] << 3) | (b[j][2] << 2) | (b[j][3] << 1) | b[j][4]; + n = (b[j][1] << 3) | (b[j][2] << 2) | (b[j][3] << 1) | b[j][4]; - for (k = 0; k < 4; k++) - b[j][k] = (sbox[j][m][n] & (1 << (3 - k))) ? 1 : 0; - } + for (k = 0; k < 4; k++) + b[j][k] = (sbox[j][m][n] & (1 << (3 - k))) ? 1 : 0; + } - for (j = 0; j < 8; j++) - for (k = 0; k < 4; k++) - cb[j * 4 + k] = b[j][k]; - permute(pcb, cb, perm5, 32); + for (j = 0; j < 8; j++) + for (k = 0; k < 4; k++) + cb[j * 4 + k] = b[j][k]; + permute(pcb, cb, perm5, 32); - xor(r2, l, pcb, 32); + xor(r2, l, pcb, 32); - for (j = 0; j < 32; j++) - l[j] = r[j]; + for (j = 0; j < 32; j++) + l[j] = r[j]; - for (j = 0; j < 32; j++) - r[j] = r2[j]; + for (j = 0; j < 32; j++) + r[j] = r2[j]; } concat(rl, r, l, 32, 32); @@ -292,7 +291,7 @@ str_to_key(unsigned char *str, unsigned char *key) key[6] = ((str[5] & 0x3F) << 1) | (str[6] >> 7); key[7] = str[6] & 0x7F; for (i = 0; i < 8; i++) { - key[i] = (key[i] << 1); + key[i] = (key[i] << 1); } } @@ -309,28 +308,27 @@ smbhash(unsigned char *out, unsigned char *in, unsigned char *key) str_to_key(key, key2); for (i = 0; i < 64; i++) { - inb[i] = (in[i / 8] & (1 << (7 - (i % 8)))) ? 1 : 0; - keyb[i] = (key2[i / 8] & (1 << (7 - (i % 8)))) ? 1 : 0; - outb[i] = 0; + inb[i] = (in[i / 8] & (1 << (7 - (i % 8)))) ? 1 : 0; + keyb[i] = (key2[i / 8] & (1 << (7 - (i % 8)))) ? 1 : 0; + outb[i] = 0; } dohash(outb, inb, keyb); for (i = 0; i < 8; i++) { - out[i] = 0; + out[i] = 0; } for (i = 0; i < 64; i++) { - if (outb[i]) - out[i / 8] |= (1 << (7 - (i % 8))); + if (outb[i]) + out[i / 8] |= (1 << (7 - (i % 8))); } } void E_P16(unsigned char *p14, unsigned char *p16) { - unsigned char sp8[8] = - {0x4b, 0x47, 0x53, 0x21, 0x40, 0x23, 0x24, 0x25}; + unsigned char sp8[8] = {0x4b, 0x47, 0x53, 0x21, 0x40, 0x23, 0x24, 0x25}; smbhash(p16, sp8, p14); smbhash(p16 + 8, sp8, p14 + 7); } diff --git a/helpers/basic_auth/MSNT/smbencrypt.c b/helpers/basic_auth/MSNT/smbencrypt.c index 6e9361f8a7..bffd64b9de 100644 --- a/helpers/basic_auth/MSNT/smbencrypt.c +++ b/helpers/basic_auth/MSNT/smbencrypt.c @@ -1,20 +1,20 @@ -/* +/* * Unix SMB/Netbios implementation. * Version 1.9. * SMB parameters and setup * Copyright (C) Andrew Tridgell 1992-1997 * Modified by Jeremy Allison 1995. - * + * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -50,7 +50,7 @@ static void strupper(char *s); /* * This implements the X/Open SMB password encryption - * It takes a password, a 8 byte "crypt key" and puts 24 bytes of + * It takes a password, a 8 byte "crypt key" and puts 24 bytes of * encrypted password into p24 */ void SMBencrypt(uchar * passwd, uchar * c8, uchar * p24) @@ -72,13 +72,13 @@ _my_wcslen(int16 * str) { int len = 0; while (*str++ != 0) - len++; + len++; return len; } /* * Convert a string into an NT UNICODE string. - * Note that regardless of processor type + * Note that regardless of processor type * this must be in intel (little-endian) * format. */ @@ -90,17 +90,17 @@ _my_mbstowcs(int16 * dst, uchar * src, int len) int16 val; for (i = 0; i < len; i++) { - val = *src; - SSVAL(dst, 0, val); - dst++; - src++; - if (val == 0) - break; + val = *src; + SSVAL(dst, 0, val); + dst++; + src++; + if (val == 0) + break; } return i; } -/* +/* * Creates the MD4 Hash of the users password in NT UNICODE. */ @@ -113,7 +113,7 @@ E_md4hash(uchar * passwd, uchar * p16) /* Password cannot be longer than 128 characters */ len = strlen((char *) passwd); if (len > 128) - len = 128; + len = 128; /* Password must be converted to NT unicode */ _my_mbstowcs(wpwd, passwd, len); wpwd[len] = 0; /* Ensure string is null terminated */ @@ -169,10 +169,10 @@ StrnCpy(char *dest, char *src, int n) { char *d = dest; if (!dest) - return (NULL); + return (NULL); if (!src) { - *dest = 0; - return (dest); + *dest = 0; + return (dest); } while (n-- && (*d++ = *src++)); *d = 0; @@ -185,26 +185,26 @@ strupper(char *s) while (*s) { #if UNUSED_CODE #if !defined(KANJI_WIN95_COMPATIBILITY) - if (lp_client_code_page() == KANJI_CODEPAGE) { - - if (is_shift_jis(*s)) { - if (is_sj_lower(s[0], s[1])) - s[1] = sj_toupper2(s[1]); - s += 2; - } else if (is_kana(*s)) { - s++; - } else { - if (islower((int)(unsigned char)*s)) - *s = toupper((int)(unsigned char)*s); - s++; - } - } else + if (lp_client_code_page() == KANJI_CODEPAGE) { + + if (is_shift_jis(*s)) { + if (is_sj_lower(s[0], s[1])) + s[1] = sj_toupper2(s[1]); + s += 2; + } else if (is_kana(*s)) { + s++; + } else { + if (islower((int)(unsigned char)*s)) + *s = toupper((int)(unsigned char)*s); + s++; + } + } else #endif /* KANJI_WIN95_COMPATIBILITY */ #endif /* UNUSED_CODE */ - { - if (islower((int)(unsigned char)*s)) - *s = toupper((int)(unsigned char)*s); - s++; - } + { + if (islower((int)(unsigned char)*s)) + *s = toupper((int)(unsigned char)*s); + s++; + } } } diff --git a/helpers/basic_auth/MSNT/smblib-common.h b/helpers/basic_auth/MSNT/smblib-common.h index b1ab26cb7f..df6c74de92 100644 --- a/helpers/basic_auth/MSNT/smblib-common.h +++ b/helpers/basic_auth/MSNT/smblib-common.h @@ -1,10 +1,10 @@ /* UNIX SMBlib NetBIOS implementation - * + * * Version 1.0 * SMBlib Common Defines - * + * * Copyright (C) Richard Sharpe 1996 - * + * */ /* @@ -12,12 +12,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. diff --git a/helpers/basic_auth/MSNT/smblib-priv.h b/helpers/basic_auth/MSNT/smblib-priv.h index f112c5a7db..aad6ffb2b4 100644 --- a/helpers/basic_auth/MSNT/smblib-priv.h +++ b/helpers/basic_auth/MSNT/smblib-priv.h @@ -1,10 +1,10 @@ /* UNIX SMBlib NetBIOS implementation - * + * * Version 1.0 * SMBlib private Defines - * + * * Copyright (C) Richard Sharpe 1996 - * + * */ /* @@ -12,12 +12,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -282,8 +282,8 @@ typedef unsigned char UCHAR; #define SMB_openx_axr_offset 34 /* Reserved */ #define SMB_openx_axo_offset 35 /* offset of next wct */ #define SMB_openx_flg_offset 37 /* Flags, bit0 = need more info */ - /* bit1 = exclusive oplock */ - /* bit2 = batch oplock */ +/* bit1 = exclusive oplock */ +/* bit2 = batch oplock */ #define SMB_openx_mod_offset 39 /* mode to open with */ #define SMB_openx_atr_offset 41 /* search attributes */ #define SMB_openx_fat_offset 43 /* File attributes */ @@ -378,7 +378,7 @@ typedef unsigned char UCHAR; #define SMB_ssetpLM_buf_offset 55 #define SMB_ssetpNTLM_mbs_offset 37 /* Max Buffer Size for NT LM 0.12 */ - /* and above */ +/* and above */ #define SMB_ssetpNTLM_mmc_offset 39 /* Max Multiplex count */ #define SMB_ssetpNTLM_vcn_offset 41 /* VC Number */ #define SMB_ssetpNTLM_snk_offset 43 /* Session key */ @@ -505,12 +505,12 @@ extern int SMB_Types[]; typedef struct SMB_Status { union { - struct { - unsigned char ErrorClass; - unsigned char Reserved; - unsigned short Error; - } DosError; - unsigned int NtStatus; + struct { + unsigned char ErrorClass; + unsigned char Reserved; + unsigned short Error; + } DosError; + unsigned int NtStatus; } status; } SMB_Status; diff --git a/helpers/basic_auth/MSNT/smblib-util.c b/helpers/basic_auth/MSNT/smblib-util.c index fcc7de0ae4..417b2f07a3 100644 --- a/helpers/basic_auth/MSNT/smblib-util.c +++ b/helpers/basic_auth/MSNT/smblib-util.c @@ -1,10 +1,10 @@ /* UNIX SMBlib NetBIOS implementation - * + * * Version 1.0 * SMBlib Utility Routines - * + * * Copyright (C) Richard Sharpe 1996 - * + * */ /* @@ -12,12 +12,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -35,35 +35,35 @@ #include #include -const char *SMB_Prots[] = -{"PC NETWORK PROGRAM 1.0", - "MICROSOFT NETWORKS 1.03", - "MICROSOFT NETWORKS 3.0", - "DOS LANMAN1.0", - "LANMAN1.0", - "DOS LM1.2X002", - "LM1.2X002", - "DOS LANMAN2.1", - "LANMAN2.1", - "Samba", - "NT LM 0.12", - "NT LANMAN 1.0", - NULL}; - -int SMB_Types[] = -{SMB_P_Core, - SMB_P_CorePlus, - SMB_P_DOSLanMan1, - SMB_P_DOSLanMan1, - SMB_P_LanMan1, - SMB_P_DOSLanMan2, - SMB_P_LanMan2, - SMB_P_LanMan2_1, - SMB_P_LanMan2_1, - SMB_P_NT1, - SMB_P_NT1, - SMB_P_NT1, - -1}; +const char *SMB_Prots[] = {"PC NETWORK PROGRAM 1.0", + "MICROSOFT NETWORKS 1.03", + "MICROSOFT NETWORKS 3.0", + "DOS LANMAN1.0", + "LANMAN1.0", + "DOS LM1.2X002", + "LM1.2X002", + "DOS LANMAN2.1", + "LANMAN2.1", + "Samba", + "NT LM 0.12", + "NT LANMAN 1.0", + NULL + }; + +int SMB_Types[] = {SMB_P_Core, + SMB_P_CorePlus, + SMB_P_DOSLanMan1, + SMB_P_DOSLanMan1, + SMB_P_LanMan1, + SMB_P_DOSLanMan2, + SMB_P_LanMan2, + SMB_P_LanMan2_1, + SMB_P_LanMan2_1, + SMB_P_NT1, + SMB_P_NT1, + SMB_P_NT1, + -1 + }; /* Figure out what protocol was accepted, given the list of dialect strings */ /* We offered, and the index back from the server. We allow for a user */ @@ -76,22 +76,22 @@ SMB_Figure_Protocol(const char *dialects[], int prot_index) if (dialects == SMB_Prots) { /* The jobs is easy, just index into table */ - return (SMB_Types[prot_index]); + return (SMB_Types[prot_index]); } else { /* Search through SMB_Prots looking for a match */ - for (i = 0; SMB_Prots[i] != NULL; i++) { + for (i = 0; SMB_Prots[i] != NULL; i++) { - if (strcmp(dialects[prot_index], SMB_Prots[i]) == 0) { /* A match */ + if (strcmp(dialects[prot_index], SMB_Prots[i]) == 0) { /* A match */ - return (SMB_Types[i]); + return (SMB_Types[i]); - } - } + } + } - /* If we got here, then we are in trouble, because the protocol was not */ - /* One we understand ... */ + /* If we got here, then we are in trouble, because the protocol was not */ + /* One we understand ... */ - return (SMB_P_Unknown); + return (SMB_P_Unknown); } @@ -115,7 +115,7 @@ SMB_Negotiate(SMB_Handle_Type Con_Handle, const char *Prots[]) for (i = 0; Prots[i] != NULL; i++) { - prots_len = prots_len + strlen(Prots[i]) + 2; /* Account for null etc */ + prots_len = prots_len + strlen(Prots[i]) + 2; /* Account for null etc */ } @@ -129,11 +129,11 @@ SMB_Negotiate(SMB_Handle_Type Con_Handle, const char *Prots[]) if (pkt_len < (SMB_hdr_wct_offset + (19 * 2) + 40)) { - alloc_len = SMB_hdr_wct_offset + (19 * 2) + 40; + alloc_len = SMB_hdr_wct_offset + (19 * 2) + 40; } else { - alloc_len = pkt_len; + alloc_len = pkt_len; } @@ -141,8 +141,8 @@ SMB_Negotiate(SMB_Handle_Type Con_Handle, const char *Prots[]) if (pkt == NULL) { - SMBlib_errno = SMBlibE_NoSpace; - return (SMBlibE_BAD); + SMBlib_errno = SMBlibE_NoSpace; + return (SMBlibE_BAD); } /* Now plug in the bits we need */ @@ -164,9 +164,9 @@ SMB_Negotiate(SMB_Handle_Type Con_Handle, const char *Prots[]) for (i = 0; Prots[i] != NULL; i++) { - *p = SMBdialectID; - strcpy(p + 1, Prots[i]); - p = p + strlen(Prots[i]) + 2; /* Adjust len of p for null plus dialectID */ + *p = SMBdialectID; + strcpy(p + 1, Prots[i]); + p = p + strlen(Prots[i]) + 2; /* Adjust len of p for null plus dialectID */ } @@ -176,12 +176,12 @@ SMB_Negotiate(SMB_Handle_Type Con_Handle, const char *Prots[]) #ifdef DEBUG - fprintf(stderr, "Error sending negotiate protocol\n"); + fprintf(stderr, "Error sending negotiate protocol\n"); #endif - RFCNB_Free_Pkt(pkt); - SMBlib_errno = -SMBlibE_SendFailed; /* Failed, check lower layer errno */ - return (SMBlibE_BAD); + RFCNB_Free_Pkt(pkt); + SMBlib_errno = -SMBlibE_SendFailed; /* Failed, check lower layer errno */ + return (SMBlibE_BAD); } /* Now get the response ... */ @@ -189,37 +189,37 @@ SMB_Negotiate(SMB_Handle_Type Con_Handle, const char *Prots[]) if (RFCNB_Recv(Con_Handle->Trans_Connect, pkt, alloc_len) < 0) { #ifdef DEBUG - fprintf(stderr, "Error receiving response to negotiate\n"); + fprintf(stderr, "Error receiving response to negotiate\n"); #endif - RFCNB_Free_Pkt(pkt); - SMBlib_errno = -SMBlibE_RecvFailed; /* Failed, check lower layer errno */ - return (SMBlibE_BAD); + RFCNB_Free_Pkt(pkt); + SMBlib_errno = -SMBlibE_RecvFailed; /* Failed, check lower layer errno */ + return (SMBlibE_BAD); } if (CVAL(SMB_Hdr(pkt), SMB_hdr_rcls_offset) != SMBC_SUCCESS) { /* Process error */ #ifdef DEBUG - fprintf(stderr, "SMB_Negotiate failed with errorclass = %i, Error Code = %i\n", - CVAL(SMB_Hdr(pkt), SMB_hdr_rcls_offset), - SVAL(SMB_Hdr(pkt), SMB_hdr_err_offset)); + fprintf(stderr, "SMB_Negotiate failed with errorclass = %i, Error Code = %i\n", + CVAL(SMB_Hdr(pkt), SMB_hdr_rcls_offset), + SVAL(SMB_Hdr(pkt), SMB_hdr_err_offset)); #endif - SMBlib_SMB_Error = IVAL(SMB_Hdr(pkt), SMB_hdr_rcls_offset); - RFCNB_Free_Pkt(pkt); - SMBlib_errno = SMBlibE_Remote; - return (SMBlibE_BAD); + SMBlib_SMB_Error = IVAL(SMB_Hdr(pkt), SMB_hdr_rcls_offset); + RFCNB_Free_Pkt(pkt); + SMBlib_errno = SMBlibE_Remote; + return (SMBlibE_BAD); } if (SVAL(SMB_Hdr(pkt), SMB_negrCP_idx_offset) == 0xFFFF) { #ifdef DEBUG - fprintf(stderr, "None of our protocols was accepted ... "); + fprintf(stderr, "None of our protocols was accepted ... "); #endif - RFCNB_Free_Pkt(pkt); - SMBlib_errno = SMBlibE_NegNoProt; - return (SMBlibE_BAD); + RFCNB_Free_Pkt(pkt); + SMBlib_errno = SMBlibE_NegNoProt; + return (SMBlibE_BAD); } /* Now, unpack the info from the response, if any and evaluate the proto */ @@ -230,70 +230,70 @@ SMB_Negotiate(SMB_Handle_Type Con_Handle, const char *Prots[]) if (Con_Handle->protocol == SMB_P_Unknown) { /* No good ... */ - RFCNB_Free_Pkt(pkt); - SMBlib_errno = SMBlibE_ProtUnknown; - return (SMBlibE_BAD); + RFCNB_Free_Pkt(pkt); + SMBlib_errno = SMBlibE_ProtUnknown; + return (SMBlibE_BAD); } switch (CVAL(SMB_Hdr(pkt), SMB_hdr_wct_offset)) { case 0x01: /* No more info ... */ - break; + break; case 13: /* Up to and including LanMan 2.1 */ - Con_Handle->Security = SVAL(SMB_Hdr(pkt), SMB_negrLM_sec_offset); - Con_Handle->encrypt_passwords = ((Con_Handle->Security & SMB_sec_encrypt_mask) != 0x00); - Con_Handle->Security = Con_Handle->Security & SMB_sec_user_mask; + Con_Handle->Security = SVAL(SMB_Hdr(pkt), SMB_negrLM_sec_offset); + Con_Handle->encrypt_passwords = ((Con_Handle->Security & SMB_sec_encrypt_mask) != 0x00); + Con_Handle->Security = Con_Handle->Security & SMB_sec_user_mask; - Con_Handle->max_xmit = SVAL(SMB_Hdr(pkt), SMB_negrLM_mbs_offset); - Con_Handle->MaxMPX = SVAL(SMB_Hdr(pkt), SMB_negrLM_mmc_offset); - Con_Handle->MaxVC = SVAL(SMB_Hdr(pkt), SMB_negrLM_mnv_offset); - Con_Handle->Raw_Support = SVAL(SMB_Hdr(pkt), SMB_negrLM_rm_offset); - Con_Handle->SessionKey = IVAL(SMB_Hdr(pkt), SMB_negrLM_sk_offset); - Con_Handle->SvrTZ = SVAL(SMB_Hdr(pkt), SMB_negrLM_stz_offset); - Con_Handle->Encrypt_Key_Len = SVAL(SMB_Hdr(pkt), SMB_negrLM_ekl_offset); + Con_Handle->max_xmit = SVAL(SMB_Hdr(pkt), SMB_negrLM_mbs_offset); + Con_Handle->MaxMPX = SVAL(SMB_Hdr(pkt), SMB_negrLM_mmc_offset); + Con_Handle->MaxVC = SVAL(SMB_Hdr(pkt), SMB_negrLM_mnv_offset); + Con_Handle->Raw_Support = SVAL(SMB_Hdr(pkt), SMB_negrLM_rm_offset); + Con_Handle->SessionKey = IVAL(SMB_Hdr(pkt), SMB_negrLM_sk_offset); + Con_Handle->SvrTZ = SVAL(SMB_Hdr(pkt), SMB_negrLM_stz_offset); + Con_Handle->Encrypt_Key_Len = SVAL(SMB_Hdr(pkt), SMB_negrLM_ekl_offset); - p = (SMB_Hdr(pkt) + SMB_negrLM_buf_offset); - memcpy(Con_Handle->Encrypt_Key, p, 8); + p = (SMB_Hdr(pkt) + SMB_negrLM_buf_offset); + memcpy(Con_Handle->Encrypt_Key, p, 8); - p = (SMB_Hdr(pkt) + SMB_negrLM_buf_offset + Con_Handle->Encrypt_Key_Len); + p = (SMB_Hdr(pkt) + SMB_negrLM_buf_offset + Con_Handle->Encrypt_Key_Len); - strncpy(p, Con_Handle->Svr_PDom, sizeof(Con_Handle->Svr_PDom) - 1); + strncpy(p, Con_Handle->Svr_PDom, sizeof(Con_Handle->Svr_PDom) - 1); - break; + break; case 17: /* NT LM 0.12 and LN LM 1.0 */ - Con_Handle->Security = SVAL(SMB_Hdr(pkt), SMB_negrNTLM_sec_offset); - Con_Handle->encrypt_passwords = ((Con_Handle->Security & SMB_sec_encrypt_mask) != 0x00); - Con_Handle->Security = Con_Handle->Security & SMB_sec_user_mask; + Con_Handle->Security = SVAL(SMB_Hdr(pkt), SMB_negrNTLM_sec_offset); + Con_Handle->encrypt_passwords = ((Con_Handle->Security & SMB_sec_encrypt_mask) != 0x00); + Con_Handle->Security = Con_Handle->Security & SMB_sec_user_mask; - Con_Handle->max_xmit = IVAL(SMB_Hdr(pkt), SMB_negrNTLM_mbs_offset); - Con_Handle->MaxMPX = SVAL(SMB_Hdr(pkt), SMB_negrNTLM_mmc_offset); - Con_Handle->MaxVC = SVAL(SMB_Hdr(pkt), SMB_negrNTLM_mnv_offset); - Con_Handle->MaxRaw = IVAL(SMB_Hdr(pkt), SMB_negrNTLM_mrs_offset); - Con_Handle->SessionKey = IVAL(SMB_Hdr(pkt), SMB_negrNTLM_sk_offset); - Con_Handle->SvrTZ = SVAL(SMB_Hdr(pkt), SMB_negrNTLM_stz_offset); - Con_Handle->Encrypt_Key_Len = CVAL(SMB_Hdr(pkt), SMB_negrNTLM_ekl_offset); + Con_Handle->max_xmit = IVAL(SMB_Hdr(pkt), SMB_negrNTLM_mbs_offset); + Con_Handle->MaxMPX = SVAL(SMB_Hdr(pkt), SMB_negrNTLM_mmc_offset); + Con_Handle->MaxVC = SVAL(SMB_Hdr(pkt), SMB_negrNTLM_mnv_offset); + Con_Handle->MaxRaw = IVAL(SMB_Hdr(pkt), SMB_negrNTLM_mrs_offset); + Con_Handle->SessionKey = IVAL(SMB_Hdr(pkt), SMB_negrNTLM_sk_offset); + Con_Handle->SvrTZ = SVAL(SMB_Hdr(pkt), SMB_negrNTLM_stz_offset); + Con_Handle->Encrypt_Key_Len = CVAL(SMB_Hdr(pkt), SMB_negrNTLM_ekl_offset); - p = (SMB_Hdr(pkt) + SMB_negrNTLM_buf_offset); - memcpy(Con_Handle->Encrypt_Key, p, 8); - p = (SMB_Hdr(pkt) + SMB_negrNTLM_buf_offset + Con_Handle->Encrypt_Key_Len); + p = (SMB_Hdr(pkt) + SMB_negrNTLM_buf_offset); + memcpy(Con_Handle->Encrypt_Key, p, 8); + p = (SMB_Hdr(pkt) + SMB_negrNTLM_buf_offset + Con_Handle->Encrypt_Key_Len); - strncpy(p, Con_Handle->Svr_PDom, sizeof(Con_Handle->Svr_PDom) - 1); + strncpy(p, Con_Handle->Svr_PDom, sizeof(Con_Handle->Svr_PDom) - 1); - break; + break; default: #ifdef DEBUG - fprintf(stderr, "Unknown NegProt response format ... Ignored\n"); - fprintf(stderr, " wct = %i\n", CVAL(SMB_Hdr(pkt), SMB_hdr_wct_offset)); + fprintf(stderr, "Unknown NegProt response format ... Ignored\n"); + fprintf(stderr, " wct = %i\n", CVAL(SMB_Hdr(pkt), SMB_hdr_wct_offset)); #endif - break; + break; } #ifdef DEBUG @@ -313,13 +313,13 @@ SMB_Get_My_Name(char *name, int len) if (gethostname(name, len) < 0) { /* Error getting name */ - strncpy(name, "unknown", len); + strncpy(name, "unknown", len); - /* Should check the error */ + /* Should check the error */ #ifdef DEBUG - fprintf(stderr, "gethostname in SMB_Get_My_Name returned error:"); - perror(""); + fprintf(stderr, "gethostname in SMB_Get_My_Name returned error:"); + perror(""); #endif } @@ -332,10 +332,10 @@ SMB_Get_My_Name(char *name, int len) SMB_Tree_Handle SMB_TreeConnect(SMB_Handle_Type Con_Handle, - SMB_Tree_Handle Tree_Handle, - char *path, - char *password, - const char *device) + SMB_Tree_Handle Tree_Handle, + char *path, + char *password, + const char *device) { struct RFCNB_Pkt *pkt; int param_len, pkt_len; @@ -347,11 +347,11 @@ SMB_TreeConnect(SMB_Handle_Type Con_Handle, if ((path == NULL) | (password == NULL) | (device == NULL)) { #ifdef DEBUG - fprintf(stderr, "Bad parameter passed to SMB_TreeConnect\n"); + fprintf(stderr, "Bad parameter passed to SMB_TreeConnect\n"); #endif - SMBlib_errno = SMBlibE_BadParam; - return (NULL); + SMBlib_errno = SMBlibE_BadParam; + return (NULL); } /* The + 2 is because of the \0 and the marker ... */ @@ -367,26 +367,26 @@ SMB_TreeConnect(SMB_Handle_Type Con_Handle, if (pkt == NULL) { - SMBlib_errno = SMBlibE_NoSpace; - return (NULL); /* Should handle the error */ + SMBlib_errno = SMBlibE_NoSpace; + return (NULL); /* Should handle the error */ } /* Now allocate a tree for this to go into ... */ if (Tree_Handle == NULL) { - tree = (SMB_Tree_Handle) malloc(sizeof(struct SMB_Tree_Structure)); + tree = (SMB_Tree_Handle) malloc(sizeof(struct SMB_Tree_Structure)); - if (tree == NULL) { + if (tree == NULL) { - RFCNB_Free_Pkt(pkt); - SMBlib_errno = SMBlibE_NoSpace; - return (NULL); + RFCNB_Free_Pkt(pkt); + SMBlib_errno = SMBlibE_NoSpace; + return (NULL); - } + } } else { - tree = Tree_Handle; + tree = Tree_Handle; } @@ -425,14 +425,14 @@ SMB_TreeConnect(SMB_Handle_Type Con_Handle, if (RFCNB_Send(Con_Handle->Trans_Connect, pkt, pkt_len) < 0) { #ifdef DEBUG - fprintf(stderr, "Error sending TCon request\n"); + fprintf(stderr, "Error sending TCon request\n"); #endif - if (Tree_Handle == NULL) - free(tree); - RFCNB_Free_Pkt(pkt); - SMBlib_errno = -SMBlibE_SendFailed; - return (NULL); + if (Tree_Handle == NULL) + free(tree); + RFCNB_Free_Pkt(pkt); + SMBlib_errno = -SMBlibE_SendFailed; + return (NULL); } /* Now get the response ... */ @@ -440,14 +440,14 @@ SMB_TreeConnect(SMB_Handle_Type Con_Handle, if (RFCNB_Recv(Con_Handle->Trans_Connect, pkt, pkt_len) < 0) { #ifdef DEBUG - fprintf(stderr, "Error receiving response to TCon\n"); + fprintf(stderr, "Error receiving response to TCon\n"); #endif - if (Tree_Handle == NULL) - free(tree); - RFCNB_Free_Pkt(pkt); - SMBlib_errno = -SMBlibE_RecvFailed; - return (NULL); + if (Tree_Handle == NULL) + free(tree); + RFCNB_Free_Pkt(pkt); + SMBlib_errno = -SMBlibE_RecvFailed; + return (NULL); } /* Check out the response type ... */ @@ -455,17 +455,17 @@ SMB_TreeConnect(SMB_Handle_Type Con_Handle, if (CVAL(SMB_Hdr(pkt), SMB_hdr_rcls_offset) != SMBC_SUCCESS) { /* Process error */ #ifdef DEBUG - fprintf(stderr, "SMB_TCon failed with errorclass = %i, Error Code = %i\n", - CVAL(SMB_Hdr(pkt), SMB_hdr_rcls_offset), - SVAL(SMB_Hdr(pkt), SMB_hdr_err_offset)); + fprintf(stderr, "SMB_TCon failed with errorclass = %i, Error Code = %i\n", + CVAL(SMB_Hdr(pkt), SMB_hdr_rcls_offset), + SVAL(SMB_Hdr(pkt), SMB_hdr_err_offset)); #endif - if (Tree_Handle == NULL) - free(tree); - SMBlib_SMB_Error = IVAL(SMB_Hdr(pkt), SMB_hdr_rcls_offset); - RFCNB_Free_Pkt(pkt); - SMBlib_errno = SMBlibE_Remote; - return (NULL); + if (Tree_Handle == NULL) + free(tree); + SMBlib_SMB_Error = IVAL(SMB_Hdr(pkt), SMB_hdr_rcls_offset); + RFCNB_Free_Pkt(pkt); + SMBlib_errno = SMBlibE_Remote; + return (NULL); } tree->tid = SVAL(SMB_Hdr(pkt), SMB_tconr_tid_offset); @@ -473,21 +473,21 @@ SMB_TreeConnect(SMB_Handle_Type Con_Handle, #ifdef DEBUG fprintf(stderr, "TConn succeeded, with TID=%i, Max Xmit=%i\n", - tree->tid, tree->mbs); + tree->tid, tree->mbs); #endif /* Now link the Tree to the Server Structure ... */ if (Con_Handle->first_tree == NULL) { - Con_Handle->first_tree = tree; - Con_Handle->last_tree = tree; + Con_Handle->first_tree = tree; + Con_Handle->last_tree = tree; } else { - Con_Handle->last_tree->next = tree; - tree->prev = Con_Handle->last_tree; - Con_Handle->last_tree = tree; + Con_Handle->last_tree->next = tree; + tree->prev = Con_Handle->last_tree; + Con_Handle->last_tree = tree; } @@ -521,8 +521,7 @@ SMB_Get_Last_SMB_Err() /* Keep this table in sync with the message codes in smblib-common.h */ -static const char *SMBlib_Error_Messages[] = -{ +static const char *SMBlib_Error_Messages[] = { "Request completed sucessfully.", "Server returned a non-zero SMB Error Class and Code.", @@ -537,9 +536,10 @@ static const char *SMBlib_Error_Messages[] = "The logon request failed, but you were logged in as guest.", "The attempt to call the remote server failed. See protocol error info.", "The protocol dialect specified in a NegProt and accepted by the server is unknown.", - /* This next one simplifies error handling */ + /* This next one simplifies error handling */ "No such error code.", - NULL}; + NULL +}; void SMB_Get_Error_Msg(int msg, char *msgbuf, int len) @@ -547,31 +547,31 @@ SMB_Get_Error_Msg(int msg, char *msgbuf, int len) if (msg >= 0) { - strncpy(msgbuf, - SMBlib_Error_Messages[msg > SMBlibE_NoSuchMsg ? SMBlibE_NoSuchMsg : msg], - len - 1); - msgbuf[len - 1] = 0; /* Make sure it is a string */ + strncpy(msgbuf, + SMBlib_Error_Messages[msg > SMBlibE_NoSuchMsg ? SMBlibE_NoSuchMsg : msg], + len - 1); + msgbuf[len - 1] = 0; /* Make sure it is a string */ } else { /* Add the lower layer message ... */ - char prot_msg[1024]; + char prot_msg[1024]; - msg = -msg; /* Make it positive */ + msg = -msg; /* Make it positive */ - strncpy(msgbuf, - SMBlib_Error_Messages[msg > SMBlibE_NoSuchMsg ? SMBlibE_NoSuchMsg : msg], - len - 1); + strncpy(msgbuf, + SMBlib_Error_Messages[msg > SMBlibE_NoSuchMsg ? SMBlibE_NoSuchMsg : msg], + len - 1); - msgbuf[len - 1] = 0; /* make sure it is a string */ + msgbuf[len - 1] = 0; /* make sure it is a string */ - if (strlen(msgbuf) < len) { /* If there is space, put rest in */ + if (strlen(msgbuf) < len) { /* If there is space, put rest in */ - strncat(msgbuf, "\n\t", len - strlen(msgbuf)); + strncat(msgbuf, "\n\t", len - strlen(msgbuf)); - RFCNB_Get_Error(prot_msg, sizeof(prot_msg) - 1); + RFCNB_Get_Error(prot_msg, sizeof(prot_msg) - 1); - strncat(msgbuf, prot_msg, len - strlen(msgbuf)); + strncat(msgbuf, prot_msg, len - strlen(msgbuf)); - } + } } } diff --git a/helpers/basic_auth/MSNT/smblib.c b/helpers/basic_auth/MSNT/smblib.c index d9b202b902..b59cc722c3 100644 --- a/helpers/basic_auth/MSNT/smblib.c +++ b/helpers/basic_auth/MSNT/smblib.c @@ -1,10 +1,10 @@ /* UNIX SMBlib NetBIOS implementation - * + * * Version 1.0 * SMBlib Routines - * + * * Copyright (C) Richard Sharpe 1996 - * + * */ /* @@ -12,12 +12,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -53,7 +53,7 @@ SMB_Init(void) signal(SIGPIPE, SIG_IGN); /* Ignore these ... */ -/* If SMBLIB_Instrument is defines, turn on the instrumentation stuff */ + /* If SMBLIB_Instrument is defines, turn on the instrumentation stuff */ #ifdef SMBLIB_INSTRUMENT SMBlib_Instrument_Init(); @@ -81,7 +81,7 @@ SMB_Create_Con_Handle(void) SMB_Handle_Type SMB_Connect_Server(SMB_Handle_Type Con_Handle, - char *server, char *NTdomain) + char *server, char *NTdomain) { SMB_Handle_Type con; char called[80], calling[80], *address; @@ -93,12 +93,12 @@ SMB_Connect_Server(SMB_Handle_Type Con_Handle, if (Con_Handle == NULL) { - if ((con = (struct SMB_Connect_Def *) malloc(sizeof(struct SMB_Connect_Def))) == NULL) { + if ((con = (struct SMB_Connect_Def *) malloc(sizeof(struct SMB_Connect_Def))) == NULL) { - SMBlib_errno = SMBlibE_NoSpace; - return NULL; - } + SMBlib_errno = SMBlibE_NoSpace; + return NULL; + } } /* Init some things ... */ @@ -128,35 +128,35 @@ SMB_Connect_Server(SMB_Handle_Type Con_Handle, * service we are going to call, sine some servers want it in uppercase */ for (i = 0; i < strlen(server); i++) - called[i] = xtoupper(server[i]); + called[i] = xtoupper(server[i]); called[strlen(server)] = 0; /* Make it a string */ for (i = 0; i < strlen(con->myname); i++) - calling[i] = xtoupper(con->myname[i]); + calling[i] = xtoupper(con->myname[i]); calling[strlen(con->myname)] = 0; /* Make it a string */ if (strcmp(con->address, "") == 0) - address = con->desthost; + address = con->desthost; else - address = con->address; + address = con->address; con->Trans_Connect = RFCNB_Call(called, - calling, - address, /* Protocol specific */ - con->port); + calling, + address, /* Protocol specific */ + con->port); /* Did we get one? */ if (con->Trans_Connect == NULL) { - if (Con_Handle == NULL) { - Con_Handle = NULL; - free(con); - } - SMBlib_errno = -SMBlibE_CallFailed; - return NULL; + if (Con_Handle == NULL) { + Con_Handle = NULL; + free(con); + } + SMBlib_errno = -SMBlibE_CallFailed; + return NULL; } return (con); @@ -167,17 +167,17 @@ SMB_Connect_Server(SMB_Handle_Type Con_Handle, /* If Con_Handle == NULL then create a handle and connect, otherwise */ /* use the handle passed */ -const char *SMB_Prots_Restrict[] = -{"PC NETWORK PROGRAM 1.0", - NULL}; +const char *SMB_Prots_Restrict[] = {"PC NETWORK PROGRAM 1.0", + NULL + }; SMB_Handle_Type SMB_Connect(SMB_Handle_Type Con_Handle, - SMB_Tree_Handle * tree, - char *service, - char *username, - char *password) + SMB_Tree_Handle * tree, + char *service, + char *username, + char *password) { SMB_Handle_Type con; char *host, *address; @@ -190,11 +190,11 @@ SMB_Connect(SMB_Handle_Type Con_Handle, if (Con_Handle == NULL) { - if ((con = (struct SMB_Connect_Def *) malloc(sizeof(struct SMB_Connect_Def))) == NULL) { + if ((con = (struct SMB_Connect_Def *) malloc(sizeof(struct SMB_Connect_Def))) == NULL) { - SMBlib_errno = SMBlibE_NoSpace; - return NULL; - } + SMBlib_errno = SMBlibE_NoSpace; + return NULL; + } } /* Init some things ... */ @@ -230,52 +230,52 @@ SMB_Connect(SMB_Handle_Type Con_Handle, * service we are going to call, sine some servers want it in uppercase */ for (i = 0; i < strlen(host); i++) - called[i] = xtoupper(host[i]); + called[i] = xtoupper(host[i]); called[strlen(host)] = 0; /* Make it a string */ for (i = 0; i < strlen(con->myname); i++) - calling[i] = xtoupper(con->myname[i]); + calling[i] = xtoupper(con->myname[i]); calling[strlen(con->myname)] = 0; /* Make it a string */ if (strcmp(con->address, "") == 0) - address = con->desthost; + address = con->desthost; else - address = con->address; + address = con->address; con->Trans_Connect = RFCNB_Call(called, - calling, - address, /* Protocol specific */ - con->port); + calling, + address, /* Protocol specific */ + con->port); /* Did we get one? */ if (con->Trans_Connect == NULL) { - if (Con_Handle == NULL) { - free(con); - Con_Handle = NULL; - } - SMBlib_errno = -SMBlibE_CallFailed; - return NULL; + if (Con_Handle == NULL) { + free(con); + Con_Handle = NULL; + } + SMBlib_errno = -SMBlibE_CallFailed; + return NULL; } /* Now, negotiate the protocol */ if (SMB_Negotiate(con, SMB_Prots_Restrict) < 0) { - /* Hmmm what should we do here ... We have a connection, but could not - * negotiate ... */ + /* Hmmm what should we do here ... We have a connection, but could not + * negotiate ... */ - return NULL; + return NULL; } /* Now connect to the service ... */ if ((*tree = SMB_TreeConnect(con, NULL, service, password, "A:")) == NULL) { - return NULL; + return NULL; } return (con); @@ -287,7 +287,7 @@ SMB_Connect(SMB_Handle_Type Con_Handle, int SMB_Logon_Server(SMB_Handle_Type Con_Handle, char *UserName, - char *PassWord) + char *PassWord) { struct RFCNB_Pkt *pkt; int param_len, pkt_len, pass_len; @@ -299,151 +299,151 @@ SMB_Logon_Server(SMB_Handle_Type Con_Handle, char *UserName, if (Con_Handle->protocol < SMB_P_LanMan1) { - SMBlib_errno = SMBlibE_ProtLow; - return (SMBlibE_BAD); + SMBlib_errno = SMBlibE_ProtLow; + return (SMBlibE_BAD); } strcpy(pword, PassWord); #ifdef PAM_SMB_ENC_PASS if (Con_Handle->encrypt_passwords) { - pass_len = 24; - SMBencrypt((uchar *) PassWord, (uchar *) Con_Handle->Encrypt_Key, (uchar *) pword); + pass_len = 24; + SMBencrypt((uchar *) PassWord, (uchar *) Con_Handle->Encrypt_Key, (uchar *) pword); } else #endif - pass_len = strlen(pword); + pass_len = strlen(pword); /* Now build the correct structure */ if (Con_Handle->protocol < SMB_P_NT1) { - param_len = strlen(UserName) + 1 + pass_len + 1 + - strlen(Con_Handle->PDomain) + 1 + - strlen(Con_Handle->OSName) + 1; + param_len = strlen(UserName) + 1 + pass_len + 1 + + strlen(Con_Handle->PDomain) + 1 + + strlen(Con_Handle->OSName) + 1; - pkt_len = SMB_ssetpLM_len + param_len; + pkt_len = SMB_ssetpLM_len + param_len; - pkt = (struct RFCNB_Pkt *) RFCNB_Alloc_Pkt(pkt_len); + pkt = (struct RFCNB_Pkt *) RFCNB_Alloc_Pkt(pkt_len); - if (pkt == NULL) { + if (pkt == NULL) { - SMBlib_errno = SMBlibE_NoSpace; - return (SMBlibE_BAD); /* Should handle the error */ + SMBlib_errno = SMBlibE_NoSpace; + return (SMBlibE_BAD); /* Should handle the error */ - } - memset(SMB_Hdr(pkt), 0, SMB_ssetpLM_len); - SIVAL(SMB_Hdr(pkt), SMB_hdr_idf_offset, SMB_DEF_IDF); /* Plunk in IDF */ - *(SMB_Hdr(pkt) + SMB_hdr_com_offset) = SMBsesssetupX; - SSVAL(SMB_Hdr(pkt), SMB_hdr_pid_offset, Con_Handle->pid); - SSVAL(SMB_Hdr(pkt), SMB_hdr_tid_offset, 0); - SSVAL(SMB_Hdr(pkt), SMB_hdr_mid_offset, Con_Handle->mid); - SSVAL(SMB_Hdr(pkt), SMB_hdr_uid_offset, Con_Handle->uid); - *(SMB_Hdr(pkt) + SMB_hdr_wct_offset) = 10; - *(SMB_Hdr(pkt) + SMB_hdr_axc_offset) = 0xFF; /* No extra command */ - SSVAL(SMB_Hdr(pkt), SMB_hdr_axo_offset, 0); + } + memset(SMB_Hdr(pkt), 0, SMB_ssetpLM_len); + SIVAL(SMB_Hdr(pkt), SMB_hdr_idf_offset, SMB_DEF_IDF); /* Plunk in IDF */ + *(SMB_Hdr(pkt) + SMB_hdr_com_offset) = SMBsesssetupX; + SSVAL(SMB_Hdr(pkt), SMB_hdr_pid_offset, Con_Handle->pid); + SSVAL(SMB_Hdr(pkt), SMB_hdr_tid_offset, 0); + SSVAL(SMB_Hdr(pkt), SMB_hdr_mid_offset, Con_Handle->mid); + SSVAL(SMB_Hdr(pkt), SMB_hdr_uid_offset, Con_Handle->uid); + *(SMB_Hdr(pkt) + SMB_hdr_wct_offset) = 10; + *(SMB_Hdr(pkt) + SMB_hdr_axc_offset) = 0xFF; /* No extra command */ + SSVAL(SMB_Hdr(pkt), SMB_hdr_axo_offset, 0); - SSVAL(SMB_Hdr(pkt), SMB_ssetpLM_mbs_offset, SMBLIB_MAX_XMIT); - SSVAL(SMB_Hdr(pkt), SMB_ssetpLM_mmc_offset, 2); - SSVAL(SMB_Hdr(pkt), SMB_ssetpLM_vcn_offset, Con_Handle->pid); - SIVAL(SMB_Hdr(pkt), SMB_ssetpLM_snk_offset, 0); - SSVAL(SMB_Hdr(pkt), SMB_ssetpLM_pwl_offset, pass_len + 1); - SIVAL(SMB_Hdr(pkt), SMB_ssetpLM_res_offset, 0); - SSVAL(SMB_Hdr(pkt), SMB_ssetpLM_bcc_offset, param_len); + SSVAL(SMB_Hdr(pkt), SMB_ssetpLM_mbs_offset, SMBLIB_MAX_XMIT); + SSVAL(SMB_Hdr(pkt), SMB_ssetpLM_mmc_offset, 2); + SSVAL(SMB_Hdr(pkt), SMB_ssetpLM_vcn_offset, Con_Handle->pid); + SIVAL(SMB_Hdr(pkt), SMB_ssetpLM_snk_offset, 0); + SSVAL(SMB_Hdr(pkt), SMB_ssetpLM_pwl_offset, pass_len + 1); + SIVAL(SMB_Hdr(pkt), SMB_ssetpLM_res_offset, 0); + SSVAL(SMB_Hdr(pkt), SMB_ssetpLM_bcc_offset, param_len); - /* Now copy the param strings in with the right stuff */ + /* Now copy the param strings in with the right stuff */ - p = (char *) (SMB_Hdr(pkt) + SMB_ssetpLM_buf_offset); + p = (char *) (SMB_Hdr(pkt) + SMB_ssetpLM_buf_offset); - /* Copy in password, then the rest. Password has a null at end */ + /* Copy in password, then the rest. Password has a null at end */ - memcpy(p, pword, pass_len); + memcpy(p, pword, pass_len); - p = p + pass_len + 1; + p = p + pass_len + 1; - strcpy(p, UserName); - p = p + strlen(UserName); - *p = 0; + strcpy(p, UserName); + p = p + strlen(UserName); + *p = 0; - p = p + 1; + p = p + 1; - strcpy(p, Con_Handle->PDomain); - p = p + strlen(Con_Handle->PDomain); - *p = 0; - p = p + 1; + strcpy(p, Con_Handle->PDomain); + p = p + strlen(Con_Handle->PDomain); + *p = 0; + p = p + 1; - strcpy(p, Con_Handle->OSName); - p = p + strlen(Con_Handle->OSName); - *p = 0; + strcpy(p, Con_Handle->OSName); + p = p + strlen(Con_Handle->OSName); + *p = 0; } else { - /* We don't admit to UNICODE support ... */ + /* We don't admit to UNICODE support ... */ - param_len = strlen(UserName) + 1 + pass_len + - strlen(Con_Handle->PDomain) + 1 + - strlen(Con_Handle->OSName) + 1 + - strlen(Con_Handle->LMType) + 1; + param_len = strlen(UserName) + 1 + pass_len + + strlen(Con_Handle->PDomain) + 1 + + strlen(Con_Handle->OSName) + 1 + + strlen(Con_Handle->LMType) + 1; - pkt_len = SMB_ssetpNTLM_len + param_len; + pkt_len = SMB_ssetpNTLM_len + param_len; - pkt = (struct RFCNB_Pkt *) RFCNB_Alloc_Pkt(pkt_len); + pkt = (struct RFCNB_Pkt *) RFCNB_Alloc_Pkt(pkt_len); - if (pkt == NULL) { + if (pkt == NULL) { - SMBlib_errno = SMBlibE_NoSpace; - return (-1); /* Should handle the error */ + SMBlib_errno = SMBlibE_NoSpace; + return (-1); /* Should handle the error */ - } - memset(SMB_Hdr(pkt), 0, SMB_ssetpNTLM_len); - SIVAL(SMB_Hdr(pkt), SMB_hdr_idf_offset, SMB_DEF_IDF); /* Plunk in IDF */ - *(SMB_Hdr(pkt) + SMB_hdr_com_offset) = SMBsesssetupX; - SSVAL(SMB_Hdr(pkt), SMB_hdr_pid_offset, Con_Handle->pid); - SSVAL(SMB_Hdr(pkt), SMB_hdr_tid_offset, 0); - SSVAL(SMB_Hdr(pkt), SMB_hdr_mid_offset, Con_Handle->mid); - SSVAL(SMB_Hdr(pkt), SMB_hdr_uid_offset, Con_Handle->uid); - *(SMB_Hdr(pkt) + SMB_hdr_wct_offset) = 13; - *(SMB_Hdr(pkt) + SMB_hdr_axc_offset) = 0xFF; /* No extra command */ - SSVAL(SMB_Hdr(pkt), SMB_hdr_axo_offset, 0); + } + memset(SMB_Hdr(pkt), 0, SMB_ssetpNTLM_len); + SIVAL(SMB_Hdr(pkt), SMB_hdr_idf_offset, SMB_DEF_IDF); /* Plunk in IDF */ + *(SMB_Hdr(pkt) + SMB_hdr_com_offset) = SMBsesssetupX; + SSVAL(SMB_Hdr(pkt), SMB_hdr_pid_offset, Con_Handle->pid); + SSVAL(SMB_Hdr(pkt), SMB_hdr_tid_offset, 0); + SSVAL(SMB_Hdr(pkt), SMB_hdr_mid_offset, Con_Handle->mid); + SSVAL(SMB_Hdr(pkt), SMB_hdr_uid_offset, Con_Handle->uid); + *(SMB_Hdr(pkt) + SMB_hdr_wct_offset) = 13; + *(SMB_Hdr(pkt) + SMB_hdr_axc_offset) = 0xFF; /* No extra command */ + SSVAL(SMB_Hdr(pkt), SMB_hdr_axo_offset, 0); - SSVAL(SMB_Hdr(pkt), SMB_ssetpNTLM_mbs_offset, SMBLIB_MAX_XMIT); - SSVAL(SMB_Hdr(pkt), SMB_ssetpNTLM_mmc_offset, 0); - SSVAL(SMB_Hdr(pkt), SMB_ssetpNTLM_vcn_offset, 0); - SIVAL(SMB_Hdr(pkt), SMB_ssetpNTLM_snk_offset, 0); - SSVAL(SMB_Hdr(pkt), SMB_ssetpNTLM_cipl_offset, pass_len); - SSVAL(SMB_Hdr(pkt), SMB_ssetpNTLM_cspl_offset, 0); - SIVAL(SMB_Hdr(pkt), SMB_ssetpNTLM_res_offset, 0); - SIVAL(SMB_Hdr(pkt), SMB_ssetpNTLM_cap_offset, 0); - SSVAL(SMB_Hdr(pkt), SMB_ssetpNTLM_bcc_offset, param_len); + SSVAL(SMB_Hdr(pkt), SMB_ssetpNTLM_mbs_offset, SMBLIB_MAX_XMIT); + SSVAL(SMB_Hdr(pkt), SMB_ssetpNTLM_mmc_offset, 0); + SSVAL(SMB_Hdr(pkt), SMB_ssetpNTLM_vcn_offset, 0); + SIVAL(SMB_Hdr(pkt), SMB_ssetpNTLM_snk_offset, 0); + SSVAL(SMB_Hdr(pkt), SMB_ssetpNTLM_cipl_offset, pass_len); + SSVAL(SMB_Hdr(pkt), SMB_ssetpNTLM_cspl_offset, 0); + SIVAL(SMB_Hdr(pkt), SMB_ssetpNTLM_res_offset, 0); + SIVAL(SMB_Hdr(pkt), SMB_ssetpNTLM_cap_offset, 0); + SSVAL(SMB_Hdr(pkt), SMB_ssetpNTLM_bcc_offset, param_len); - /* Now copy the param strings in with the right stuff */ + /* Now copy the param strings in with the right stuff */ - p = (char *) (SMB_Hdr(pkt) + SMB_ssetpNTLM_buf_offset); + p = (char *) (SMB_Hdr(pkt) + SMB_ssetpNTLM_buf_offset); - /* Copy in password, then the rest. Password has no null at end */ + /* Copy in password, then the rest. Password has no null at end */ - memcpy(p, pword, pass_len); + memcpy(p, pword, pass_len); - p = p + pass_len; + p = p + pass_len; - strcpy(p, UserName); - p = p + strlen(UserName); - *p = 0; + strcpy(p, UserName); + p = p + strlen(UserName); + *p = 0; - p = p + 1; + p = p + 1; - strcpy(p, Con_Handle->PDomain); - p = p + strlen(Con_Handle->PDomain); - *p = 0; - p = p + 1; + strcpy(p, Con_Handle->PDomain); + p = p + strlen(Con_Handle->PDomain); + *p = 0; + p = p + 1; - strcpy(p, Con_Handle->OSName); - p = p + strlen(Con_Handle->OSName); - *p = 0; - p = p + 1; + strcpy(p, Con_Handle->OSName); + p = p + strlen(Con_Handle->OSName); + *p = 0; + p = p + 1; - strcpy(p, Con_Handle->LMType); - p = p + strlen(Con_Handle->LMType); - *p = 0; + strcpy(p, Con_Handle->LMType); + p = p + strlen(Con_Handle->LMType); + *p = 0; } @@ -452,12 +452,12 @@ SMB_Logon_Server(SMB_Handle_Type Con_Handle, char *UserName, if (RFCNB_Send(Con_Handle->Trans_Connect, pkt, pkt_len) < 0) { #ifdef DEBUG - fprintf(stderr, "Error sending SessSetupX request\n"); + fprintf(stderr, "Error sending SessSetupX request\n"); #endif - RFCNB_Free_Pkt(pkt); - SMBlib_errno = SMBlibE_SendFailed; - return (SMBlibE_BAD); + RFCNB_Free_Pkt(pkt); + SMBlib_errno = SMBlibE_SendFailed; + return (SMBlibE_BAD); } /* Now get the response ... */ @@ -465,12 +465,12 @@ SMB_Logon_Server(SMB_Handle_Type Con_Handle, char *UserName, if (RFCNB_Recv(Con_Handle->Trans_Connect, pkt, pkt_len) < 0) { #ifdef DEBUG - fprintf(stderr, "Error receiving response to SessSetupAndX\n"); + fprintf(stderr, "Error receiving response to SessSetupAndX\n"); #endif - RFCNB_Free_Pkt(pkt); - SMBlib_errno = SMBlibE_RecvFailed; - return (SMBlibE_BAD); + RFCNB_Free_Pkt(pkt); + SMBlib_errno = SMBlibE_RecvFailed; + return (SMBlibE_BAD); } /* Check out the response type ... */ @@ -478,20 +478,20 @@ SMB_Logon_Server(SMB_Handle_Type Con_Handle, char *UserName, if (CVAL(SMB_Hdr(pkt), SMB_hdr_rcls_offset) != SMBC_SUCCESS) { /* Process error */ #ifdef DEBUG - fprintf(stderr, "SMB_SessSetupAndX failed with errorclass = %i, Error Code = %i\n", - CVAL(SMB_Hdr(pkt), SMB_hdr_rcls_offset), - SVAL(SMB_Hdr(pkt), SMB_hdr_err_offset)); + fprintf(stderr, "SMB_SessSetupAndX failed with errorclass = %i, Error Code = %i\n", + CVAL(SMB_Hdr(pkt), SMB_hdr_rcls_offset), + SVAL(SMB_Hdr(pkt), SMB_hdr_err_offset)); #endif - SMBlib_SMB_Error = IVAL(SMB_Hdr(pkt), SMB_hdr_rcls_offset); - RFCNB_Free_Pkt(pkt); - SMBlib_errno = SMBlibE_Remote; - return (SMBlibE_BAD); + SMBlib_SMB_Error = IVAL(SMB_Hdr(pkt), SMB_hdr_rcls_offset); + RFCNB_Free_Pkt(pkt); + SMBlib_errno = SMBlibE_Remote; + return (SMBlibE_BAD); } #ifdef DEBUG fprintf(stderr, "SessSetupAndX response. Action = %i\n", - SVAL(SMB_Hdr(pkt), SMB_ssetpr_act_offset)); + SVAL(SMB_Hdr(pkt), SMB_ssetpr_act_offset)); #endif /* Now pick up the UID for future reference ... */ @@ -515,7 +515,7 @@ SMB_Discon(SMB_Handle_Type Con_Handle, BOOL KeepHandle) RFCNB_Hangup(Con_Handle->Trans_Connect); if (!KeepHandle) - free(Con_Handle); + free(Con_Handle); return (0); diff --git a/helpers/basic_auth/MSNT/smblib.h b/helpers/basic_auth/MSNT/smblib.h index 5ebfe1141f..aaa4742d3a 100644 --- a/helpers/basic_auth/MSNT/smblib.h +++ b/helpers/basic_auth/MSNT/smblib.h @@ -1,10 +1,10 @@ /* UNIX SMBlib NetBIOS implementation - * + * * Version 1.0 * SMBlib Defines - * + * * Copyright (C) Richard Sharpe 1996 - * + * */ /* @@ -12,12 +12,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -40,10 +40,10 @@ SMB_Handle_Type SMB_Connect_Server(SMB_Handle_Type, char *server, char *NTdomain /* The handle and populate it with defaults */ SMB_Handle_Type SMB_Connect(SMB_Handle_Type Con_Handle, - SMB_Tree_Handle * tree, - char *service, - char *username, - char *password); + SMB_Tree_Handle * tree, + char *service, + char *username, + char *password); /* Negotiate a protocol */ @@ -52,7 +52,7 @@ int SMB_Negotiate(SMB_Handle_Type Con_Handle, const char *Prots[]); /* Connect to a tree ... */ SMB_Tree_Handle SMB_TreeConnect(SMB_Handle_Type con_handle, SMB_Tree_Handle tree_handle, - char *path, char *password, const char *dev); + char *path, char *password, const char *dev); /* Disconnect a tree ... */ @@ -61,10 +61,10 @@ int SMB_TreeDisconect(void *tree_handle); /* Open a file */ void *SMB_Open(void *tree_handle, - void *file_handle, - char *file_name, - unsigned short mode, - unsigned short search); + void *file_handle, + char *file_name, + unsigned short mode, + unsigned short search); /* Close a file */ @@ -76,9 +76,9 @@ int SMB_Close(void *file_handle); int SMB_Discon(SMB_Handle_Type Con_Handle, BOOL KeepHandle); void *SMB_Create(void *Tree_Handle, - void *File_Handle, - char *file_name, - short search); + void *File_Handle, + char *file_name, + short search); int SMB_Delete(void *tree, char *file_name, short search); @@ -95,7 +95,7 @@ int SMB_Get_Last_SMB_Err(void); void SMB_Get_Error_Msg(int msg, char *msgbuf, int len); void *SMB_Logon_And_TCon(void *con, void *tree, char *user, char *pass, - char *service, char *st); + char *service, char *st); void SMB_Get_My_Name(char *, int); diff --git a/helpers/basic_auth/MSNT/std-defines.h b/helpers/basic_auth/MSNT/std-defines.h index 2d16102aae..4108015086 100644 --- a/helpers/basic_auth/MSNT/std-defines.h +++ b/helpers/basic_auth/MSNT/std-defines.h @@ -1,8 +1,8 @@ /* RFCNB Standard includes ... */ /* - * + * * SMBlib Standard Includes - * + * * Copyright (C) 1996, Richard Sharpe */ /* One day we will conditionalize these on OS types ... */ @@ -12,12 +12,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. diff --git a/helpers/basic_auth/MSNT/std-includes.h b/helpers/basic_auth/MSNT/std-includes.h index ccf6042532..9419829392 100644 --- a/helpers/basic_auth/MSNT/std-includes.h +++ b/helpers/basic_auth/MSNT/std-includes.h @@ -1,8 +1,8 @@ /* RFCNB Standard includes ... */ /* - * + * * RFCNB Standard Includes - * + * * Copyright (C) 1996, Richard Sharpe */ /* One day we will conditionalize these on OS types ... */ @@ -12,12 +12,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. diff --git a/helpers/basic_auth/MSNT/usersfile.c b/helpers/basic_auth/MSNT/usersfile.c index 90dc7598ea..ce842222a1 100644 --- a/helpers/basic_auth/MSNT/usersfile.c +++ b/helpers/basic_auth/MSNT/usersfile.c @@ -3,7 +3,7 @@ * usersfile.c * (C) 2000 Antonino Iannella, Stellar-X Pty Ltd * Released under GPL, see COPYING-2.0 for details. - * + * * These routines are to allow users attempting to use the proxy which * have been explicitly allowed by the system administrator. * The code originated from denyusers.c. @@ -38,9 +38,9 @@ free_names(usersfile * uf) { int i; for (i = 0; i < uf->Inuse; i++) { - if (uf->names[i]) - free(uf->names[i]); - uf->names[i] = NULL; + if (uf->names[i]) + free(uf->names[i]); + uf->names[i] = NULL; } uf->Inuse = 0; } @@ -62,59 +62,59 @@ Read_usersfile(const char *path, usersfile * uf) free_names(uf); if (NULL == path) { - path = uf->path; + path = uf->path; } else { - if (uf->path) - free(uf->path); - uf->path = strdup(path); + if (uf->path) + free(uf->path); + uf->path = strdup(path); } /* Open the users file. Report any errors. */ fp = fopen(path, "r"); if (NULL == fp) { - uf->LMT = 0; - if (errno == ENOENT) - return 0; - syslog(LOG_ERR, "%s: %s", path, strerror(errno)); - return 1; + uf->LMT = 0; + if (errno == ENOENT) + return 0; + syslog(LOG_ERR, "%s: %s", path, strerror(errno)); + return 1; } /* Stat the file. If it does not exist, save the size as zero. * Clear the allowed user string. Return. */ if (fstat(fileno(fp), &FileBuf) < 0) { - syslog(LOG_ERR, "%s: %s", path, strerror(errno)); - return 1; + syslog(LOG_ERR, "%s: %s", path, strerror(errno)); + return 1; } /* If it exists, save the modification time and size */ uf->LMT = FileBuf.st_mtime; /* Handle the special case of a zero length file */ if (FileBuf.st_size == 0) - return 0; + return 0; /* * Read the file into memory * XXX assumes one username per input line */ while (fgets(buf, 1024, fp) != NULL) { - /* ensure no names longer than our limit */ - buf[NAMELEN] = '\0'; - /* skip bad input lines */ - if (NULL == strtok(buf, "\r\n")) - continue; - /* grow the list if necessary */ - if (0 == uf->Alloc) { - uf->Alloc = 256; - uf->names = calloc(uf->Alloc, sizeof(*uf->names)); - } else if (uf->Inuse == uf->Alloc) { - uf->Alloc = uf->Alloc << 1; - uf->names = realloc(uf->names, uf->Alloc * sizeof(*uf->names)); - /* zero out the newly allocated memory */ - memset(&uf->names[uf->Alloc >> 1], - '\0', - (uf->Alloc >> 1) * sizeof(*uf->names)); - } - uf->names[uf->Inuse] = strdup(buf); - uf->Inuse++; + /* ensure no names longer than our limit */ + buf[NAMELEN] = '\0'; + /* skip bad input lines */ + if (NULL == strtok(buf, "\r\n")) + continue; + /* grow the list if necessary */ + if (0 == uf->Alloc) { + uf->Alloc = 256; + uf->names = calloc(uf->Alloc, sizeof(*uf->names)); + } else if (uf->Inuse == uf->Alloc) { + uf->Alloc = uf->Alloc << 1; + uf->names = realloc(uf->names, uf->Alloc * sizeof(*uf->names)); + /* zero out the newly allocated memory */ + memset(&uf->names[uf->Alloc >> 1], + '\0', + (uf->Alloc >> 1) * sizeof(*uf->names)); + } + uf->names[uf->Inuse] = strdup(buf); + uf->Inuse++; } fclose(fp); fp = NULL; @@ -137,24 +137,24 @@ Check_userlist(usersfile * uf, char *User) /* Empty users are always in the list */ if (User[0] == '\0') - return 1; + return 1; /* If allowed user list is empty, allow all users. * If no users are supposed to be using the proxy, stop squid instead. */ if (0 == uf->Inuse) - return 1; + return 1; /* Check if username string is found in the allowed user list. * If so, allow. If not, deny. Reconstruct the username * to have whitespace, to avoid finding wrong string subsets. */ p = bsearch(&User, - uf->names, - uf->Inuse, - sizeof(*uf->names), - name_cmp); + uf->names, + uf->Inuse, + sizeof(*uf->names), + name_cmp); if (NULL == p) { - return 0; + return 0; } return 1; } @@ -171,20 +171,20 @@ Check_forfilechange(usersfile * uf) /* Stat the allowed users file. If it cannot be accessed, return. */ if (uf->path == NULL) - return; + return; if (stat(uf->path, &ChkBuf) < 0) { - if (errno == ENOENT) { - uf->LMT = 0; - free_names(uf); - } else { /* Report error when accessing file */ - syslog(LOG_ERR, "%s: %s", uf->path, strerror(errno)); - } - return; + if (errno == ENOENT) { + uf->LMT = 0; + free_names(uf); + } else { /* Report error when accessing file */ + syslog(LOG_ERR, "%s: %s", uf->path, strerror(errno)); + } + return; } /* return if no change */ if (ChkBuf.st_mtime == uf->LMT) - return; + return; /* * The file changed, so re-read it. diff --git a/helpers/basic_auth/MSNT/valid.c b/helpers/basic_auth/MSNT/valid.c index 9c6b0f07ed..233cf3af96 100644 --- a/helpers/basic_auth/MSNT/valid.c +++ b/helpers/basic_auth/MSNT/valid.c @@ -9,33 +9,33 @@ int Valid_User(char *USERNAME, char *PASSWORD, char *SERVER, char *BACKUP, char *DOMAIN) { - const char *SMB_Prots[] = - {"PC NETWORK PROGRAM 1.0", - "MICROSOFT NETWORKS 1.03", - "MICROSOFT NETWORKS 3.0", - "LANMAN1.0", - "LM1.2X002", - "Samba", - "NT LM 0.12", - "NT LANMAN 1.0", - NULL}; + const char *SMB_Prots[] = {"PC NETWORK PROGRAM 1.0", + "MICROSOFT NETWORKS 1.03", + "MICROSOFT NETWORKS 3.0", + "LANMAN1.0", + "LM1.2X002", + "Samba", + "NT LM 0.12", + "NT LANMAN 1.0", + NULL + }; void *con; SMB_Init(); con = SMB_Connect_Server(NULL, SERVER, DOMAIN); if (con == NULL) { /* Error ... */ - con = SMB_Connect_Server(NULL, BACKUP, DOMAIN); - if (con == NULL) { - return (NTV_SERVER_ERROR); - } + con = SMB_Connect_Server(NULL, BACKUP, DOMAIN); + if (con == NULL) { + return (NTV_SERVER_ERROR); + } } if (SMB_Negotiate(con, SMB_Prots) < 0) { /* An error */ - SMB_Discon(con, 0); - return (NTV_PROTOCOL_ERROR); + SMB_Discon(con, 0); + return (NTV_PROTOCOL_ERROR); } if (SMB_Logon_Server(con, USERNAME, PASSWORD) < 0) { - SMB_Discon(con, 0); - return (NTV_LOGON_ERROR); + SMB_Discon(con, 0); + return (NTV_LOGON_ERROR); } SMB_Discon(con, 0); return (NTV_NO_ERROR); diff --git a/helpers/basic_auth/NCSA/crypt_md5.c b/helpers/basic_auth/NCSA/crypt_md5.c index d342fcedc4..d366e6f446 100644 --- a/helpers/basic_auth/NCSA/crypt_md5.c +++ b/helpers/basic_auth/NCSA/crypt_md5.c @@ -28,8 +28,8 @@ static unsigned char itoa64[] = /* 0 ... 63 => ascii - 64 */ static void md5to64(char *s, unsigned long v, int n) { while (--n >= 0) { - *s++ = itoa64[v & 0x3f]; - v >>= 6; + *s++ = itoa64[v & 0x3f]; + v >>= 6; } } @@ -55,16 +55,16 @@ char *crypt_md5(const char *pw, const char *salt) unsigned long l; if (*salt == '$') { - magic = salt++; - while(*salt && *salt != '$') - salt++; - if (*salt == '$') { - salt++; - magiclen = salt - magic; - } else { - salt = magic; - magic = "$1$"; - } + magic = salt++; + while (*salt && *salt != '$') + salt++; + if (*salt == '$') { + salt++; + magiclen = salt - magic; + } else { + salt = magic; + magic = "$1$"; + } } /* Refine the Salt first */ @@ -72,7 +72,7 @@ char *crypt_md5(const char *pw, const char *salt) /* It stops at the first '$', max 8 chars */ for (ep = sp; *ep && *ep != '$' && ep < (sp + 8); ep++) - continue; + continue; /* get the length of the true salt */ sl = ep - sp; @@ -95,17 +95,17 @@ char *crypt_md5(const char *pw, const char *salt) SquidMD5Update(&ctx1, (unsigned const char *) pw, strlen(pw)); SquidMD5Final(final, &ctx1); for (pl = strlen(pw); pl > 0; pl -= 16) - SquidMD5Update(&ctx, (unsigned const char *) final, pl > 16 ? 16 : pl); + SquidMD5Update(&ctx, (unsigned const char *) final, pl > 16 ? 16 : pl); /* Don't leave anything around in vm they could use. */ memset(final, 0, sizeof final); /* Then something really weird... */ for (j = 0, i = strlen(pw); i; i >>= 1) - if (i & 1) - SquidMD5Update(&ctx, (unsigned const char *) final + j, 1); - else - SquidMD5Update(&ctx, (unsigned const char *) pw + j, 1); + if (i & 1) + SquidMD5Update(&ctx, (unsigned const char *) final + j, 1); + else + SquidMD5Update(&ctx, (unsigned const char *) pw + j, 1); /* Now make the output string */ memset(passwd, 0, sizeof(passwd)); @@ -121,23 +121,23 @@ char *crypt_md5(const char *pw, const char *salt) * need 30 seconds to build a 1000 entry dictionary... */ for (i = 0; i < 1000; i++) { - SquidMD5Init(&ctx1); - if (i & 1) - SquidMD5Update(&ctx1, (unsigned const char *) pw, strlen(pw)); - else - SquidMD5Update(&ctx1, (unsigned const char *) final, 16); - - if (i % 3) - SquidMD5Update(&ctx1, (unsigned const char *) sp, sl); - - if (i % 7) - SquidMD5Update(&ctx1, (unsigned const char *) pw, strlen(pw)); - - if (i & 1) - SquidMD5Update(&ctx1, (unsigned const char *) final, 16); - else - SquidMD5Update(&ctx1, (unsigned const char *) pw, strlen(pw)); - SquidMD5Final(final, &ctx1); + SquidMD5Init(&ctx1); + if (i & 1) + SquidMD5Update(&ctx1, (unsigned const char *) pw, strlen(pw)); + else + SquidMD5Update(&ctx1, (unsigned const char *) final, 16); + + if (i % 3) + SquidMD5Update(&ctx1, (unsigned const char *) sp, sl); + + if (i % 7) + SquidMD5Update(&ctx1, (unsigned const char *) pw, strlen(pw)); + + if (i & 1) + SquidMD5Update(&ctx1, (unsigned const char *) final, 16); + else + SquidMD5Update(&ctx1, (unsigned const char *) pw, strlen(pw)); + SquidMD5Final(final, &ctx1); } p = passwd + strlen(passwd); @@ -171,26 +171,27 @@ char *crypt_md5(const char *pw, const char *salt) /* Created by Ramon de Carvalho Refined by Rodrigo Rubira Branco */ -char *md5sum(const char *s){ - static unsigned char digest[16]; - SquidMD5_CTX ctx; - int idx; - static char sum[33]; +char *md5sum(const char *s) +{ + static unsigned char digest[16]; + SquidMD5_CTX ctx; + int idx; + static char sum[33]; - memset(digest,0,16); + memset(digest,0,16); - SquidMD5Init(&ctx); - SquidMD5Update(&ctx,(const unsigned char *)s,strlen(s)); - SquidMD5Final(digest,&ctx); + SquidMD5Init(&ctx); + SquidMD5Update(&ctx,(const unsigned char *)s,strlen(s)); + SquidMD5Final(digest,&ctx); - for(idx=0;idx<16;idx++) - sprintf(&sum[idx*2],"%02x",digest[idx]); + for (idx=0;idx<16;idx++) + sprintf(&sum[idx*2],"%02x",digest[idx]); - sum[32]='\0'; + sum[32]='\0'; - /* Don't leave anything around in vm they could use. */ - memset(digest, 0, sizeof digest); + /* Don't leave anything around in vm they could use. */ + memset(digest, 0, sizeof digest); - return sum; + return sum; } diff --git a/helpers/basic_auth/NCSA/ncsa_auth.c b/helpers/basic_auth/NCSA/ncsa_auth.c index 7d690515d7..3048f4c219 100644 --- a/helpers/basic_auth/NCSA/ncsa_auth.c +++ b/helpers/basic_auth/NCSA/ncsa_auth.c @@ -72,32 +72,32 @@ read_passwd_file(const char *passwdfile) char *user; char *passwd; if (hash != NULL) { - hashFreeItems(hash, my_free); - hashFreeMemory(hash); + hashFreeItems(hash, my_free); + hashFreeMemory(hash); } /* initial setup */ hash = hash_create((HASHCMP *) strcmp, 7921, hash_string); if (NULL == hash) { - fprintf(stderr, "ncsa_auth: cannot create hash table\n"); - exit(1); + fprintf(stderr, "ncsa_auth: cannot create hash table\n"); + exit(1); } f = fopen(passwdfile, "r"); if (NULL == f) { - fprintf(stderr, "%s: %s\n", passwdfile, xstrerror()); - exit(1); + fprintf(stderr, "%s: %s\n", passwdfile, xstrerror()); + exit(1); } while (fgets(buf, 8192, f) != NULL) { - if ((buf[0] == '#') || (buf[0] == ' ') || (buf[0] == '\t') || - (buf[0] == '\n')) - continue; - user = strtok(buf, ":\n\r"); - passwd = strtok(NULL, ":\n\r"); - if ((strlen(user) > 0) && passwd) { - u = xmalloc(sizeof(*u)); - u->user = xstrdup(user); - u->passwd = xstrdup(passwd); - hash_join(hash, (hash_link *) u); - } + if ((buf[0] == '#') || (buf[0] == ' ') || (buf[0] == '\t') || + (buf[0] == '\n')) + continue; + user = strtok(buf, ":\n\r"); + passwd = strtok(NULL, ":\n\r"); + if ((strlen(user) > 0) && passwd) { + u = xmalloc(sizeof(*u)); + u->user = xstrdup(user); + u->passwd = xstrdup(passwd); + hash_join(hash, (hash_link *) u); + } } fclose(f); } @@ -112,50 +112,50 @@ main(int argc, char **argv) user_data *u; setbuf(stdout, NULL); if (argc != 2) { - fprintf(stderr, "Usage: ncsa_auth \n"); - exit(1); + fprintf(stderr, "Usage: ncsa_auth \n"); + exit(1); } if (stat(argv[1], &sb) != 0) { - fprintf(stderr, "cannot stat %s\n", argv[1]); - exit(1); + fprintf(stderr, "cannot stat %s\n", argv[1]); + exit(1); } while (fgets(buf, 256, stdin) != NULL) { - if ((p = strchr(buf, '\n')) != NULL) - *p = '\0'; /* strip \n */ - if (stat(argv[1], &sb) == 0) { - if (sb.st_mtime != change_time) { - read_passwd_file(argv[1]); - change_time = sb.st_mtime; - } - } - if ((user = strtok(buf, " ")) == NULL) { - printf("ERR\n"); - continue; - } - if ((passwd = strtok(NULL, "")) == NULL) { - printf("ERR\n"); - continue; - } - rfc1738_unescape(user); - rfc1738_unescape(passwd); - u = (user_data *) hash_lookup(hash, user); - if (u == NULL) { - printf("ERR No such user\n"); + if ((p = strchr(buf, '\n')) != NULL) + *p = '\0'; /* strip \n */ + if (stat(argv[1], &sb) == 0) { + if (sb.st_mtime != change_time) { + read_passwd_file(argv[1]); + change_time = sb.st_mtime; + } + } + if ((user = strtok(buf, " ")) == NULL) { + printf("ERR\n"); + continue; + } + if ((passwd = strtok(NULL, "")) == NULL) { + printf("ERR\n"); + continue; + } + rfc1738_unescape(user); + rfc1738_unescape(passwd); + u = (user_data *) hash_lookup(hash, user); + if (u == NULL) { + printf("ERR No such user\n"); #if HAVE_CRYPT - } else if (strcmp(u->passwd, (char *) crypt(passwd, u->passwd)) == 0) { - printf("OK\n"); + } else if (strcmp(u->passwd, (char *) crypt(passwd, u->passwd)) == 0) { + printf("OK\n"); #endif - } else if (strcmp(u->passwd, (char *) crypt_md5(passwd, u->passwd)) == 0) { - printf("OK\n"); - } else if (strcmp(u->passwd, (char *) md5sum(passwd)) == 0) { /* md5 without salt and magic strings - Added by Ramon de Carvalho and Rodrigo Rubira Branco */ - printf("OK\n"); - } else { - printf("ERR Wrong password\n"); - } + } else if (strcmp(u->passwd, (char *) crypt_md5(passwd, u->passwd)) == 0) { + printf("OK\n"); + } else if (strcmp(u->passwd, (char *) md5sum(passwd)) == 0) { /* md5 without salt and magic strings - Added by Ramon de Carvalho and Rodrigo Rubira Branco */ + printf("OK\n"); + } else { + printf("ERR Wrong password\n"); + } } if (hash != NULL) { - hashFreeItems(hash, my_free); - hashFreeMemory(hash); + hashFreeItems(hash, my_free); + hashFreeMemory(hash); } exit(0); } diff --git a/helpers/basic_auth/PAM/pam_auth.c b/helpers/basic_auth/PAM/pam_auth.c index c098b0f824..a5196e2282 100644 --- a/helpers/basic_auth/PAM/pam_auth.c +++ b/helpers/basic_auth/PAM/pam_auth.c @@ -100,23 +100,23 @@ static int password_conversation(int num_msg, const struct pam_message **msg, struct pam_response **resp, void *appdata_ptr) { if (num_msg != 1 || msg[0]->msg_style != PAM_PROMPT_ECHO_OFF) { - fprintf(stderr, "ERROR: Unexpected PAM converstaion '%d/%s'\n", msg[0]->msg_style, msg[0]->msg); - return PAM_CONV_ERR; + fprintf(stderr, "ERROR: Unexpected PAM converstaion '%d/%s'\n", msg[0]->msg_style, msg[0]->msg); + return PAM_CONV_ERR; } if (!appdata_ptr) { - /* Workaround for Solaris 2.6 where the PAM library is broken - * and does not pass appdata_ptr to the conversation routine - */ - appdata_ptr = password; + /* Workaround for Solaris 2.6 where the PAM library is broken + * and does not pass appdata_ptr to the conversation routine + */ + appdata_ptr = password; } if (!appdata_ptr) { - fprintf(stderr, "ERROR: No password available to password_converstation!\n"); - return PAM_CONV_ERR; + fprintf(stderr, "ERROR: No password available to password_converstation!\n"); + return PAM_CONV_ERR; } *resp = calloc(num_msg, sizeof(struct pam_response)); if (!*resp) { - fprintf(stderr, "ERROR: Out of memory!\n"); - return PAM_CONV_ERR; + fprintf(stderr, "ERROR: Out of memory!\n"); + return PAM_CONV_ERR; } (*resp)[0].resp = strdup((char *) appdata_ptr); (*resp)[0].resp_retcode = 0; @@ -124,8 +124,7 @@ password_conversation(int num_msg, const struct pam_message **msg, struct pam_re return ((*resp)[0].resp ? PAM_SUCCESS : PAM_CONV_ERR); } -static struct pam_conv conv = -{ +static struct pam_conv conv = { &password_conversation, NULL }; @@ -159,118 +158,118 @@ main(int argc, char *argv[]) setvbuf(stdout, NULL, _IOLBF, 0); while (1) { - int ch = getopt(argc, argv, "1n:t:o"); - switch (ch) { - case -1: - goto start; - case 'n': - service = optarg; - break; - case 't': - ttl = atoi(optarg); - break; - case '1': - ttl = 0; - break; - case 'o': - no_acct_mgmt = 1; - break; - default: - fprintf(stderr, "Unknown getopt value '%c'\n", ch); - usage(argv[0]); - exit(1); - } + int ch = getopt(argc, argv, "1n:t:o"); + switch (ch) { + case -1: + goto start; + case 'n': + service = optarg; + break; + case 't': + ttl = atoi(optarg); + break; + case '1': + ttl = 0; + break; + case 'o': + no_acct_mgmt = 1; + break; + default: + fprintf(stderr, "Unknown getopt value '%c'\n", ch); + usage(argv[0]); + exit(1); + } } start: if (optind < argc) { - fprintf(stderr, "Unknown option '%s'\n", argv[optind]); - usage(argv[0]); - exit(1); + fprintf(stderr, "Unknown option '%s'\n", argv[optind]); + usage(argv[0]); + exit(1); } while (fgets(buf, BUFSIZE, stdin)) { - user = buf; - password = strchr(buf, '\n'); - if (!password) { - fprintf(stderr, "authenticator: Unexpected input '%s'\n", buf); - goto error; - } - *password = '\0'; - password = strchr(buf, ' '); - if (!password) { - fprintf(stderr, "authenticator: Unexpected input '%s'\n", buf); - goto error; - } - *password++ = '\0'; - rfc1738_unescape(user); - rfc1738_unescape(password); - conv.appdata_ptr = (char *) password; /* from buf above. not allocated */ + user = buf; + password = strchr(buf, '\n'); + if (!password) { + fprintf(stderr, "authenticator: Unexpected input '%s'\n", buf); + goto error; + } + *password = '\0'; + password = strchr(buf, ' '); + if (!password) { + fprintf(stderr, "authenticator: Unexpected input '%s'\n", buf); + goto error; + } + *password++ = '\0'; + rfc1738_unescape(user); + rfc1738_unescape(password); + conv.appdata_ptr = (char *) password; /* from buf above. not allocated */ - if (ttl == 0) { - /* Create PAM connection */ - retval = pam_start(service, user, &conv, &pamh); - if (retval != PAM_SUCCESS) { - fprintf(stderr, "ERROR: failed to create PAM authenticator\n"); - goto error; - } - } else if (!pamh || (time(NULL) - pamh_created) >= ttl || pamh_created > time(NULL)) { - /* Close previous PAM connection */ - if (pamh) { - retval = pam_end(pamh, retval); - if (retval != PAM_SUCCESS) { - fprintf(stderr, "WARNING: failed to release PAM authenticator\n"); - } - pamh = NULL; - } - /* Initialize persistent PAM connection */ - retval = pam_start(service, "squid@", &conv, &pamh); - if (retval != PAM_SUCCESS) { - fprintf(stderr, "ERROR: failed to create PAM authenticator\n"); - goto error; - } - pamh_created = time(NULL); - } - /* Authentication */ - retval = PAM_SUCCESS; - if (ttl != 0) { - if (retval == PAM_SUCCESS) - retval = pam_set_item(pamh, PAM_USER, user); - if (retval == PAM_SUCCESS) - retval = pam_set_item(pamh, PAM_CONV, &conv); - } - if (retval == PAM_SUCCESS) - retval = pam_authenticate(pamh, 0); - if (retval == PAM_SUCCESS && !no_acct_mgmt) - retval = pam_acct_mgmt(pamh, 0); - if (retval == PAM_SUCCESS) { - fprintf(stdout, "OK\n"); - } else { + if (ttl == 0) { + /* Create PAM connection */ + retval = pam_start(service, user, &conv, &pamh); + if (retval != PAM_SUCCESS) { + fprintf(stderr, "ERROR: failed to create PAM authenticator\n"); + goto error; + } + } else if (!pamh || (time(NULL) - pamh_created) >= ttl || pamh_created > time(NULL)) { + /* Close previous PAM connection */ + if (pamh) { + retval = pam_end(pamh, retval); + if (retval != PAM_SUCCESS) { + fprintf(stderr, "WARNING: failed to release PAM authenticator\n"); + } + pamh = NULL; + } + /* Initialize persistent PAM connection */ + retval = pam_start(service, "squid@", &conv, &pamh); + if (retval != PAM_SUCCESS) { + fprintf(stderr, "ERROR: failed to create PAM authenticator\n"); + goto error; + } + pamh_created = time(NULL); + } + /* Authentication */ + retval = PAM_SUCCESS; + if (ttl != 0) { + if (retval == PAM_SUCCESS) + retval = pam_set_item(pamh, PAM_USER, user); + if (retval == PAM_SUCCESS) + retval = pam_set_item(pamh, PAM_CONV, &conv); + } + if (retval == PAM_SUCCESS) + retval = pam_authenticate(pamh, 0); + if (retval == PAM_SUCCESS && !no_acct_mgmt) + retval = pam_acct_mgmt(pamh, 0); + if (retval == PAM_SUCCESS) { + fprintf(stdout, "OK\n"); + } else { error: - fprintf(stdout, "ERR\n"); - } - /* cleanup */ - retval = PAM_SUCCESS; + fprintf(stdout, "ERR\n"); + } + /* cleanup */ + retval = PAM_SUCCESS; #ifdef PAM_AUTHTOK - if (ttl != 0) { - if (retval == PAM_SUCCESS) - retval = pam_set_item(pamh, PAM_AUTHTOK, NULL); - } + if (ttl != 0) { + if (retval == PAM_SUCCESS) + retval = pam_set_item(pamh, PAM_AUTHTOK, NULL); + } #endif - if (ttl == 0 || retval != PAM_SUCCESS) { - retval = pam_end(pamh, retval); - if (retval != PAM_SUCCESS) { - fprintf(stderr, "WARNING: failed to release PAM authenticator\n"); - } - pamh = NULL; - } + if (ttl == 0 || retval != PAM_SUCCESS) { + retval = pam_end(pamh, retval); + if (retval != PAM_SUCCESS) { + fprintf(stderr, "WARNING: failed to release PAM authenticator\n"); + } + pamh = NULL; + } } if (pamh) { - retval = pam_end(pamh, retval); - if (retval != PAM_SUCCESS) { - pamh = NULL; - fprintf(stderr, "ERROR: failed to release PAM authenticator\n"); - } + retval = pam_end(pamh, retval); + if (retval != PAM_SUCCESS) { + pamh = NULL; + fprintf(stderr, "ERROR: failed to release PAM authenticator\n"); + } } return 0; } diff --git a/helpers/basic_auth/SASL/sasl_auth.c b/helpers/basic_auth/SASL/sasl_auth.c index 294da7454b..832a3923ca 100644 --- a/helpers/basic_auth/SASL/sasl_auth.c +++ b/helpers/basic_auth/SASL/sasl_auth.c @@ -44,83 +44,82 @@ int main(int argc, char *argv[]) { - char line[8192]; - char *username, *password; + char line[8192]; + char *username, *password; #if SASL_VERSION_MAJOR < 2 - const char *errstr; + const char *errstr; #endif - int rc; - sasl_conn_t *conn = NULL; - - /* make standard output line buffered */ - setvbuf(stdout, NULL, _IOLBF, 0); - - rc = sasl_server_init( NULL, APP_NAME_SASL ); - - if ( rc != SASL_OK ) { - fprintf( stderr, "error %d %s\n", rc, sasl_errstring(rc, NULL, NULL )); - fprintf( stdout, "ERR\n" ); - return 1; - } - - #if SASL_VERSION_MAJOR < 2 - rc = sasl_server_new( APP_NAME_SASL, NULL, NULL, NULL, 0, &conn ); - #else - rc = sasl_server_new( APP_NAME_SASL, NULL, NULL, NULL, NULL, NULL, 0, &conn ); - #endif - - if ( rc != SASL_OK ) { - fprintf( stderr, "error %d %s\n", rc, sasl_errstring(rc, NULL, NULL )); - fprintf( stdout, "ERR\n" ); - return 1; - } - - while ( fgets( line, sizeof( line ), stdin )) { - username = &line[0]; - password = strchr( line, '\n' ); - if ( !password) { - fprintf( stderr, "authenticator: Unexpected input '%s'\n", line ); - fprintf( stdout, "ERR\n" ); - continue; - } - *password = '\0'; - password = strchr ( line, ' ' ); - if ( !password) { - fprintf( stderr, "authenticator: Unexpected input '%s'\n", line ); - fprintf( stdout, "ERR\n" ); - continue; - } - *password++ = '\0'; - - rfc1738_unescape(username); - rfc1738_unescape(password); - - #if SASL_VERSION_MAJOR < 2 - rc = sasl_checkpass(conn, username, strlen(username), password, strlen(password), &errstr); - #else - rc = sasl_checkpass(conn, username, strlen(username), password, strlen(password)); - #endif - - if ( rc != SASL_OK ) { - #if SASL_VERSION_MAJOR < 2 - if ( errstr ) { - fprintf( stderr, "errstr %s\n", errstr ); - } - if ( rc != SASL_BADAUTH ) { - fprintf( stderr, "error %d %s\n", rc, sasl_errstring(rc, NULL, NULL )); - } - #endif - fprintf( stdout, "ERR\n" ); - } - else { - fprintf( stdout, "OK\n" ); - } - - } - - sasl_dispose( &conn ); - sasl_done(); - - return 0; + int rc; + sasl_conn_t *conn = NULL; + + /* make standard output line buffered */ + setvbuf(stdout, NULL, _IOLBF, 0); + + rc = sasl_server_init( NULL, APP_NAME_SASL ); + + if ( rc != SASL_OK ) { + fprintf( stderr, "error %d %s\n", rc, sasl_errstring(rc, NULL, NULL )); + fprintf( stdout, "ERR\n" ); + return 1; + } + +#if SASL_VERSION_MAJOR < 2 + rc = sasl_server_new( APP_NAME_SASL, NULL, NULL, NULL, 0, &conn ); +#else + rc = sasl_server_new( APP_NAME_SASL, NULL, NULL, NULL, NULL, NULL, 0, &conn ); +#endif + + if ( rc != SASL_OK ) { + fprintf( stderr, "error %d %s\n", rc, sasl_errstring(rc, NULL, NULL )); + fprintf( stdout, "ERR\n" ); + return 1; + } + + while ( fgets( line, sizeof( line ), stdin )) { + username = &line[0]; + password = strchr( line, '\n' ); + if ( !password) { + fprintf( stderr, "authenticator: Unexpected input '%s'\n", line ); + fprintf( stdout, "ERR\n" ); + continue; + } + *password = '\0'; + password = strchr ( line, ' ' ); + if ( !password) { + fprintf( stderr, "authenticator: Unexpected input '%s'\n", line ); + fprintf( stdout, "ERR\n" ); + continue; + } + *password++ = '\0'; + + rfc1738_unescape(username); + rfc1738_unescape(password); + +#if SASL_VERSION_MAJOR < 2 + rc = sasl_checkpass(conn, username, strlen(username), password, strlen(password), &errstr); +#else + rc = sasl_checkpass(conn, username, strlen(username), password, strlen(password)); +#endif + + if ( rc != SASL_OK ) { +#if SASL_VERSION_MAJOR < 2 + if ( errstr ) { + fprintf( stderr, "errstr %s\n", errstr ); + } + if ( rc != SASL_BADAUTH ) { + fprintf( stderr, "error %d %s\n", rc, sasl_errstring(rc, NULL, NULL )); + } +#endif + fprintf( stdout, "ERR\n" ); + } else { + fprintf( stdout, "OK\n" ); + } + + } + + sasl_dispose( &conn ); + sasl_done(); + + return 0; } diff --git a/helpers/basic_auth/SMB/smb_auth.c b/helpers/basic_auth/SMB/smb_auth.c index 0be3c893f6..ef866df618 100644 --- a/helpers/basic_auth/SMB/smb_auth.c +++ b/helpers/basic_auth/SMB/smb_auth.c @@ -30,12 +30,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -78,20 +78,20 @@ print_esc(FILE * p, char *s) int i = 0; for (t = s; *t != '\0'; t++) { - if (i > 250) { - buf[i] = '\0'; - (void) fputs(buf, p); - i = 0; - } - if (*t == '\\') - buf[i++] = '\\'; + if (i > 250) { + buf[i] = '\0'; + (void) fputs(buf, p); + i = 0; + } + if (*t == '\\') + buf[i++] = '\\'; - buf[i++] = *t; + buf[i++] = *t; } if (i > 0) { - buf[i] = '\0'; - (void) fputs(buf, p); + buf[i] = '\0'; + (void) fputs(buf, p); } } @@ -111,150 +111,150 @@ main(int argc, char *argv[]) /* make standard output line buffered */ if (setvbuf(stdout, NULL, _IOLBF, 0) != 0) - return 1; + return 1; /* parse command line arguments */ for (i = 1; i < argc; i++) { - if (strcmp(argv[i], "-d") == 0) { - debug = 1; - continue; - } - /* the next options require an argument */ - if (i + 1 == argc) - break; + if (strcmp(argv[i], "-d") == 0) { + debug = 1; + continue; + } + /* the next options require an argument */ + if (i + 1 == argc) + break; - if (strcmp(argv[i], "-W") == 0) { - if ((dom = (struct SMBDOMAIN *) malloc(sizeof(struct SMBDOMAIN))) == NULL) - return 1; + if (strcmp(argv[i], "-W") == 0) { + if ((dom = (struct SMBDOMAIN *) malloc(sizeof(struct SMBDOMAIN))) == NULL) + return 1; - dom->name = dom->sname = argv[++i]; - dom->passthrough = ""; - dom->nmbaddr = ""; - dom->nmbcast = NMB_BROADCAST; - dom->authshare = "NETLOGON"; - dom->authfile = "proxyauth"; - dom->next = NULL; + dom->name = dom->sname = argv[++i]; + dom->passthrough = ""; + dom->nmbaddr = ""; + dom->nmbcast = NMB_BROADCAST; + dom->authshare = "NETLOGON"; + dom->authfile = "proxyauth"; + dom->next = NULL; - /* append to linked list */ - if (lastdom != NULL) - lastdom->next = dom; - else - firstdom = dom; + /* append to linked list */ + if (lastdom != NULL) + lastdom->next = dom; + else + firstdom = dom; - lastdom = dom; - continue; - } - if (strcmp(argv[i], "-w") == 0) { - if (lastdom != NULL) - lastdom->sname = argv[++i]; - continue; - } - if (strcmp(argv[i], "-P") == 0) { - if (lastdom != NULL) - lastdom->passthrough = argv[++i]; - continue; - } - if (strcmp(argv[i], "-B") == 0) { - if (lastdom != NULL) { - lastdom->nmbaddr = argv[++i]; - lastdom->nmbcast = NMB_BROADCAST; - } - continue; - } - if (strcmp(argv[i], "-U") == 0) { - if (lastdom != NULL) { - lastdom->nmbaddr = argv[++i]; - lastdom->nmbcast = NMB_UNICAST; - } - continue; - } - if (strcmp(argv[i], "-S") == 0) { - if (lastdom != NULL) { - if ((lastdom->authshare = strdup(argv[++i])) == NULL) - return 1; + lastdom = dom; + continue; + } + if (strcmp(argv[i], "-w") == 0) { + if (lastdom != NULL) + lastdom->sname = argv[++i]; + continue; + } + if (strcmp(argv[i], "-P") == 0) { + if (lastdom != NULL) + lastdom->passthrough = argv[++i]; + continue; + } + if (strcmp(argv[i], "-B") == 0) { + if (lastdom != NULL) { + lastdom->nmbaddr = argv[++i]; + lastdom->nmbcast = NMB_BROADCAST; + } + continue; + } + if (strcmp(argv[i], "-U") == 0) { + if (lastdom != NULL) { + lastdom->nmbaddr = argv[++i]; + lastdom->nmbcast = NMB_UNICAST; + } + continue; + } + if (strcmp(argv[i], "-S") == 0) { + if (lastdom != NULL) { + if ((lastdom->authshare = strdup(argv[++i])) == NULL) + return 1; - /* convert backslashes to forward slashes */ - for (s = lastdom->authshare; *s != '\0'; s++) - if (*s == '\\') - *s = '/'; + /* convert backslashes to forward slashes */ + for (s = lastdom->authshare; *s != '\0'; s++) + if (*s == '\\') + *s = '/'; - /* strip leading forward slash from share name */ - if (*lastdom->authshare == '/') - lastdom->authshare++; + /* strip leading forward slash from share name */ + if (*lastdom->authshare == '/') + lastdom->authshare++; - if ((s = strchr(lastdom->authshare, '/')) != NULL) { - *s = '\0'; - lastdom->authfile = s + 1; - } - } - continue; - } + if ((s = strchr(lastdom->authshare, '/')) != NULL) { + *s = '\0'; + lastdom->authfile = s + 1; + } + } + continue; + } } shcmd = debug ? HELPERSCRIPT : HELPERSCRIPT " > /dev/null 2>&1"; /* pass to helper script */ if (putenv("SAMBAPREFIX=" SAMBAPREFIX) != 0) - return 1; + return 1; while (1) { - if (fgets(buf, BUFSIZE, stdin) == NULL) - break; + if (fgets(buf, BUFSIZE, stdin) == NULL) + break; - if ((s = strchr(buf, '\n')) == NULL) - continue; - *s = '\0'; + if ((s = strchr(buf, '\n')) == NULL) + continue; + *s = '\0'; - if ((s = strchr(buf, ' ')) == NULL) { - (void) printf("ERR\n"); - continue; - } - *s = '\0'; + if ((s = strchr(buf, ' ')) == NULL) { + (void) printf("ERR\n"); + continue; + } + *s = '\0'; - user = buf; - pass = s + 1; - domname = NULL; + user = buf; + pass = s + 1; + domname = NULL; - rfc1738_unescape(user); - rfc1738_unescape(pass); + rfc1738_unescape(user); + rfc1738_unescape(pass); - if ((s = strchr(user, '\\')) != NULL) { - *s = '\0'; - domname = user; - user = s + 1; - } - /* match domname with linked list */ - if (domname != NULL && strlen(domname) > 0) { - for (dom = firstdom; dom != NULL; dom = dom->next) - if (strcasecmp(dom->sname, domname) == 0) - break; - } else - dom = firstdom; + if ((s = strchr(user, '\\')) != NULL) { + *s = '\0'; + domname = user; + user = s + 1; + } + /* match domname with linked list */ + if (domname != NULL && strlen(domname) > 0) { + for (dom = firstdom; dom != NULL; dom = dom->next) + if (strcasecmp(dom->sname, domname) == 0) + break; + } else + dom = firstdom; - if (dom == NULL) { - (void) printf("ERR\n"); - continue; - } - if ((p = popen(shcmd, "w")) == NULL) { - (void) printf("ERR\n"); - continue; - } - (void) fprintf(p, "%s\n", dom->name); - (void) fprintf(p, "%s\n", dom->passthrough); - (void) fprintf(p, "%s\n", dom->nmbaddr); - (void) fprintf(p, "%d\n", dom->nmbcast); - (void) fprintf(p, "%s\n", dom->authshare); - (void) fprintf(p, "%s\n", dom->authfile); - (void) fprintf(p, "%s\n", user); - /* the password can contain special characters */ - print_esc(p, pass); - (void) fputc('\n', p); - (void) fflush(p); + if (dom == NULL) { + (void) printf("ERR\n"); + continue; + } + if ((p = popen(shcmd, "w")) == NULL) { + (void) printf("ERR\n"); + continue; + } + (void) fprintf(p, "%s\n", dom->name); + (void) fprintf(p, "%s\n", dom->passthrough); + (void) fprintf(p, "%s\n", dom->nmbaddr); + (void) fprintf(p, "%d\n", dom->nmbcast); + (void) fprintf(p, "%s\n", dom->authshare); + (void) fprintf(p, "%s\n", dom->authfile); + (void) fprintf(p, "%s\n", user); + /* the password can contain special characters */ + print_esc(p, pass); + (void) fputc('\n', p); + (void) fflush(p); - if (pclose(p) == 0) - (void) printf("OK\n"); - else - (void) printf("ERR\n"); + if (pclose(p) == 0) + (void) printf("OK\n"); + else + (void) printf("ERR\n"); } /* while (1) */ return 0; diff --git a/helpers/basic_auth/YP/nis_support.c b/helpers/basic_auth/YP/nis_support.c index 05aec65293..34137d18c2 100644 --- a/helpers/basic_auth/YP/nis_support.c +++ b/helpers/basic_auth/YP/nis_support.c @@ -29,8 +29,8 @@ get_nis_password(char *user, char *nisdomain, char *nismap) /* Free last entry */ if (val) { - free(val); - val = NULL; + free(val); + val = NULL; } /* Get NIS entry */ @@ -38,15 +38,16 @@ get_nis_password(char *user, char *nisdomain, char *nismap) switch (res) { case NO_YPERR: - /* username = */ (void) strtok(val, ":"); - password = strtok(NULL, ",:"); - return password; + /* username = */ + (void) strtok(val, ":"); + password = strtok(NULL, ",:"); + return password; case YPERR_YPBIND: - syslog(LOG_ERR, "Squid Authentication through ypbind failure: can't communicate with ypbind"); - return NULL; + syslog(LOG_ERR, "Squid Authentication through ypbind failure: can't communicate with ypbind"); + return NULL; case YPERR_KEY: /* No such key in map */ - return NULL; + return NULL; default: - return NULL; + return NULL; } } diff --git a/helpers/basic_auth/YP/nis_support.h b/helpers/basic_auth/YP/nis_support.h index 2f42585aab..bb0ecc3de5 100644 --- a/helpers/basic_auth/YP/nis_support.h +++ b/helpers/basic_auth/YP/nis_support.h @@ -1 +1 @@ -extern char * get_nis_password(char *user, char *nisdomain, char *nismap); +extern char * get_nis_password(char *user, char *nisdomain, char *nismap); diff --git a/helpers/basic_auth/YP/yp_auth.c b/helpers/basic_auth/YP/yp_auth.c index 06b39d167d..4f6d23634f 100644 --- a/helpers/basic_auth/YP/yp_auth.c +++ b/helpers/basic_auth/YP/yp_auth.c @@ -43,42 +43,42 @@ main(int argc, char **argv) setbuf(stdout, NULL); if (argc != 3) { - fprintf(stderr, "Usage: yp_auth \n"); - fprintf(stderr, "\n"); - fprintf(stderr, "Example yp_auth mydomain.com passwd.byname\n"); - exit(1); + fprintf(stderr, "Usage: yp_auth \n"); + fprintf(stderr, "\n"); + fprintf(stderr, "Example yp_auth mydomain.com passwd.byname\n"); + exit(1); } nisdomain = argv[1]; nismap = argv[2]; while (fgets(buf, 256, stdin) != NULL) { - if ((p = strchr(buf, '\n')) != NULL) - *p = '\0'; /* strip \n */ + if ((p = strchr(buf, '\n')) != NULL) + *p = '\0'; /* strip \n */ - if ((user = strtok(buf, " ")) == NULL) { - printf("ERR\n"); - continue; - } - if ((passwd = strtok(NULL, "")) == NULL) { - printf("ERR\n"); - continue; - } + if ((user = strtok(buf, " ")) == NULL) { + printf("ERR\n"); + continue; + } + if ((passwd = strtok(NULL, "")) == NULL) { + printf("ERR\n"); + continue; + } - rfc1738_unescape(user); - rfc1738_unescape(passwd); + rfc1738_unescape(user); + rfc1738_unescape(passwd); - nispasswd = get_nis_password(user, nisdomain, nismap); + nispasswd = get_nis_password(user, nisdomain, nismap); - if (!nispasswd) { - /* User does not exist */ - printf("ERR No such user\n"); - } else if (strcmp(nispasswd, (char *) crypt(passwd, nispasswd)) == 0) { - /* All ok !, thanks... */ - printf("OK\n"); - } else { - /* Password incorrect */ - printf("ERR Wrong password\n"); - } + if (!nispasswd) { + /* User does not exist */ + printf("ERR No such user\n"); + } else if (strcmp(nispasswd, (char *) crypt(passwd, nispasswd)) == 0) { + /* All ok !, thanks... */ + printf("OK\n"); + } else { + /* Password incorrect */ + printf("ERR Wrong password\n"); + } } exit(0); } diff --git a/helpers/basic_auth/getpwnam/getpwnam_auth.c b/helpers/basic_auth/getpwnam/getpwnam_auth.c index 4caa4820fb..1d0c1dfc6b 100644 --- a/helpers/basic_auth/getpwnam/getpwnam_auth.c +++ b/helpers/basic_auth/getpwnam/getpwnam_auth.c @@ -10,7 +10,7 @@ * * Uses getpwnam() routines for authentication. * This has the following advantages over the NCSA module: - * + * * - Allow authentication of all know local users * - Allows authentication through nsswitch.conf * + can handle NIS(+) requests @@ -18,7 +18,7 @@ * + can handle PAM request * * 2006-07: Giancarlo Razzolini - * + * * Added functionality for doing shadow authentication too, * using the getspnam() function on systems that support it. * @@ -53,36 +53,36 @@ #define ERR "ERR\n" #define OK "OK\n" -static int +static int passwd_auth(char *user, char *passwd) { struct passwd *pwd; pwd = getpwnam(user); if (pwd == NULL) { - return 0; /* User does not exist */ + return 0; /* User does not exist */ } else { - if (strcmp(pwd->pw_passwd, (char *) crypt(passwd, pwd->pw_passwd))) { - return 2; /* Wrong password */ - } else { - return 1; /* Authentication Sucessful */ - } + if (strcmp(pwd->pw_passwd, (char *) crypt(passwd, pwd->pw_passwd))) { + return 2; /* Wrong password */ + } else { + return 1; /* Authentication Sucessful */ + } } } #if HAVE_SHADOW_H -static int +static int shadow_auth(char *user, char *passwd) { struct spwd *pwd; pwd = getspnam(user); if (pwd == NULL) { - return passwd_auth(user, passwd); /* Fall back to passwd_auth */ + return passwd_auth(user, passwd); /* Fall back to passwd_auth */ } else { - if (strcmp(pwd->sp_pwdp, crypt(passwd, pwd->sp_pwdp))) { - return 2; /* Wrong password */ - } else { - return 1; /* Authentication Sucessful */ - } + if (strcmp(pwd->sp_pwdp, crypt(passwd, pwd->sp_pwdp))) { + return 2; /* Wrong password */ + } else { + return 1; /* Authentication Sucessful */ + } } } #endif @@ -97,33 +97,33 @@ main(int argc, char **argv) setbuf(stdout, NULL); while (fgets(buf, 256, stdin) != NULL) { - if ((p = strchr(buf, '\n')) != NULL) - *p = '\0'; /* strip \n */ + if ((p = strchr(buf, '\n')) != NULL) + *p = '\0'; /* strip \n */ - if ((user = strtok(buf, " ")) == NULL) { - printf(ERR); - continue; - } - if ((passwd = strtok(NULL, "")) == NULL) { - printf(ERR); - continue; - } - rfc1738_unescape(user); - rfc1738_unescape(passwd); + if ((user = strtok(buf, " ")) == NULL) { + printf(ERR); + continue; + } + if ((passwd = strtok(NULL, "")) == NULL) { + printf(ERR); + continue; + } + rfc1738_unescape(user); + rfc1738_unescape(passwd); #if HAVE_SHADOW_H - auth = shadow_auth(user, passwd); + auth = shadow_auth(user, passwd); #else - auth = passwd_auth(user, passwd); + auth = passwd_auth(user, passwd); #endif - if (auth == 0) { - printf("ERR No such user\n"); - } else { - if (auth == 2) { - printf("ERR Wrong password\n"); - } else { - printf(OK); - } - } + if (auth == 0) { + printf("ERR No such user\n"); + } else { + if (auth == 2) { + printf("ERR Wrong password\n"); + } else { + printf(OK); + } + } } exit(0); } diff --git a/helpers/basic_auth/mswin_sspi/mswin_auth.c b/helpers/basic_auth/mswin_sspi/mswin_auth.c index ac7f00a651..08a45abd4a 100644 --- a/helpers/basic_auth/mswin_sspi/mswin_auth.c +++ b/helpers/basic_auth/mswin_sspi/mswin_auth.c @@ -18,15 +18,15 @@ * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - + * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. */ #include "config.h" -#include -#include +#include +#include #include "util.h" /* Check if we try to compile on a Windows Platform */ @@ -53,13 +53,13 @@ void usage() { fprintf(stderr, - "%s usage:\n%s [-A|D UserGroup][-O DefaultDomain][-d]\n" - "-A can specify a Windows Local Group name allowed to authenticate\n" - "-D can specify a Windows Local Group name not allowed to authenticate\n" - "-O can specify the default Domain against to authenticate\n" - "-d enable debugging.\n" - "-h this message\n\n", - my_program_name, my_program_name); + "%s usage:\n%s [-A|D UserGroup][-O DefaultDomain][-d]\n" + "-A can specify a Windows Local Group name allowed to authenticate\n" + "-D can specify a Windows Local Group name not allowed to authenticate\n" + "-O can specify the default Domain against to authenticate\n" + "-d enable debugging.\n" + "-h this message\n\n", + my_program_name, my_program_name); } void @@ -67,37 +67,37 @@ process_options(int argc, char *argv[]) { int opt, had_error = 0; while (-1 != (opt = getopt(argc, argv, "dhA:D:O:"))) { - switch (opt) { - case 'A': - safe_free(NTAllowedGroup); - NTAllowedGroup=xstrdup(optarg); - UseAllowedGroup = 1; - break; - case 'D': - safe_free(NTDisAllowedGroup); - NTDisAllowedGroup=xstrdup(optarg); - UseDisallowedGroup = 1; - break; - case 'O': - strncpy(Default_NTDomain, optarg, DNLEN); - break; - case 'd': - debug_enabled = 1; - break; - case 'h': - usage(argv[0]); - exit(0); - case '?': - opt = optopt; - /* fall thru to default */ - default: - fprintf(stderr, "Unknown option: -%c. Exiting\n", opt); - had_error = 1; - } + switch (opt) { + case 'A': + safe_free(NTAllowedGroup); + NTAllowedGroup=xstrdup(optarg); + UseAllowedGroup = 1; + break; + case 'D': + safe_free(NTDisAllowedGroup); + NTDisAllowedGroup=xstrdup(optarg); + UseDisallowedGroup = 1; + break; + case 'O': + strncpy(Default_NTDomain, optarg, DNLEN); + break; + case 'd': + debug_enabled = 1; + break; + case 'h': + usage(argv[0]); + exit(0); + case '?': + opt = optopt; + /* fall thru to default */ + default: + fprintf(stderr, "Unknown option: -%c. Exiting\n", opt); + had_error = 1; + } } if (had_error) { - usage(); - exit(1); + usage(); + exit(1); } } @@ -121,62 +121,62 @@ main(int argc, char **argv) debug("%s build " __DATE__ ", " __TIME__ " starting up...\n", my_program_name); if (LoadSecurityDll(SSP_BASIC, NTLM_PACKAGE_NAME) == NULL) { - fprintf(stderr, "FATAL, can't initialize SSPI, exiting.\n"); - exit(1); + fprintf(stderr, "FATAL, can't initialize SSPI, exiting.\n"); + exit(1); } debug("SSPI initialized OK\n"); atexit(UnloadSecurityDll); - /* initialize FDescs */ + /* initialize FDescs */ setbuf(stdout, NULL); setbuf(stderr, NULL); while (1) { - /* Read whole line from standard input. Terminate on break. */ - if (fgets(wstr, 255, stdin) == NULL) - break; - - if (NULL == strchr(wstr, '\n')) { - err = 1; - continue; - } - if (err) { - fprintf(stderr, "Oversized message\n"); + /* Read whole line from standard input. Terminate on break. */ + if (fgets(wstr, 255, stdin) == NULL) + break; + + if (NULL == strchr(wstr, '\n')) { + err = 1; + continue; + } + if (err) { + fprintf(stderr, "Oversized message\n"); puts("ERR"); - goto error; - } - - if ((p = strchr(wstr, '\n')) != NULL) - *p = '\0'; /* strip \n */ - if ((p = strchr(wstr, '\r')) != NULL) - *p = '\0'; /* strip \r */ - /* Clear any current settings */ - username[0] = '\0'; - password[0] = '\0'; - sscanf(wstr, "%s %s", username, password); /* Extract parameters */ + goto error; + } + + if ((p = strchr(wstr, '\n')) != NULL) + *p = '\0'; /* strip \n */ + if ((p = strchr(wstr, '\r')) != NULL) + *p = '\0'; /* strip \r */ + /* Clear any current settings */ + username[0] = '\0'; + password[0] = '\0'; + sscanf(wstr, "%s %s", username, password); /* Extract parameters */ debug("Got %s from Squid\n", wstr); - /* Check for invalid or blank entries */ - if ((username[0] == '\0') || (password[0] == '\0')) { - fprintf(stderr, "Invalid Request\n"); - puts("ERR"); - fflush(stdout); - continue; - } - rfc1738_unescape(username); - rfc1738_unescape(password); + /* Check for invalid or blank entries */ + if ((username[0] == '\0') || (password[0] == '\0')) { + fprintf(stderr, "Invalid Request\n"); + puts("ERR"); + fflush(stdout); + continue; + } + rfc1738_unescape(username); + rfc1738_unescape(password); debug("Trying to validate; %s %s\n", username, password); - if (Valid_User(username, password, NTGroup) == NTV_NO_ERROR) - puts("OK"); - else + if (Valid_User(username, password, NTGroup) == NTV_NO_ERROR) + puts("OK"); + else printf("ERR %s\n", errormsg); error: - err = 0; - fflush(stdout); + err = 0; + fflush(stdout); } return 0; } diff --git a/helpers/basic_auth/mswin_sspi/valid.c b/helpers/basic_auth/mswin_sspi/valid.c index e9cbccdbb3..ecb15c8311 100644 --- a/helpers/basic_auth/mswin_sspi/valid.c +++ b/helpers/basic_auth/mswin_sspi/valid.c @@ -20,7 +20,7 @@ * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - + * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -63,52 +63,52 @@ Valid_Group(char *UserName, char *Group) DWORD i; DWORD dwTotalCount = 0; -/* Convert ANSI User Name and Group to Unicode */ + /* Convert ANSI User Name and Group to Unicode */ MultiByteToWideChar(CP_ACP, 0, UserName, - strlen(UserName) + 1, wszUserName, - sizeof(wszUserName) / sizeof(wszUserName[0])); + strlen(UserName) + 1, wszUserName, + sizeof(wszUserName) / sizeof(wszUserName[0])); MultiByteToWideChar(CP_ACP, 0, Group, - strlen(Group) + 1, wszGroup, sizeof(wszGroup) / sizeof(wszGroup[0])); + strlen(Group) + 1, wszGroup, sizeof(wszGroup) / sizeof(wszGroup[0])); /* - * Call the NetUserGetLocalGroups function - * specifying information level 0. - * - * The LG_INCLUDE_INDIRECT flag specifies that the - * function should also return the names of the local - * groups in which the user is indirectly a member. - */ - nStatus = NetUserGetLocalGroups(NULL, - wszUserName, - dwLevel, - dwFlags, - (LPBYTE *) & pBuf, dwPrefMaxLen, &dwEntriesRead, &dwTotalEntries); - /* - * If the call succeeds, - */ + * Call the NetUserGetLocalGroups function + * specifying information level 0. + * + * The LG_INCLUDE_INDIRECT flag specifies that the + * function should also return the names of the local + * groups in which the user is indirectly a member. + */ + nStatus = NetUserGetLocalGroups(NULL, + wszUserName, + dwLevel, + dwFlags, + (LPBYTE *) & pBuf, dwPrefMaxLen, &dwEntriesRead, &dwTotalEntries); + /* + * If the call succeeds, + */ if (nStatus == NERR_Success) { - if ((pTmpBuf = pBuf) != NULL) { - for (i = 0; i < dwEntriesRead; i++) { - if (pTmpBuf == NULL) { - result = FALSE; - break; - } - if (wcscmp(pTmpBuf->lgrui0_name, wszGroup) == 0) { - result = TRUE; - break; - } - pTmpBuf++; - dwTotalCount++; - } - } + if ((pTmpBuf = pBuf) != NULL) { + for (i = 0; i < dwEntriesRead; i++) { + if (pTmpBuf == NULL) { + result = FALSE; + break; + } + if (wcscmp(pTmpBuf->lgrui0_name, wszGroup) == 0) { + result = TRUE; + break; + } + pTmpBuf++; + dwTotalCount++; + } + } } else - result = FALSE; -/* - * Free the allocated memory. - */ + result = FALSE; + /* + * Free the allocated memory. + */ if (pBuf != NULL) - NetApiBufferFree(pBuf); + NetApiBufferFree(pBuf); return result; } @@ -137,40 +137,40 @@ Valid_User(char *UserName, char *Password, char *Group) break; } if (domain_qualify == NULL) { - strcpy(User, NTDomain); - strcpy(NTDomain, Default_NTDomain); + strcpy(User, NTDomain); + strcpy(NTDomain, Default_NTDomain); } else { - strcpy(User, domain_qualify + 1); - domain_qualify[0] = '\0'; + strcpy(User, domain_qualify + 1); + domain_qualify[0] = '\0'; } /* Log the client on to the local computer. */ if (!SSP_LogonUser(User, Password, NTDomain)) { - result = NTV_LOGON_ERROR; + result = NTV_LOGON_ERROR; errormsg = NTV_LOGON_ERROR_MSG; debug("%s\n", errormsg); } else { - result = NTV_NO_ERROR; - if (strcmp(NTDomain, NTV_DEFAULT_DOMAIN) == 0) - strcpy(DomainUser, User); - else { - strcpy(DomainUser, NTDomain); - strcat(DomainUser, "\\"); - strcat(DomainUser, User); - } - if (UseAllowedGroup) { - if (!Valid_Group(DomainUser, NTAllowedGroup)) { - result = NTV_GROUP_ERROR; + result = NTV_NO_ERROR; + if (strcmp(NTDomain, NTV_DEFAULT_DOMAIN) == 0) + strcpy(DomainUser, User); + else { + strcpy(DomainUser, NTDomain); + strcat(DomainUser, "\\"); + strcat(DomainUser, User); + } + if (UseAllowedGroup) { + if (!Valid_Group(DomainUser, NTAllowedGroup)) { + result = NTV_GROUP_ERROR; errormsg = NTV_GROUP_ERROR_MSG; debug("%s\n", errormsg); - } - } - if (UseDisallowedGroup) { - if (Valid_Group(DomainUser, NTDisAllowedGroup)) { - result = NTV_GROUP_ERROR; + } + } + if (UseDisallowedGroup) { + if (Valid_Group(DomainUser, NTDisAllowedGroup)) { + result = NTV_GROUP_ERROR; errormsg = NTV_GROUP_ERROR_MSG; debug("%s\n", errormsg); - } - } + } + } } return result; } diff --git a/helpers/basic_auth/mswin_sspi/valid.h b/helpers/basic_auth/mswin_sspi/valid.h index 391df85831..8e8ef50b25 100644 --- a/helpers/basic_auth/mswin_sspi/valid.h +++ b/helpers/basic_auth/mswin_sspi/valid.h @@ -19,7 +19,7 @@ * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - + * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -85,17 +85,17 @@ static char *__foo; #endif /* DEBUG */ #else /* __GNUC__ */ static void -debug(char *format,...) +debug(char *format,...) { #ifdef DEBUG #ifdef _SQUID_MSWIN_ if (debug_enabled) { - va_list args; + va_list args; - va_start(args,format); - fprintf(stderr, "nt_auth[%d]: ",getpid()); - vfprintf(stderr, format, args); - va_end(args); + va_start(args,format); + fprintf(stderr, "nt_auth[%d]: ",getpid()); + vfprintf(stderr, format, args); + va_end(args); } #endif /* _SQUID_MSWIN_ */ #endif /* DEBUG */ diff --git a/helpers/basic_auth/squid_radius_auth/radius-util.c b/helpers/basic_auth/squid_radius_auth/radius-util.c index 7dc2cfe4ad..a647810bbb 100644 --- a/helpers/basic_auth/squid_radius_auth/radius-util.c +++ b/helpers/basic_auth/squid_radius_auth/radius-util.c @@ -19,7 +19,7 @@ * in advertising or publicity pertaining to distribution of the * program without specific prior permission, and notice be given * in supporting documentation that copying and distribution is by - * permission of Livingston Enterprises, Inc. + * permission of Livingston Enterprises, Inc. * * Livingston Enterprises, Inc. makes no representations about * the suitability of this software for any purpose. It is @@ -33,8 +33,8 @@ */ char util_sccsid[] = -"@(#)util.c 1.5 Copyright 1992 Livingston Enterprises Inc\n" -" 2.1 Copyright 1997 Cistron Internet Services B.V."; + "@(#)util.c 1.5 Copyright 1992 Livingston Enterprises Inc\n" + " 2.1 Copyright 1997 Cistron Internet Services B.V."; #include "config.h" @@ -81,33 +81,30 @@ char util_sccsid[] = */ static int good_ipaddr(char *addr) { - int dot_count; - int digit_count; + int dot_count; + int digit_count; - dot_count = 0; - digit_count = 0; - while(*addr != '\0' && *addr != ' ') { - if(*addr == '.') { - dot_count++; - digit_count = 0; - } - else if(!isdigit(*addr)) { - dot_count = 5; - } - else { - digit_count++; - if(digit_count > 3) { - dot_count = 5; - } - } - addr++; - } - if(dot_count != 3) { - return(-1); - } - else { - return(0); - } + dot_count = 0; + digit_count = 0; + while (*addr != '\0' && *addr != ' ') { + if (*addr == '.') { + dot_count++; + digit_count = 0; + } else if (!isdigit(*addr)) { + dot_count = 5; + } else { + digit_count++; + if (digit_count > 3) { + dot_count = 5; + } + } + addr++; + } + if (dot_count != 3) { + return(-1); + } else { + return(0); + } } /* @@ -116,37 +113,37 @@ static int good_ipaddr(char *addr) */ static u_int32_t ipstr2long(char *ip_str) { - char buf[6]; - char *ptr; - int i; - int count; - u_int32_t ipaddr; - int cur_byte; + char buf[6]; + char *ptr; + int i; + int count; + u_int32_t ipaddr; + int cur_byte; - ipaddr = (u_int32_t)0; - for(i = 0;i < 4;i++) { - ptr = buf; - count = 0; - *ptr = '\0'; - while(*ip_str != '.' && *ip_str != '\0' && count < 4) { - if(!isdigit(*ip_str)) { - return((u_int32_t)0); - } - *ptr++ = *ip_str++; - count++; - } - if(count >= 4 || count == 0) { - return((u_int32_t)0); - } - *ptr = '\0'; - cur_byte = atoi(buf); - if(cur_byte < 0 || cur_byte > 255) { - return((u_int32_t)0); - } - ip_str++; - ipaddr = ipaddr << 8 | (u_int32_t)cur_byte; - } - return(ipaddr); + ipaddr = (u_int32_t)0; + for (i = 0;i < 4;i++) { + ptr = buf; + count = 0; + *ptr = '\0'; + while (*ip_str != '.' && *ip_str != '\0' && count < 4) { + if (!isdigit(*ip_str)) { + return((u_int32_t)0); + } + *ptr++ = *ip_str++; + count++; + } + if (count >= 4 || count == 0) { + return((u_int32_t)0); + } + *ptr = '\0'; + cur_byte = atoi(buf); + if (cur_byte < 0 || cur_byte > 255) { + return((u_int32_t)0); + } + ip_str++; + ipaddr = ipaddr << 8 | (u_int32_t)cur_byte; + } + return(ipaddr); } /* @@ -155,23 +152,22 @@ static u_int32_t ipstr2long(char *ip_str) */ u_int32_t get_ipaddr(char *host) { - struct hostent *hp; + struct hostent *hp; - if(good_ipaddr(host) == 0) { - return(ipstr2long(host)); - } - else if((hp = gethostbyname(host)) == (struct hostent *)NULL) { - return((u_int32_t)0); - } - return(ntohl(*(u_int32_t *)hp->h_addr)); + if (good_ipaddr(host) == 0) { + return(ipstr2long(host)); + } else if ((hp = gethostbyname(host)) == (struct hostent *)NULL) { + return((u_int32_t)0); + } + return(ntohl(*(u_int32_t *)hp->h_addr)); } void md5_calc(unsigned char *output, unsigned char *input, unsigned int inlen) { - SquidMD5_CTX context; + SquidMD5_CTX context; - SquidMD5Init(&context); - SquidMD5Update(&context, input, inlen); - SquidMD5Final(output, &context); + SquidMD5Init(&context); + SquidMD5Update(&context, input, inlen); + SquidMD5Final(output, &context); } diff --git a/helpers/basic_auth/squid_radius_auth/radius.h b/helpers/basic_auth/squid_radius_auth/radius.h index 359f6c20a2..aa5f3d6a7c 100644 --- a/helpers/basic_auth/squid_radius_auth/radius.h +++ b/helpers/basic_auth/squid_radius_auth/radius.h @@ -17,7 +17,7 @@ * in advertising or publicity pertaining to distribution of the * program without specific prior permission, and notice be given * in supporting documentation that copying and distribution is by - * permission of Livingston Enterprises, Inc. + * permission of Livingston Enterprises, Inc. * * Livingston Enterprises, Inc. makes no representations about * the suitability of this software for any purpose. It is @@ -35,11 +35,11 @@ typedef struct pw_auth_hdr { - u_char code; - u_char id; - u_short length; - u_char vector[AUTH_VECTOR_LEN]; - u_char data[2]; + u_char code; + u_char id; + u_short length; + u_char vector[AUTH_VECTOR_LEN]; + u_char data[2]; } AUTH_HDR; #define AUTH_HDR_LEN 20 diff --git a/helpers/basic_auth/squid_radius_auth/squid_rad_auth.c b/helpers/basic_auth/squid_radius_auth/squid_rad_auth.c index fc5d16774a..1252d18289 100644 --- a/helpers/basic_auth/squid_radius_auth/squid_rad_auth.c +++ b/helpers/basic_auth/squid_radius_auth/squid_rad_auth.c @@ -16,7 +16,7 @@ * in advertising or publicity pertaining to distribution of the * program without specific prior permission, and notice be given * in supporting documentation that copying and distribution is by - * permission of Livingston Enterprises, Inc. + * permission of Livingston Enterprises, Inc. * * Livingston Enterprises, Inc. makes no representations about * the suitability of this software for any purpose. It is @@ -187,14 +187,14 @@ result_recv(u_int32_t host, u_short udp_port, char *buffer, int length) totallen = ntohs(auth->length); if (totallen != length) { - fprintf(stderr, - "Squid_rad_auth: Received invalid reply length from server (want %d/ got %d)\n", - totallen, length); - return -1; + fprintf(stderr, + "Squid_rad_auth: Received invalid reply length from server (want %d/ got %d)\n", + totallen, length); + return -1; } if (auth->id != request_id) { - /* Duplicate response of an earlier query, ignore */ - return -1; + /* Duplicate response of an earlier query, ignore */ + return -1; } /* Verify the reply digest */ memcpy(reply_digest, auth->vector, AUTH_VECTOR_LEN); @@ -204,11 +204,11 @@ result_recv(u_int32_t host, u_short udp_port, char *buffer, int length) md5_calc(calc_digest, (unsigned char *) auth, length + secretlen); if (memcmp(reply_digest, calc_digest, AUTH_VECTOR_LEN) != 0) { - fprintf(stderr, "Warning: Received invalid reply digest from server\n"); - return -1; + fprintf(stderr, "Warning: Received invalid reply digest from server\n"); + return -1; } if (auth->code != PW_AUTHENTICATION_ACK) - return 1; + return 1; return 0; } @@ -225,10 +225,10 @@ random_vector(char *vector) srand((time(0) ^ rand()) + rand()); for (i = 0; i < AUTH_VECTOR_LEN;) { - randno = rand(); - memcpy(vector, &randno, sizeof(int)); - vector += sizeof(int); - i += sizeof(int); + randno = rand(); + memcpy(vector, &randno, sizeof(int)); + vector += sizeof(int); + i += sizeof(int); } } @@ -247,23 +247,23 @@ rad_auth_config(const char *cfname) int srv = 0, crt = 0; if ((cf = fopen(cfname, "r")) == NULL) { - perror(cfname); - return -1; + perror(cfname); + return -1; } while (fgets(line, MAXLINE, cf) != NULL) { - if (!memcmp(line, "server", 6)) - srv = sscanf(line, "server %s", server); - if (!memcmp(line, "secret", 6)) - crt = sscanf(line, "secret %s", secretkey); - if (!memcmp(line, "identifier", 10)) - sscanf(line, "identifier %s", identifier); - if (!memcmp(line, "service", 7)) - sscanf(line, "service %s", svc_name); - if (!memcmp(line, "port", 4)) - sscanf(line, "port %s", svc_name); + if (!memcmp(line, "server", 6)) + srv = sscanf(line, "server %s", server); + if (!memcmp(line, "secret", 6)) + crt = sscanf(line, "secret %s", secretkey); + if (!memcmp(line, "identifier", 10)) + sscanf(line, "identifier %s", identifier); + if (!memcmp(line, "service", 7)) + sscanf(line, "service %s", svc_name); + if (!memcmp(line, "port", 4)) + sscanf(line, "port %s", svc_name); } if (srv && crt) - return 0; + return 0; return -1; } @@ -273,15 +273,15 @@ urldecode(char *dst, const char *src, int size) char tmp[3]; tmp[2] = '\0'; while (*src && size > 1) { - if (*src == '%' && src[1] != '\0' && src[2] != '\0') { - src++; - tmp[0] = *src++; - tmp[1] = *src++; - *dst++ = strtol(tmp, NULL, 16); - } else { - *dst++ = *src++; - } - size--; + if (*src == '%' && src[1] != '\0' && src[2] != '\0') { + src++; + tmp[0] = *src++; + tmp[1] = *src++; + *dst++ = strtol(tmp, NULL, 16); + } else { + *dst++ = *src++; + } + size--; } *dst++ = '\0'; } @@ -321,7 +321,7 @@ authenticate(int sockfd, const char *username, const char *passwd) *ptr++ = PW_USER_NAME; length = strlen(username); if (length > MAXPWNAM) { - length = MAXPWNAM; + length = MAXPWNAM; } *ptr++ = length + 2; memcpy(ptr, username, length); @@ -333,14 +333,14 @@ authenticate(int sockfd, const char *username, const char *passwd) */ length = strlen(passwd); if (length > MAXPASS) { - length = MAXPASS; + length = MAXPASS; } memset(passbuf, 0, MAXPASS); memcpy(passbuf, passwd, length); - /* + /* * Length is rounded up to multiple of 16, - * and the password is encoded in blocks of 16 + * and the password is encoded in blocks of 16 * with cipher block chaining */ length = ((length / AUTH_VECTOR_LEN) + 1) * AUTH_VECTOR_LEN; @@ -352,15 +352,15 @@ authenticate(int sockfd, const char *username, const char *passwd) /* Set up the Cipher block chain */ memcpy(cbc, auth->vector, AUTH_VECTOR_LEN); for (j = 0; j < length; j += AUTH_VECTOR_LEN) { - /* Calculate the MD5 Digest */ - strcpy((char *) md5buf, secretkey); - memcpy(md5buf + secretlen, cbc, AUTH_VECTOR_LEN); - md5_calc(cbc, md5buf, secretlen + AUTH_VECTOR_LEN); - - /* Xor the password into the MD5 digest */ - for (i = 0; i < AUTH_VECTOR_LEN; i++) { - *ptr++ = (cbc[i] ^= passbuf[j + i]); - } + /* Calculate the MD5 Digest */ + strcpy((char *) md5buf, secretkey); + memcpy(md5buf + secretlen, cbc, AUTH_VECTOR_LEN); + md5_calc(cbc, md5buf, secretlen + AUTH_VECTOR_LEN); + + /* Xor the password into the MD5 digest */ + for (i = 0; i < AUTH_VECTOR_LEN; i++) { + *ptr++ = (cbc[i] ^= passbuf[j + i]); + } } total_length += length + 2; @@ -381,19 +381,19 @@ authenticate(int sockfd, const char *username, const char *passwd) total_length += 6; if (*identifier) { - int len = strlen(identifier); - *ptr++ = PW_NAS_ID; - *ptr++ = len + 2; - memcpy(ptr, identifier, len); - ptr += len; + int len = strlen(identifier); + *ptr++ = PW_NAS_ID; + *ptr++ = len + 2; + memcpy(ptr, identifier, len); + ptr += len; } else { - *ptr++ = PW_NAS_IP_ADDRESS; - *ptr++ = 6; + *ptr++ = PW_NAS_IP_ADDRESS; + *ptr++ = 6; - ui = htonl(nas_ipaddr); - memcpy(ptr, &ui, 4); - ptr += 4; - total_length += 6; + ui = htonl(nas_ipaddr); + memcpy(ptr, &ui, 4); + ptr += 4; + total_length += 6; } /* Klaus Weidner changed this @@ -401,46 +401,46 @@ authenticate(int sockfd, const char *username, const char *passwd) * you trouble or not. That depends on the byte * order of your system. * The symptom was that the radius server - * ignored the requests, because they had zero + * ignored the requests, because they had zero * length according to the data header. */ auth->length = htons(total_length); while (retry--) { - int time_spent; - struct timeval sent; - /* - * Send the request we've built. - */ - gettimeofday(&sent, NULL); - send(sockfd, (char *) auth, total_length, 0); - while ((time_spent = time_since(&sent)) < 1000000) { - struct timeval tv; - int rc, len; - if (!time_spent) { - tv.tv_sec = 1; - tv.tv_usec = 0; - } else { - tv.tv_sec = 0; - tv.tv_usec = 1000000 - time_spent; - } - FD_ZERO(&readfds); - FD_SET(sockfd, &readfds); - if (select(sockfd + 1, &readfds, NULL, NULL, &tv) == 0) /* Select timeout */ - break; - salen = sizeof(saremote); - len = recvfrom(sockfd, recv_buffer, sizeof(i_recv_buffer), - 0, (struct sockaddr *) &saremote, &salen); - - if (len < 0) - continue; - - rc = result_recv(saremote.sin_addr.s_addr, saremote.sin_port, recv_buffer, len); - if (rc == 0) - return 1; - if (rc == 1) - return 0; - } + int time_spent; + struct timeval sent; + /* + * Send the request we've built. + */ + gettimeofday(&sent, NULL); + send(sockfd, (char *) auth, total_length, 0); + while ((time_spent = time_since(&sent)) < 1000000) { + struct timeval tv; + int rc, len; + if (!time_spent) { + tv.tv_sec = 1; + tv.tv_usec = 0; + } else { + tv.tv_sec = 0; + tv.tv_usec = 1000000 - time_spent; + } + FD_ZERO(&readfds); + FD_SET(sockfd, &readfds); + if (select(sockfd + 1, &readfds, NULL, NULL, &tv) == 0) /* Select timeout */ + break; + salen = sizeof(saremote); + len = recvfrom(sockfd, recv_buffer, sizeof(i_recv_buffer), + 0, (struct sockaddr *) &saremote, &salen); + + if (len < 0) + continue; + + rc = result_recv(saremote.sin_addr.s_addr, saremote.sin_port, recv_buffer, len); + if (rc == 0) + return 1; + if (rc == 1) + return 0; + } } fprintf(stderr, "%s: No response from RADIUS server\n", progname); @@ -465,50 +465,50 @@ main(int argc, char **argv) int c; while ((c = getopt(argc, argv, "h:p:f:w:i:t:")) != -1) { - switch (c) { - case 'f': - cfname = optarg; - break; - case 'h': - strcpy(server, optarg); - break; - case 'p': - strcpy(svc_name, optarg); - break; - case 'w': - strcpy(secretkey, optarg); - break; - case 'i': - strcpy(identifier, optarg); - break; - case 't': - retries = atoi(optarg); - break; - } + switch (c) { + case 'f': + cfname = optarg; + break; + case 'h': + strcpy(server, optarg); + break; + case 'p': + strcpy(svc_name, optarg); + break; + case 'w': + strcpy(secretkey, optarg); + break; + case 'i': + strcpy(identifier, optarg); + break; + case 't': + retries = atoi(optarg); + break; + } } /* make standard output line buffered */ if (setvbuf(stdout, NULL, _IOLBF, 0) != 0) - return 1; + return 1; if (cfname) { - if (rad_auth_config(cfname) < 0) { - fprintf(stderr, "%s: can't open configuration file '%s'.\n", argv[0], cfname); - exit(1); - } + if (rad_auth_config(cfname) < 0) { + fprintf(stderr, "%s: can't open configuration file '%s'.\n", argv[0], cfname); + exit(1); + } } if (!*server) { - fprintf(stderr, "%s: Server not specified\n", argv[0]); - exit(1); + fprintf(stderr, "%s: Server not specified\n", argv[0]); + exit(1); } if (!*secretkey) { - fprintf(stderr, "%s: Shared secret not specified\n", argv[0]); - exit(1); + fprintf(stderr, "%s: Shared secret not specified\n", argv[0]); + exit(1); } #ifdef _SQUID_MSWIN_ { - WSADATA wsaData; - WSAStartup(2, &wsaData); - atexit(Win32SockCleanup); + WSADATA wsaData; + WSAStartup(2, &wsaData); + atexit(Win32SockCleanup); } #endif /* @@ -516,21 +516,21 @@ main(int argc, char **argv) */ svp = getservbyname(svc_name, "udp"); if (svp != NULL) - svc_port = ntohs((u_short) svp->s_port); + svc_port = ntohs((u_short) svp->s_port); else - svc_port = atoi(svc_name); + svc_port = atoi(svc_name); if (svc_port == 0) - svc_port = PW_AUTH_UDP_PORT; + svc_port = PW_AUTH_UDP_PORT; /* Get the IP address of the authentication server */ if ((auth_ipaddr = get_ipaddr(server)) == 0) { - fprintf(stderr, "Couldn't find host %s\n", server); - exit(1); + fprintf(stderr, "Couldn't find host %s\n", server); + exit(1); } sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd < 0) { - perror("socket"); - exit(1); + perror("socket"); + exit(1); } memset(&saremote, 0, sizeof(saremote)); saremote.sin_family = AF_INET; @@ -538,56 +538,56 @@ main(int argc, char **argv) saremote.sin_port = htons(svc_port); if (connect(sockfd, (struct sockaddr *) &saremote, sizeof(saremote)) < 0) { - perror("connect"); - exit(1); + perror("connect"); + exit(1); } salen = sizeof(salocal); if (getsockname(sockfd, (struct sockaddr *) &salocal, &salen) < 0) { - perror("getsockname"); - exit(1); + perror("getsockname"); + exit(1); } #ifdef O_NONBLOCK fcntl(sockfd, F_SETFL, fcntl(sockfd, F_GETFL, 0) | O_NONBLOCK); #endif nas_ipaddr = ntohl(salocal.sin_addr.s_addr); while (fgets(authstring, MAXLINE, stdin) != NULL) { - char *end; - /* protect me form to long lines */ - if ((end = strchr(authstring, '\n')) == NULL) { - err = 1; - continue; - } - if (err) { - printf("ERR\n"); - err = 0; - continue; - } - if (strlen(authstring) > MAXLINE) { - printf("ERR\n"); - continue; - } - /* Strip off the trailing newline */ - *end = '\0'; - - /* Parse out the username and password */ - ptr = authstring; - while (isspace(*ptr)) - ptr++; - if ((end = strchr(ptr, ' ')) == NULL) { - printf("ERR\n"); /* No password */ - continue; - } - *end = '\0'; - urldecode(username, ptr, MAXPWNAM); - ptr = end + 1; - while (isspace(*ptr)) - ptr++; - urldecode(passwd, ptr, MAXPASS); - - if (authenticate(sockfd, username, passwd)) - printf("OK\n"); - else - printf("ERR\n"); + char *end; + /* protect me form to long lines */ + if ((end = strchr(authstring, '\n')) == NULL) { + err = 1; + continue; + } + if (err) { + printf("ERR\n"); + err = 0; + continue; + } + if (strlen(authstring) > MAXLINE) { + printf("ERR\n"); + continue; + } + /* Strip off the trailing newline */ + *end = '\0'; + + /* Parse out the username and password */ + ptr = authstring; + while (isspace(*ptr)) + ptr++; + if ((end = strchr(ptr, ' ')) == NULL) { + printf("ERR\n"); /* No password */ + continue; + } + *end = '\0'; + urldecode(username, ptr, MAXPWNAM); + ptr = end + 1; + while (isspace(*ptr)) + ptr++; + urldecode(passwd, ptr, MAXPASS); + + if (authenticate(sockfd, username, passwd)) + printf("OK\n"); + else + printf("ERR\n"); } close(sockfd); exit(1); diff --git a/helpers/digest_auth/eDirectory/digest_common.h b/helpers/digest_auth/eDirectory/digest_common.h index 71ce579030..2f4a46ddcd 100644 --- a/helpers/digest_auth/eDirectory/digest_common.h +++ b/helpers/digest_auth/eDirectory/digest_common.h @@ -53,8 +53,8 @@ typedef struct _request_data { int error; } RequestData; -/* to use a backend, include your backend.h file - * and define thusly: +/* to use a backend, include your backend.h file + * and define thusly: * #define ProcessArguments(A, B) MyHandleArguments(A,B) * #define GetHHA1(A) MyGetHHA1(A) */ diff --git a/helpers/digest_auth/eDirectory/digest_pw_auth.c b/helpers/digest_auth/eDirectory/digest_pw_auth.c index b81a84d8d1..2f5f2016db 100644 --- a/helpers/digest_auth/eDirectory/digest_pw_auth.c +++ b/helpers/digest_auth/eDirectory/digest_pw_auth.c @@ -12,7 +12,7 @@ * - comment lines are possible and should start with a '#'; * - empty or blank lines are possible; * - file format is username:password - * + * * To build a directory integrated backend, you need to be able to * calculate the HA1 returned to squid. To avoid storing a plaintext * password you can calculate MD5(username:realm:password) when the @@ -47,13 +47,13 @@ ParseBuffer(char *buf, RequestData * requestData) char *p; requestData->parsed = 0; if ((p = strchr(buf, '\n')) != NULL) - *p = '\0'; /* strip \n */ + *p = '\0'; /* strip \n */ if ((requestData->user = strtok(buf, "\"")) == NULL) - return; + return; if ((requestData->realm = strtok(NULL, "\"")) == NULL) - return; + return; if ((requestData->realm = strtok(NULL, "\"")) == NULL) - return; + return; requestData->parsed = -1; } @@ -63,8 +63,8 @@ OutputHHA1(RequestData * requestData) requestData->error = 0; GetHHA1(requestData); if (requestData->error) { - printf("ERR No such user\n"); - return; + printf("ERR No such user\n"); + return; } printf("%s\n", requestData->HHA1); } @@ -75,8 +75,8 @@ DoOneRequest(char *buf) RequestData requestData; ParseBuffer(buf, &requestData); if (!requestData.parsed) { - printf("ERR\n"); - return; + printf("ERR\n"); + return; } OutputHHA1(&requestData); } @@ -87,7 +87,7 @@ ProcessArguments(int argc, char **argv) int i; i = LDAPArguments(argc, argv); if (i) - exit(i); + exit(i); } int @@ -97,6 +97,6 @@ main(int argc, char **argv) setbuf(stdout, NULL); ProcessArguments(argc, argv); while (fgets(buf, 256, stdin) != NULL) - DoOneRequest(buf); + DoOneRequest(buf); exit(0); } diff --git a/helpers/digest_auth/eDirectory/edir_ldapext.c b/helpers/digest_auth/eDirectory/edir_ldapext.c index 3aafb08f65..1106a38de2 100644 --- a/helpers/digest_auth/eDirectory/edir_ldapext.c +++ b/helpers/digest_auth/eDirectory/edir_ldapext.c @@ -1,4 +1,4 @@ -/* +/* * NDS LDAP helper functions * Copied From Samba-3.0.24 pdb_nds.c and trimmed down to the * limited functionality needed to access the plain text password only @@ -6,21 +6,21 @@ * Original copyright & license follows: * * Copyright (C) Vince Brimhall 2004-2005 - * + * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - * + * */ #include "digest_common.h" @@ -69,86 +69,73 @@ **********************************************************************/ static int berEncodePasswordData( - struct berval **requestBV, - const char *objectDN, - const char *password, - const char *password2) + struct berval **requestBV, + const char *objectDN, + const char *password, + const char *password2) { - int err = 0, rc=0; - BerElement *requestBer = NULL; - - const char * utf8ObjPtr = NULL; - int utf8ObjSize = 0; - const char * utf8PwdPtr = NULL; - int utf8PwdSize = 0; - const char * utf8Pwd2Ptr = NULL; - int utf8Pwd2Size = 0; - - - /* Convert objectDN and tag strings from Unicode to UTF-8 */ - utf8ObjSize = strlen(objectDN)+1; - utf8ObjPtr = objectDN; - - if (password != NULL) - { - utf8PwdSize = strlen(password)+1; - utf8PwdPtr = password; - } - - if (password2 != NULL) - { - utf8Pwd2Size = strlen(password2)+1; - utf8Pwd2Ptr = password2; - } - - /* Allocate a BerElement for the request parameters. */ - if((requestBer = ber_alloc()) == NULL) - { - err = LDAP_ENCODING_ERROR; - goto Cleanup; - } - - if (password != NULL && password2 != NULL) - { - /* BER encode the NMAS Version, the objectDN, and the password */ - rc = ber_printf(requestBer, "{iooo}", NMAS_LDAP_EXT_VERSION, utf8ObjPtr, utf8ObjSize, utf8PwdPtr, utf8PwdSize, utf8Pwd2Ptr, utf8Pwd2Size); - } - else if (password != NULL) - { - /* BER encode the NMAS Version, the objectDN, and the password */ - rc = ber_printf(requestBer, "{ioo}", NMAS_LDAP_EXT_VERSION, utf8ObjPtr, utf8ObjSize, utf8PwdPtr, utf8PwdSize); - } - else - { - /* BER encode the NMAS Version and the objectDN */ - rc = ber_printf(requestBer, "{io}", NMAS_LDAP_EXT_VERSION, utf8ObjPtr, utf8ObjSize); - } - - if (rc < 0) - { - err = LDAP_ENCODING_ERROR; - goto Cleanup; - } - else - { - err = 0; - } - - /* Convert the BER we just built to a berval that we'll send with the extended request. */ - if(ber_flatten(requestBer, requestBV) == LBER_ERROR) - { - err = LDAP_ENCODING_ERROR; - goto Cleanup; - } + int err = 0, rc=0; + BerElement *requestBer = NULL; + + const char * utf8ObjPtr = NULL; + int utf8ObjSize = 0; + const char * utf8PwdPtr = NULL; + int utf8PwdSize = 0; + const char * utf8Pwd2Ptr = NULL; + int utf8Pwd2Size = 0; + + + /* Convert objectDN and tag strings from Unicode to UTF-8 */ + utf8ObjSize = strlen(objectDN)+1; + utf8ObjPtr = objectDN; + + if (password != NULL) { + utf8PwdSize = strlen(password)+1; + utf8PwdPtr = password; + } + + if (password2 != NULL) { + utf8Pwd2Size = strlen(password2)+1; + utf8Pwd2Ptr = password2; + } + + /* Allocate a BerElement for the request parameters. */ + if ((requestBer = ber_alloc()) == NULL) { + err = LDAP_ENCODING_ERROR; + goto Cleanup; + } + + if (password != NULL && password2 != NULL) { + /* BER encode the NMAS Version, the objectDN, and the password */ + rc = ber_printf(requestBer, "{iooo}", NMAS_LDAP_EXT_VERSION, utf8ObjPtr, utf8ObjSize, utf8PwdPtr, utf8PwdSize, utf8Pwd2Ptr, utf8Pwd2Size); + } else if (password != NULL) { + /* BER encode the NMAS Version, the objectDN, and the password */ + rc = ber_printf(requestBer, "{ioo}", NMAS_LDAP_EXT_VERSION, utf8ObjPtr, utf8ObjSize, utf8PwdPtr, utf8PwdSize); + } else { + /* BER encode the NMAS Version and the objectDN */ + rc = ber_printf(requestBer, "{io}", NMAS_LDAP_EXT_VERSION, utf8ObjPtr, utf8ObjSize); + } + + if (rc < 0) { + err = LDAP_ENCODING_ERROR; + goto Cleanup; + } else { + err = 0; + } + + /* Convert the BER we just built to a berval that we'll send with the extended request. */ + if (ber_flatten(requestBer, requestBV) == LBER_ERROR) { + err = LDAP_ENCODING_ERROR; + goto Cleanup; + } Cleanup: - if(requestBer) - { - ber_free(requestBer, 1); - } + if (requestBer) { + ber_free(requestBer, 1); + } - return err; + return err; } /********************************************************************** @@ -157,89 +144,79 @@ Cleanup: **********************************************************************/ static int berEncodeLoginData( - struct berval **requestBV, - char *objectDN, - unsigned int methodIDLen, - unsigned int *methodID, - char *tag, - size_t putDataLen, - void *putData) + struct berval **requestBV, + char *objectDN, + unsigned int methodIDLen, + unsigned int *methodID, + char *tag, + size_t putDataLen, + void *putData) { - int err = 0; - BerElement *requestBer = NULL; - - unsigned int i; - unsigned int elemCnt = methodIDLen / sizeof(unsigned int); - - char *utf8ObjPtr=NULL; - int utf8ObjSize = 0; - - char *utf8TagPtr = NULL; - int utf8TagSize = 0; - - utf8ObjPtr = objectDN; - utf8ObjSize = strlen(utf8ObjPtr)+1; - - utf8TagPtr = tag; - utf8TagSize = strlen(utf8TagPtr)+1; - - /* Allocate a BerElement for the request parameters. */ - if((requestBer = ber_alloc()) == NULL) - { - err = LDAP_ENCODING_ERROR; - goto Cleanup; - } - - /* BER encode the NMAS Version and the objectDN */ - err = (ber_printf(requestBer, "{io", NMAS_LDAP_EXT_VERSION, utf8ObjPtr, utf8ObjSize) < 0) ? LDAP_ENCODING_ERROR : 0; - - /* BER encode the MethodID Length and value */ - if (!err) - { - err = (ber_printf(requestBer, "{i{", methodIDLen) < 0) ? LDAP_ENCODING_ERROR : 0; - } - - for (i = 0; !err && i < elemCnt; i++) - { - err = (ber_printf(requestBer, "i", methodID[i]) < 0) ? LDAP_ENCODING_ERROR : 0; - } - - if (!err) - { - err = (ber_printf(requestBer, "}}", 0) < 0) ? LDAP_ENCODING_ERROR : 0; - } - - if(putData) - { - /* BER Encode the the tag and data */ - err = (ber_printf(requestBer, "oio}", utf8TagPtr, utf8TagSize, putDataLen, putData, putDataLen) < 0) ? LDAP_ENCODING_ERROR : 0; - } - else - { - /* BER Encode the the tag */ - err = (ber_printf(requestBer, "o}", utf8TagPtr, utf8TagSize) < 0) ? LDAP_ENCODING_ERROR : 0; - } - - if (err) - { - goto Cleanup; - } - - /* Convert the BER we just built to a berval that we'll send with the extended request. */ - if(ber_flatten(requestBer, requestBV) == LBER_ERROR) - { - err = LDAP_ENCODING_ERROR; - goto Cleanup; - } + int err = 0; + BerElement *requestBer = NULL; + + unsigned int i; + unsigned int elemCnt = methodIDLen / sizeof(unsigned int); + + char *utf8ObjPtr=NULL; + int utf8ObjSize = 0; + + char *utf8TagPtr = NULL; + int utf8TagSize = 0; + + utf8ObjPtr = objectDN; + utf8ObjSize = strlen(utf8ObjPtr)+1; + + utf8TagPtr = tag; + utf8TagSize = strlen(utf8TagPtr)+1; + + /* Allocate a BerElement for the request parameters. */ + if ((requestBer = ber_alloc()) == NULL) { + err = LDAP_ENCODING_ERROR; + goto Cleanup; + } + + /* BER encode the NMAS Version and the objectDN */ + err = (ber_printf(requestBer, "{io", NMAS_LDAP_EXT_VERSION, utf8ObjPtr, utf8ObjSize) < 0) ? LDAP_ENCODING_ERROR : 0; + + /* BER encode the MethodID Length and value */ + if (!err) { + err = (ber_printf(requestBer, "{i{", methodIDLen) < 0) ? LDAP_ENCODING_ERROR : 0; + } + + for (i = 0; !err && i < elemCnt; i++) { + err = (ber_printf(requestBer, "i", methodID[i]) < 0) ? LDAP_ENCODING_ERROR : 0; + } + + if (!err) { + err = (ber_printf(requestBer, "}}", 0) < 0) ? LDAP_ENCODING_ERROR : 0; + } + + if (putData) { + /* BER Encode the the tag and data */ + err = (ber_printf(requestBer, "oio}", utf8TagPtr, utf8TagSize, putDataLen, putData, putDataLen) < 0) ? LDAP_ENCODING_ERROR : 0; + } else { + /* BER Encode the the tag */ + err = (ber_printf(requestBer, "o}", utf8TagPtr, utf8TagSize) < 0) ? LDAP_ENCODING_ERROR : 0; + } + + if (err) { + goto Cleanup; + } + + /* Convert the BER we just built to a berval that we'll send with the extended request. */ + if (ber_flatten(requestBer, requestBV) == LBER_ERROR) { + err = LDAP_ENCODING_ERROR; + goto Cleanup; + } Cleanup: - if(requestBer) - { - ber_free(requestBer, 1); - } + if (requestBer) { + ber_free(requestBer, 1); + } - return err; + return err; } /********************************************************************** @@ -249,75 +226,60 @@ Cleanup: **********************************************************************/ static int berDecodeLoginData( - struct berval *replyBV, - int *serverVersion, - size_t *retDataLen, - void *retData ) + struct berval *replyBV, + int *serverVersion, + size_t *retDataLen, + void *retData ) { - int err = 0; - BerElement *replyBer = NULL; - char *retOctStr = NULL; - size_t retOctStrLen = 0; - - if((replyBer = ber_init(replyBV)) == NULL) - { - err = LDAP_OPERATIONS_ERROR; - goto Cleanup; - } - - if(retData) - { - retOctStrLen = *retDataLen + 1; - retOctStr = SMB_MALLOC_ARRAY(char, retOctStrLen); - if(!retOctStr) - { - err = LDAP_OPERATIONS_ERROR; - goto Cleanup; - } - - if(ber_scanf(replyBer, "{iis}", serverVersion, &err, retOctStr, &retOctStrLen) != -1) - { - if (*retDataLen >= retOctStrLen) - { - memcpy(retData, retOctStr, retOctStrLen); - } - else if (!err) - { - err = LDAP_NO_MEMORY; - } - - *retDataLen = retOctStrLen; - } - else if (!err) - { - err = LDAP_DECODING_ERROR; - } - } - else - { - if(ber_scanf(replyBer, "{ii}", serverVersion, &err) == -1) - { - if (!err) - { - err = LDAP_DECODING_ERROR; - } - } - } + int err = 0; + BerElement *replyBer = NULL; + char *retOctStr = NULL; + size_t retOctStrLen = 0; + + if ((replyBer = ber_init(replyBV)) == NULL) { + err = LDAP_OPERATIONS_ERROR; + goto Cleanup; + } + + if (retData) { + retOctStrLen = *retDataLen + 1; + retOctStr = SMB_MALLOC_ARRAY(char, retOctStrLen); + if (!retOctStr) { + err = LDAP_OPERATIONS_ERROR; + goto Cleanup; + } + + if (ber_scanf(replyBer, "{iis}", serverVersion, &err, retOctStr, &retOctStrLen) != -1) { + if (*retDataLen >= retOctStrLen) { + memcpy(retData, retOctStr, retOctStrLen); + } else if (!err) { + err = LDAP_NO_MEMORY; + } + + *retDataLen = retOctStrLen; + } else if (!err) { + err = LDAP_DECODING_ERROR; + } + } else { + if (ber_scanf(replyBer, "{ii}", serverVersion, &err) == -1) { + if (!err) { + err = LDAP_DECODING_ERROR; + } + } + } Cleanup: - if(replyBer) - { - ber_free(replyBer, 1); - } + if (replyBer) { + ber_free(replyBer, 1); + } - if (retOctStr != NULL) - { - memset(retOctStr, 0, retOctStrLen); - free(retOctStr); - } + if (retOctStr != NULL) { + memset(retOctStr, 0, retOctStrLen); + free(retOctStr); + } - return err; + return err; } /********************************************************************** @@ -326,91 +288,81 @@ Cleanup: **********************************************************************/ static int getLoginConfig( - LDAP *ld, - char *objectDN, - unsigned int methodIDLen, - unsigned int *methodID, - char *tag, - size_t *dataLen, - void *data ) + LDAP *ld, + char *objectDN, + unsigned int methodIDLen, + unsigned int *methodID, + char *tag, + size_t *dataLen, + void *data ) { - int err = 0; - struct berval *requestBV = NULL; - char *replyOID = NULL; - struct berval *replyBV = NULL; - int serverVersion = 0; - - /* Validate unicode parameters. */ - if((strlen(objectDN) == 0) || ld == NULL) - { - return LDAP_NO_SUCH_ATTRIBUTE; - } - - err = berEncodeLoginData(&requestBV, objectDN, methodIDLen, methodID, tag, 0, NULL); - if(err) - { - goto Cleanup; - } - - /* Call the ldap_extended_operation (synchronously) */ - if((err = ldap_extended_operation_s(ld, NMASLDAP_GET_LOGIN_CONFIG_REQUEST, - requestBV, NULL, NULL, &replyOID, &replyBV))) - { - goto Cleanup; - } - - /* Make sure there is a return OID */ - if(!replyOID) - { - err = LDAP_NOT_SUPPORTED; - goto Cleanup; - } - - /* Is this what we were expecting to get back. */ - if(strcmp(replyOID, NMASLDAP_GET_LOGIN_CONFIG_RESPONSE)) - { - err = LDAP_NOT_SUPPORTED; - goto Cleanup; - } - - /* Do we have a good returned berval? */ - if(!replyBV) - { - /* No; returned berval means we experienced a rather drastic error. */ - /* Return operations error. */ - err = LDAP_OPERATIONS_ERROR; - goto Cleanup; - } - - err = berDecodeLoginData(replyBV, &serverVersion, dataLen, data); - - if(serverVersion != NMAS_LDAP_EXT_VERSION) - { - err = LDAP_OPERATIONS_ERROR; - goto Cleanup; - } + int err = 0; + struct berval *requestBV = NULL; + char *replyOID = NULL; + struct berval *replyBV = NULL; + int serverVersion = 0; + + /* Validate unicode parameters. */ + if ((strlen(objectDN) == 0) || ld == NULL) { + return LDAP_NO_SUCH_ATTRIBUTE; + } + + err = berEncodeLoginData(&requestBV, objectDN, methodIDLen, methodID, tag, 0, NULL); + if (err) { + goto Cleanup; + } + + /* Call the ldap_extended_operation (synchronously) */ + if ((err = ldap_extended_operation_s(ld, NMASLDAP_GET_LOGIN_CONFIG_REQUEST, + requestBV, NULL, NULL, &replyOID, &replyBV))) { + goto Cleanup; + } + + /* Make sure there is a return OID */ + if (!replyOID) { + err = LDAP_NOT_SUPPORTED; + goto Cleanup; + } + + /* Is this what we were expecting to get back. */ + if (strcmp(replyOID, NMASLDAP_GET_LOGIN_CONFIG_RESPONSE)) { + err = LDAP_NOT_SUPPORTED; + goto Cleanup; + } + + /* Do we have a good returned berval? */ + if (!replyBV) { + /* No; returned berval means we experienced a rather drastic error. */ + /* Return operations error. */ + err = LDAP_OPERATIONS_ERROR; + goto Cleanup; + } + + err = berDecodeLoginData(replyBV, &serverVersion, dataLen, data); + + if (serverVersion != NMAS_LDAP_EXT_VERSION) { + err = LDAP_OPERATIONS_ERROR; + goto Cleanup; + } Cleanup: - if(replyBV) - { - ber_bvfree(replyBV); - } - - /* Free the return OID string if one was returned. */ - if(replyOID) - { - ldap_memfree(replyOID); - } - - /* Free memory allocated while building the request ber and berval. */ - if(requestBV) - { - ber_bvfree(requestBV); - } - - /* Return the appropriate error/success code. */ - return err; + if (replyBV) { + ber_bvfree(replyBV); + } + + /* Free the return OID string if one was returned. */ + if (replyOID) { + ldap_memfree(replyOID); + } + + /* Free memory allocated while building the request ber and berval. */ + if (requestBV) { + ber_bvfree(requestBV); + } + + /* Return the appropriate error/success code. */ + return err; } /********************************************************************** @@ -418,66 +370,57 @@ Cleanup: **********************************************************************/ static int nmasldap_get_simple_pwd( - LDAP *ld, - char *objectDN, - size_t pwdLen, - char *pwd ) + LDAP *ld, + char *objectDN, + size_t pwdLen, + char *pwd ) { - int err = 0; - unsigned int methodID = 0; - unsigned int methodIDLen = sizeof(methodID); - char tag[] = {'P','A','S','S','W','O','R','D',' ','H','A','S','H',0}; - char *pwdBuf=NULL; - size_t pwdBufLen, bufferLen; - - bufferLen = pwdBufLen = pwdLen+2; - pwdBuf = SMB_MALLOC_ARRAY(char, pwdBufLen); /* digest and null */ - if(pwdBuf == NULL) - { - return LDAP_NO_MEMORY; - } - - err = getLoginConfig(ld, objectDN, methodIDLen, &methodID, tag, &pwdBufLen, pwdBuf); - if (err == 0) - { - if (pwdBufLen !=0) - { - pwdBuf[pwdBufLen] = 0; /* null terminate */ - - switch (pwdBuf[0]) - { - case 1: /* cleartext password */ - break; - case 2: /* SHA1 HASH */ - case 3: /* MD5_ID */ - case 4: /* UNIXCrypt_ID */ - case 8: /* SSHA_ID */ - default: /* Unknown digest */ - err = LDAP_INAPPROPRIATE_AUTH; /* only return clear text */ - break; - } - - if (!err) - { - if (pwdLen >= pwdBufLen-1) - { - memcpy(pwd, &pwdBuf[1], pwdBufLen-1); /* skip digest tag and include null */ - } - else - { - err = LDAP_NO_MEMORY; - } - } - } - } - - if (pwdBuf != NULL) - { - memset(pwdBuf, 0, bufferLen); - free(pwdBuf); - } - - return err; + int err = 0; + unsigned int methodID = 0; + unsigned int methodIDLen = sizeof(methodID); + char tag[] = {'P','A','S','S','W','O','R','D',' ','H','A','S','H',0}; + char *pwdBuf=NULL; + size_t pwdBufLen, bufferLen; + + bufferLen = pwdBufLen = pwdLen+2; + pwdBuf = SMB_MALLOC_ARRAY(char, pwdBufLen); /* digest and null */ + if (pwdBuf == NULL) { + return LDAP_NO_MEMORY; + } + + err = getLoginConfig(ld, objectDN, methodIDLen, &methodID, tag, &pwdBufLen, pwdBuf); + if (err == 0) { + if (pwdBufLen !=0) { + pwdBuf[pwdBufLen] = 0; /* null terminate */ + + switch (pwdBuf[0]) { + case 1: /* cleartext password */ + break; + case 2: /* SHA1 HASH */ + case 3: /* MD5_ID */ + case 4: /* UNIXCrypt_ID */ + case 8: /* SSHA_ID */ + default: /* Unknown digest */ + err = LDAP_INAPPROPRIATE_AUTH; /* only return clear text */ + break; + } + + if (!err) { + if (pwdLen >= pwdBufLen-1) { + memcpy(pwd, &pwdBuf[1], pwdBufLen-1); /* skip digest tag and include null */ + } else { + err = LDAP_NO_MEMORY; + } + } + } + } + + if (pwdBuf != NULL) { + memset(pwdBuf, 0, bufferLen); + free(pwdBuf); + } + + return err; } @@ -486,113 +429,99 @@ static int nmasldap_get_simple_pwd( **********************************************************************/ static int nmasldap_get_password( - LDAP *ld, - char *objectDN, - size_t *pwdSize, /* in bytes */ - unsigned char *pwd ) + LDAP *ld, + char *objectDN, + size_t *pwdSize, /* in bytes */ + unsigned char *pwd ) { - int err = 0; - - struct berval *requestBV = NULL; - char *replyOID = NULL; - struct berval *replyBV = NULL; - int serverVersion; - char *pwdBuf; - size_t pwdBufLen, bufferLen; - - /* Validate char parameters. */ - if(objectDN == NULL || (strlen(objectDN) == 0) || pwdSize == NULL || ld == NULL) - { - return LDAP_NO_SUCH_ATTRIBUTE; - } - - bufferLen = pwdBufLen = *pwdSize; - pwdBuf = SMB_MALLOC_ARRAY(char, pwdBufLen+2); - if(pwdBuf == NULL) - { - return LDAP_NO_MEMORY; - } - - err = berEncodePasswordData(&requestBV, objectDN, NULL, NULL); - if(err) - { - goto Cleanup; - } - - /* Call the ldap_extended_operation (synchronously) */ - if((err = ldap_extended_operation_s(ld, NMASLDAP_GET_PASSWORD_REQUEST, requestBV, NULL, NULL, &replyOID, &replyBV))) - { - goto Cleanup; - } - - /* Make sure there is a return OID */ - if(!replyOID) - { - err = LDAP_NOT_SUPPORTED; - goto Cleanup; - } - - /* Is this what we were expecting to get back. */ - if(strcmp(replyOID, NMASLDAP_GET_PASSWORD_RESPONSE)) - { - err = LDAP_NOT_SUPPORTED; - goto Cleanup; - } - - /* Do we have a good returned berval? */ - if(!replyBV) - { - /* No; returned berval means we experienced a rather drastic error. */ - /* Return operations error. */ - err = LDAP_OPERATIONS_ERROR; - goto Cleanup; - } - - err = berDecodeLoginData(replyBV, &serverVersion, &pwdBufLen, pwdBuf); - - if(serverVersion != NMAS_LDAP_EXT_VERSION) - { - err = LDAP_OPERATIONS_ERROR; - goto Cleanup; - } - - if (!err && pwdBufLen != 0) - { - if (*pwdSize >= pwdBufLen+1 && pwd != NULL) - { - memcpy(pwd, pwdBuf, pwdBufLen); - pwd[pwdBufLen] = 0; /* add null termination */ - } - *pwdSize = pwdBufLen; /* does not include null termination */ - } + int err = 0; + + struct berval *requestBV = NULL; + char *replyOID = NULL; + struct berval *replyBV = NULL; + int serverVersion; + char *pwdBuf; + size_t pwdBufLen, bufferLen; + + /* Validate char parameters. */ + if (objectDN == NULL || (strlen(objectDN) == 0) || pwdSize == NULL || ld == NULL) { + return LDAP_NO_SUCH_ATTRIBUTE; + } + + bufferLen = pwdBufLen = *pwdSize; + pwdBuf = SMB_MALLOC_ARRAY(char, pwdBufLen+2); + if (pwdBuf == NULL) { + return LDAP_NO_MEMORY; + } + + err = berEncodePasswordData(&requestBV, objectDN, NULL, NULL); + if (err) { + goto Cleanup; + } + + /* Call the ldap_extended_operation (synchronously) */ + if ((err = ldap_extended_operation_s(ld, NMASLDAP_GET_PASSWORD_REQUEST, requestBV, NULL, NULL, &replyOID, &replyBV))) { + goto Cleanup; + } + + /* Make sure there is a return OID */ + if (!replyOID) { + err = LDAP_NOT_SUPPORTED; + goto Cleanup; + } + + /* Is this what we were expecting to get back. */ + if (strcmp(replyOID, NMASLDAP_GET_PASSWORD_RESPONSE)) { + err = LDAP_NOT_SUPPORTED; + goto Cleanup; + } + + /* Do we have a good returned berval? */ + if (!replyBV) { + /* No; returned berval means we experienced a rather drastic error. */ + /* Return operations error. */ + err = LDAP_OPERATIONS_ERROR; + goto Cleanup; + } + + err = berDecodeLoginData(replyBV, &serverVersion, &pwdBufLen, pwdBuf); + + if (serverVersion != NMAS_LDAP_EXT_VERSION) { + err = LDAP_OPERATIONS_ERROR; + goto Cleanup; + } + + if (!err && pwdBufLen != 0) { + if (*pwdSize >= pwdBufLen+1 && pwd != NULL) { + memcpy(pwd, pwdBuf, pwdBufLen); + pwd[pwdBufLen] = 0; /* add null termination */ + } + *pwdSize = pwdBufLen; /* does not include null termination */ + } Cleanup: - if(replyBV) - { - ber_bvfree(replyBV); - } - - /* Free the return OID string if one was returned. */ - if(replyOID) - { - ldap_memfree(replyOID); - } - - /* Free memory allocated while building the request ber and berval. */ - if(requestBV) - { - ber_bvfree(requestBV); - } - - if (pwdBuf != NULL) - { - memset(pwdBuf, 0, bufferLen); - free(pwdBuf); - } - - /* Return the appropriate error/success code. */ - return err; + if (replyBV) { + ber_bvfree(replyBV); + } + + /* Free the return OID string if one was returned. */ + if (replyOID) { + ldap_memfree(replyOID); + } + + /* Free memory allocated while building the request ber and berval. */ + if (requestBV) { + ber_bvfree(requestBV); + } + + if (pwdBuf != NULL) { + memset(pwdBuf, 0, bufferLen); + free(pwdBuf); + } + + /* Return the appropriate error/success code. */ + return err; } /********************************************************************** @@ -600,38 +529,38 @@ Cleanup: *********************************************************************/ int nds_get_password( - LDAP *ld, - char *object_dn, - size_t *pwd_len, - char *pwd ) + LDAP *ld, + char *object_dn, + size_t *pwd_len, + char *pwd ) { - int rc = -1; + int rc = -1; - rc = nmasldap_get_password(ld, object_dn, pwd_len, (unsigned char *)pwd); - if (rc == LDAP_SUCCESS) { + rc = nmasldap_get_password(ld, object_dn, pwd_len, (unsigned char *)pwd); + if (rc == LDAP_SUCCESS) { #ifdef DEBUG_PASSWORD - DEBUG(100,("nmasldap_get_password returned %s for %s\n", pwd, object_dn)); -#endif - DEBUG(5, ("NDS Universal Password retrieved for %s\n", object_dn)); - } else { - DEBUG(3, ("NDS Universal Password NOT retrieved for %s\n", object_dn)); - } - - if (rc != LDAP_SUCCESS) { - rc = nmasldap_get_simple_pwd(ld, object_dn, *pwd_len, pwd); - if (rc == LDAP_SUCCESS) { + DEBUG(100,("nmasldap_get_password returned %s for %s\n", pwd, object_dn)); +#endif + DEBUG(5, ("NDS Universal Password retrieved for %s\n", object_dn)); + } else { + DEBUG(3, ("NDS Universal Password NOT retrieved for %s\n", object_dn)); + } + + if (rc != LDAP_SUCCESS) { + rc = nmasldap_get_simple_pwd(ld, object_dn, *pwd_len, pwd); + if (rc == LDAP_SUCCESS) { #ifdef DEBUG_PASSWORD - DEBUG(100,("nmasldap_get_simple_pwd returned %s for %s\n", pwd, object_dn)); -#endif - DEBUG(5, ("NDS Simple Password retrieved for %s\n", object_dn)); - } else { - /* We couldn't get the password */ - DEBUG(3, ("NDS Simple Password NOT retrieved for %s\n", object_dn)); - return LDAP_INVALID_CREDENTIALS; - } - } - - /* We got the password */ - return LDAP_SUCCESS; + DEBUG(100,("nmasldap_get_simple_pwd returned %s for %s\n", pwd, object_dn)); +#endif + DEBUG(5, ("NDS Simple Password retrieved for %s\n", object_dn)); + } else { + /* We couldn't get the password */ + DEBUG(3, ("NDS Simple Password NOT retrieved for %s\n", object_dn)); + return LDAP_INVALID_CREDENTIALS; + } + } + + /* We got the password */ + return LDAP_SUCCESS; } diff --git a/helpers/digest_auth/eDirectory/edir_ldapext.h b/helpers/digest_auth/eDirectory/edir_ldapext.h index 9b861e82e7..8f154841e4 100644 --- a/helpers/digest_auth/eDirectory/edir_ldapext.h +++ b/helpers/digest_auth/eDirectory/edir_ldapext.h @@ -1 +1 @@ -int nds_get_password(LDAP *ld, char *object_dn, size_t * pwd_len, char *pwd); +int nds_get_password(LDAP *ld, char *object_dn, size_t * pwd_len, char *pwd); diff --git a/helpers/digest_auth/eDirectory/ldap_backend.c b/helpers/digest_auth/eDirectory/ldap_backend.c index 1db3e28455..397c0d037d 100644 --- a/helpers/digest_auth/eDirectory/ldap_backend.c +++ b/helpers/digest_auth/eDirectory/ldap_backend.c @@ -93,7 +93,7 @@ squid_ldap_set_aliasderef(int deref) static void squid_ldap_set_referrals(int referrals) { - int *value = referrals ? LDAP_OPT_ON : LDAP_OPT_OFF; + int *value = referrals ? LDAP_OPT_ON :LDAP_OPT_OFF; ldap_set_option(ld, LDAP_OPT_REFERRALS, value); } static void @@ -130,9 +130,9 @@ static void squid_ldap_set_referrals(int referrals) { if (referrals) - ld->ld_options |= ~LDAP_OPT_REFERRALS; + ld->ld_options |= ~LDAP_OPT_REFERRALS; else - ld->ld_options &= ~LDAP_OPT_REFERRALS; + ld->ld_options &= ~LDAP_OPT_REFERRALS; } static void squid_ldap_set_timelimit(int timelimit) @@ -163,24 +163,24 @@ ldap_escape_value(char *escaped, int size, const char *src) { int n = 0; while (size > 4 && *src) { - switch (*src) { - case '*': - case '(': - case ')': - case '\\': - n += 3; - size -= 3; - if (size > 0) { - *escaped++ = '\\'; - snprintf(escaped, 3, "%02x", (int) *src++); - escaped += 2; - } - break; - default: - *escaped++ = *src++; - n++; - size--; - } + switch (*src) { + case '*': + case '(': + case ')': + case '\\': + n += 3; + size -= 3; + if (size > 0) { + *escaped++ = '\\'; + snprintf(escaped, 3, "%02x", (int) *src++); + escaped += 2; + } + break; + default: + *escaped++ = *src++; + n++; + size--; + } } *escaped = '\0'; return n; @@ -202,127 +202,127 @@ getpassword(char *login, char *realm) int nmas_res = 0; int rc = -1; if (ld) { - if (usersearchfilter) { - char escaped_login[1024]; - snprintf(searchbase, sizeof(searchbase), "%s", userbasedn); - ldap_escape_value(escaped_login, sizeof(escaped_login), login); - snprintf(filter, sizeof(filter), usersearchfilter, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login); - - retrysrch: - if (debug) - fprintf(stderr, "user filter '%s', searchbase '%s'\n", filter, searchbase); - - rc = ldap_search_s(ld, searchbase, searchscope, filter, NULL, 0, &res); - if (rc != LDAP_SUCCESS) { - if (noreferrals && rc == LDAP_PARTIAL_RESULTS) { - /* Everything is fine. This is expected when referrals - * are disabled. - */ - rc = LDAP_SUCCESS; - } else { - fprintf(stderr, PROGRAM_NAME " WARNING, LDAP search error '%s'\n", ldap_err2string(rc)); + if (usersearchfilter) { + char escaped_login[1024]; + snprintf(searchbase, sizeof(searchbase), "%s", userbasedn); + ldap_escape_value(escaped_login, sizeof(escaped_login), login); + snprintf(filter, sizeof(filter), usersearchfilter, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login); + +retrysrch: + if (debug) + fprintf(stderr, "user filter '%s', searchbase '%s'\n", filter, searchbase); + + rc = ldap_search_s(ld, searchbase, searchscope, filter, NULL, 0, &res); + if (rc != LDAP_SUCCESS) { + if (noreferrals && rc == LDAP_PARTIAL_RESULTS) { + /* Everything is fine. This is expected when referrals + * are disabled. + */ + rc = LDAP_SUCCESS; + } else { + fprintf(stderr, PROGRAM_NAME " WARNING, LDAP search error '%s'\n", ldap_err2string(rc)); #if defined(NETSCAPE_SSL) - if (sslpath && ((rc == LDAP_SERVER_DOWN) || (rc == LDAP_CONNECT_ERROR))) { - int sslerr = PORT_GetError(); - fprintf(stderr, PROGRAM_NAME ": WARNING, SSL error %d (%s)\n", sslerr, ldapssl_err2string(sslerr)); - } + if (sslpath && ((rc == LDAP_SERVER_DOWN) || (rc == LDAP_CONNECT_ERROR))) { + int sslerr = PORT_GetError(); + fprintf(stderr, PROGRAM_NAME ": WARNING, SSL error %d (%s)\n", sslerr, ldapssl_err2string(sslerr)); + } #endif - fprintf(stderr, PROGRAM_NAME " WARNING, LDAP search error, trying to recover'%s'\n", ldap_err2string(rc)); - ldap_msgfree(res); - /* try to connect to the LDAP server agin, maybe my persisten conexion failed. */ - if (!retry) { - retry++; - ldap_unbind(ld); - ld = NULL; - ldapconnect(); - goto retrysrch; - } - return NULL; - - } - } - } else if (userdnattr) { - sprintf(searchbase, "%s=%s, %s", userdnattr, login, userbasedn); - - retrydnattr: - if (debug) - fprintf(stderr, "searchbase '%s'\n", searchbase); - rc = ldap_search_s(ld, searchbase, searchscope, NULL, NULL, 0, &res); - } - if (rc == LDAP_SUCCESS) { - entry = ldap_first_entry(ld, res); - if (entry) { - if (debug) - printf("ldap dn: %s\n", ldap_get_dn(ld, entry)); - if (edir_universal_passwd) { - - /* allocate some memory for the universal password returned by NMAS */ - universal_password = malloc(universal_password_len); - memset(universal_password, 0, universal_password_len); - values = malloc(sizeof(char *)); - - /* actually talk to NMAS to get a password */ - nmas_res = nds_get_password(ld, ldap_get_dn(ld, entry), &universal_password_len, universal_password); - if (nmas_res == LDAP_SUCCESS && universal_password) { - if (debug) - printf("NMAS returned value %s\n", universal_password); - values[0] = universal_password; - } else { - if (debug) - printf("Error reading Universal Password: %d = %s\n", nmas_res, ldap_err2string(nmas_res)); - } - } else { - values = ldap_get_values(ld, entry, passattr); - } - } else { - ldap_msgfree(res); - return NULL; - } - if (!values) { - if (debug) - printf("No attribute value found\n"); - if (edir_universal_passwd) - free(universal_password); - ldap_msgfree(res); - return NULL; - } - value = values; - while (*value) { - if (encrpass) { - if (strcmp(strtok(*value, delimiter), realm) == 0) { - password = strtok(NULL, delimiter); - break; - } - } else { - password = *value; - break; - } - value++; - } - if (debug) - printf("password: %s\n", password); - if (password) - password = strdup(password); - if (edir_universal_passwd) { - free(values); - free(universal_password); - } else { - ldap_value_free(values); - } - ldap_msgfree(res); - return password; - } else { - fprintf(stderr, PROGRAM_NAME " WARNING, LDAP error '%s'\n", ldap_err2string(rc)); - /* try to connect to the LDAP server agin, maybe my persisten conexion failed. */ - if (!retry) { - retry++; - ldap_unbind(ld); - ld = NULL; - ldapconnect(); - goto retrydnattr; - } - return NULL; - } + fprintf(stderr, PROGRAM_NAME " WARNING, LDAP search error, trying to recover'%s'\n", ldap_err2string(rc)); + ldap_msgfree(res); + /* try to connect to the LDAP server agin, maybe my persisten conexion failed. */ + if (!retry) { + retry++; + ldap_unbind(ld); + ld = NULL; + ldapconnect(); + goto retrysrch; + } + return NULL; + + } + } + } else if (userdnattr) { + sprintf(searchbase, "%s=%s, %s", userdnattr, login, userbasedn); + +retrydnattr: + if (debug) + fprintf(stderr, "searchbase '%s'\n", searchbase); + rc = ldap_search_s(ld, searchbase, searchscope, NULL, NULL, 0, &res); + } + if (rc == LDAP_SUCCESS) { + entry = ldap_first_entry(ld, res); + if (entry) { + if (debug) + printf("ldap dn: %s\n", ldap_get_dn(ld, entry)); + if (edir_universal_passwd) { + + /* allocate some memory for the universal password returned by NMAS */ + universal_password = malloc(universal_password_len); + memset(universal_password, 0, universal_password_len); + values = malloc(sizeof(char *)); + + /* actually talk to NMAS to get a password */ + nmas_res = nds_get_password(ld, ldap_get_dn(ld, entry), &universal_password_len, universal_password); + if (nmas_res == LDAP_SUCCESS && universal_password) { + if (debug) + printf("NMAS returned value %s\n", universal_password); + values[0] = universal_password; + } else { + if (debug) + printf("Error reading Universal Password: %d = %s\n", nmas_res, ldap_err2string(nmas_res)); + } + } else { + values = ldap_get_values(ld, entry, passattr); + } + } else { + ldap_msgfree(res); + return NULL; + } + if (!values) { + if (debug) + printf("No attribute value found\n"); + if (edir_universal_passwd) + free(universal_password); + ldap_msgfree(res); + return NULL; + } + value = values; + while (*value) { + if (encrpass) { + if (strcmp(strtok(*value, delimiter), realm) == 0) { + password = strtok(NULL, delimiter); + break; + } + } else { + password = *value; + break; + } + value++; + } + if (debug) + printf("password: %s\n", password); + if (password) + password = strdup(password); + if (edir_universal_passwd) { + free(values); + free(universal_password); + } else { + ldap_value_free(values); + } + ldap_msgfree(res); + return password; + } else { + fprintf(stderr, PROGRAM_NAME " WARNING, LDAP error '%s'\n", ldap_err2string(rc)); + /* try to connect to the LDAP server agin, maybe my persisten conexion failed. */ + if (!retry) { + retry++; + ldap_unbind(ld); + ld = NULL; + ldapconnect(); + goto retrydnattr; + } + return NULL; + } } return NULL; } @@ -334,91 +334,91 @@ ldapconnect(void) { int rc; -/* On Windows ldap_start_tls_s is available starting from Windows XP, - * so we need to bind at run-time with the function entry point - */ + /* On Windows ldap_start_tls_s is available starting from Windows XP, + * so we need to bind at run-time with the function entry point + */ #ifdef _SQUID_MSWIN_ if (use_tls) { - HMODULE WLDAP32Handle; + HMODULE WLDAP32Handle; - WLDAP32Handle = GetModuleHandle("wldap32"); - if ((Win32_ldap_start_tls_s = (PFldap_start_tls_s) GetProcAddress(WLDAP32Handle, LDAP_START_TLS_S)) == NULL) { - fprintf(stderr, PROGRAM_NAME ": ERROR: TLS (-Z) not supported on this platform.\n"); - exit(1); - } + WLDAP32Handle = GetModuleHandle("wldap32"); + if ((Win32_ldap_start_tls_s = (PFldap_start_tls_s) GetProcAddress(WLDAP32Handle, LDAP_START_TLS_S)) == NULL) { + fprintf(stderr, PROGRAM_NAME ": ERROR: TLS (-Z) not supported on this platform.\n"); + exit(1); + } } #endif if (ld == NULL) { #if HAS_URI_SUPPORT - if (strstr(ldapServer, "://") != NULL) { - rc = ldap_initialize(&ld, ldapServer); - if (rc != LDAP_SUCCESS) { - fprintf(stderr, "\nUnable to connect to LDAPURI:%s\n", ldapServer); - } - } else + if (strstr(ldapServer, "://") != NULL) { + rc = ldap_initialize(&ld, ldapServer); + if (rc != LDAP_SUCCESS) { + fprintf(stderr, "\nUnable to connect to LDAPURI:%s\n", ldapServer); + } + } else #endif #if NETSCAPE_SSL - if (sslpath) { - if (!sslinit && (ldapssl_client_init(sslpath, NULL) != LDAP_SUCCESS)) { - fprintf(stderr, "\nUnable to initialise SSL with cert path %s\n", - sslpath); - exit(1); - } else { - sslinit++; - } - if ((ld = ldapssl_init(ldapServer, port, 1)) == NULL) { - fprintf(stderr, "\nUnable to connect to SSL LDAP server: %s port:%d\n", - ldapServer, port); - exit(1); - } - } else + if (sslpath) { + if (!sslinit && (ldapssl_client_init(sslpath, NULL) != LDAP_SUCCESS)) { + fprintf(stderr, "\nUnable to initialise SSL with cert path %s\n", + sslpath); + exit(1); + } else { + sslinit++; + } + if ((ld = ldapssl_init(ldapServer, port, 1)) == NULL) { + fprintf(stderr, "\nUnable to connect to SSL LDAP server: %s port:%d\n", + ldapServer, port); + exit(1); + } + } else #endif - if ((ld = ldap_init(ldapServer, port)) == NULL) { - fprintf(stderr, "\nUnable to connect to LDAP server:%s port:%d\n", ldapServer, port); - } - if (connect_timeout) - squid_ldap_set_connect_timeout(connect_timeout); + if ((ld = ldap_init(ldapServer, port)) == NULL) { + fprintf(stderr, "\nUnable to connect to LDAP server:%s port:%d\n", ldapServer, port); + } + if (connect_timeout) + squid_ldap_set_connect_timeout(connect_timeout); #ifdef LDAP_VERSION3 - if (version == -1) { - version = LDAP_VERSION2; - } - if (ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &version) - != LDAP_SUCCESS) { - fprintf(stderr, "Could not set LDAP_OPT_PROTOCOL_VERSION %d\n", - version); - ldap_unbind(ld); - ld = NULL; - } - if (use_tls) { + if (version == -1) { + version = LDAP_VERSION2; + } + if (ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &version) + != LDAP_SUCCESS) { + fprintf(stderr, "Could not set LDAP_OPT_PROTOCOL_VERSION %d\n", + version); + ldap_unbind(ld); + ld = NULL; + } + if (use_tls) { #ifdef LDAP_OPT_X_TLS - if ((version == LDAP_VERSION3) && (ldap_start_tls_s(ld, NULL, NULL) == LDAP_SUCCESS)) { - fprintf(stderr, "Could not Activate TLS connection\n"); - ldap_unbind(ld); - ld = NULL; - } + if ((version == LDAP_VERSION3) && (ldap_start_tls_s(ld, NULL, NULL) == LDAP_SUCCESS)) { + fprintf(stderr, "Could not Activate TLS connection\n"); + ldap_unbind(ld); + ld = NULL; + } #else - fprintf(stderr, "TLS not supported with your LDAP library\n"); - ldap_unbind(ld); - ld = NULL; + fprintf(stderr, "TLS not supported with your LDAP library\n"); + ldap_unbind(ld); + ld = NULL; #endif - } + } #endif - squid_ldap_set_timelimit(timelimit); - squid_ldap_set_referrals(!noreferrals); - squid_ldap_set_aliasderef(aliasderef); - if (binddn && bindpasswd && *binddn && *bindpasswd) { - rc = ldap_simple_bind_s(ld, binddn, bindpasswd); - if (rc != LDAP_SUCCESS) { - fprintf(stderr, PROGRAM_NAME " WARNING, could not bind to binddn '%s'\n", ldap_err2string(rc)); - ldap_unbind(ld); - ld = NULL; - } - } - if (debug) - fprintf(stderr, "Connected OK\n"); + squid_ldap_set_timelimit(timelimit); + squid_ldap_set_referrals(!noreferrals); + squid_ldap_set_aliasderef(aliasderef); + if (binddn && bindpasswd && *binddn && *bindpasswd) { + rc = ldap_simple_bind_s(ld, binddn, bindpasswd); + if (rc != LDAP_SUCCESS) { + fprintf(stderr, PROGRAM_NAME " WARNING, could not bind to binddn '%s'\n", ldap_err2string(rc)); + ldap_unbind(ld); + ld = NULL; + } + } + if (debug) + fprintf(stderr, "Connected OK\n"); } } int @@ -427,219 +427,219 @@ LDAPArguments(int argc, char **argv) setbuf(stdout, NULL); while (argc > 1 && argv[1][0] == '-') { - const char *value = ""; - char option = argv[1][1]; - switch (option) { - case 'P': - case 'R': - case 'z': - case 'Z': - case 'g': - case 'e': - case 'S': - case 'n': - case 'd': - break; - default: - if (strlen(argv[1]) > 2) { - value = argv[1] + 2; - } else if (argc > 2) { - value = argv[2]; - argv++; - argc--; - } else - value = ""; - break; - } - argv++; - argc--; - switch (option) { - case 'H': + const char *value = ""; + char option = argv[1][1]; + switch (option) { + case 'P': + case 'R': + case 'z': + case 'Z': + case 'g': + case 'e': + case 'S': + case 'n': + case 'd': + break; + default: + if (strlen(argv[1]) > 2) { + value = argv[1] + 2; + } else if (argc > 2) { + value = argv[2]; + argv++; + argc--; + } else + value = ""; + break; + } + argv++; + argc--; + switch (option) { + case 'H': #if !HAS_URI_SUPPORT - fprintf(stderr, "ERROR: Your LDAP library does not have URI support\n"); - return 1; + fprintf(stderr, "ERROR: Your LDAP library does not have URI support\n"); + return 1; #endif - /* Fall thru to -h */ - case 'h': - if (ldapServer) { - int len = strlen(ldapServer) + 1 + strlen(value) + 1; - char *newhost = malloc(len); - snprintf(newhost, len, "%s %s", ldapServer, value); - free(ldapServer); - ldapServer = newhost; - } else { - ldapServer = strdup(value); - } - break; - case 'A': - passattr = value; - break; - case 'e': - encrpass = 1; - break; - case 'l': - delimiter = value; - break; - case 'b': - userbasedn = value; - break; - case 'F': - usersearchfilter = value; - break; - case 'u': - userdnattr = value; - break; - case 's': - if (strcmp(value, "base") == 0) - searchscope = LDAP_SCOPE_BASE; - else if (strcmp(value, "one") == 0) - searchscope = LDAP_SCOPE_ONELEVEL; - else if (strcmp(value, "sub") == 0) - searchscope = LDAP_SCOPE_SUBTREE; - else { - fprintf(stderr, PROGRAM_NAME " ERROR: Unknown search scope '%s'\n", value); - return 1; - } - break; - case 'S': + /* Fall thru to -h */ + case 'h': + if (ldapServer) { + int len = strlen(ldapServer) + 1 + strlen(value) + 1; + char *newhost = malloc(len); + snprintf(newhost, len, "%s %s", ldapServer, value); + free(ldapServer); + ldapServer = newhost; + } else { + ldapServer = strdup(value); + } + break; + case 'A': + passattr = value; + break; + case 'e': + encrpass = 1; + break; + case 'l': + delimiter = value; + break; + case 'b': + userbasedn = value; + break; + case 'F': + usersearchfilter = value; + break; + case 'u': + userdnattr = value; + break; + case 's': + if (strcmp(value, "base") == 0) + searchscope = LDAP_SCOPE_BASE; + else if (strcmp(value, "one") == 0) + searchscope = LDAP_SCOPE_ONELEVEL; + else if (strcmp(value, "sub") == 0) + searchscope = LDAP_SCOPE_SUBTREE; + else { + fprintf(stderr, PROGRAM_NAME " ERROR: Unknown search scope '%s'\n", value); + return 1; + } + break; + case 'S': #if defined(NETSCAPE_SSL) - sslpath = value; - if (port == LDAP_PORT) - port = LDAPS_PORT; + sslpath = value; + if (port == LDAP_PORT) + port = LDAPS_PORT; #else - fprintf(stderr, PROGRAM_NAME " ERROR: -E unsupported with this LDAP library\n"); - return 1; + fprintf(stderr, PROGRAM_NAME " ERROR: -E unsupported with this LDAP library\n"); + return 1; #endif - break; - case 'c': - connect_timeout = atoi(value); - break; - case 't': - timelimit = atoi(value); - break; - case 'a': - if (strcmp(value, "never") == 0) - aliasderef = LDAP_DEREF_NEVER; - else if (strcmp(value, "always") == 0) - aliasderef = LDAP_DEREF_ALWAYS; - else if (strcmp(value, "search") == 0) - aliasderef = LDAP_DEREF_SEARCHING; - else if (strcmp(value, "find") == 0) - aliasderef = LDAP_DEREF_FINDING; - else { - fprintf(stderr, PROGRAM_NAME " ERROR: Unknown alias dereference method '%s'\n", value); - return 1; - } - break; - case 'D': - binddn = value; - break; - case 'w': - bindpasswd = value; - break; - case 'W': - readSecret(value); - break; - case 'P': - persistent = !persistent; - break; - case 'p': - port = atoi(value); - break; - case 'R': - noreferrals = !noreferrals; - break; + break; + case 'c': + connect_timeout = atoi(value); + break; + case 't': + timelimit = atoi(value); + break; + case 'a': + if (strcmp(value, "never") == 0) + aliasderef = LDAP_DEREF_NEVER; + else if (strcmp(value, "always") == 0) + aliasderef = LDAP_DEREF_ALWAYS; + else if (strcmp(value, "search") == 0) + aliasderef = LDAP_DEREF_SEARCHING; + else if (strcmp(value, "find") == 0) + aliasderef = LDAP_DEREF_FINDING; + else { + fprintf(stderr, PROGRAM_NAME " ERROR: Unknown alias dereference method '%s'\n", value); + return 1; + } + break; + case 'D': + binddn = value; + break; + case 'w': + bindpasswd = value; + break; + case 'W': + readSecret(value); + break; + case 'P': + persistent = !persistent; + break; + case 'p': + port = atoi(value); + break; + case 'R': + noreferrals = !noreferrals; + break; #ifdef LDAP_VERSION3 - case 'v': - switch (atoi(value)) { - case 2: - version = LDAP_VERSION2; - break; - case 3: - version = LDAP_VERSION3; - break; - default: - fprintf(stderr, "Protocol version should be 2 or 3\n"); - return 1; - } - break; - case 'Z': - if (version == LDAP_VERSION2) { - fprintf(stderr, "TLS (-Z) is incompatible with version %d\n", - version); - return 1; - } - version = LDAP_VERSION3; - use_tls = 1; - break; + case 'v': + switch (atoi(value)) { + case 2: + version = LDAP_VERSION2; + break; + case 3: + version = LDAP_VERSION3; + break; + default: + fprintf(stderr, "Protocol version should be 2 or 3\n"); + return 1; + } + break; + case 'Z': + if (version == LDAP_VERSION2) { + fprintf(stderr, "TLS (-Z) is incompatible with version %d\n", + version); + return 1; + } + version = LDAP_VERSION3; + use_tls = 1; + break; #endif - case 'd': - debug = 1; - break; - case 'E': - strip_nt_domain = 1; - break; - case 'n': - edir_universal_passwd = 1; - break; - default: - fprintf(stderr, PROGRAM_NAME " ERROR: Unknown command line option '%c'\n", option); - return 1; - } + case 'd': + debug = 1; + break; + case 'E': + strip_nt_domain = 1; + break; + case 'n': + edir_universal_passwd = 1; + break; + default: + fprintf(stderr, PROGRAM_NAME " ERROR: Unknown command line option '%c'\n", option); + return 1; + } } while (argc > 1) { - char *value = argv[1]; - if (ldapServer) { - int len = strlen(ldapServer) + 1 + strlen(value) + 1; - char *newhost = malloc(len); - snprintf(newhost, len, "%s %s", ldapServer, value); - free(ldapServer); - ldapServer = newhost; - } else { - ldapServer = strdup(value); - } - argc--; - argv++; + char *value = argv[1]; + if (ldapServer) { + int len = strlen(ldapServer) + 1 + strlen(value) + 1; + char *newhost = malloc(len); + snprintf(newhost, len, "%s %s", ldapServer, value); + free(ldapServer); + ldapServer = newhost; + } else { + ldapServer = strdup(value); + } + argc--; + argv++; } if (!ldapServer) - ldapServer = (char *) "localhost"; + ldapServer = (char *) "localhost"; if (!userbasedn || !((passattr != NULL) || (edir_universal_passwd && usersearchfilter && version == LDAP_VERSION3 && use_tls))) { - fprintf(stderr, "Usage: " PROGRAM_NAME " -b basedn -f filter [options] ldap_server_name\n\n"); - fprintf(stderr, "\t-A password attribute(REQUIRED)\t\tUser attribute that contains the password\n"); - fprintf(stderr, "\t-l password realm delimiter(REQUIRED)\tCharater(s) that devides the password attribute\n\t\t\t\t\t\tin realm and password tokens, default ':' realm:password\n"); - fprintf(stderr, "\t-b basedn (REQUIRED)\t\t\tbase dn under where to search for users\n"); - fprintf(stderr, "\t-e Encrypted passwords(REQUIRED)\tPassword are stored encrypted using HHA1\n"); - fprintf(stderr, "\t-F filter\t\t\t\tuser search filter pattern. %%s = login\n"); - fprintf(stderr, "\t-u attribute\t\t\t\tattribute to use in combination with the basedn to create the user DN\n"); - fprintf(stderr, "\t-s base|one|sub\t\t\t\tsearch scope\n"); - fprintf(stderr, "\t-D binddn\t\t\t\tDN to bind as to perform searches\n"); - fprintf(stderr, "\t-w bindpasswd\t\t\t\tpassword for binddn\n"); - fprintf(stderr, "\t-W secretfile\t\t\t\tread password for binddn from file secretfile\n"); + fprintf(stderr, "Usage: " PROGRAM_NAME " -b basedn -f filter [options] ldap_server_name\n\n"); + fprintf(stderr, "\t-A password attribute(REQUIRED)\t\tUser attribute that contains the password\n"); + fprintf(stderr, "\t-l password realm delimiter(REQUIRED)\tCharater(s) that devides the password attribute\n\t\t\t\t\t\tin realm and password tokens, default ':' realm:password\n"); + fprintf(stderr, "\t-b basedn (REQUIRED)\t\t\tbase dn under where to search for users\n"); + fprintf(stderr, "\t-e Encrypted passwords(REQUIRED)\tPassword are stored encrypted using HHA1\n"); + fprintf(stderr, "\t-F filter\t\t\t\tuser search filter pattern. %%s = login\n"); + fprintf(stderr, "\t-u attribute\t\t\t\tattribute to use in combination with the basedn to create the user DN\n"); + fprintf(stderr, "\t-s base|one|sub\t\t\t\tsearch scope\n"); + fprintf(stderr, "\t-D binddn\t\t\t\tDN to bind as to perform searches\n"); + fprintf(stderr, "\t-w bindpasswd\t\t\t\tpassword for binddn\n"); + fprintf(stderr, "\t-W secretfile\t\t\t\tread password for binddn from file secretfile\n"); #if HAS_URI_SUPPORT - fprintf(stderr, "\t-H URI\t\t\t\t\tLDAPURI (defaults to ldap://localhost)\n"); + fprintf(stderr, "\t-H URI\t\t\t\t\tLDAPURI (defaults to ldap://localhost)\n"); #endif - fprintf(stderr, "\t-h server\t\t\t\tLDAP server (defaults to localhost)\n"); - fprintf(stderr, "\t-p port\t\t\t\t\tLDAP server port (defaults to %d)\n", LDAP_PORT); - fprintf(stderr, "\t-P\t\t\t\t\tpersistent LDAP connection\n"); + fprintf(stderr, "\t-h server\t\t\t\tLDAP server (defaults to localhost)\n"); + fprintf(stderr, "\t-p port\t\t\t\t\tLDAP server port (defaults to %d)\n", LDAP_PORT); + fprintf(stderr, "\t-P\t\t\t\t\tpersistent LDAP connection\n"); #if defined(NETSCAPE_SSL) - fprintf(stderr, "\t-E sslcertpath\t\t\t\tenable LDAP over SSL\n"); + fprintf(stderr, "\t-E sslcertpath\t\t\t\tenable LDAP over SSL\n"); #endif - fprintf(stderr, "\t-c timeout\t\t\t\tconnect timeout\n"); - fprintf(stderr, "\t-t timelimit\t\t\t\tsearch time limit\n"); - fprintf(stderr, "\t-R\t\t\t\t\tdo not follow referrals\n"); - fprintf(stderr, "\t-a never|always|search|find\t\twhen to dereference aliases\n"); + fprintf(stderr, "\t-c timeout\t\t\t\tconnect timeout\n"); + fprintf(stderr, "\t-t timelimit\t\t\t\tsearch time limit\n"); + fprintf(stderr, "\t-R\t\t\t\t\tdo not follow referrals\n"); + fprintf(stderr, "\t-a never|always|search|find\t\twhen to dereference aliases\n"); #ifdef LDAP_VERSION3 - fprintf(stderr, "\t-v 2|3\t\t\t\t\tLDAP version\n"); - fprintf(stderr, "\t-Z\t\t\t\t\tTLS encrypt the LDAP connection, requires\n\t\t\t\tLDAP version 3\n"); + fprintf(stderr, "\t-v 2|3\t\t\t\t\tLDAP version\n"); + fprintf(stderr, "\t-Z\t\t\t\t\tTLS encrypt the LDAP connection, requires\n\t\t\t\tLDAP version 3\n"); #endif - fprintf(stderr, "\t-S\t\t\t\t\tStrip NT domain from usernames\n"); - fprintf(stderr, "\t-n\t\t\t\t\tGet an eDirectory Universal Password from Novell NMAS\n\t\t\t\t\t\t(requires bind credentials, version 3, TLS, and a search filter)\n"); - fprintf(stderr, "\n"); - fprintf(stderr, "\tIf you need to bind as a user to perform searches then use the\n\t-D binddn -w bindpasswd or -D binddn -W secretfile options\n\n"); - return -1; + fprintf(stderr, "\t-S\t\t\t\t\tStrip NT domain from usernames\n"); + fprintf(stderr, "\t-n\t\t\t\t\tGet an eDirectory Universal Password from Novell NMAS\n\t\t\t\t\t\t(requires bind credentials, version 3, TLS, and a search filter)\n"); + fprintf(stderr, "\n"); + fprintf(stderr, "\tIf you need to bind as a user to perform searches then use the\n\t-D binddn -w bindpasswd or -D binddn -W secretfile options\n\n"); + return -1; } return 0; } @@ -651,23 +651,23 @@ readSecret(const char *filename) FILE *f; if (!(f = fopen(filename, "r"))) { - fprintf(stderr, PROGRAM_NAME " ERROR: Can not read secret file %s\n", filename); - return 1; + fprintf(stderr, PROGRAM_NAME " ERROR: Can not read secret file %s\n", filename); + return 1; } if (!fgets(buf, sizeof(buf) - 1, f)) { - fprintf(stderr, PROGRAM_NAME " ERROR: Secret file %s is empty\n", filename); - fclose(f); - return 1; + fprintf(stderr, PROGRAM_NAME " ERROR: Secret file %s is empty\n", filename); + fclose(f); + return 1; } /* strip whitespaces on end */ if ((e = strrchr(buf, '\n'))) - *e = 0; + *e = 0; if ((e = strrchr(buf, '\r'))) - *e = 0; + *e = 0; bindpasswd = strdup(buf); if (!bindpasswd) { - fprintf(stderr, PROGRAM_NAME " ERROR: can not allocate memory\n"); + fprintf(stderr, PROGRAM_NAME " ERROR: can not allocate memory\n"); } fclose(f); @@ -681,15 +681,15 @@ LDAPHHA1(RequestData * requestData) ldapconnect(); password = getpassword(requestData->user, requestData->realm); if (password != NULL) { - if (encrpass) - xstrncpy(requestData->HHA1, password, sizeof(requestData->HHA1)); - else { - HASH HA1; - DigestCalcHA1("md5", requestData->user, requestData->realm, password, NULL, NULL, HA1, requestData->HHA1); - } - free(password); + if (encrpass) + xstrncpy(requestData->HHA1, password, sizeof(requestData->HHA1)); + else { + HASH HA1; + DigestCalcHA1("md5", requestData->user, requestData->realm, password, NULL, NULL, HA1, requestData->HHA1); + } + free(password); } else { - requestData->error = -1; + requestData->error = -1; } } diff --git a/helpers/digest_auth/ldap/digest_common.h b/helpers/digest_auth/ldap/digest_common.h index 21e77a002f..1844bd783d 100644 --- a/helpers/digest_auth/ldap/digest_common.h +++ b/helpers/digest_auth/ldap/digest_common.h @@ -50,8 +50,8 @@ typedef struct _request_data { int error; } RequestData; -/* to use a backend, include your backend.h file - * and define thusly: +/* to use a backend, include your backend.h file + * and define thusly: * #define ProcessArguments(A, B) MyHandleArguments(A,B) * #define GetHHA1(A) MyGetHHA1(A) */ diff --git a/helpers/digest_auth/ldap/digest_pw_auth.c b/helpers/digest_auth/ldap/digest_pw_auth.c index b81a84d8d1..2f5f2016db 100644 --- a/helpers/digest_auth/ldap/digest_pw_auth.c +++ b/helpers/digest_auth/ldap/digest_pw_auth.c @@ -12,7 +12,7 @@ * - comment lines are possible and should start with a '#'; * - empty or blank lines are possible; * - file format is username:password - * + * * To build a directory integrated backend, you need to be able to * calculate the HA1 returned to squid. To avoid storing a plaintext * password you can calculate MD5(username:realm:password) when the @@ -47,13 +47,13 @@ ParseBuffer(char *buf, RequestData * requestData) char *p; requestData->parsed = 0; if ((p = strchr(buf, '\n')) != NULL) - *p = '\0'; /* strip \n */ + *p = '\0'; /* strip \n */ if ((requestData->user = strtok(buf, "\"")) == NULL) - return; + return; if ((requestData->realm = strtok(NULL, "\"")) == NULL) - return; + return; if ((requestData->realm = strtok(NULL, "\"")) == NULL) - return; + return; requestData->parsed = -1; } @@ -63,8 +63,8 @@ OutputHHA1(RequestData * requestData) requestData->error = 0; GetHHA1(requestData); if (requestData->error) { - printf("ERR No such user\n"); - return; + printf("ERR No such user\n"); + return; } printf("%s\n", requestData->HHA1); } @@ -75,8 +75,8 @@ DoOneRequest(char *buf) RequestData requestData; ParseBuffer(buf, &requestData); if (!requestData.parsed) { - printf("ERR\n"); - return; + printf("ERR\n"); + return; } OutputHHA1(&requestData); } @@ -87,7 +87,7 @@ ProcessArguments(int argc, char **argv) int i; i = LDAPArguments(argc, argv); if (i) - exit(i); + exit(i); } int @@ -97,6 +97,6 @@ main(int argc, char **argv) setbuf(stdout, NULL); ProcessArguments(argc, argv); while (fgets(buf, 256, stdin) != NULL) - DoOneRequest(buf); + DoOneRequest(buf); exit(0); } diff --git a/helpers/digest_auth/ldap/ldap_backend.c b/helpers/digest_auth/ldap/ldap_backend.c index 4594a610ec..0e4a9fecda 100644 --- a/helpers/digest_auth/ldap/ldap_backend.c +++ b/helpers/digest_auth/ldap/ldap_backend.c @@ -91,7 +91,7 @@ squid_ldap_set_aliasderef(int deref) static void squid_ldap_set_referrals(int referrals) { - int *value = referrals ? LDAP_OPT_ON : LDAP_OPT_OFF; + int *value = referrals ? LDAP_OPT_ON :LDAP_OPT_OFF; ldap_set_option(ld, LDAP_OPT_REFERRALS, value); } static void @@ -128,9 +128,9 @@ static void squid_ldap_set_referrals(int referrals) { if (referrals) - ld->ld_options |= ~LDAP_OPT_REFERRALS; + ld->ld_options |= ~LDAP_OPT_REFERRALS; else - ld->ld_options &= ~LDAP_OPT_REFERRALS; + ld->ld_options &= ~LDAP_OPT_REFERRALS; } static void squid_ldap_set_timelimit(int timelimit) @@ -161,24 +161,24 @@ ldap_escape_value(char *escaped, int size, const char *src) { int n = 0; while (size > 4 && *src) { - switch (*src) { - case '*': - case '(': - case ')': - case '\\': - n += 3; - size -= 3; - if (size > 0) { - *escaped++ = '\\'; - snprintf(escaped, 3, "%02x", (int) *src++); - escaped += 2; - } - break; - default: - *escaped++ = *src++; - n++; - size--; - } + switch (*src) { + case '*': + case '(': + case ')': + case '\\': + n += 3; + size -= 3; + if (size > 0) { + *escaped++ = '\\'; + snprintf(escaped, 3, "%02x", (int) *src++); + escaped += 2; + } + break; + default: + *escaped++ = *src++; + n++; + size--; + } } *escaped = '\0'; return n; @@ -197,99 +197,99 @@ getpassword(char *login, char *realm) char searchbase[8192]; int rc = -1; if (ld) { - if (usersearchfilter) { - char escaped_login[1024]; - snprintf(searchbase, sizeof(searchbase), "%s", userbasedn); - ldap_escape_value(escaped_login, sizeof(escaped_login), login); - snprintf(filter, sizeof(filter), usersearchfilter, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login); - - retrysrch: - if (debug) - fprintf(stderr, "user filter '%s', searchbase '%s'\n", filter, searchbase); - - rc = ldap_search_s(ld, searchbase, searchscope, filter, NULL, 0, &res); - if (rc != LDAP_SUCCESS) { - if (noreferrals && rc == LDAP_PARTIAL_RESULTS) { - /* Everything is fine. This is expected when referrals - * are disabled. - */ - rc = LDAP_SUCCESS; - } else { - fprintf(stderr, PROGRAM_NAME " WARNING, LDAP search error '%s'\n", ldap_err2string(rc)); + if (usersearchfilter) { + char escaped_login[1024]; + snprintf(searchbase, sizeof(searchbase), "%s", userbasedn); + ldap_escape_value(escaped_login, sizeof(escaped_login), login); + snprintf(filter, sizeof(filter), usersearchfilter, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login); + +retrysrch: + if (debug) + fprintf(stderr, "user filter '%s', searchbase '%s'\n", filter, searchbase); + + rc = ldap_search_s(ld, searchbase, searchscope, filter, NULL, 0, &res); + if (rc != LDAP_SUCCESS) { + if (noreferrals && rc == LDAP_PARTIAL_RESULTS) { + /* Everything is fine. This is expected when referrals + * are disabled. + */ + rc = LDAP_SUCCESS; + } else { + fprintf(stderr, PROGRAM_NAME " WARNING, LDAP search error '%s'\n", ldap_err2string(rc)); #if defined(NETSCAPE_SSL) - if (sslpath && ((rc == LDAP_SERVER_DOWN) || (rc == LDAP_CONNECT_ERROR))) { - int sslerr = PORT_GetError(); - fprintf(stderr, PROGRAM_NAME ": WARNING, SSL error %d (%s)\n", sslerr, ldapssl_err2string(sslerr)); - } + if (sslpath && ((rc == LDAP_SERVER_DOWN) || (rc == LDAP_CONNECT_ERROR))) { + int sslerr = PORT_GetError(); + fprintf(stderr, PROGRAM_NAME ": WARNING, SSL error %d (%s)\n", sslerr, ldapssl_err2string(sslerr)); + } #endif - fprintf(stderr, PROGRAM_NAME " WARNING, LDAP search error, trying to recover'%s'\n", ldap_err2string(rc)); - ldap_msgfree(res); - /* try to connect to the LDAP server agin, maybe my persisten conexion failed. */ - if (!retry) { - retry++; - ldap_unbind(ld); - ld = NULL; - ldapconnect(); - goto retrysrch; - } - return NULL; - - } - } - } else if (userdnattr) { - sprintf(searchbase, "%s=%s, %s", userdnattr, login, userbasedn); - - retrydnattr: - if (debug) - fprintf(stderr, "searchbase '%s'\n", searchbase); - rc = ldap_search_s(ld, searchbase, searchscope, NULL, NULL, 0, &res); - } - if (rc == LDAP_SUCCESS) { - entry = ldap_first_entry(ld, res); - if (entry) - values = ldap_get_values(ld, entry, passattr); - else { - ldap_msgfree(res); - return NULL; - } - if (!values) { - if (debug) - printf("No attribute value found\n"); - ldap_msgfree(res); - return NULL; - } - value = values; - while (*value) { - if (encrpass) { - if (strcmp(strtok(*value, delimiter), realm) == 0) { - password = strtok(NULL, delimiter); - break; - } - } else { - password = *value; - break; - } - value++; - } - if (debug) - printf("password: %s\n", password); - if (password) - password = strdup(password); - ldap_value_free(values); - ldap_msgfree(res); - return password; - } else { - fprintf(stderr, PROGRAM_NAME " WARNING, LDAP error '%s'\n", ldap_err2string(rc)); - /* try to connect to the LDAP server agin, maybe my persisten conexion failed. */ - if (!retry) { - retry++; - ldap_unbind(ld); - ld = NULL; - ldapconnect(); - goto retrydnattr; - } - return NULL; - } + fprintf(stderr, PROGRAM_NAME " WARNING, LDAP search error, trying to recover'%s'\n", ldap_err2string(rc)); + ldap_msgfree(res); + /* try to connect to the LDAP server agin, maybe my persisten conexion failed. */ + if (!retry) { + retry++; + ldap_unbind(ld); + ld = NULL; + ldapconnect(); + goto retrysrch; + } + return NULL; + + } + } + } else if (userdnattr) { + sprintf(searchbase, "%s=%s, %s", userdnattr, login, userbasedn); + +retrydnattr: + if (debug) + fprintf(stderr, "searchbase '%s'\n", searchbase); + rc = ldap_search_s(ld, searchbase, searchscope, NULL, NULL, 0, &res); + } + if (rc == LDAP_SUCCESS) { + entry = ldap_first_entry(ld, res); + if (entry) + values = ldap_get_values(ld, entry, passattr); + else { + ldap_msgfree(res); + return NULL; + } + if (!values) { + if (debug) + printf("No attribute value found\n"); + ldap_msgfree(res); + return NULL; + } + value = values; + while (*value) { + if (encrpass) { + if (strcmp(strtok(*value, delimiter), realm) == 0) { + password = strtok(NULL, delimiter); + break; + } + } else { + password = *value; + break; + } + value++; + } + if (debug) + printf("password: %s\n", password); + if (password) + password = strdup(password); + ldap_value_free(values); + ldap_msgfree(res); + return password; + } else { + fprintf(stderr, PROGRAM_NAME " WARNING, LDAP error '%s'\n", ldap_err2string(rc)); + /* try to connect to the LDAP server agin, maybe my persisten conexion failed. */ + if (!retry) { + retry++; + ldap_unbind(ld); + ld = NULL; + ldapconnect(); + goto retrydnattr; + } + return NULL; + } } return NULL; } @@ -301,91 +301,91 @@ ldapconnect(void) { int rc; -/* On Windows ldap_start_tls_s is available starting from Windows XP, - * so we need to bind at run-time with the function entry point - */ + /* On Windows ldap_start_tls_s is available starting from Windows XP, + * so we need to bind at run-time with the function entry point + */ #ifdef _SQUID_MSWIN_ if (use_tls) { - HMODULE WLDAP32Handle; + HMODULE WLDAP32Handle; - WLDAP32Handle = GetModuleHandle("wldap32"); - if ((Win32_ldap_start_tls_s = (PFldap_start_tls_s) GetProcAddress(WLDAP32Handle, LDAP_START_TLS_S)) == NULL) { - fprintf(stderr, PROGRAM_NAME ": ERROR: TLS (-Z) not supported on this platform.\n"); - exit(1); - } + WLDAP32Handle = GetModuleHandle("wldap32"); + if ((Win32_ldap_start_tls_s = (PFldap_start_tls_s) GetProcAddress(WLDAP32Handle, LDAP_START_TLS_S)) == NULL) { + fprintf(stderr, PROGRAM_NAME ": ERROR: TLS (-Z) not supported on this platform.\n"); + exit(1); + } } #endif if (ld == NULL) { #if HAS_URI_SUPPORT - if (strstr(ldapServer, "://") != NULL) { - rc = ldap_initialize(&ld, ldapServer); - if (rc != LDAP_SUCCESS) { - fprintf(stderr, "\nUnable to connect to LDAPURI:%s\n", ldapServer); - } - } else + if (strstr(ldapServer, "://") != NULL) { + rc = ldap_initialize(&ld, ldapServer); + if (rc != LDAP_SUCCESS) { + fprintf(stderr, "\nUnable to connect to LDAPURI:%s\n", ldapServer); + } + } else #endif #if NETSCAPE_SSL - if (sslpath) { - if (!sslinit && (ldapssl_client_init(sslpath, NULL) != LDAP_SUCCESS)) { - fprintf(stderr, "\nUnable to initialise SSL with cert path %s\n", - sslpath); - exit(1); - } else { - sslinit++; - } - if ((ld = ldapssl_init(ldapServer, port, 1)) == NULL) { - fprintf(stderr, "\nUnable to connect to SSL LDAP server: %s port:%d\n", - ldapServer, port); - exit(1); - } - } else + if (sslpath) { + if (!sslinit && (ldapssl_client_init(sslpath, NULL) != LDAP_SUCCESS)) { + fprintf(stderr, "\nUnable to initialise SSL with cert path %s\n", + sslpath); + exit(1); + } else { + sslinit++; + } + if ((ld = ldapssl_init(ldapServer, port, 1)) == NULL) { + fprintf(stderr, "\nUnable to connect to SSL LDAP server: %s port:%d\n", + ldapServer, port); + exit(1); + } + } else #endif - if ((ld = ldap_init(ldapServer, port)) == NULL) { - fprintf(stderr, "\nUnable to connect to LDAP server:%s port:%d\n", ldapServer, port); - } - if (connect_timeout) - squid_ldap_set_connect_timeout(connect_timeout); + if ((ld = ldap_init(ldapServer, port)) == NULL) { + fprintf(stderr, "\nUnable to connect to LDAP server:%s port:%d\n", ldapServer, port); + } + if (connect_timeout) + squid_ldap_set_connect_timeout(connect_timeout); #ifdef LDAP_VERSION3 - if (version == -1) { - version = LDAP_VERSION2; - } - if (ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &version) - != LDAP_SUCCESS) { - fprintf(stderr, "Could not set LDAP_OPT_PROTOCOL_VERSION %d\n", - version); - ldap_unbind(ld); - ld = NULL; - } - if (use_tls) { + if (version == -1) { + version = LDAP_VERSION2; + } + if (ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &version) + != LDAP_SUCCESS) { + fprintf(stderr, "Could not set LDAP_OPT_PROTOCOL_VERSION %d\n", + version); + ldap_unbind(ld); + ld = NULL; + } + if (use_tls) { #ifdef LDAP_OPT_X_TLS - if ((version == LDAP_VERSION3) && (ldap_start_tls_s(ld, NULL, NULL) == LDAP_SUCCESS)) { - fprintf(stderr, "Could not Activate TLS connection\n"); - ldap_unbind(ld); - ld = NULL; - } + if ((version == LDAP_VERSION3) && (ldap_start_tls_s(ld, NULL, NULL) == LDAP_SUCCESS)) { + fprintf(stderr, "Could not Activate TLS connection\n"); + ldap_unbind(ld); + ld = NULL; + } #else - fprintf(stderr, "TLS not supported with your LDAP library\n"); - ldap_unbind(ld); - ld = NULL; + fprintf(stderr, "TLS not supported with your LDAP library\n"); + ldap_unbind(ld); + ld = NULL; #endif - } + } #endif - squid_ldap_set_timelimit(timelimit); - squid_ldap_set_referrals(!noreferrals); - squid_ldap_set_aliasderef(aliasderef); - if (binddn && bindpasswd && *binddn && *bindpasswd) { - rc = ldap_simple_bind_s(ld, binddn, bindpasswd); - if (rc != LDAP_SUCCESS) { - fprintf(stderr, PROGRAM_NAME " WARNING, could not bind to binddn '%s'\n", ldap_err2string(rc)); - ldap_unbind(ld); - ld = NULL; - } - } - if (debug) - fprintf(stderr, "Connected OK\n"); + squid_ldap_set_timelimit(timelimit); + squid_ldap_set_referrals(!noreferrals); + squid_ldap_set_aliasderef(aliasderef); + if (binddn && bindpasswd && *binddn && *bindpasswd) { + rc = ldap_simple_bind_s(ld, binddn, bindpasswd); + if (rc != LDAP_SUCCESS) { + fprintf(stderr, PROGRAM_NAME " WARNING, could not bind to binddn '%s'\n", ldap_err2string(rc)); + ldap_unbind(ld); + ld = NULL; + } + } + if (debug) + fprintf(stderr, "Connected OK\n"); } } int @@ -394,213 +394,213 @@ LDAPArguments(int argc, char **argv) setbuf(stdout, NULL); while (argc > 1 && argv[1][0] == '-') { - const char *value = ""; - char option = argv[1][1]; - switch (option) { - case 'P': - case 'R': - case 'z': - case 'Z': - case 'g': - case 'e': - case 'S': - break; - default: - if (strlen(argv[1]) > 2) { - value = argv[1] + 2; - } else if (argc > 2) { - value = argv[2]; - argv++; - argc--; - } else - value = ""; - break; - } - argv++; - argc--; - switch (option) { - case 'H': + const char *value = ""; + char option = argv[1][1]; + switch (option) { + case 'P': + case 'R': + case 'z': + case 'Z': + case 'g': + case 'e': + case 'S': + break; + default: + if (strlen(argv[1]) > 2) { + value = argv[1] + 2; + } else if (argc > 2) { + value = argv[2]; + argv++; + argc--; + } else + value = ""; + break; + } + argv++; + argc--; + switch (option) { + case 'H': #if !HAS_URI_SUPPORT - fprintf(stderr, "ERROR: Your LDAP library does not have URI support\n"); - return 1; + fprintf(stderr, "ERROR: Your LDAP library does not have URI support\n"); + return 1; #endif - /* Fall thru to -h */ - case 'h': - if (ldapServer) { - int len = strlen(ldapServer) + 1 + strlen(value) + 1; - char *newhost = malloc(len); - snprintf(newhost, len, "%s %s", ldapServer, value); - free(ldapServer); - ldapServer = newhost; - } else { - ldapServer = strdup(value); - } - break; - case 'A': - passattr = value; - break; - case 'e': - encrpass = 1; - break; - case 'l': - delimiter = value; - break; - case 'b': - userbasedn = value; - break; - case 'F': - usersearchfilter = value; - break; - case 'u': - userdnattr = value; - break; - case 's': - if (strcmp(value, "base") == 0) - searchscope = LDAP_SCOPE_BASE; - else if (strcmp(value, "one") == 0) - searchscope = LDAP_SCOPE_ONELEVEL; - else if (strcmp(value, "sub") == 0) - searchscope = LDAP_SCOPE_SUBTREE; - else { - fprintf(stderr, PROGRAM_NAME " ERROR: Unknown search scope '%s'\n", value); - return 1; - } - break; - case 'S': + /* Fall thru to -h */ + case 'h': + if (ldapServer) { + int len = strlen(ldapServer) + 1 + strlen(value) + 1; + char *newhost = malloc(len); + snprintf(newhost, len, "%s %s", ldapServer, value); + free(ldapServer); + ldapServer = newhost; + } else { + ldapServer = strdup(value); + } + break; + case 'A': + passattr = value; + break; + case 'e': + encrpass = 1; + break; + case 'l': + delimiter = value; + break; + case 'b': + userbasedn = value; + break; + case 'F': + usersearchfilter = value; + break; + case 'u': + userdnattr = value; + break; + case 's': + if (strcmp(value, "base") == 0) + searchscope = LDAP_SCOPE_BASE; + else if (strcmp(value, "one") == 0) + searchscope = LDAP_SCOPE_ONELEVEL; + else if (strcmp(value, "sub") == 0) + searchscope = LDAP_SCOPE_SUBTREE; + else { + fprintf(stderr, PROGRAM_NAME " ERROR: Unknown search scope '%s'\n", value); + return 1; + } + break; + case 'S': #if defined(NETSCAPE_SSL) - sslpath = value; - if (port == LDAP_PORT) - port = LDAPS_PORT; + sslpath = value; + if (port == LDAP_PORT) + port = LDAPS_PORT; #else - fprintf(stderr, PROGRAM_NAME " ERROR: -E unsupported with this LDAP library\n"); - return 1; + fprintf(stderr, PROGRAM_NAME " ERROR: -E unsupported with this LDAP library\n"); + return 1; #endif - break; - case 'c': - connect_timeout = atoi(value); - break; - case 't': - timelimit = atoi(value); - break; - case 'a': - if (strcmp(value, "never") == 0) - aliasderef = LDAP_DEREF_NEVER; - else if (strcmp(value, "always") == 0) - aliasderef = LDAP_DEREF_ALWAYS; - else if (strcmp(value, "search") == 0) - aliasderef = LDAP_DEREF_SEARCHING; - else if (strcmp(value, "find") == 0) - aliasderef = LDAP_DEREF_FINDING; - else { - fprintf(stderr, PROGRAM_NAME " ERROR: Unknown alias dereference method '%s'\n", value); - return 1; - } - break; - case 'D': - binddn = value; - break; - case 'w': - bindpasswd = value; - break; - case 'W': - readSecret(value); - break; - case 'P': - persistent = !persistent; - break; - case 'p': - port = atoi(value); - break; - case 'R': - noreferrals = !noreferrals; - break; + break; + case 'c': + connect_timeout = atoi(value); + break; + case 't': + timelimit = atoi(value); + break; + case 'a': + if (strcmp(value, "never") == 0) + aliasderef = LDAP_DEREF_NEVER; + else if (strcmp(value, "always") == 0) + aliasderef = LDAP_DEREF_ALWAYS; + else if (strcmp(value, "search") == 0) + aliasderef = LDAP_DEREF_SEARCHING; + else if (strcmp(value, "find") == 0) + aliasderef = LDAP_DEREF_FINDING; + else { + fprintf(stderr, PROGRAM_NAME " ERROR: Unknown alias dereference method '%s'\n", value); + return 1; + } + break; + case 'D': + binddn = value; + break; + case 'w': + bindpasswd = value; + break; + case 'W': + readSecret(value); + break; + case 'P': + persistent = !persistent; + break; + case 'p': + port = atoi(value); + break; + case 'R': + noreferrals = !noreferrals; + break; #ifdef LDAP_VERSION3 - case 'v': - switch (atoi(value)) { - case 2: - version = LDAP_VERSION2; - break; - case 3: - version = LDAP_VERSION3; - break; - default: - fprintf(stderr, "Protocol version should be 2 or 3\n"); - return 1; - } - break; - case 'Z': - if (version == LDAP_VERSION2) { - fprintf(stderr, "TLS (-Z) is incompatible with version %d\n", - version); - return 1; - } - version = LDAP_VERSION3; - use_tls = 1; - break; + case 'v': + switch (atoi(value)) { + case 2: + version = LDAP_VERSION2; + break; + case 3: + version = LDAP_VERSION3; + break; + default: + fprintf(stderr, "Protocol version should be 2 or 3\n"); + return 1; + } + break; + case 'Z': + if (version == LDAP_VERSION2) { + fprintf(stderr, "TLS (-Z) is incompatible with version %d\n", + version); + return 1; + } + version = LDAP_VERSION3; + use_tls = 1; + break; #endif - case 'd': - debug = 1; - break; - case 'E': - strip_nt_domain = 1; - break; - default: - fprintf(stderr, PROGRAM_NAME " ERROR: Unknown command line option '%c'\n", option); - return 1; - } + case 'd': + debug = 1; + break; + case 'E': + strip_nt_domain = 1; + break; + default: + fprintf(stderr, PROGRAM_NAME " ERROR: Unknown command line option '%c'\n", option); + return 1; + } } while (argc > 1) { - char *value = argv[1]; - if (ldapServer) { - int len = strlen(ldapServer) + 1 + strlen(value) + 1; - char *newhost = malloc(len); - snprintf(newhost, len, "%s %s", ldapServer, value); - free(ldapServer); - ldapServer = newhost; - } else { - ldapServer = strdup(value); - } - argc--; - argv++; + char *value = argv[1]; + if (ldapServer) { + int len = strlen(ldapServer) + 1 + strlen(value) + 1; + char *newhost = malloc(len); + snprintf(newhost, len, "%s %s", ldapServer, value); + free(ldapServer); + ldapServer = newhost; + } else { + ldapServer = strdup(value); + } + argc--; + argv++; } if (!ldapServer) - ldapServer = (char *) "localhost"; + ldapServer = (char *) "localhost"; if (!userbasedn || !passattr) { - fprintf(stderr, "Usage: " PROGRAM_NAME " -b basedn -f filter [options] ldap_server_name\n\n"); - fprintf(stderr, "\t-A password attribute(REQUIRED)\t\tUser attribute that contains the password\n"); - fprintf(stderr, "\t-l password realm delimiter(REQUIRED)\tCharater(s) that devides the password attribute\n\t\t\t\t\t\tin realm and password tokens, default ':' realm:password\n"); - fprintf(stderr, "\t-b basedn (REQUIRED)\t\t\tbase dn under where to search for users\n"); - fprintf(stderr, "\t-e Encrypted passwords(REQUIRED)\tPassword are stored encrypted using HHA1\n"); - fprintf(stderr, "\t-F filter\t\t\t\tuser search filter pattern. %%s = login\n"); - fprintf(stderr, "\t-u attribute\t\t\t\tattribute to use in combination with the basedn to create the user DN\n"); - fprintf(stderr, "\t-s base|one|sub\t\t\t\tsearch scope\n"); - fprintf(stderr, "\t-D binddn\t\t\t\tDN to bind as to perform searches\n"); - fprintf(stderr, "\t-w bindpasswd\t\t\t\tpassword for binddn\n"); - fprintf(stderr, "\t-W secretfile\t\t\t\tread password for binddn from file secretfile\n"); + fprintf(stderr, "Usage: " PROGRAM_NAME " -b basedn -f filter [options] ldap_server_name\n\n"); + fprintf(stderr, "\t-A password attribute(REQUIRED)\t\tUser attribute that contains the password\n"); + fprintf(stderr, "\t-l password realm delimiter(REQUIRED)\tCharater(s) that devides the password attribute\n\t\t\t\t\t\tin realm and password tokens, default ':' realm:password\n"); + fprintf(stderr, "\t-b basedn (REQUIRED)\t\t\tbase dn under where to search for users\n"); + fprintf(stderr, "\t-e Encrypted passwords(REQUIRED)\tPassword are stored encrypted using HHA1\n"); + fprintf(stderr, "\t-F filter\t\t\t\tuser search filter pattern. %%s = login\n"); + fprintf(stderr, "\t-u attribute\t\t\t\tattribute to use in combination with the basedn to create the user DN\n"); + fprintf(stderr, "\t-s base|one|sub\t\t\t\tsearch scope\n"); + fprintf(stderr, "\t-D binddn\t\t\t\tDN to bind as to perform searches\n"); + fprintf(stderr, "\t-w bindpasswd\t\t\t\tpassword for binddn\n"); + fprintf(stderr, "\t-W secretfile\t\t\t\tread password for binddn from file secretfile\n"); #if HAS_URI_SUPPORT - fprintf(stderr, "\t-H URI\t\t\t\t\tLDAPURI (defaults to ldap://localhost)\n"); + fprintf(stderr, "\t-H URI\t\t\t\t\tLDAPURI (defaults to ldap://localhost)\n"); #endif - fprintf(stderr, "\t-h server\t\t\t\tLDAP server (defaults to localhost)\n"); - fprintf(stderr, "\t-p port\t\t\t\t\tLDAP server port (defaults to %d)\n", LDAP_PORT); - fprintf(stderr, "\t-P\t\t\t\t\tpersistent LDAP connection\n"); + fprintf(stderr, "\t-h server\t\t\t\tLDAP server (defaults to localhost)\n"); + fprintf(stderr, "\t-p port\t\t\t\t\tLDAP server port (defaults to %d)\n", LDAP_PORT); + fprintf(stderr, "\t-P\t\t\t\t\tpersistent LDAP connection\n"); #if defined(NETSCAPE_SSL) - fprintf(stderr, "\t-E sslcertpath\t\t\t\tenable LDAP over SSL\n"); + fprintf(stderr, "\t-E sslcertpath\t\t\t\tenable LDAP over SSL\n"); #endif - fprintf(stderr, "\t-c timeout\t\t\t\tconnect timeout\n"); - fprintf(stderr, "\t-t timelimit\t\t\t\tsearch time limit\n"); - fprintf(stderr, "\t-R\t\t\t\t\tdo not follow referrals\n"); - fprintf(stderr, "\t-a never|always|search|find\t\twhen to dereference aliases\n"); + fprintf(stderr, "\t-c timeout\t\t\t\tconnect timeout\n"); + fprintf(stderr, "\t-t timelimit\t\t\t\tsearch time limit\n"); + fprintf(stderr, "\t-R\t\t\t\t\tdo not follow referrals\n"); + fprintf(stderr, "\t-a never|always|search|find\t\twhen to dereference aliases\n"); #ifdef LDAP_VERSION3 - fprintf(stderr, "\t-v 2|3\t\t\t\t\tLDAP version\n"); - fprintf(stderr, "\t-Z\t\t\t\t\tTLS encrypt the LDAP connection, requires\n\t\t\t\tLDAP version 3\n"); + fprintf(stderr, "\t-v 2|3\t\t\t\t\tLDAP version\n"); + fprintf(stderr, "\t-Z\t\t\t\t\tTLS encrypt the LDAP connection, requires\n\t\t\t\tLDAP version 3\n"); #endif - fprintf(stderr, "\t-S\t\t\t\t\tStrip NT domain from usernames\n"); - fprintf(stderr, "\n"); - fprintf(stderr, "\tIf you need to bind as a user to perform searches then use the\n\t-D binddn -w bindpasswd or -D binddn -W secretfile options\n\n"); - return -1; + fprintf(stderr, "\t-S\t\t\t\t\tStrip NT domain from usernames\n"); + fprintf(stderr, "\n"); + fprintf(stderr, "\tIf you need to bind as a user to perform searches then use the\n\t-D binddn -w bindpasswd or -D binddn -W secretfile options\n\n"); + return -1; } return 0; } @@ -612,23 +612,23 @@ readSecret(const char *filename) FILE *f; if (!(f = fopen(filename, "r"))) { - fprintf(stderr, PROGRAM_NAME " ERROR: Can not read secret file %s\n", filename); - return 1; + fprintf(stderr, PROGRAM_NAME " ERROR: Can not read secret file %s\n", filename); + return 1; } if (!fgets(buf, sizeof(buf) - 1, f)) { - fprintf(stderr, PROGRAM_NAME " ERROR: Secret file %s is empty\n", filename); - fclose(f); - return 1; + fprintf(stderr, PROGRAM_NAME " ERROR: Secret file %s is empty\n", filename); + fclose(f); + return 1; } /* strip whitespaces on end */ if ((e = strrchr(buf, '\n'))) - *e = 0; + *e = 0; if ((e = strrchr(buf, '\r'))) - *e = 0; + *e = 0; bindpasswd = strdup(buf); if (!bindpasswd) { - fprintf(stderr, PROGRAM_NAME " ERROR: can not allocate memory\n"); + fprintf(stderr, PROGRAM_NAME " ERROR: can not allocate memory\n"); } fclose(f); @@ -642,15 +642,15 @@ LDAPHHA1(RequestData * requestData) ldapconnect(); password = getpassword(requestData->user, requestData->realm); if (password != NULL) { - if (encrpass) - xstrncpy(requestData->HHA1, password, sizeof(requestData->HHA1)); - else { - HASH HA1; - DigestCalcHA1("md5", requestData->user, requestData->realm, password, NULL, NULL, HA1, requestData->HHA1); - } - free(password); + if (encrpass) + xstrncpy(requestData->HHA1, password, sizeof(requestData->HHA1)); + else { + HASH HA1; + DigestCalcHA1("md5", requestData->user, requestData->realm, password, NULL, NULL, HA1, requestData->HHA1); + } + free(password); } else { - requestData->error = -1; + requestData->error = -1; } } diff --git a/helpers/digest_auth/password/digest_common.h b/helpers/digest_auth/password/digest_common.h index 8804745aab..42affb8cc9 100644 --- a/helpers/digest_auth/password/digest_common.h +++ b/helpers/digest_auth/password/digest_common.h @@ -47,8 +47,8 @@ typedef struct _request_data { int error; } RequestData; -/* to use a backend, include your backend.h file - * and define thusly: +/* to use a backend, include your backend.h file + * and define thusly: * #define ProcessArguments(A, B) MyHandleArguments(A,B) * #define GetHHA1(A) MyGetHHA1(A) */ diff --git a/helpers/digest_auth/password/digest_pw_auth.c b/helpers/digest_auth/password/digest_pw_auth.c index 57e10eb419..65e6cc6137 100644 --- a/helpers/digest_auth/password/digest_pw_auth.c +++ b/helpers/digest_auth/password/digest_pw_auth.c @@ -12,7 +12,7 @@ * - comment lines are possible and should start with a '#'; * - empty or blank lines are possible; * - file format is username:password - * + * * To build a directory integrated backend, you need to be able to * calculate the HA1 returned to squid. To avoid storing a plaintext * password you can calculate MD5(username:realm:password) when the @@ -46,13 +46,13 @@ ParseBuffer(char *buf, RequestData * requestData) char *p; requestData->parsed = 0; if ((p = strchr(buf, '\n')) != NULL) - *p = '\0'; /* strip \n */ + *p = '\0'; /* strip \n */ if ((requestData->user = strtok(buf, "\"")) == NULL) - return; + return; if ((requestData->realm = strtok(NULL, "\"")) == NULL) - return; + return; if ((requestData->realm = strtok(NULL, "\"")) == NULL) - return; + return; requestData->parsed = -1; } @@ -62,8 +62,8 @@ OutputHHA1(RequestData * requestData) requestData->error = 0; GetHHA1(requestData); if (requestData->error) { - printf("ERR No such user\n"); - return; + printf("ERR No such user\n"); + return; } printf("%s\n", requestData->HHA1); } @@ -74,8 +74,8 @@ DoOneRequest(char *buf) RequestData requestData; ParseBuffer(buf, &requestData); if (!requestData.parsed) { - printf("ERR\n"); - return; + printf("ERR\n"); + return; } OutputHHA1(&requestData); } @@ -93,6 +93,6 @@ main(int argc, char **argv) setbuf(stdout, NULL); ProcessArguments(argc, argv); while (fgets(buf, 256, stdin) != NULL) - DoOneRequest(buf); + DoOneRequest(buf); exit(0); } diff --git a/helpers/digest_auth/password/text_backend.c b/helpers/digest_auth/password/text_backend.c index 78a94a885e..384045670d 100644 --- a/helpers/digest_auth/password/text_backend.c +++ b/helpers/digest_auth/password/text_backend.c @@ -11,7 +11,7 @@ * - comment lines are possible and should start with a '#'; * - empty or blank lines are possible; * - file format is username:plaintext or username:realm:HA1 - * + * * To build a directory integrated backend, you need to be able to * calculate the HA1 returned to squid. To avoid storing a plaintext * password you can calculate MD5(username:realm:password) when the @@ -64,55 +64,55 @@ read_passwd_file(const char *passwdfile, int ha1mode) char *realm; if (hash != NULL) { - hashFreeItems(hash, my_free); + hashFreeItems(hash, my_free); } /* initial setup */ hash = hash_create((HASHCMP *) strcmp, 7921, hash_string); if (NULL == hash) { - fprintf(stderr, "digest_pw_auth: cannot create hash table\n"); - exit(1); + fprintf(stderr, "digest_pw_auth: cannot create hash table\n"); + exit(1); } f = fopen(passwdfile, "r"); while (fgets(buf, 8192, f) != NULL) { - if ((buf[0] == '#') || (buf[0] == ' ') || (buf[0] == '\t') || - (buf[0] == '\n')) - continue; - user = strtok(buf, ":\n"); - realm = strtok(NULL, ":\n"); - passwd = strtok(NULL, ":\n"); - if (!passwd) { - passwd = realm; - realm = NULL; - } - if ((strlen(user) > 0) && passwd) { - if (strncmp(passwd, "{HHA1}", 6) == 0) { - ha1 = passwd + 6; - passwd = NULL; - } else if (ha1mode) { - ha1 = passwd; - passwd = NULL; - } - if (ha1 && strlen(ha1) != 32) { - /* We cannot accept plaintext passwords when using HA1 encoding, - * as the passwords may be output to cache.log if debugging is on. - */ - fprintf(stderr, "digest_pw_auth: ignoring invalid password for %s\n", user); - continue; - } - u = xcalloc(1, sizeof(*u)); - if (realm) { - int len = strlen(user) + strlen(realm) + 2; - u->hash.key = malloc(len); - snprintf(u->hash.key, len, "%s:%s", user, realm); - } else { - u->hash.key = xstrdup(user); - } - if (ha1) - u->ha1 = xstrdup(ha1); - else - u->passwd = xstrdup(passwd); - hash_join(hash, &u->hash); - } + if ((buf[0] == '#') || (buf[0] == ' ') || (buf[0] == '\t') || + (buf[0] == '\n')) + continue; + user = strtok(buf, ":\n"); + realm = strtok(NULL, ":\n"); + passwd = strtok(NULL, ":\n"); + if (!passwd) { + passwd = realm; + realm = NULL; + } + if ((strlen(user) > 0) && passwd) { + if (strncmp(passwd, "{HHA1}", 6) == 0) { + ha1 = passwd + 6; + passwd = NULL; + } else if (ha1mode) { + ha1 = passwd; + passwd = NULL; + } + if (ha1 && strlen(ha1) != 32) { + /* We cannot accept plaintext passwords when using HA1 encoding, + * as the passwords may be output to cache.log if debugging is on. + */ + fprintf(stderr, "digest_pw_auth: ignoring invalid password for %s\n", user); + continue; + } + u = xcalloc(1, sizeof(*u)); + if (realm) { + int len = strlen(user) + strlen(realm) + 2; + u->hash.key = malloc(len); + snprintf(u->hash.key, len, "%s:%s", user, realm); + } else { + u->hash.key = xstrdup(user); + } + if (ha1) + u->ha1 = xstrdup(ha1); + else + u->passwd = xstrdup(passwd); + hash_join(hash, &u->hash); + } } fclose(f); } @@ -123,19 +123,19 @@ TextArguments(int argc, char **argv) { struct stat sb; if (argc == 2) - passwdfile = argv[1]; + passwdfile = argv[1]; if ((argc == 3) && !strcmp("-c", argv[1])) { - ha1mode = 1; - passwdfile = argv[2]; + ha1mode = 1; + passwdfile = argv[2]; } if (!passwdfile) { - fprintf(stderr, "Usage: digest_pw_auth [OPTIONS] \n"); - fprintf(stderr, " -c accept digest hashed passwords rather than plaintext in passwordfile\n"); - exit(1); + fprintf(stderr, "Usage: digest_pw_auth [OPTIONS] \n"); + fprintf(stderr, " -c accept digest hashed passwords rather than plaintext in passwordfile\n"); + exit(1); } if (stat(passwdfile, &sb) != 0) { - fprintf(stderr, "cannot stat %s\n", passwdfile); - exit(1); + fprintf(stderr, "cannot stat %s\n", passwdfile); + exit(1); } } @@ -147,19 +147,19 @@ GetPassword(RequestData * requestData) char buf[256]; int len; if (stat(passwdfile, &sb) == 0) { - if (sb.st_mtime != change_time) { - read_passwd_file(passwdfile, ha1mode); - change_time = sb.st_mtime; - } + if (sb.st_mtime != change_time) { + read_passwd_file(passwdfile, ha1mode); + change_time = sb.st_mtime; + } } if (!hash) - return NULL; + return NULL; len = snprintf(buf, sizeof(buf), "%s:%s", requestData->user, requestData->realm); if (len >= sizeof(buf)) - return NULL; + return NULL; u = (user_data *) hash_lookup(hash, buf); if (u) - return u; + return u; u = (user_data *) hash_lookup(hash, requestData->user); return u; } @@ -169,13 +169,13 @@ TextHHA1(RequestData * requestData) { const user_data *u = GetPassword(requestData); if (!u) { - requestData->error = -1; - return; + requestData->error = -1; + return; } if (u->ha1) { - xstrncpy(requestData->HHA1, u->ha1, sizeof(requestData->HHA1)); + xstrncpy(requestData->HHA1, u->ha1, sizeof(requestData->HHA1)); } else { - HASH HA1; - DigestCalcHA1("md5", requestData->user, requestData->realm, u->passwd, NULL, NULL, HA1, requestData->HHA1); + HASH HA1; + DigestCalcHA1("md5", requestData->user, requestData->realm, u->passwd, NULL, NULL, HA1, requestData->HHA1); } } diff --git a/helpers/digest_auth/password/text_backend.h b/helpers/digest_auth/password/text_backend.h index 7c9aee6db4..63c69c9759 100644 --- a/helpers/digest_auth/password/text_backend.h +++ b/helpers/digest_auth/password/text_backend.h @@ -8,7 +8,7 @@ * - comment lines are possible and should start with a '#'; * - empty or blank lines are possible; * - file format is username:password - * + * * This implementation could be improved by using such a triple for * the file format. However storing such a triple does little to * improve security: If compromised the username:realm:HA1 combination diff --git a/helpers/external_acl/ip_user/dict.c b/helpers/external_acl/ip_user/dict.c index 830355ac6e..ce2064699e 100644 --- a/helpers/external_acl/ip_user/dict.c +++ b/helpers/external_acl/ip_user/dict.c @@ -1,24 +1,24 @@ -/* $Id: dict.c,v 1.2 2003/01/23 00:36:01 robertc Exp $ +/* $Id: dict.c,v 1.2 2003/01/23 00:36:01 robertc Exp $ * Copyright (C) 2002 Rodrigo Campos * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. -* +* * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. -* +* * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * Author: Rodrigo Campos (rodrigo@geekbunker.org) -* +* */ - + #include #include #include @@ -34,7 +34,7 @@ #endif -/* This function parses the dictionary file and loads it +/* This function parses the dictionary file and loads it * in memory. All IP addresses are processed with a bitwise AND * with their netmasks before they are stored. * If there´s no netmask (no /) in the in the lhs , a mask @@ -42,66 +42,65 @@ * It returns a pointer to the first entry of the linked list */ struct ip_user_dict * -load_dict (FILE * FH) -{ - struct ip_user_dict *current_entry; /* the structure used to + load_dict (FILE * FH) { + struct ip_user_dict *current_entry; /* the structure used to store data */ - struct ip_user_dict *first_entry = NULL; /* the head of the + struct ip_user_dict *first_entry = NULL; /* the head of the linked list */ - char line[BUFSIZE]; /* the buffer for the lines read + char line[BUFSIZE]; /* the buffer for the lines read from the dict file */ - char *cp; /* a char pointer used to parse + char *cp; /* a char pointer used to parse each line */ - char *username; /* for the username */ - char *tmpbuf; /* for the address before the + char *username; /* for the username */ + char *tmpbuf; /* for the address before the bitwise AND */ - /* the pointer to the first entry in the linked list */ - first_entry = malloc (sizeof (struct ip_user_dict)); - current_entry = first_entry; + /* the pointer to the first entry in the linked list */ + first_entry = malloc (sizeof (struct ip_user_dict)); + current_entry = first_entry; - while ((cp = fgets (line, sizeof (line), FH)) != NULL) { - if (line[0] == '#') { - continue; - } - if ((cp = strchr (line, '\n')) != NULL) { - /* chop \n characters */ - *cp = '\0'; - } - if ((cp = strtok (line, "\t ")) != NULL) { - /* get the username */ - username = strtok (NULL, "\t "); - /* look for a netmask */ - if ((cp = strtok (line, "/")) != NULL) { - /* store the ip address in a temporary buffer */ - tmpbuf = cp; - cp = strtok (NULL, "/"); - if (cp != NULL) { - /* if we have a slash in the lhs, we have a netmask */ - current_entry->netmask = (inet_addr (cp)); - current_entry->address = - (((inet_addr (tmpbuf))) & current_entry->netmask); - } else { - /* when theres no slash, we figure the netmask is /32 */ - current_entry->address = (inet_addr (tmpbuf)); - current_entry->netmask = (inet_addr ("255.255.255.255")); - } - } - /* get space for the username */ - current_entry->username = - calloc (strlen (username) + 1, sizeof (char)); - strcpy (current_entry->username, username); + while ((cp = fgets (line, sizeof (line), FH)) != NULL) { + if (line[0] == '#') { + continue; + } + if ((cp = strchr (line, '\n')) != NULL) { + /* chop \n characters */ + *cp = '\0'; + } + if ((cp = strtok (line, "\t ")) != NULL) { + /* get the username */ + username = strtok (NULL, "\t "); + /* look for a netmask */ + if ((cp = strtok (line, "/")) != NULL) { + /* store the ip address in a temporary buffer */ + tmpbuf = cp; + cp = strtok (NULL, "/"); + if (cp != NULL) { + /* if we have a slash in the lhs, we have a netmask */ + current_entry->netmask = (inet_addr (cp)); + current_entry->address = + (((inet_addr (tmpbuf))) & current_entry->netmask); + } else { + /* when theres no slash, we figure the netmask is /32 */ + current_entry->address = (inet_addr (tmpbuf)); + current_entry->netmask = (inet_addr ("255.255.255.255")); + } + } + /* get space for the username */ + current_entry->username = + calloc (strlen (username) + 1, sizeof (char)); + strcpy (current_entry->username, username); - /* get space and point current_entry to the new entry */ - current_entry->next_entry = - malloc (sizeof (struct ip_user_dict)); - current_entry = current_entry->next_entry; - } + /* get space and point current_entry to the new entry */ + current_entry->next_entry = + malloc (sizeof (struct ip_user_dict)); + current_entry = current_entry->next_entry; + } - } + } - /* Return a pointer to the first entry linked list */ - return first_entry; + /* Return a pointer to the first entry linked list */ + return first_entry; } /* load_dict */ /* This function looks for a matching ip/mask in @@ -110,33 +109,33 @@ load_dict (FILE * FH) */ int dict_lookup (struct ip_user_dict *first_entry, char *username, - char *address) + char *address) { - /* Move the pointer to the first entry of the linked list. */ - struct ip_user_dict *current_entry = first_entry; + /* Move the pointer to the first entry of the linked list. */ + struct ip_user_dict *current_entry = first_entry; - while (current_entry->username != NULL) { + while (current_entry->username != NULL) { #ifdef DEBUG - printf ("user: %s\naddr: %lu\nmask: %lu\n\n", - current_entry->username, current_entry->address, - current_entry->netmask); + printf ("user: %s\naddr: %lu\nmask: %lu\n\n", + current_entry->username, current_entry->address, + current_entry->netmask); #endif - if ((inet_addr (address) & (unsigned long) current_entry-> - netmask) == current_entry->address) { - /* If the username contains an @ we assume it´s a group and - call the corresponding function */ - if ((strchr (current_entry->username, '@')) == NULL) { - if ((match_user (current_entry->username, username)) == 1) - return 1; - } else { - if ((match_group (current_entry->username, username)) == 1) - return 1; - } + if ((inet_addr (address) & (unsigned long) current_entry-> + netmask) == current_entry->address) { + /* If the username contains an @ we assume it´s a group and + call the corresponding function */ + if ((strchr (current_entry->username, '@')) == NULL) { + if ((match_user (current_entry->username, username)) == 1) + return 1; + } else { + if ((match_group (current_entry->username, username)) == 1) + return 1; + } + } + current_entry = current_entry->next_entry; } - current_entry = current_entry->next_entry; - } - /* If no match was found we return 0 */ - return 0; + /* If no match was found we return 0 */ + return 0; } /* dict_lookup */ diff --git a/helpers/external_acl/ip_user/ip_user.h b/helpers/external_acl/ip_user/ip_user.h index b6b8093793..5cb31fce84 100644 --- a/helpers/external_acl/ip_user/ip_user.h +++ b/helpers/external_acl/ip_user/ip_user.h @@ -5,29 +5,28 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. -* +* * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. -* +* * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * Author: Rodrigo Campos (rodrigo@geekbunker.org) -* +* */ -struct ip_user_dict -{ - unsigned long address; - unsigned long netmask; - char *username; - struct ip_user_dict *next_entry; +struct ip_user_dict { + unsigned long address; + unsigned long netmask; + char *username; + struct ip_user_dict *next_entry; }; extern int match_user(char *, char *); diff --git a/helpers/external_acl/ip_user/main.c b/helpers/external_acl/ip_user/main.c index 197badd54d..77bff08f32 100644 --- a/helpers/external_acl/ip_user/main.c +++ b/helpers/external_acl/ip_user/main.c @@ -1,22 +1,22 @@ -/* $Id: main.c,v 1.6 2007/07/19 03:36:12 hno Exp $ +/* $Id: main.c,v 1.6 2007/07/19 03:36:12 hno Exp $ * Copyright (C) 2002 Rodrigo Campos * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. -* +* * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. -* +* * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * Author: Rodrigo Campos (rodrigo@geekbunker.org) -* +* */ #include "util.h" @@ -31,73 +31,73 @@ static void usage (char *program_name) { - fprintf (stderr, "Usage:\n%s -f \n", - program_name); + fprintf (stderr, "Usage:\n%s -f \n", + program_name); } int main (int argc, char *argv[]) { - FILE *FH; - char *filename = NULL; - char *program_name = argv[0]; - char *cp; - char *username, *address; - char line[BUFSIZE]; - struct ip_user_dict *current_entry; - int ch; + FILE *FH; + char *filename = NULL; + char *program_name = argv[0]; + char *cp; + char *username, *address; + char line[BUFSIZE]; + struct ip_user_dict *current_entry; + int ch; - setvbuf (stdout, NULL, _IOLBF, 0); - while ((ch = getopt (argc, argv, "f:")) != -1) { - switch (ch) { - case 'f': - filename = optarg; - break; - default: - usage (program_name); - exit (1); + setvbuf (stdout, NULL, _IOLBF, 0); + while ((ch = getopt (argc, argv, "f:")) != -1) { + switch (ch) { + case 'f': + filename = optarg; + break; + default: + usage (program_name); + exit (1); + } } - } - if (filename == NULL) { - usage (program_name); - exit(1); - } - FH = fopen (filename, "r"); - current_entry = load_dict (FH); - - while (fgets (line, sizeof (line), stdin)) { - if ((cp = strchr (line, '\n')) == NULL) { - /* too large message received.. skip and deny */ - fprintf(stderr, "%s: ERROR: Too large: %s\n", argv[0], line); - while (fgets(line, sizeof(line), stdin)) { - fprintf(stderr, "%s: ERROR: Too large..: %s\n", argv[0], line); - if (strchr(line, '\n') != NULL) - break; - } - goto error; - } - *cp = '\0'; - address = strtok (line, " \t"); - username = strtok (NULL, " \t"); - if (!address || !username) { - fprintf (stderr, "%s: unable to read tokens\n", argv[0]); - goto error; + if (filename == NULL) { + usage (program_name); + exit(1); } - rfc1738_unescape(address); - rfc1738_unescape(username); + FH = fopen (filename, "r"); + current_entry = load_dict (FH); + + while (fgets (line, sizeof (line), stdin)) { + if ((cp = strchr (line, '\n')) == NULL) { + /* too large message received.. skip and deny */ + fprintf(stderr, "%s: ERROR: Too large: %s\n", argv[0], line); + while (fgets(line, sizeof(line), stdin)) { + fprintf(stderr, "%s: ERROR: Too large..: %s\n", argv[0], line); + if (strchr(line, '\n') != NULL) + break; + } + goto error; + } + *cp = '\0'; + address = strtok (line, " \t"); + username = strtok (NULL, " \t"); + if (!address || !username) { + fprintf (stderr, "%s: unable to read tokens\n", argv[0]); + goto error; + } + rfc1738_unescape(address); + rfc1738_unescape(username); #ifdef DEBUG - printf ("result: %d\n", - dict_lookup (current_entry, username, address)); + printf ("result: %d\n", + dict_lookup (current_entry, username, address)); #endif - if ((dict_lookup (current_entry, username, address)) != 0) { - printf ("OK\n"); - } else { + if ((dict_lookup (current_entry, username, address)) != 0) { + printf ("OK\n"); + } else { error: - printf ("ERR\n"); + printf ("ERR\n"); + } } - } - fclose (FH); - return 0; + fclose (FH); + return 0; } diff --git a/helpers/external_acl/ip_user/match.c b/helpers/external_acl/ip_user/match.c index 0171d72fc2..9b8bd20139 100644 --- a/helpers/external_acl/ip_user/match.c +++ b/helpers/external_acl/ip_user/match.c @@ -1,22 +1,22 @@ -/* $Id: match.c,v 1.3 2007/07/19 03:36:12 hno Exp $ +/* $Id: match.c,v 1.3 2007/07/19 03:36:12 hno Exp $ * Copyright (C) 2002 Rodrigo Campos * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. -* +* * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. -* +* * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * Author: Rodrigo Campos (rodrigo@geekbunker.org) -* +* */ #include #include @@ -28,35 +28,35 @@ int match_user (char *dict_username, char *username) { - if ((strcmp (dict_username, username)) == 0) { - return 1; - } else { - if ((strcmp (dict_username, "ALL")) == 0) { - return 1; + if ((strcmp (dict_username, username)) == 0) { + return 1; + } else { + if ((strcmp (dict_username, "ALL")) == 0) { + return 1; + } } - } - return 0; + return 0; } /* match_user */ int match_group (char *dict_group, char *username) { - struct group *g; /* a struct to hold group entries */ - dict_group++; /* the @ should be the first char - so we rip it off by incrementing + struct group *g; /* a struct to hold group entries */ + dict_group++; /* the @ should be the first char + so we rip it off by incrementing * the pointer by one */ - if ((g = getgrnam (dict_group)) == NULL) { - fprintf (stderr, "helper: Group does not exist '%s'\n", - dict_group); - return 0; - } else { - while (*(g->gr_mem) != NULL) { - if (strcmp (*((g->gr_mem)++), username) == 0) { - return 1; - } + if ((g = getgrnam (dict_group)) == NULL) { + fprintf (stderr, "helper: Group does not exist '%s'\n", + dict_group); + return 0; + } else { + while (*(g->gr_mem) != NULL) { + if (strcmp (*((g->gr_mem)++), username) == 0) { + return 1; + } + } } - } - return 0; + return 0; } /* match_group */ diff --git a/helpers/external_acl/ldap_group/squid_ldap_group.c b/helpers/external_acl/ldap_group/squid_ldap_group.c index 26e8d574f0..73e12f1205 100644 --- a/helpers/external_acl/ldap_group/squid_ldap_group.c +++ b/helpers/external_acl/ldap_group/squid_ldap_group.c @@ -7,7 +7,7 @@ * and/or modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2, * or (at your option) any later version. - * + * * Authors: * Flavio Pescuma * Henrik Nordstrom @@ -19,17 +19,17 @@ * * Latest version of this program can always be found from MARA Systems * at http://marasystems.com/download/LDAP_Group/ - * + * * Dependencies: You need to get the OpenLDAP libraries * from http://www.openldap.org or use another compatible * LDAP C-API library. * * If you want to make a TLS enabled connection you will also need the * OpenSSL libraries linked into openldap. See http://www.openssl.org/ - * - * License: squid_ldap_group is free software; you can redistribute it - * and/or modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2, + * + * License: squid_ldap_group is free software; you can redistribute it + * and/or modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2, * or (at your option) any later version. */ @@ -136,7 +136,7 @@ squid_ldap_set_aliasderef(LDAP * ld, int deref) static void squid_ldap_set_referrals(LDAP * ld, int referrals) { - int *value = referrals ? LDAP_OPT_ON : LDAP_OPT_OFF; + int *value = referrals ? LDAP_OPT_ON :LDAP_OPT_OFF; ldap_set_option(ld, LDAP_OPT_REFERRALS, value); } static void @@ -178,9 +178,9 @@ static void squid_ldap_set_referrals(LDAP * ld, int referrals) { if (referrals) - ld->ld_options |= ~LDAP_OPT_REFERRALS; + ld->ld_options |= ~LDAP_OPT_REFERRALS; else - ld->ld_options &= ~LDAP_OPT_REFERRALS; + ld->ld_options &= ~LDAP_OPT_REFERRALS; } static void squid_ldap_set_timelimit(LDAP * ld, int timelimit) @@ -223,384 +223,384 @@ main(int argc, char **argv) setbuf(stdout, NULL); while (argc > 1 && argv[1][0] == '-') { - const char *value = ""; - char option = argv[1][1]; - switch (option) { - case 'P': - case 'R': - case 'z': - case 'Z': - case 'd': - case 'g': - case 'S': - break; - default: - if (strlen(argv[1]) > 2) { - value = argv[1] + 2; - } else if (argc > 2) { - value = argv[2]; - argv++; - argc--; - } else - value = ""; - break; - } - argv++; - argc--; - switch (option) { - case 'H': + const char *value = ""; + char option = argv[1][1]; + switch (option) { + case 'P': + case 'R': + case 'z': + case 'Z': + case 'd': + case 'g': + case 'S': + break; + default: + if (strlen(argv[1]) > 2) { + value = argv[1] + 2; + } else if (argc > 2) { + value = argv[2]; + argv++; + argc--; + } else + value = ""; + break; + } + argv++; + argc--; + switch (option) { + case 'H': #if !HAS_URI_SUPPORT - fprintf(stderr, "ERROR: Your LDAP library does not have URI support\n"); - exit(1); + fprintf(stderr, "ERROR: Your LDAP library does not have URI support\n"); + exit(1); #endif - /* Fall thru to -h */ - case 'h': - if (ldapServer) { - int len = strlen(ldapServer) + 1 + strlen(value) + 1; - char *newhost = malloc(len); - snprintf(newhost, len, "%s %s", ldapServer, value); - free(ldapServer); - ldapServer = newhost; - } else { - ldapServer = strdup(value); - } - break; - case 'b': - basedn = value; - break; - case 'f': - searchfilter = value; - break; - case 'B': - userbasedn = value; - break; - case 'F': - usersearchfilter = value; - break; - case 'u': - userdnattr = value; - break; - case 's': - if (strcmp(value, "base") == 0) - searchscope = LDAP_SCOPE_BASE; - else if (strcmp(value, "one") == 0) - searchscope = LDAP_SCOPE_ONELEVEL; - else if (strcmp(value, "sub") == 0) - searchscope = LDAP_SCOPE_SUBTREE; - else { - fprintf(stderr, PROGRAM_NAME " ERROR: Unknown search scope '%s'\n", value); - exit(1); - } - break; - case 'E': + /* Fall thru to -h */ + case 'h': + if (ldapServer) { + int len = strlen(ldapServer) + 1 + strlen(value) + 1; + char *newhost = malloc(len); + snprintf(newhost, len, "%s %s", ldapServer, value); + free(ldapServer); + ldapServer = newhost; + } else { + ldapServer = strdup(value); + } + break; + case 'b': + basedn = value; + break; + case 'f': + searchfilter = value; + break; + case 'B': + userbasedn = value; + break; + case 'F': + usersearchfilter = value; + break; + case 'u': + userdnattr = value; + break; + case 's': + if (strcmp(value, "base") == 0) + searchscope = LDAP_SCOPE_BASE; + else if (strcmp(value, "one") == 0) + searchscope = LDAP_SCOPE_ONELEVEL; + else if (strcmp(value, "sub") == 0) + searchscope = LDAP_SCOPE_SUBTREE; + else { + fprintf(stderr, PROGRAM_NAME " ERROR: Unknown search scope '%s'\n", value); + exit(1); + } + break; + case 'E': #if defined(NETSCAPE_SSL) - sslpath = value; - if (port == LDAP_PORT) - port = LDAPS_PORT; + sslpath = value; + if (port == LDAP_PORT) + port = LDAPS_PORT; #else - fprintf(stderr, PROGRAM_NAME " ERROR: -E unsupported with this LDAP library\n"); - exit(1); + fprintf(stderr, PROGRAM_NAME " ERROR: -E unsupported with this LDAP library\n"); + exit(1); #endif - break; - case 'c': - connect_timeout = atoi(value); - break; - case 't': - timelimit = atoi(value); - break; - case 'a': - if (strcmp(value, "never") == 0) - aliasderef = LDAP_DEREF_NEVER; - else if (strcmp(value, "always") == 0) - aliasderef = LDAP_DEREF_ALWAYS; - else if (strcmp(value, "search") == 0) - aliasderef = LDAP_DEREF_SEARCHING; - else if (strcmp(value, "find") == 0) - aliasderef = LDAP_DEREF_FINDING; - else { - fprintf(stderr, PROGRAM_NAME " ERROR: Unknown alias dereference method '%s'\n", value); - exit(1); - } - break; - case 'D': - binddn = value; - break; - case 'w': - bindpasswd = value; - break; - case 'W': - readSecret(value); - break; - case 'P': - persistent = !persistent; - break; - case 'p': - port = atoi(value); - break; - case 'R': - noreferrals = !noreferrals; - break; + break; + case 'c': + connect_timeout = atoi(value); + break; + case 't': + timelimit = atoi(value); + break; + case 'a': + if (strcmp(value, "never") == 0) + aliasderef = LDAP_DEREF_NEVER; + else if (strcmp(value, "always") == 0) + aliasderef = LDAP_DEREF_ALWAYS; + else if (strcmp(value, "search") == 0) + aliasderef = LDAP_DEREF_SEARCHING; + else if (strcmp(value, "find") == 0) + aliasderef = LDAP_DEREF_FINDING; + else { + fprintf(stderr, PROGRAM_NAME " ERROR: Unknown alias dereference method '%s'\n", value); + exit(1); + } + break; + case 'D': + binddn = value; + break; + case 'w': + bindpasswd = value; + break; + case 'W': + readSecret(value); + break; + case 'P': + persistent = !persistent; + break; + case 'p': + port = atoi(value); + break; + case 'R': + noreferrals = !noreferrals; + break; #ifdef LDAP_VERSION3 - case 'v': - switch (atoi(value)) { - case 2: - version = LDAP_VERSION2; - break; - case 3: - version = LDAP_VERSION3; - break; - default: - fprintf(stderr, "Protocol version should be 2 or 3\n"); - exit(1); - } - break; - case 'Z': - if (version == LDAP_VERSION2) { - fprintf(stderr, "TLS (-Z) is incompatible with version %d\n", - version); - exit(1); - } - version = LDAP_VERSION3; - use_tls = 1; - break; + case 'v': + switch (atoi(value)) { + case 2: + version = LDAP_VERSION2; + break; + case 3: + version = LDAP_VERSION3; + break; + default: + fprintf(stderr, "Protocol version should be 2 or 3\n"); + exit(1); + } + break; + case 'Z': + if (version == LDAP_VERSION2) { + fprintf(stderr, "TLS (-Z) is incompatible with version %d\n", + version); + exit(1); + } + version = LDAP_VERSION3; + use_tls = 1; + break; #endif - case 'd': - debug = 1; - break; - case 'g': - use_extension_dn = 1; - break; - case 'S': - strip_nt_domain = 1; - break; - case 'K': - strip_kerberos_realm = 1; - break; - default: - fprintf(stderr, PROGRAM_NAME " ERROR: Unknown command line option '%c'\n", option); - exit(1); - } + case 'd': + debug = 1; + break; + case 'g': + use_extension_dn = 1; + break; + case 'S': + strip_nt_domain = 1; + break; + case 'K': + strip_kerberos_realm = 1; + break; + default: + fprintf(stderr, PROGRAM_NAME " ERROR: Unknown command line option '%c'\n", option); + exit(1); + } } while (argc > 1) { - char *value = argv[1]; - if (ldapServer) { - int len = strlen(ldapServer) + 1 + strlen(value) + 1; - char *newhost = malloc(len); - snprintf(newhost, len, "%s %s", ldapServer, value); - free(ldapServer); - ldapServer = newhost; - } else { - ldapServer = strdup(value); - } - argc--; - argv++; + char *value = argv[1]; + if (ldapServer) { + int len = strlen(ldapServer) + 1 + strlen(value) + 1; + char *newhost = malloc(len); + snprintf(newhost, len, "%s %s", ldapServer, value); + free(ldapServer); + ldapServer = newhost; + } else { + ldapServer = strdup(value); + } + argc--; + argv++; } if (!ldapServer) - ldapServer = (char *) "localhost"; + ldapServer = (char *) "localhost"; if (!basedn || !searchfilter) { - fprintf(stderr, "\n" PROGRAM_NAME " version " PROGRAM_VERSION "\n\n"); - fprintf(stderr, "Usage: " PROGRAM_NAME " -b basedn -f filter [options] ldap_server_name\n\n"); - fprintf(stderr, "\t-b basedn (REQUIRED)\tbase dn under where to search for groups\n"); - fprintf(stderr, "\t-f filter (REQUIRED)\tgroup search filter pattern. %%u = user,\n\t\t\t\t%%v = group\n"); - fprintf(stderr, "\t-B basedn (REQUIRED)\tbase dn under where to search for users\n"); - fprintf(stderr, "\t-F filter (REQUIRED)\tuser search filter pattern. %%s = login\n"); - fprintf(stderr, "\t-s base|one|sub\t\tsearch scope\n"); - fprintf(stderr, "\t-D binddn\t\tDN to bind as to perform searches\n"); - fprintf(stderr, "\t-w bindpasswd\t\tpassword for binddn\n"); - fprintf(stderr, "\t-W secretfile\t\tread password for binddn from file secretfile\n"); + fprintf(stderr, "\n" PROGRAM_NAME " version " PROGRAM_VERSION "\n\n"); + fprintf(stderr, "Usage: " PROGRAM_NAME " -b basedn -f filter [options] ldap_server_name\n\n"); + fprintf(stderr, "\t-b basedn (REQUIRED)\tbase dn under where to search for groups\n"); + fprintf(stderr, "\t-f filter (REQUIRED)\tgroup search filter pattern. %%u = user,\n\t\t\t\t%%v = group\n"); + fprintf(stderr, "\t-B basedn (REQUIRED)\tbase dn under where to search for users\n"); + fprintf(stderr, "\t-F filter (REQUIRED)\tuser search filter pattern. %%s = login\n"); + fprintf(stderr, "\t-s base|one|sub\t\tsearch scope\n"); + fprintf(stderr, "\t-D binddn\t\tDN to bind as to perform searches\n"); + fprintf(stderr, "\t-w bindpasswd\t\tpassword for binddn\n"); + fprintf(stderr, "\t-W secretfile\t\tread password for binddn from file secretfile\n"); #if HAS_URI_SUPPORT - fprintf(stderr, "\t-H URI\t\t\tLDAPURI (defaults to ldap://localhost)\n"); + fprintf(stderr, "\t-H URI\t\t\tLDAPURI (defaults to ldap://localhost)\n"); #endif - fprintf(stderr, "\t-h server\t\tLDAP server (defaults to localhost)\n"); - fprintf(stderr, "\t-p port\t\t\tLDAP server port (defaults to %d)\n", LDAP_PORT); - fprintf(stderr, "\t-P\t\t\tpersistent LDAP connection\n"); + fprintf(stderr, "\t-h server\t\tLDAP server (defaults to localhost)\n"); + fprintf(stderr, "\t-p port\t\t\tLDAP server port (defaults to %d)\n", LDAP_PORT); + fprintf(stderr, "\t-P\t\t\tpersistent LDAP connection\n"); #if defined(NETSCAPE_SSL) - fprintf(stderr, "\t-E sslcertpath\t\tenable LDAP over SSL\n"); + fprintf(stderr, "\t-E sslcertpath\t\tenable LDAP over SSL\n"); #endif - fprintf(stderr, "\t-c timeout\t\tconnect timeout\n"); - fprintf(stderr, "\t-t timelimit\t\tsearch time limit\n"); - fprintf(stderr, "\t-R\t\t\tdo not follow referrals\n"); - fprintf(stderr, "\t-a never|always|search|find\n\t\t\t\twhen to dereference aliases\n"); + fprintf(stderr, "\t-c timeout\t\tconnect timeout\n"); + fprintf(stderr, "\t-t timelimit\t\tsearch time limit\n"); + fprintf(stderr, "\t-R\t\t\tdo not follow referrals\n"); + fprintf(stderr, "\t-a never|always|search|find\n\t\t\t\twhen to dereference aliases\n"); #ifdef LDAP_VERSION3 - fprintf(stderr, "\t-v 2|3\t\t\tLDAP version\n"); - fprintf(stderr, "\t-Z\t\t\tTLS encrypt the LDAP connection, requires\n\t\t\t\tLDAP version 3\n"); + fprintf(stderr, "\t-v 2|3\t\t\tLDAP version\n"); + fprintf(stderr, "\t-Z\t\t\tTLS encrypt the LDAP connection, requires\n\t\t\t\tLDAP version 3\n"); #endif - fprintf(stderr, "\t-g\t\t\tfirst query parameter is base DN extension\n\t\t\t\tfor this query\n"); - fprintf(stderr, "\t-S\t\t\tStrip NT domain from usernames\n"); - fprintf(stderr, "\t-K\t\t\tStrip Kerberos realm from usernames\n"); - fprintf(stderr, "\n"); - fprintf(stderr, "\tIf you need to bind as a user to perform searches then use the\n\t-D binddn -w bindpasswd or -D binddn -W secretfile options\n\n"); - exit(1); + fprintf(stderr, "\t-g\t\t\tfirst query parameter is base DN extension\n\t\t\t\tfor this query\n"); + fprintf(stderr, "\t-S\t\t\tStrip NT domain from usernames\n"); + fprintf(stderr, "\t-K\t\t\tStrip Kerberos realm from usernames\n"); + fprintf(stderr, "\n"); + fprintf(stderr, "\tIf you need to bind as a user to perform searches then use the\n\t-D binddn -w bindpasswd or -D binddn -W secretfile options\n\n"); + exit(1); } -/* On Windows ldap_start_tls_s is available starting from Windows XP, - * so we need to bind at run-time with the function entry point - */ + /* On Windows ldap_start_tls_s is available starting from Windows XP, + * so we need to bind at run-time with the function entry point + */ #ifdef _SQUID_MSWIN_ if (use_tls) { - HMODULE WLDAP32Handle; + HMODULE WLDAP32Handle; - WLDAP32Handle = GetModuleHandle("wldap32"); - if ((Win32_ldap_start_tls_s = (PFldap_start_tls_s) GetProcAddress(WLDAP32Handle, LDAP_START_TLS_S)) == NULL) { - fprintf(stderr, PROGRAM_NAME ": ERROR: TLS (-Z) not supported on this platform.\n"); - exit(1); - } + WLDAP32Handle = GetModuleHandle("wldap32"); + if ((Win32_ldap_start_tls_s = (PFldap_start_tls_s) GetProcAddress(WLDAP32Handle, LDAP_START_TLS_S)) == NULL) { + fprintf(stderr, PROGRAM_NAME ": ERROR: TLS (-Z) not supported on this platform.\n"); + exit(1); + } } #endif while (fgets(buf, 256, stdin) != NULL) { - int found = 0; - if (!strchr(buf, '\n')) { - /* too large message received.. skip and deny */ - fprintf(stderr, "%s: ERROR: Too large: %s\n", argv[0], buf); - while (fgets(buf, sizeof(buf), stdin)) { - fprintf(stderr, "%s: ERROR: Too large..: %s\n", argv[0], buf); - if (strchr(buf, '\n') != NULL) - break; - } - goto error; - } - user = strtok(buf, " \n"); - if (!user) { - fprintf(stderr, "%s: Invalid request\n", argv[0]); - goto error; - } - rfc1738_unescape(user); - if (strip_nt_domain) { - char *u = strchr(user, '\\'); - if (!u) - u = strchr(user, '/'); - if (u && u[1]) - user = u + 1; - } - if (strip_kerberos_realm) { - char *u = strchr(user, '@'); - if (u != NULL) { - *u = '\0'; - } - } - if (use_extension_dn) { - extension_dn = strtok(NULL, " \n"); - if (!extension_dn) { - fprintf(stderr, "%s: Invalid request\n", argv[0]); - goto error; - } - rfc1738_unescape(extension_dn); - } - while (!found && user && (group = strtok(NULL, " \n")) != NULL) { - rfc1738_unescape(group); - - recover: - if (ld == NULL) { + int found = 0; + if (!strchr(buf, '\n')) { + /* too large message received.. skip and deny */ + fprintf(stderr, "%s: ERROR: Too large: %s\n", argv[0], buf); + while (fgets(buf, sizeof(buf), stdin)) { + fprintf(stderr, "%s: ERROR: Too large..: %s\n", argv[0], buf); + if (strchr(buf, '\n') != NULL) + break; + } + goto error; + } + user = strtok(buf, " \n"); + if (!user) { + fprintf(stderr, "%s: Invalid request\n", argv[0]); + goto error; + } + rfc1738_unescape(user); + if (strip_nt_domain) { + char *u = strchr(user, '\\'); + if (!u) + u = strchr(user, '/'); + if (u && u[1]) + user = u + 1; + } + if (strip_kerberos_realm) { + char *u = strchr(user, '@'); + if (u != NULL) { + *u = '\0'; + } + } + if (use_extension_dn) { + extension_dn = strtok(NULL, " \n"); + if (!extension_dn) { + fprintf(stderr, "%s: Invalid request\n", argv[0]); + goto error; + } + rfc1738_unescape(extension_dn); + } + while (!found && user && (group = strtok(NULL, " \n")) != NULL) { + rfc1738_unescape(group); + +recover: + if (ld == NULL) { #if HAS_URI_SUPPORT - if (strstr(ldapServer, "://") != NULL) { - rc = ldap_initialize(&ld, ldapServer); - if (rc != LDAP_SUCCESS) { - fprintf(stderr, "\nUnable to connect to LDAPURI:%s\n", ldapServer); - break; - } - } else + if (strstr(ldapServer, "://") != NULL) { + rc = ldap_initialize(&ld, ldapServer); + if (rc != LDAP_SUCCESS) { + fprintf(stderr, "\nUnable to connect to LDAPURI:%s\n", ldapServer); + break; + } + } else #endif #if NETSCAPE_SSL - if (sslpath) { - if (!sslinit && (ldapssl_client_init(sslpath, NULL) != LDAP_SUCCESS)) { - fprintf(stderr, "\nUnable to initialise SSL with cert path %s\n", - sslpath); - exit(1); - } else { - sslinit++; - } - if ((ld = ldapssl_init(ldapServer, port, 1)) == NULL) { - fprintf(stderr, "\nUnable to connect to SSL LDAP server: %s port:%d\n", - ldapServer, port); - exit(1); - } - } else + if (sslpath) { + if (!sslinit && (ldapssl_client_init(sslpath, NULL) != LDAP_SUCCESS)) { + fprintf(stderr, "\nUnable to initialise SSL with cert path %s\n", + sslpath); + exit(1); + } else { + sslinit++; + } + if ((ld = ldapssl_init(ldapServer, port, 1)) == NULL) { + fprintf(stderr, "\nUnable to connect to SSL LDAP server: %s port:%d\n", + ldapServer, port); + exit(1); + } + } else #endif - if ((ld = ldap_init(ldapServer, port)) == NULL) { - fprintf(stderr, "\nUnable to connect to LDAP server:%s port:%d\n", ldapServer, port); - break; - } - if (connect_timeout) - squid_ldap_set_connect_timeout(ld, connect_timeout); + if ((ld = ldap_init(ldapServer, port)) == NULL) { + fprintf(stderr, "\nUnable to connect to LDAP server:%s port:%d\n", ldapServer, port); + break; + } + if (connect_timeout) + squid_ldap_set_connect_timeout(ld, connect_timeout); #ifdef LDAP_VERSION3 - if (version == -1) { - version = LDAP_VERSION2; - } - if (ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &version) != LDAP_SUCCESS) { - fprintf(stderr, "Could not set LDAP_OPT_PROTOCOL_VERSION %d\n", - version); - ldap_unbind(ld); - ld = NULL; - break; - } - if (use_tls) { + if (version == -1) { + version = LDAP_VERSION2; + } + if (ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &version) != LDAP_SUCCESS) { + fprintf(stderr, "Could not set LDAP_OPT_PROTOCOL_VERSION %d\n", + version); + ldap_unbind(ld); + ld = NULL; + break; + } + if (use_tls) { #ifdef LDAP_OPT_X_TLS - if (version != LDAP_VERSION3) { - fprintf(stderr, "TLS requires LDAP version 3\n"); - exit(1); - } else if (ldap_start_tls_s(ld, NULL, NULL) != LDAP_SUCCESS) { - fprintf(stderr, "Could not Activate TLS connection\n"); - ldap_unbind(ld); - ld = NULL; - break; - } + if (version != LDAP_VERSION3) { + fprintf(stderr, "TLS requires LDAP version 3\n"); + exit(1); + } else if (ldap_start_tls_s(ld, NULL, NULL) != LDAP_SUCCESS) { + fprintf(stderr, "Could not Activate TLS connection\n"); + ldap_unbind(ld); + ld = NULL; + break; + } #else - fprintf(stderr, "TLS not supported with your LDAP library\n"); - exit(1); + fprintf(stderr, "TLS not supported with your LDAP library\n"); + exit(1); #endif - } + } #endif - squid_ldap_set_timelimit(ld, timelimit); - squid_ldap_set_referrals(ld, !noreferrals); - squid_ldap_set_aliasderef(ld, aliasderef); - if (binddn && bindpasswd && *binddn && *bindpasswd) { - rc = ldap_simple_bind_s(ld, binddn, bindpasswd); - if (rc != LDAP_SUCCESS) { - fprintf(stderr, PROGRAM_NAME " WARNING, could not bind to binddn '%s'\n", ldap_err2string(rc)); - ldap_unbind(ld); - ld = NULL; - break; - } - } - if (debug) - fprintf(stderr, "Connected OK\n"); - } - if (searchLDAP(ld, group, user, extension_dn) == 0) { - found = 1; - break; - } else { - if (tryagain) { - tryagain = 0; - ldap_unbind(ld); - ld = NULL; - goto recover; - } - } - } - if (found) - printf("OK\n"); - else { - error: - printf("ERR\n"); - } - - if (ld != NULL) { - if (!persistent || (squid_ldap_errno(ld) != LDAP_SUCCESS && squid_ldap_errno(ld) != LDAP_INVALID_CREDENTIALS)) { - ldap_unbind(ld); - ld = NULL; - } else { - tryagain = 1; - } - } - err = 0; + squid_ldap_set_timelimit(ld, timelimit); + squid_ldap_set_referrals(ld, !noreferrals); + squid_ldap_set_aliasderef(ld, aliasderef); + if (binddn && bindpasswd && *binddn && *bindpasswd) { + rc = ldap_simple_bind_s(ld, binddn, bindpasswd); + if (rc != LDAP_SUCCESS) { + fprintf(stderr, PROGRAM_NAME " WARNING, could not bind to binddn '%s'\n", ldap_err2string(rc)); + ldap_unbind(ld); + ld = NULL; + break; + } + } + if (debug) + fprintf(stderr, "Connected OK\n"); + } + if (searchLDAP(ld, group, user, extension_dn) == 0) { + found = 1; + break; + } else { + if (tryagain) { + tryagain = 0; + ldap_unbind(ld); + ld = NULL; + goto recover; + } + } + } + if (found) + printf("OK\n"); + else { +error: + printf("ERR\n"); + } + + if (ld != NULL) { + if (!persistent || (squid_ldap_errno(ld) != LDAP_SUCCESS && squid_ldap_errno(ld) != LDAP_INVALID_CREDENTIALS)) { + ldap_unbind(ld); + ld = NULL; + } else { + tryagain = 1; + } + } + err = 0; } if (ld) - ldap_unbind(ld); + ldap_unbind(ld); return 0; } @@ -609,24 +609,24 @@ ldap_escape_value(char *escaped, int size, const char *src) { int n = 0; while (size > 4 && *src) { - switch (*src) { - case '*': - case '(': - case ')': - case '\\': - n += 3; - size -= 3; - if (size > 0) { - *escaped++ = '\\'; - snprintf(escaped, 3, "%02x", (unsigned char) *src++); - escaped += 2; - } - break; - default: - *escaped++ = *src++; - n++; - size--; - } + switch (*src) { + case '*': + case '(': + case ')': + case '\\': + n += 3; + size -= 3; + if (size > 0) { + *escaped++ = '\\'; + snprintf(escaped, 3, "%02x", (unsigned char) *src++); + escaped += 2; + } + break; + default: + *escaped++ = *src++; + n++; + size--; + } } *escaped = '\0'; return n; @@ -637,46 +637,46 @@ build_filter(char *filter, int size, const char *template, const char *user, con { int n; while (*template && size > 0) { - switch (*template) { - case '%': - template++; - switch (*template) { - case 'u': - case 'v': - template++; - n = ldap_escape_value(filter, size, user); - size -= n; - filter += n; - break; - case 'g': - case 'a': - template++; - n = ldap_escape_value(filter, size, group); - size -= n; - filter += n; - break; - default: - fprintf(stderr, "ERROR: Unknown filter template string %%%c\n", *template); - return 1; - break; - } - break; - case '\\': - template++; - if (*template) { - *filter++ = *template++; - size--; - } - break; - default: - *filter++ = *template++; - size--; - break; - } + switch (*template) { + case '%': + template++; + switch (*template) { + case 'u': + case 'v': + template++; + n = ldap_escape_value(filter, size, user); + size -= n; + filter += n; + break; + case 'g': + case 'a': + template++; + n = ldap_escape_value(filter, size, group); + size -= n; + filter += n; + break; + default: + fprintf(stderr, "ERROR: Unknown filter template string %%%c\n", *template); + return 1; + break; + } + break; + case '\\': + template++; + if (*template) { + *filter++ = *template++; + size--; + } + break; + default: + *filter++ = *template++; + size--; + break; + } } if (size <= 0) { - fprintf(stderr, "ERROR: Filter too large\n"); - return 1; + fprintf(stderr, "ERROR: Filter too large\n"); + return 1; } *filter = '\0'; return 0; @@ -690,43 +690,42 @@ searchLDAPGroup(LDAP * ld, char *group, char *member, char *extension_dn) LDAPMessage *res = NULL; LDAPMessage *entry; int rc; - char *searchattr[] = - {(char *) LDAP_NO_ATTRS, NULL}; + char *searchattr[] = {(char *) LDAP_NO_ATTRS, NULL}; if (extension_dn && *extension_dn) - snprintf(searchbase, sizeof(searchbase), "%s,%s", extension_dn, basedn); + snprintf(searchbase, sizeof(searchbase), "%s,%s", extension_dn, basedn); else - snprintf(searchbase, sizeof(searchbase), "%s", basedn); + snprintf(searchbase, sizeof(searchbase), "%s", basedn); if (build_filter(filter, sizeof(filter), searchfilter, member, group) != 0) { - fprintf(stderr, PROGRAM_NAME " ERROR, Failed to construct LDAP search filter. filter=\"%s\", user=\"%s\", group=\"%s\"\n", filter, member, group); - return 1; + fprintf(stderr, PROGRAM_NAME " ERROR, Failed to construct LDAP search filter. filter=\"%s\", user=\"%s\", group=\"%s\"\n", filter, member, group); + return 1; } if (debug) - fprintf(stderr, "group filter '%s', searchbase '%s'\n", filter, searchbase); + fprintf(stderr, "group filter '%s', searchbase '%s'\n", filter, searchbase); rc = ldap_search_s(ld, searchbase, searchscope, filter, searchattr, 1, &res); if (rc != LDAP_SUCCESS) { - if (noreferrals && rc == LDAP_PARTIAL_RESULTS) { - /* Everything is fine. This is expected when referrals - * are disabled. - */ - } else { - fprintf(stderr, PROGRAM_NAME " WARNING, LDAP search error '%s'\n", ldap_err2string(rc)); + if (noreferrals && rc == LDAP_PARTIAL_RESULTS) { + /* Everything is fine. This is expected when referrals + * are disabled. + */ + } else { + fprintf(stderr, PROGRAM_NAME " WARNING, LDAP search error '%s'\n", ldap_err2string(rc)); #if defined(NETSCAPE_SSL) - if (sslpath && ((rc == LDAP_SERVER_DOWN) || (rc == LDAP_CONNECT_ERROR))) { - int sslerr = PORT_GetError(); - fprintf(stderr, PROGRAM_NAME ": WARNING, SSL error %d (%s)\n", sslerr, ldapssl_err2string(sslerr)); - } + if (sslpath && ((rc == LDAP_SERVER_DOWN) || (rc == LDAP_CONNECT_ERROR))) { + int sslerr = PORT_GetError(); + fprintf(stderr, PROGRAM_NAME ": WARNING, SSL error %d (%s)\n", sslerr, ldapssl_err2string(sslerr)); + } #endif - ldap_msgfree(res); - return 1; - } + ldap_msgfree(res); + return 1; + } } entry = ldap_first_entry(ld, res); if (!entry) { - ldap_msgfree(res); - return 1; + ldap_msgfree(res); + return 1; } ldap_msgfree(res); return 0; @@ -737,61 +736,60 @@ searchLDAP(LDAP * ld, char *group, char *login, char *extension_dn) { if (usersearchfilter) { - char filter[8192]; - char searchbase[8192]; - char escaped_login[1024]; - LDAPMessage *res = NULL; - LDAPMessage *entry; - int rc; - char *userdn; - char *searchattr[] = - {(char *) LDAP_NO_ATTRS, NULL}; - if (extension_dn && *extension_dn) - snprintf(searchbase, sizeof(searchbase), "%s,%s", extension_dn, userbasedn ? userbasedn : basedn); - else - snprintf(searchbase, sizeof(searchbase), "%s", userbasedn ? userbasedn : basedn); - ldap_escape_value(escaped_login, sizeof(escaped_login), login); - snprintf(filter, sizeof(filter), usersearchfilter, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login); - if (debug) - fprintf(stderr, "user filter '%s', searchbase '%s'\n", filter, searchbase); - rc = ldap_search_s(ld, searchbase, searchscope, filter, searchattr, 1, &res); - if (rc != LDAP_SUCCESS) { - if (noreferrals && rc == LDAP_PARTIAL_RESULTS) { - /* Everything is fine. This is expected when referrals - * are disabled. - */ - } else { - fprintf(stderr, PROGRAM_NAME " WARNING, LDAP search error '%s'\n", ldap_err2string(rc)); + char filter[8192]; + char searchbase[8192]; + char escaped_login[1024]; + LDAPMessage *res = NULL; + LDAPMessage *entry; + int rc; + char *userdn; + char *searchattr[] = {(char *) LDAP_NO_ATTRS, NULL}; + if (extension_dn && *extension_dn) + snprintf(searchbase, sizeof(searchbase), "%s,%s", extension_dn, userbasedn ? userbasedn : basedn); + else + snprintf(searchbase, sizeof(searchbase), "%s", userbasedn ? userbasedn : basedn); + ldap_escape_value(escaped_login, sizeof(escaped_login), login); + snprintf(filter, sizeof(filter), usersearchfilter, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login); + if (debug) + fprintf(stderr, "user filter '%s', searchbase '%s'\n", filter, searchbase); + rc = ldap_search_s(ld, searchbase, searchscope, filter, searchattr, 1, &res); + if (rc != LDAP_SUCCESS) { + if (noreferrals && rc == LDAP_PARTIAL_RESULTS) { + /* Everything is fine. This is expected when referrals + * are disabled. + */ + } else { + fprintf(stderr, PROGRAM_NAME " WARNING, LDAP search error '%s'\n", ldap_err2string(rc)); #if defined(NETSCAPE_SSL) - if (sslpath && ((rc == LDAP_SERVER_DOWN) || (rc == LDAP_CONNECT_ERROR))) { - int sslerr = PORT_GetError(); - fprintf(stderr, PROGRAM_NAME ": WARNING, SSL error %d (%s)\n", sslerr, ldapssl_err2string(sslerr)); - } + if (sslpath && ((rc == LDAP_SERVER_DOWN) || (rc == LDAP_CONNECT_ERROR))) { + int sslerr = PORT_GetError(); + fprintf(stderr, PROGRAM_NAME ": WARNING, SSL error %d (%s)\n", sslerr, ldapssl_err2string(sslerr)); + } #endif - ldap_msgfree(res); - return 1; - } - } - entry = ldap_first_entry(ld, res); - if (!entry) { - fprintf(stderr, PROGRAM_NAME " WARNING, User '%s' not found in '%s'\n", login, searchbase); - ldap_msgfree(res); - return 1; - } - userdn = ldap_get_dn(ld, entry); - rc = searchLDAPGroup(ld, group, userdn, extension_dn); - squid_ldap_memfree(userdn); - ldap_msgfree(res); - return rc; + ldap_msgfree(res); + return 1; + } + } + entry = ldap_first_entry(ld, res); + if (!entry) { + fprintf(stderr, PROGRAM_NAME " WARNING, User '%s' not found in '%s'\n", login, searchbase); + ldap_msgfree(res); + return 1; + } + userdn = ldap_get_dn(ld, entry); + rc = searchLDAPGroup(ld, group, userdn, extension_dn); + squid_ldap_memfree(userdn); + ldap_msgfree(res); + return rc; } else if (userdnattr) { - char dn[8192]; - if (extension_dn && *extension_dn) - sprintf(dn, "%s=%s, %s, %s", userdnattr, login, extension_dn, userbasedn ? userbasedn : basedn); - else - sprintf(dn, "%s=%s, %s", userdnattr, login, userbasedn ? userbasedn : basedn); - return searchLDAPGroup(ld, group, dn, extension_dn); + char dn[8192]; + if (extension_dn && *extension_dn) + sprintf(dn, "%s=%s, %s, %s", userdnattr, login, extension_dn, userbasedn ? userbasedn : basedn); + else + sprintf(dn, "%s=%s, %s", userdnattr, login, userbasedn ? userbasedn : basedn); + return searchLDAPGroup(ld, group, dn, extension_dn); } else { - return searchLDAPGroup(ld, group, login, extension_dn); + return searchLDAPGroup(ld, group, login, extension_dn); } } @@ -804,23 +802,23 @@ readSecret(const char *filename) FILE *f; if (!(f = fopen(filename, "r"))) { - fprintf(stderr, PROGRAM_NAME " ERROR: Can not read secret file %s\n", filename); - return 1; + fprintf(stderr, PROGRAM_NAME " ERROR: Can not read secret file %s\n", filename); + return 1; } if (!fgets(buf, sizeof(buf) - 1, f)) { - fprintf(stderr, PROGRAM_NAME " ERROR: Secret file %s is empty\n", filename); - fclose(f); - return 1; + fprintf(stderr, PROGRAM_NAME " ERROR: Secret file %s is empty\n", filename); + fclose(f); + return 1; } /* strip whitespaces on end */ if ((e = strrchr(buf, '\n'))) - *e = 0; + *e = 0; if ((e = strrchr(buf, '\r'))) - *e = 0; + *e = 0; bindpasswd = strdup(buf); if (!bindpasswd) { - fprintf(stderr, PROGRAM_NAME " ERROR: can not allocate memory\n"); + fprintf(stderr, PROGRAM_NAME " ERROR: can not allocate memory\n"); } fclose(f); diff --git a/helpers/external_acl/mswin_ad_group/mswin_check_ad_group.c b/helpers/external_acl/mswin_ad_group/mswin_check_ad_group.c index 40f7eca6a9..f0edab38b5 100644 --- a/helpers/external_acl/mswin_ad_group/mswin_check_ad_group.c +++ b/helpers/external_acl/mswin_ad_group/mswin_check_ad_group.c @@ -36,7 +36,7 @@ * First release, based on mswin_check_lm_group. * * This is a helper for the external ACL interface for Squid Cache - * + * * It reads from the standard input the domain username and a list of * groups and tries to match it against the groups membership of the * specified username. @@ -93,46 +93,46 @@ GetDomainName(void) DWORD netret; if ((netret = DsRoleGetPrimaryDomainInformation(NULL, DsRolePrimaryDomainInfoBasic, (PBYTE *) & pDSRoleInfo) == ERROR_SUCCESS)) { - /* - * Check the machine role. - */ - - if ((pDSRoleInfo->MachineRole == DsRole_RoleMemberWorkstation) || - (pDSRoleInfo->MachineRole == DsRole_RoleMemberServer) || - (pDSRoleInfo->MachineRole == DsRole_RoleBackupDomainController) || - (pDSRoleInfo->MachineRole == DsRole_RolePrimaryDomainController)) { - - size_t len = wcslen(pDSRoleInfo->DomainNameFlat); - - /* allocate buffer for str + null termination */ - safe_free(DomainName); - DomainName = (char *) xmalloc(len + 1); - if (DomainName == NULL) - return NULL; - - /* copy unicode buffer */ - WideCharToMultiByte(CP_ACP, 0, pDSRoleInfo->DomainNameFlat, -1, DomainName, len, NULL, NULL); - - /* add null termination */ - DomainName[len] = '\0'; - - /* - * Member of a domain. Display it in debug mode. - */ - debug("Member of Domain %s\n", DomainName); - debug("Into forest %S\n", pDSRoleInfo->DomainForestName); - - } else { - debug("Not a Domain member\n"); - } + /* + * Check the machine role. + */ + + if ((pDSRoleInfo->MachineRole == DsRole_RoleMemberWorkstation) || + (pDSRoleInfo->MachineRole == DsRole_RoleMemberServer) || + (pDSRoleInfo->MachineRole == DsRole_RoleBackupDomainController) || + (pDSRoleInfo->MachineRole == DsRole_RolePrimaryDomainController)) { + + size_t len = wcslen(pDSRoleInfo->DomainNameFlat); + + /* allocate buffer for str + null termination */ + safe_free(DomainName); + DomainName = (char *) xmalloc(len + 1); + if (DomainName == NULL) + return NULL; + + /* copy unicode buffer */ + WideCharToMultiByte(CP_ACP, 0, pDSRoleInfo->DomainNameFlat, -1, DomainName, len, NULL, NULL); + + /* add null termination */ + DomainName[len] = '\0'; + + /* + * Member of a domain. Display it in debug mode. + */ + debug("Member of Domain %s\n", DomainName); + debug("Into forest %S\n", pDSRoleInfo->DomainForestName); + + } else { + debug("Not a Domain member\n"); + } } else - debug("DsRoleGetPrimaryDomainInformation Error: %ld\n", netret); + debug("DsRoleGetPrimaryDomainInformation Error: %ld\n", netret); /* * Free the allocated memory. */ if (pDSRoleInfo != NULL) - DsRoleFreeMemory(pDSRoleInfo); + DsRoleFreeMemory(pDSRoleInfo); return DomainName; } @@ -144,12 +144,12 @@ wcstrcmparray(const wchar_t * str, const char **array) WCHAR wszGroup[GNLEN + 1]; // Unicode Group while (*array) { - MultiByteToWideChar(CP_ACP, 0, *array, - strlen(*array) + 1, wszGroup, sizeof(wszGroup) / sizeof(wszGroup[0])); - debug("Windows group: %S, Squid group: %S\n", str, wszGroup); - if ((use_case_insensitive_compare ? _wcsicmp(str, wszGroup) : wcscmp(str, wszGroup)) == 0) - return 0; - array++; + MultiByteToWideChar(CP_ACP, 0, *array, + strlen(*array) + 1, wszGroup, sizeof(wszGroup) / sizeof(wszGroup[0])); + debug("Windows group: %S, Squid group: %S\n", str, wszGroup); + if ((use_case_insensitive_compare ? _wcsicmp(str, wszGroup) : wcscmp(str, wszGroup)) == 0) + return 0; + array++; } return -1; } @@ -175,58 +175,58 @@ Valid_Local_Groups(char *UserName, const char **Groups) LPBYTE pBufTmp = NULL; if ((Domain_Separator = strchr(UserName, '/')) != NULL) - *Domain_Separator = '\\'; + *Domain_Separator = '\\'; debug("Valid_Local_Groups: checking group membership of '%s'.\n", UserName); -/* Convert ANSI User Name and Group to Unicode */ + /* Convert ANSI User Name and Group to Unicode */ MultiByteToWideChar(CP_ACP, 0, UserName, - strlen(UserName) + 1, wszUserName, sizeof(wszUserName) / sizeof(wszUserName[0])); + strlen(UserName) + 1, wszUserName, sizeof(wszUserName) / sizeof(wszUserName[0])); /* - * Call the NetUserGetLocalGroups function + * Call the NetUserGetLocalGroups function * specifying information level 0. - * - * The LG_INCLUDE_INDIRECT flag specifies that the - * function should also return the names of the local + * + * The LG_INCLUDE_INDIRECT flag specifies that the + * function should also return the names of the local * groups in which the user is indirectly a member. */ nStatus = NetUserGetLocalGroups(NULL, - wszUserName, - dwLevel, - dwFlags, - &pBufTmp, - dwPrefMaxLen, - &dwEntriesRead, - &dwTotalEntries); + wszUserName, + dwLevel, + dwFlags, + &pBufTmp, + dwPrefMaxLen, + &dwEntriesRead, + &dwTotalEntries); pBuf = (LPLOCALGROUP_USERS_INFO_0) pBufTmp; /* * If the call succeeds, */ if (nStatus == NERR_Success) { - if ((pTmpBuf = pBuf) != NULL) { - for (i = 0; i < dwEntriesRead; i++) { - assert(pTmpBuf != NULL); - if (pTmpBuf == NULL) { - result = 0; - break; - } - if (wcstrcmparray(pTmpBuf->lgrui0_name, Groups) == 0) { - result = 1; - break; - } - pTmpBuf++; - dwTotalCount++; - } - } + if ((pTmpBuf = pBuf) != NULL) { + for (i = 0; i < dwEntriesRead; i++) { + assert(pTmpBuf != NULL); + if (pTmpBuf == NULL) { + result = 0; + break; + } + if (wcstrcmparray(pTmpBuf->lgrui0_name, Groups) == 0) { + result = 1; + break; + } + pTmpBuf++; + dwTotalCount++; + } + } } else - result = 0; -/* - * Free the allocated memory. - */ + result = 0; + /* + * Free the allocated memory. + */ if (pBuf != NULL) - NetApiBufferFree(pBuf); + NetApiBufferFree(pBuf); return result; } @@ -260,16 +260,16 @@ Valid_Global_Groups(char *UserName, const char **Groups) strncpy(NTDomain, UserName, sizeof(NTDomain)); for (j = 0; j < strlen(NTV_VALID_DOMAIN_SEPARATOR); j++) { - if ((domain_qualify = strchr(NTDomain, NTV_VALID_DOMAIN_SEPARATOR[j])) != NULL) - break; + if ((domain_qualify = strchr(NTDomain, NTV_VALID_DOMAIN_SEPARATOR[j])) != NULL) + break; } if (domain_qualify == NULL) { - strcpy(User, NTDomain); - strcpy(NTDomain, DefaultDomain); + strcpy(User, NTDomain); + strcpy(NTDomain, DefaultDomain); } else { - strcpy(User, domain_qualify + 1); - domain_qualify[0] = '\0'; - strlwr(NTDomain); + strcpy(User, domain_qualify + 1); + domain_qualify[0] = '\0'; + strlwr(NTDomain); } debug("Valid_Global_Groups: checking group membership of '%s\\%s'.\n", NTDomain, User); @@ -277,71 +277,71 @@ Valid_Global_Groups(char *UserName, const char **Groups) /* Convert ANSI User Name to Unicode */ MultiByteToWideChar(CP_ACP, 0, User, - strlen(User) + 1, wszUserName, - sizeof(wszUserName) / sizeof(wszUserName[0])); + strlen(User) + 1, wszUserName, + sizeof(wszUserName) / sizeof(wszUserName[0])); /* Query AD for a DC */ if (DsGetDcName(NULL, NTDomain, NULL, NULL, DS_IS_FLAT_NAME | DS_RETURN_FLAT_NAME, &pDCInfo) != NO_ERROR) { - fprintf(stderr, "%s DsGetDcName() failed.'\n", myname); - if (pDCInfo != NULL) - NetApiBufferFree(pDCInfo); - return result; + fprintf(stderr, "%s DsGetDcName() failed.'\n", myname); + if (pDCInfo != NULL) + NetApiBufferFree(pDCInfo); + return result; } /* Convert ANSI Domain Controller Name to Unicode */ MultiByteToWideChar(CP_ACP, 0, pDCInfo->DomainControllerName, - strlen(pDCInfo->DomainControllerName) + 1, wszDomainControllerName, - sizeof(wszDomainControllerName) / sizeof(wszDomainControllerName[0])); + strlen(pDCInfo->DomainControllerName) + 1, wszDomainControllerName, + sizeof(wszDomainControllerName) / sizeof(wszDomainControllerName[0])); debug("Using '%S' as DC for '%s' user's domain.\n", wszDomainControllerName, NTDomain); debug("DC Active Directory Site is %s\n", pDCInfo->DcSiteName); debug("Machine Active Directory Site is %s\n", pDCInfo->ClientSiteName); /* - * Call the NetUserGetGroups function + * Call the NetUserGetGroups function * specifying information level 0. */ dwLevel = 0; pBufTmp = NULL; nStatus = NetUserGetGroups(wszDomainControllerName, - wszUserName, - dwLevel, - &pBufTmp, - dwPrefMaxLen, - &dwEntriesRead, - &dwTotalEntries); + wszUserName, + dwLevel, + &pBufTmp, + dwPrefMaxLen, + &dwEntriesRead, + &dwTotalEntries); pUsrBuf = (LPGROUP_USERS_INFO_0) pBufTmp; /* * If the call succeeds, */ if (nStatus == NERR_Success) { - if ((pTmpBuf = pUsrBuf) != NULL) { - for (i = 0; i < dwEntriesRead; i++) { - assert(pTmpBuf != NULL); - if (pTmpBuf == NULL) { - result = 0; - break; - } - if (wcstrcmparray(pTmpBuf->grui0_name, Groups) == 0) { - result = 1; - break; - } - pTmpBuf++; - dwTotalCount++; - } - } + if ((pTmpBuf = pUsrBuf) != NULL) { + for (i = 0; i < dwEntriesRead; i++) { + assert(pTmpBuf != NULL); + if (pTmpBuf == NULL) { + result = 0; + break; + } + if (wcstrcmparray(pTmpBuf->grui0_name, Groups) == 0) { + result = 1; + break; + } + pTmpBuf++; + dwTotalCount++; + } + } } else { - result = 0; - fprintf(stderr, "%s NetUserGetGroups() failed.'\n", myname); + result = 0; + fprintf(stderr, "%s NetUserGetGroups() failed.'\n", myname); } /* * Free the allocated memory. */ if (pUsrBuf != NULL) - NetApiBufferFree(pUsrBuf); + NetApiBufferFree(pUsrBuf); if (pDCInfo != NULL) - NetApiBufferFree((LPVOID) pDCInfo); + NetApiBufferFree((LPVOID) pDCInfo); return result; } @@ -349,12 +349,12 @@ static void usage(char *program) { fprintf(stderr, "Usage: %s [-D domain][-G][-P][-c][-d][-h]\n" - " -D default user Domain\n" - " -G enable Domain Global group mode\n" - " -c use case insensitive compare\n" - " -d enable debugging\n" - " -h this message\n", - program); + " -D default user Domain\n" + " -G enable Domain Global group mode\n" + " -c use case insensitive compare\n" + " -d enable debugging\n" + " -h this message\n", + program); } void @@ -364,32 +364,32 @@ process_options(int argc, char *argv[]) opterr = 0; while (-1 != (opt = getopt(argc, argv, "D:Gcdh"))) { - switch (opt) { - case 'D': - DefaultDomain = xstrndup(optarg, DNLEN + 1); - strlwr(DefaultDomain); - break; - case 'G': - use_global = 1; - break; - case 'c': - use_case_insensitive_compare = 1; - break; - case 'd': - debug_enabled = 1; - break; - case 'h': - usage(argv[0]); - exit(0); - case '?': - opt = optopt; - /* fall thru to default */ - default: - fprintf(stderr, "%s Unknown option: -%c. Exiting\n", myname, opt); - usage(argv[0]); - exit(1); - break; /* not reached */ - } + switch (opt) { + case 'D': + DefaultDomain = xstrndup(optarg, DNLEN + 1); + strlwr(DefaultDomain); + break; + case 'G': + use_global = 1; + break; + case 'c': + use_case_insensitive_compare = 1; + break; + case 'd': + debug_enabled = 1; + break; + case 'h': + usage(argv[0]); + exit(0); + case '?': + opt = optopt; + /* fall thru to default */ + default: + fprintf(stderr, "%s Unknown option: -%c. Exiting\n", myname, opt); + usage(argv[0]); + exit(1); + break; /* not reached */ + } } return; } @@ -407,11 +407,11 @@ main(int argc, char *argv[]) int n; if (argc > 0) { /* should always be true */ - myname = strrchr(argv[0], '/'); - if (myname == NULL) - myname = argv[0]; + myname = strrchr(argv[0], '/'); + if (myname == NULL) + myname = argv[0]; } else { - myname = "(unknown)"; + myname = "(unknown)"; } mypid = getpid(); @@ -422,64 +422,64 @@ main(int argc, char *argv[]) process_options(argc, argv); if (use_global) { - if ((machinedomain = GetDomainName()) == NULL) { - fprintf(stderr, "%s Can't read machine domain\n", myname); - exit(1); - } - strlwr(machinedomain); - if (!DefaultDomain) - DefaultDomain = xstrdup(machinedomain); + if ((machinedomain = GetDomainName()) == NULL) { + fprintf(stderr, "%s Can't read machine domain\n", myname); + exit(1); + } + strlwr(machinedomain); + if (!DefaultDomain) + DefaultDomain = xstrdup(machinedomain); } debug("External ACL win32 group helper build " __DATE__ ", " __TIME__ - " starting up...\n"); + " starting up...\n"); if (use_global) - debug("Domain Global group mode enabled using '%s' as default domain.\n", DefaultDomain); + debug("Domain Global group mode enabled using '%s' as default domain.\n", DefaultDomain); if (use_case_insensitive_compare) - debug("Warning: running in case insensitive mode !!!\n"); + debug("Warning: running in case insensitive mode !!!\n"); /* Main Loop */ while (fgets(buf, sizeof(buf), stdin)) { - if (NULL == strchr(buf, '\n')) { - /* too large message received.. skip and deny */ - fprintf(stderr, "%s: ERROR: Too large: %s\n", argv[0], buf); - while (fgets(buf, sizeof(buf), stdin)) { - fprintf(stderr, "%s: ERROR: Too large..: %s\n", argv[0], buf); - if (strchr(buf, '\n') != NULL) - break; - } - goto error; - } - if ((p = strchr(buf, '\n')) != NULL) - *p = '\0'; /* strip \n */ - if ((p = strchr(buf, '\r')) != NULL) - *p = '\0'; /* strip \r */ - - debug("Got '%s' from Squid (length: %d).\n", buf, strlen(buf)); - - if (buf[0] == '\0') { - fprintf(stderr, "Invalid Request\n"); - goto error; - } - username = strtok(buf, " "); - for (n = 0; (group = strtok(NULL, " ")) != NULL; n++) { - rfc1738_unescape(group); - groups[n] = group; - } - groups[n] = NULL; - - if (NULL == username) { - fprintf(stderr, "Invalid Request\n"); - goto error; - } - rfc1738_unescape(username); - - if ((use_global ? Valid_Global_Groups(username, groups) : Valid_Local_Groups(username, groups))) { - printf("OK\n"); - } else { - error: - printf("ERR\n"); - } - err = 0; + if (NULL == strchr(buf, '\n')) { + /* too large message received.. skip and deny */ + fprintf(stderr, "%s: ERROR: Too large: %s\n", argv[0], buf); + while (fgets(buf, sizeof(buf), stdin)) { + fprintf(stderr, "%s: ERROR: Too large..: %s\n", argv[0], buf); + if (strchr(buf, '\n') != NULL) + break; + } + goto error; + } + if ((p = strchr(buf, '\n')) != NULL) + *p = '\0'; /* strip \n */ + if ((p = strchr(buf, '\r')) != NULL) + *p = '\0'; /* strip \r */ + + debug("Got '%s' from Squid (length: %d).\n", buf, strlen(buf)); + + if (buf[0] == '\0') { + fprintf(stderr, "Invalid Request\n"); + goto error; + } + username = strtok(buf, " "); + for (n = 0; (group = strtok(NULL, " ")) != NULL; n++) { + rfc1738_unescape(group); + groups[n] = group; + } + groups[n] = NULL; + + if (NULL == username) { + fprintf(stderr, "Invalid Request\n"); + goto error; + } + rfc1738_unescape(username); + + if ((use_global ? Valid_Global_Groups(username, groups) : Valid_Local_Groups(username, groups))) { + printf("OK\n"); + } else { +error: + printf("ERR\n"); + } + err = 0; } return 0; } diff --git a/helpers/external_acl/mswin_ad_group/mswin_check_ad_group.h b/helpers/external_acl/mswin_ad_group/mswin_check_ad_group.h index b1778a1ccc..041879ed21 100644 --- a/helpers/external_acl/mswin_ad_group/mswin_check_ad_group.h +++ b/helpers/external_acl/mswin_ad_group/mswin_check_ad_group.h @@ -9,7 +9,7 @@ * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - + * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -55,13 +55,13 @@ debug(char *format,...) #ifdef DEBUG #ifdef _SQUID_MSWIN_ if (debug_enabled) { - va_list args; + va_list args; - va_start(args, format); - fprintf(stderr, "%s[%d]: ", myname, mypid); - vfprintf(stderr, format, args); - fprintf(stderr, "\n"); - va_end(args); + va_start(args, format); + fprintf(stderr, "%s[%d]: ", myname, mypid); + vfprintf(stderr, format, args); + fprintf(stderr, "\n"); + va_end(args); } #endif /* _SQUID_MSWIN_ */ #endif /* DEBUG */ diff --git a/helpers/external_acl/mswin_lm_group/win32_check_group.c b/helpers/external_acl/mswin_lm_group/win32_check_group.c index 99398b716c..da5d41fc23 100644 --- a/helpers/external_acl/mswin_lm_group/win32_check_group.c +++ b/helpers/external_acl/mswin_lm_group/win32_check_group.c @@ -34,7 +34,7 @@ * 08-07-2005 Guido Serassio * Added -P option for force usage of PDCs for group validation. * Added support for '/' char as domain separator. - * Fixed Bugzilla #1336. + * Fixed Bugzilla #1336. * Version 1.21 * 23-04-2005 Guido Serassio * Added -D option for specify default user's domain. @@ -57,7 +57,7 @@ * from wbinfo wrote win32_group * * This is a helper for the external ACL interface for Squid Cache - * + * * It reads from the standard input the domain username and a list of * groups and tries to match it against the groups membership of the * specified username. @@ -118,7 +118,7 @@ AllocStrFromLSAStr(LSA_UNICODE_STRING LsaStr) safe_free(target); target = (char *) xmalloc(len); if (target == NULL) - return NULL; + return NULL; /* copy unicode buffer */ WideCharToMultiByte(CP_ACP, 0, LsaStr.Buffer, LsaStr.Length, target, len, NULL, NULL); @@ -140,96 +140,96 @@ GetDomainName(void) DWORD netret; char *DomainName = NULL; - /* + /* * Always initialize the object attributes to all zeroes. */ memset(&ObjectAttributes, '\0', sizeof(ObjectAttributes)); - /* + /* * You need the local workstation name. Use NetWkstaGetInfo at level * 100 to retrieve a WKSTA_INFO_100 structure. - * + * * The wki100_computername field contains a pointer to a UNICODE * string containing the local computer name. */ netret = NetWkstaGetInfo(NULL, 100, (LPBYTE *) & pwkiWorkstationInfo); if (netret == NERR_Success) { - /* - * We have the workstation name in: - * pwkiWorkstationInfo->wki100_computername - * - * Next, open the policy object for the local system using - * the LsaOpenPolicy function. - */ - status = LsaOpenPolicy( - NULL, - &ObjectAttributes, - GENERIC_READ | POLICY_VIEW_LOCAL_INFORMATION, - &PolicyHandle - ); - - /* - * Error checking. - */ - if (status) { - debug("OpenPolicy Error: %ld\n", status); - } else { - - /* - * You have a handle to the policy object. Now, get the - * domain information using LsaQueryInformationPolicy. - */ - status = LsaQueryInformationPolicy(PolicyHandle, - PolicyPrimaryDomainInformation, - (PVOID *) & ppdiDomainInfo); - if (status) { - debug("LsaQueryInformationPolicy Error: %ld\n", status); - } else { - - /* Get name in useable format */ - DomainName = AllocStrFromLSAStr(ppdiDomainInfo->Name); - - /* - * Check the Sid pointer, if it is null, the - * workstation is either a stand-alone computer - * or a member of a workgroup. - */ - if (ppdiDomainInfo->Sid) { - - /* - * Member of a domain. Display it in debug mode. - */ - debug("Member of Domain %s\n", DomainName); - } else { - DomainName = NULL; - } - } - } - - /* - * Clean up all the memory buffers created by the LSA and - * Net* APIs. - */ - NetApiBufferFree(pwkiWorkstationInfo); - LsaFreeMemory((LPVOID) ppdiDomainInfo); + /* + * We have the workstation name in: + * pwkiWorkstationInfo->wki100_computername + * + * Next, open the policy object for the local system using + * the LsaOpenPolicy function. + */ + status = LsaOpenPolicy( + NULL, + &ObjectAttributes, + GENERIC_READ | POLICY_VIEW_LOCAL_INFORMATION, + &PolicyHandle + ); + + /* + * Error checking. + */ + if (status) { + debug("OpenPolicy Error: %ld\n", status); + } else { + + /* + * You have a handle to the policy object. Now, get the + * domain information using LsaQueryInformationPolicy. + */ + status = LsaQueryInformationPolicy(PolicyHandle, + PolicyPrimaryDomainInformation, + (PVOID *) & ppdiDomainInfo); + if (status) { + debug("LsaQueryInformationPolicy Error: %ld\n", status); + } else { + + /* Get name in useable format */ + DomainName = AllocStrFromLSAStr(ppdiDomainInfo->Name); + + /* + * Check the Sid pointer, if it is null, the + * workstation is either a stand-alone computer + * or a member of a workgroup. + */ + if (ppdiDomainInfo->Sid) { + + /* + * Member of a domain. Display it in debug mode. + */ + debug("Member of Domain %s\n", DomainName); + } else { + DomainName = NULL; + } + } + } + + /* + * Clean up all the memory buffers created by the LSA and + * Net* APIs. + */ + NetApiBufferFree(pwkiWorkstationInfo); + LsaFreeMemory((LPVOID) ppdiDomainInfo); } else - debug("NetWkstaGetInfo Error: %ld\n", netret); + debug("NetWkstaGetInfo Error: %ld\n", netret); return DomainName; } /* returns 0 on match, -1 if no match */ -static int +static int wcstrcmparray(const wchar_t * str, const char **array) { WCHAR wszGroup[GNLEN + 1]; // Unicode Group while (*array) { - MultiByteToWideChar(CP_ACP, 0, *array, - strlen(*array) + 1, wszGroup, sizeof(wszGroup) / sizeof(wszGroup[0])); - debug("Windows group: %S, Squid group: %S\n", str, wszGroup); - if ((use_case_insensitive_compare ? _wcsicmp(str, wszGroup) : wcscmp(str, wszGroup)) == 0) - return 0; - array++; + MultiByteToWideChar(CP_ACP, 0, *array, + strlen(*array) + 1, wszGroup, sizeof(wszGroup) / sizeof(wszGroup[0])); + debug("Windows group: %S, Squid group: %S\n", str, wszGroup); + if ((use_case_insensitive_compare ? _wcsicmp(str, wszGroup) : wcscmp(str, wszGroup)) == 0) + return 0; + array++; } return -1; } @@ -254,58 +254,58 @@ Valid_Local_Groups(char *UserName, const char **Groups) DWORD dwTotalCount = 0; if ((Domain_Separator = strchr(UserName, '/')) != NULL) - *Domain_Separator = '\\'; + *Domain_Separator = '\\'; debug("Valid_Local_Groups: checking group membership of '%s'.\n", UserName); -/* Convert ANSI User Name and Group to Unicode */ + /* Convert ANSI User Name and Group to Unicode */ MultiByteToWideChar(CP_ACP, 0, UserName, - strlen(UserName) + 1, wszUserName, sizeof(wszUserName) / sizeof(wszUserName[0])); + strlen(UserName) + 1, wszUserName, sizeof(wszUserName) / sizeof(wszUserName[0])); /* - * Call the NetUserGetLocalGroups function + * Call the NetUserGetLocalGroups function * specifying information level 0. - * - * The LG_INCLUDE_INDIRECT flag specifies that the - * function should also return the names of the local + * + * The LG_INCLUDE_INDIRECT flag specifies that the + * function should also return the names of the local * groups in which the user is indirectly a member. */ nStatus = NetUserGetLocalGroups( - NULL, - wszUserName, - dwLevel, - dwFlags, - (LPBYTE *) & pBuf, - dwPrefMaxLen, - &dwEntriesRead, - &dwTotalEntries); + NULL, + wszUserName, + dwLevel, + dwFlags, + (LPBYTE *) & pBuf, + dwPrefMaxLen, + &dwEntriesRead, + &dwTotalEntries); /* * If the call succeeds, */ if (nStatus == NERR_Success) { - if ((pTmpBuf = pBuf) != NULL) { - for (i = 0; i < dwEntriesRead; i++) { - assert(pTmpBuf != NULL); - if (pTmpBuf == NULL) { - result = 0; - break; - } - if (wcstrcmparray(pTmpBuf->lgrui0_name, Groups) == 0) { - result = 1; - break; - } - pTmpBuf++; - dwTotalCount++; - } - } + if ((pTmpBuf = pBuf) != NULL) { + for (i = 0; i < dwEntriesRead; i++) { + assert(pTmpBuf != NULL); + if (pTmpBuf == NULL) { + result = 0; + break; + } + if (wcstrcmparray(pTmpBuf->lgrui0_name, Groups) == 0) { + result = 1; + break; + } + pTmpBuf++; + dwTotalCount++; + } + } } else - result = 0; -/* - * Free the allocated memory. - */ + result = 0; + /* + * Free the allocated memory. + */ if (pBuf != NULL) - NetApiBufferFree(pBuf); + NetApiBufferFree(pBuf); return result; } @@ -342,16 +342,16 @@ Valid_Global_Groups(char *UserName, const char **Groups) strncpy(NTDomain, UserName, sizeof(NTDomain)); for (j = 0; j < strlen(NTV_VALID_DOMAIN_SEPARATOR); j++) { - if ((domain_qualify = strchr(NTDomain, NTV_VALID_DOMAIN_SEPARATOR[j])) != NULL) - break; + if ((domain_qualify = strchr(NTDomain, NTV_VALID_DOMAIN_SEPARATOR[j])) != NULL) + break; } if (domain_qualify == NULL) { - strcpy(User, NTDomain); - strcpy(NTDomain, DefaultDomain); + strcpy(User, NTDomain); + strcpy(NTDomain, DefaultDomain); } else { - strcpy(User, domain_qualify + 1); - domain_qualify[0] = '\0'; - strlwr(NTDomain); + strcpy(User, domain_qualify + 1); + domain_qualify[0] = '\0'; + strlwr(NTDomain); } debug("Valid_Global_Groups: checking group membership of '%s\\%s'.\n", NTDomain, User); @@ -359,101 +359,101 @@ Valid_Global_Groups(char *UserName, const char **Groups) /* Convert ANSI User Name and Group to Unicode */ MultiByteToWideChar(CP_ACP, 0, User, - strlen(User) + 1, wszUserName, - sizeof(wszUserName) / sizeof(wszUserName[0])); + strlen(User) + 1, wszUserName, + sizeof(wszUserName) / sizeof(wszUserName[0])); MultiByteToWideChar(CP_ACP, 0, machinedomain, - strlen(machinedomain) + 1, wszLocalDomain, sizeof(wszLocalDomain) / sizeof(wszLocalDomain[0])); + strlen(machinedomain) + 1, wszLocalDomain, sizeof(wszLocalDomain) / sizeof(wszLocalDomain[0])); -/* Call the NetServerGetInfo function for local computer, specifying level 101. */ + /* Call the NetServerGetInfo function for local computer, specifying level 101. */ dwLevel = 101; nStatus = NetServerGetInfo(NULL, dwLevel, (LPBYTE *) & pSrvBuf); if (nStatus == NERR_Success) { - /* Check if we are running on a Domain Controller */ - if ((pSrvBuf->sv101_type & SV_TYPE_DOMAIN_CTRL) || - (pSrvBuf->sv101_type & SV_TYPE_DOMAIN_BAKCTRL)) { - LclDCptr = NULL; - debug("Running on a DC.\n"); - } else - nStatus = (use_PDC_only ? NetGetDCName(NULL, wszLocalDomain, (LPBYTE *) & LclDCptr) : NetGetAnyDCName(NULL, wszLocalDomain, (LPBYTE *) & LclDCptr)); + /* Check if we are running on a Domain Controller */ + if ((pSrvBuf->sv101_type & SV_TYPE_DOMAIN_CTRL) || + (pSrvBuf->sv101_type & SV_TYPE_DOMAIN_BAKCTRL)) { + LclDCptr = NULL; + debug("Running on a DC.\n"); + } else + nStatus = (use_PDC_only ? NetGetDCName(NULL, wszLocalDomain, (LPBYTE *) & LclDCptr) : NetGetAnyDCName(NULL, wszLocalDomain, (LPBYTE *) & LclDCptr)); } else { - fprintf(stderr, "%s NetServerGetInfo() failed.'\n", myname); - if (pSrvBuf != NULL) - NetApiBufferFree(pSrvBuf); - return result; + fprintf(stderr, "%s NetServerGetInfo() failed.'\n", myname); + if (pSrvBuf != NULL) + NetApiBufferFree(pSrvBuf); + return result; } if (nStatus == NERR_Success) { - debug("Using '%S' as DC for '%S' local domain.\n", LclDCptr, wszLocalDomain); - - if (strcmp(NTDomain, machinedomain) != 0) { - MultiByteToWideChar(CP_ACP, 0, NTDomain, - strlen(NTDomain) + 1, wszUserDomain, sizeof(wszUserDomain) / sizeof(wszUserDomain[0])); - nStatus = (use_PDC_only ? NetGetDCName(LclDCptr, wszUserDomain, (LPBYTE *) & UsrDCptr) : NetGetAnyDCName(LclDCptr, wszUserDomain, (LPBYTE *) & UsrDCptr)); - if (nStatus != NERR_Success) { - fprintf(stderr, "%s Can't find DC for user's domain '%s'\n", myname, NTDomain); - if (pSrvBuf != NULL) - NetApiBufferFree(pSrvBuf); - if (LclDCptr != NULL) - NetApiBufferFree((LPVOID) LclDCptr); - if (UsrDCptr != NULL) - NetApiBufferFree((LPVOID) UsrDCptr); - return result; - } - } else - UsrDCptr = LclDCptr; - - debug("Using '%S' as DC for '%s' user's domain.\n", UsrDCptr, NTDomain); - /* - * Call the NetUserGetGroups function - * specifying information level 0. - */ - dwLevel = 0; - nStatus = NetUserGetGroups(UsrDCptr, - wszUserName, - dwLevel, - (LPBYTE *) & pUsrBuf, - dwPrefMaxLen, - &dwEntriesRead, - &dwTotalEntries); - /* - * If the call succeeds, - */ - if (nStatus == NERR_Success) { - if ((pTmpBuf = pUsrBuf) != NULL) { - for (i = 0; i < dwEntriesRead; i++) { - assert(pTmpBuf != NULL); - if (pTmpBuf == NULL) { - result = 0; - break; - } - if (wcstrcmparray(pTmpBuf->grui0_name, Groups) == 0) { - result = 1; - break; - } - pTmpBuf++; - dwTotalCount++; - } - } - } else { - result = 0; - fprintf(stderr, "%s NetUserGetGroups() failed.'\n", myname); - } + debug("Using '%S' as DC for '%S' local domain.\n", LclDCptr, wszLocalDomain); + + if (strcmp(NTDomain, machinedomain) != 0) { + MultiByteToWideChar(CP_ACP, 0, NTDomain, + strlen(NTDomain) + 1, wszUserDomain, sizeof(wszUserDomain) / sizeof(wszUserDomain[0])); + nStatus = (use_PDC_only ? NetGetDCName(LclDCptr, wszUserDomain, (LPBYTE *) & UsrDCptr) : NetGetAnyDCName(LclDCptr, wszUserDomain, (LPBYTE *) & UsrDCptr)); + if (nStatus != NERR_Success) { + fprintf(stderr, "%s Can't find DC for user's domain '%s'\n", myname, NTDomain); + if (pSrvBuf != NULL) + NetApiBufferFree(pSrvBuf); + if (LclDCptr != NULL) + NetApiBufferFree((LPVOID) LclDCptr); + if (UsrDCptr != NULL) + NetApiBufferFree((LPVOID) UsrDCptr); + return result; + } + } else + UsrDCptr = LclDCptr; + + debug("Using '%S' as DC for '%s' user's domain.\n", UsrDCptr, NTDomain); + /* + * Call the NetUserGetGroups function + * specifying information level 0. + */ + dwLevel = 0; + nStatus = NetUserGetGroups(UsrDCptr, + wszUserName, + dwLevel, + (LPBYTE *) & pUsrBuf, + dwPrefMaxLen, + &dwEntriesRead, + &dwTotalEntries); + /* + * If the call succeeds, + */ + if (nStatus == NERR_Success) { + if ((pTmpBuf = pUsrBuf) != NULL) { + for (i = 0; i < dwEntriesRead; i++) { + assert(pTmpBuf != NULL); + if (pTmpBuf == NULL) { + result = 0; + break; + } + if (wcstrcmparray(pTmpBuf->grui0_name, Groups) == 0) { + result = 1; + break; + } + pTmpBuf++; + dwTotalCount++; + } + } + } else { + result = 0; + fprintf(stderr, "%s NetUserGetGroups() failed.'\n", myname); + } } else { - fprintf(stderr, "%s Can't find DC for local domain '%s'\n", myname, machinedomain); + fprintf(stderr, "%s Can't find DC for local domain '%s'\n", myname, machinedomain); } /* * Free the allocated memory. */ if (pSrvBuf != NULL) - NetApiBufferFree(pSrvBuf); + NetApiBufferFree(pSrvBuf); if (pUsrBuf != NULL) - NetApiBufferFree(pUsrBuf); + NetApiBufferFree(pUsrBuf); if ((UsrDCptr != NULL) && (UsrDCptr != LclDCptr)) - NetApiBufferFree((LPVOID) UsrDCptr); + NetApiBufferFree((LPVOID) UsrDCptr); if (LclDCptr != NULL) - NetApiBufferFree((LPVOID) LclDCptr); + NetApiBufferFree((LPVOID) LclDCptr); return result; } @@ -461,13 +461,13 @@ static void usage(char *program) { fprintf(stderr, "Usage: %s [-D domain][-G][-P][-c][-d][-h]\n" - " -D default user Domain\n" - " -G enable Domain Global group mode\n" - " -P use ONLY PDCs for group validation\n" - " -c use case insensitive compare\n" - " -d enable debugging\n" - " -h this message\n", - program); + " -D default user Domain\n" + " -G enable Domain Global group mode\n" + " -P use ONLY PDCs for group validation\n" + " -c use case insensitive compare\n" + " -d enable debugging\n" + " -h this message\n", + program); } void @@ -477,35 +477,35 @@ process_options(int argc, char *argv[]) opterr = 0; while (-1 != (opt = getopt(argc, argv, "D:GPcdh"))) { - switch (opt) { - case 'D': - DefaultDomain = xstrndup(optarg, DNLEN + 1); - strlwr(DefaultDomain); - break; - case 'G': - use_global = 1; - break; - case 'P': - use_PDC_only = 1; - break; - case 'c': - use_case_insensitive_compare = 1; - break; - case 'd': - debug_enabled = 1; - break; - case 'h': - usage(argv[0]); - exit(0); - case '?': - opt = optopt; - /* fall thru to default */ - default: - fprintf(stderr, "%s Unknown option: -%c. Exiting\n", myname, opt); - usage(argv[0]); - exit(1); - break; /* not reached */ - } + switch (opt) { + case 'D': + DefaultDomain = xstrndup(optarg, DNLEN + 1); + strlwr(DefaultDomain); + break; + case 'G': + use_global = 1; + break; + case 'P': + use_PDC_only = 1; + break; + case 'c': + use_case_insensitive_compare = 1; + break; + case 'd': + debug_enabled = 1; + break; + case 'h': + usage(argv[0]); + exit(0); + case '?': + opt = optopt; + /* fall thru to default */ + default: + fprintf(stderr, "%s Unknown option: -%c. Exiting\n", myname, opt); + usage(argv[0]); + exit(1); + break; /* not reached */ + } } return; } @@ -523,11 +523,11 @@ main(int argc, char *argv[]) int n; if (argc > 0) { /* should always be true */ - myname = strrchr(argv[0], '/'); - if (myname == NULL) - myname = argv[0]; + myname = strrchr(argv[0], '/'); + if (myname == NULL) + myname = argv[0]; } else { - myname = "(unknown)"; + myname = "(unknown)"; } mypid = getpid(); @@ -538,66 +538,66 @@ main(int argc, char *argv[]) process_options(argc, argv); if (use_global) { - if ((machinedomain = GetDomainName()) == NULL) { - fprintf(stderr, "%s Can't read machine domain\n", myname); - exit(1); - } - strlwr(machinedomain); - if (!DefaultDomain) - DefaultDomain = xstrdup(machinedomain); + if ((machinedomain = GetDomainName()) == NULL) { + fprintf(stderr, "%s Can't read machine domain\n", myname); + exit(1); + } + strlwr(machinedomain); + if (!DefaultDomain) + DefaultDomain = xstrdup(machinedomain); } debug("External ACL win32 group helper build " __DATE__ ", " __TIME__ - " starting up...\n"); + " starting up...\n"); if (use_global) - debug("Domain Global group mode enabled using '%s' as default domain.\n", DefaultDomain); + debug("Domain Global group mode enabled using '%s' as default domain.\n", DefaultDomain); if (use_case_insensitive_compare) - debug("Warning: running in case insensitive mode !!!\n"); + debug("Warning: running in case insensitive mode !!!\n"); if (use_PDC_only) - debug("Warning: using only PDCs for group validation !!!\n"); + debug("Warning: using only PDCs for group validation !!!\n"); /* Main Loop */ while (fgets(buf, sizeof(buf), stdin)) { - if (NULL == strchr(buf, '\n')) { - /* too large message received.. skip and deny */ - fprintf(stderr, "%s: ERROR: Too large: %s\n", argv[0], buf); - while (fgets(buf, sizeof(buf), stdin)) { - fprintf(stderr, "%s: ERROR: Too large..: %s\n", argv[0], buf); - if (strchr(buf, '\n') != NULL) - break; - } - goto error; - } - if ((p = strchr(buf, '\n')) != NULL) - *p = '\0'; /* strip \n */ - if ((p = strchr(buf, '\r')) != NULL) - *p = '\0'; /* strip \r */ - - debug("Got '%s' from Squid (length: %d).\n", buf, strlen(buf)); - - if (buf[0] == '\0') { - fprintf(stderr, "Invalid Request\n"); - goto error; - } - username = strtok(buf, " "); - for (n = 0; (group = strtok(NULL, " ")) != NULL; n++) { - rfc1738_unescape(group); - groups[n] = group; - } - groups[n] = NULL; - - if (NULL == username) { - fprintf(stderr, "Invalid Request\n"); - goto error; - } - rfc1738_unescape(username); - - if ((use_global ? Valid_Global_Groups(username, groups) : Valid_Local_Groups(username, groups))) { - printf("OK\n"); - } else { - error: - printf("ERR\n"); - } - err = 0; + if (NULL == strchr(buf, '\n')) { + /* too large message received.. skip and deny */ + fprintf(stderr, "%s: ERROR: Too large: %s\n", argv[0], buf); + while (fgets(buf, sizeof(buf), stdin)) { + fprintf(stderr, "%s: ERROR: Too large..: %s\n", argv[0], buf); + if (strchr(buf, '\n') != NULL) + break; + } + goto error; + } + if ((p = strchr(buf, '\n')) != NULL) + *p = '\0'; /* strip \n */ + if ((p = strchr(buf, '\r')) != NULL) + *p = '\0'; /* strip \r */ + + debug("Got '%s' from Squid (length: %d).\n", buf, strlen(buf)); + + if (buf[0] == '\0') { + fprintf(stderr, "Invalid Request\n"); + goto error; + } + username = strtok(buf, " "); + for (n = 0; (group = strtok(NULL, " ")) != NULL; n++) { + rfc1738_unescape(group); + groups[n] = group; + } + groups[n] = NULL; + + if (NULL == username) { + fprintf(stderr, "Invalid Request\n"); + goto error; + } + rfc1738_unescape(username); + + if ((use_global ? Valid_Global_Groups(username, groups) : Valid_Local_Groups(username, groups))) { + printf("OK\n"); + } else { +error: + printf("ERR\n"); + } + err = 0; } return 0; } diff --git a/helpers/external_acl/mswin_lm_group/win32_check_group.h b/helpers/external_acl/mswin_lm_group/win32_check_group.h index b1778a1ccc..041879ed21 100644 --- a/helpers/external_acl/mswin_lm_group/win32_check_group.h +++ b/helpers/external_acl/mswin_lm_group/win32_check_group.h @@ -9,7 +9,7 @@ * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - + * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -55,13 +55,13 @@ debug(char *format,...) #ifdef DEBUG #ifdef _SQUID_MSWIN_ if (debug_enabled) { - va_list args; + va_list args; - va_start(args, format); - fprintf(stderr, "%s[%d]: ", myname, mypid); - vfprintf(stderr, format, args); - fprintf(stderr, "\n"); - va_end(args); + va_start(args, format); + fprintf(stderr, "%s[%d]: ", myname, mypid); + vfprintf(stderr, format, args); + fprintf(stderr, "\n"); + va_end(args); } #endif /* _SQUID_MSWIN_ */ #endif /* DEBUG */ diff --git a/helpers/external_acl/session/squid_session.c b/helpers/external_acl/session/squid_session.c index bb9de88c45..2328a66fb2 100644 --- a/helpers/external_acl/session/squid_session.c +++ b/helpers/external_acl/session/squid_session.c @@ -7,12 +7,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -54,8 +54,8 @@ static void init_db(void) { db = dbopen(db_path, O_CREAT | O_RDWR, 0666, DB_BTREE, NULL); if (!db) { - fprintf(stderr, "%s: Failed to open session db '%s'\n", program_name, db_path); - exit(1); + fprintf(stderr, "%s: Failed to open session db '%s'\n", program_name, db_path); + exit(1); } } @@ -72,15 +72,15 @@ static int session_active(const char *details) key.data = (void *)details; key.size = strlen(details); if (db->get(db, &key, &data, 0) == 0) { - time_t timestamp; - if (data.size != sizeof(timestamp)) { - fprintf(stderr, "%s: CORRUPTED DATABASE (%s)\n", program_name, details); - db->del(db, &key, 0); - return 0; - } - memcpy(×tamp, data.data, sizeof(timestamp)); - if (timestamp + session_ttl >= time(NULL)) - return 1; + time_t timestamp; + if (data.size != sizeof(timestamp)) { + fprintf(stderr, "%s: CORRUPTED DATABASE (%s)\n", program_name, details); + db->del(db, &key, 0); + return 0; + } + memcpy(×tamp, data.data, sizeof(timestamp)); + if (timestamp + session_ttl >= time(NULL)) + return 1; } return 0; } @@ -120,21 +120,21 @@ int main(int argc, char **argv) program_name = argv[0]; while ((opt = getopt(argc, argv, "t:b:a?")) != -1) { - switch(opt) { - case 't': - session_ttl = strtol(optarg, NULL, 0); - break; - case 'b': - db_path = optarg; - break; - case 'a': - default_action = 0; - break; - case '?': - usage(); - exit(0); - break; - } + switch (opt) { + case 't': + session_ttl = strtol(optarg, NULL, 0); + break; + case 'b': + db_path = optarg; + break; + case 'a': + default_action = 0; + break; + case '?': + usage(); + exit(0); + break; + } } setbuf(stdout, NULL); @@ -142,36 +142,36 @@ int main(int argc, char **argv) init_db(); while (fgets(request, sizeof(request), stdin)) { - const char *index, *detail; - char *lastdetail; - int action = 0; - index = strtok(request, " \n"); - detail = strtok(NULL, "\n"); - lastdetail = strrchr(detail, ' '); - if (lastdetail) { - if (strcmp(lastdetail, " LOGIN") == 0) { - *lastdetail++ = '\0'; - action = 1; - } else if (strcmp(lastdetail, " LOGOUT") == 0) { - action = -1; - *lastdetail++ = '\0'; - } - } - if (action == -1) { - session_logout(detail); - printf("%s OK message=\"Bye\"\n", index); - } else if (action == 1) { - session_login(detail); - printf("%s OK message=\"Welcome\"\n", index); - } else if (session_active(detail)) { - session_login(detail); - printf("%s OK\n", index); - } else if (default_action == 1) { - session_login(detail); - printf("%s ERR message=\"Welcome\"\n", index); - } else { - printf("%s ERR message=\"No session available\"\n", index); - } + const char *index, *detail; + char *lastdetail; + int action = 0; + index = strtok(request, " \n"); + detail = strtok(NULL, "\n"); + lastdetail = strrchr(detail, ' '); + if (lastdetail) { + if (strcmp(lastdetail, " LOGIN") == 0) { + *lastdetail++ = '\0'; + action = 1; + } else if (strcmp(lastdetail, " LOGOUT") == 0) { + action = -1; + *lastdetail++ = '\0'; + } + } + if (action == -1) { + session_logout(detail); + printf("%s OK message=\"Bye\"\n", index); + } else if (action == 1) { + session_login(detail); + printf("%s OK message=\"Welcome\"\n", index); + } else if (session_active(detail)) { + session_login(detail); + printf("%s OK\n", index); + } else if (default_action == 1) { + session_login(detail); + printf("%s ERR message=\"Welcome\"\n", index); + } else { + printf("%s ERR message=\"No session available\"\n", index); + } } shutdown_db(); return 0; diff --git a/helpers/external_acl/unix_group/check_group.c b/helpers/external_acl/unix_group/check_group.c index 27286043d3..40cf0bb785 100644 --- a/helpers/external_acl/unix_group/check_group.c +++ b/helpers/external_acl/unix_group/check_group.c @@ -3,9 +3,9 @@ * * This is a helper for the external ACL interface for Squid Cache * Copyright (C) 2002 Rodrigo Albani de Campos (rodrigo@geekbunker.org) - * + * * It reads STDIN looking for a username that matches a specified group - * Returns `OK' if the user belongs to the group or `ERR' otherwise, as + * Returns `OK' if the user belongs to the group or `ERR' otherwise, as * described on http://devel.squid-cache.org/external_acl/config.html * To compile this program, use: * @@ -65,9 +65,9 @@ #define BUFSIZE 8192 /* the stdin buffer size */ #define MAX_GROUP 10 /* maximum number of groups specified - * on the command line */ +* on the command line */ -/* +/* * Verify if user´s primary group matches groupname * Returns 0 if user is not on the group * Returns 1 otherwise @@ -79,15 +79,15 @@ validate_user_pw(char *username, char *groupname) struct group *g; if ((p = getpwnam(username)) == NULL) { - /* Returns an error if user does not exist in the /etc/passwd */ - fprintf(stderr, "helper: User does not exist '%s'\n", username); - return 0; + /* Returns an error if user does not exist in the /etc/passwd */ + fprintf(stderr, "helper: User does not exist '%s'\n", username); + return 0; } else { - /* Verify if the this is the primary user group */ - if ((g = getgrgid(p->pw_gid)) != NULL) { - if ((strcmp(groupname, g->gr_name)) == 0) - return 1; - } + /* Verify if the this is the primary user group */ + if ((g = getgrgid(p->pw_gid)) != NULL) { + if ((strcmp(groupname, g->gr_name)) == 0) + return 1; + } } return 0; @@ -96,22 +96,22 @@ validate_user_pw(char *username, char *groupname) static int validate_user_gr(char *username, char *groupname) { - /* + /* * Verify if the user belongs to groupname as listed in the * /etc/group file */ struct group *g; if ((g = getgrnam(groupname)) == NULL) { - fprintf(stderr, "helper: Group does not exist '%s'\n", - groupname); - return 0; + fprintf(stderr, "helper: Group does not exist '%s'\n", + groupname); + return 0; } else { - while (*(g->gr_mem) != NULL) { - if (strcmp(*((g->gr_mem)++), username) == 0) { - return 1; - } - } + while (*(g->gr_mem) != NULL) { + if (strcmp(*((g->gr_mem)++), username) == 0) { + return 1; + } + } } return 0; } @@ -120,16 +120,16 @@ static void usage(char *program) { fprintf(stderr, "Usage: %s -g group1 [-g group2 ...] [-p] [-s]\n\n", - program); + program); fprintf(stderr, "-g group\n"); fprintf(stderr, - " The group name or id that the user must belong in order to\n"); + " The group name or id that the user must belong in order to\n"); fprintf(stderr, - " be allowed to authenticate.\n"); + " be allowed to authenticate.\n"); fprintf(stderr, - "-p Verify primary user group as well\n"); + "-p Verify primary user group as well\n"); fprintf(stderr, - "-s Strip NT domain from usernames\n"); + "-s Strip NT domain from usernames\n"); } @@ -146,89 +146,89 @@ main(int argc, char *argv[]) /* get user options */ while ((ch = getopt(argc, argv, "spg:")) != -1) { - switch (ch) { - case 's': - strip_dm = 1; - break; - case 'p': - check_pw = 1; - break; - case 'g': - grents[i] = calloc(strlen(optarg) + 1, sizeof(char)); - strcpy(grents[i], optarg); - if (i < MAX_GROUP) { - i++; - } else { - fprintf(stderr, - "Exceeded maximum number of allowed groups (%i)\n", i); - exit(1); - } - break; - case '?': - if (xisprint(optopt)) { - - fprintf(stderr, "Unknown option '-%c'.\n", optopt); - } else { - fprintf(stderr, "Unknown option character `\\x%x'.\n", optopt); - } - - default: - usage(argv[0]); - exit(1); - } + switch (ch) { + case 's': + strip_dm = 1; + break; + case 'p': + check_pw = 1; + break; + case 'g': + grents[i] = calloc(strlen(optarg) + 1, sizeof(char)); + strcpy(grents[i], optarg); + if (i < MAX_GROUP) { + i++; + } else { + fprintf(stderr, + "Exceeded maximum number of allowed groups (%i)\n", i); + exit(1); + } + break; + case '?': + if (xisprint(optopt)) { + + fprintf(stderr, "Unknown option '-%c'.\n", optopt); + } else { + fprintf(stderr, "Unknown option character `\\x%x'.\n", optopt); + } + + default: + usage(argv[0]); + exit(1); + } } if (optind < argc) { - fprintf(stderr, "Unknown option '%s'\n", argv[optind]); - usage(argv[0]); - exit(1); + fprintf(stderr, "Unknown option '%s'\n", argv[optind]); + usage(argv[0]); + exit(1); } while (fgets(buf, sizeof(buf), stdin)) { - j = 0; - if ((p = strchr(buf, '\n')) == NULL) { - /* too large message received.. skip and deny */ - fprintf(stderr, "%s: ERROR: Too large: %s\n", argv[0], buf); - while (fgets(buf, sizeof(buf), stdin)) { - fprintf(stderr, "%s: ERROR: Too large..: %s\n", argv[0], buf); - if (strchr(buf, '\n') != NULL) - break; - } - goto error; - } - *p = '\0'; - if ((p = strtok(buf, " ")) == NULL) { - goto error; - } else { - user = p; - rfc1738_unescape(user); - if (user && strip_dm) { - suser = strchr(user, '\\'); - if (!suser) suser = strchr(user, '/'); - if (suser && suser[1]) user = suser + 1; - } - /* check groups supplied by Squid */ - while ((p = strtok(NULL, " ")) != NULL) { - rfc1738_unescape(p); - if (check_pw == 1) - j += validate_user_pw(user, p); - - j += validate_user_gr(user, p); - } - } - - /* check groups supplied on the command line */ - for (i = 0; grents[i] != NULL; i++) { - if (check_pw == 1) { - j += validate_user_pw(user, grents[i]); - } - j += validate_user_gr(user, grents[i]); - } - - if (j > 0) { - printf("OK\n"); - } else { + j = 0; + if ((p = strchr(buf, '\n')) == NULL) { + /* too large message received.. skip and deny */ + fprintf(stderr, "%s: ERROR: Too large: %s\n", argv[0], buf); + while (fgets(buf, sizeof(buf), stdin)) { + fprintf(stderr, "%s: ERROR: Too large..: %s\n", argv[0], buf); + if (strchr(buf, '\n') != NULL) + break; + } + goto error; + } + *p = '\0'; + if ((p = strtok(buf, " ")) == NULL) { + goto error; + } else { + user = p; + rfc1738_unescape(user); + if (user && strip_dm) { + suser = strchr(user, '\\'); + if (!suser) suser = strchr(user, '/'); + if (suser && suser[1]) user = suser + 1; + } + /* check groups supplied by Squid */ + while ((p = strtok(NULL, " ")) != NULL) { + rfc1738_unescape(p); + if (check_pw == 1) + j += validate_user_pw(user, p); + + j += validate_user_gr(user, p); + } + } + + /* check groups supplied on the command line */ + for (i = 0; grents[i] != NULL; i++) { + if (check_pw == 1) { + j += validate_user_pw(user, grents[i]); + } + j += validate_user_gr(user, grents[i]); + } + + if (j > 0) { + printf("OK\n"); + } else { error: - printf("ERR\n"); - } + printf("ERR\n"); + } } return 0; } diff --git a/helpers/negotiate_auth/mswin_sspi/libnegotiatessp.c b/helpers/negotiate_auth/mswin_sspi/libnegotiatessp.c index c19a02edff..35f6f6b3dd 100644 --- a/helpers/negotiate_auth/mswin_sspi/libnegotiatessp.c +++ b/helpers/negotiate_auth/mswin_sspi/libnegotiatessp.c @@ -8,7 +8,7 @@ * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - + * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -41,13 +41,13 @@ void hex_dump(void *data, int size) char addrstr[10] = {0}; char hexstr[ 16*3 + 5] = {0}; char charstr[16*1 + 5] = {0}; - for(n=1;n<=size;n++) { + for (n=1;n<=size;n++) { if (n%16 == 1) { /* store address for this line */ snprintf(addrstr, sizeof(addrstr), "%.4x", - ((unsigned int)p-(unsigned int)data) ); + ((unsigned int)p-(unsigned int)data) ); } - + c = *p; if (xisalnum(c) == 0) { c = '.'; @@ -61,12 +61,12 @@ void hex_dump(void *data, int size) snprintf(bytestr, sizeof(bytestr), "%c", c); strncat(charstr, bytestr, sizeof(charstr)-strlen(charstr)-1); - if(n%16 == 0) { + if (n%16 == 0) { /* line completed */ fprintf(stderr, "[%4.4s] %-50.50s %s\n", addrstr, hexstr, charstr); hexstr[0] = 0; charstr[0] = 0; - } else if(n%8 == 0) { + } else if (n%8 == 0) { /* half line: add whitespaces */ strncat(hexstr, " ", sizeof(hexstr)-strlen(hexstr)-1); strncat(charstr, " ", sizeof(charstr)-strlen(charstr)-1); diff --git a/helpers/negotiate_auth/mswin_sspi/negotiate.h b/helpers/negotiate_auth/mswin_sspi/negotiate.h index 12db46c2a8..d546f84ced 100644 --- a/helpers/negotiate_auth/mswin_sspi/negotiate.h +++ b/helpers/negotiate_auth/mswin_sspi/negotiate.h @@ -9,7 +9,7 @@ * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - + * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -60,28 +60,28 @@ static char *__foo; #endif /* DEBUG */ #else /* __GNUC__ */ static void -debug(char *format,...) +debug(char *format,...) { #ifdef DEBUG #ifdef _SQUID_MSWIN_ #if FAIL_DEBUG if (debug_enabled || fail_debug_enabled) { #else - if (debug_enabled) { + if (debug_enabled) { #endif - va_list args; + va_list args; - va_start(args,format); - fprintf(stderr, "negotiate-auth[%d]: ",getpid()); - vfprintf(stderr, format, args); - va_end(args); + va_start(args,format); + fprintf(stderr, "negotiate-auth[%d]: ",getpid()); + vfprintf(stderr, format, args); + va_end(args); #if FAIL_DEBUG - fail_debug_enabled = 0; + fail_debug_enabled = 0; #endif - } + } #endif /* _SQUID_MSWIN_ */ #endif /* DEBUG */ -} + } #endif /* __GNUC__ */ diff --git a/helpers/negotiate_auth/mswin_sspi/negotiate_auth.c b/helpers/negotiate_auth/mswin_sspi/negotiate_auth.c index bd1793e60b..548f445306 100644 --- a/helpers/negotiate_auth/mswin_sspi/negotiate_auth.c +++ b/helpers/negotiate_auth/mswin_sspi/negotiate_auth.c @@ -59,8 +59,8 @@ uc(char *string) { char *p = string, c; while ((c = *p)) { - *p = xtoupper(c); - p++; + *p = xtoupper(c); + p++; } } @@ -70,8 +70,8 @@ lc(char *string) { char *p = string, c; while ((c = *p)) { - *p = xtolower(c); - p++; + *p = xtolower(c); + p++; } } @@ -95,11 +95,11 @@ void usage() { fprintf(stderr, - "Usage: %s [-d] [-v] [-h]\n" - " -d enable debugging.\n" - " -v enable verbose Negotiate packet debugging.\n" - " -h this message\n\n", - my_program_name); + "Usage: %s [-d] [-v] [-h]\n" + " -d enable debugging.\n" + " -v enable verbose Negotiate packet debugging.\n" + " -h this message\n\n", + my_program_name); } @@ -110,28 +110,28 @@ process_options(int argc, char *argv[]) opterr =0; while (-1 != (opt = getopt(argc, argv, "hdv"))) { - switch (opt) { - case 'd': - debug_enabled = 1; - break; - case 'v': - debug_enabled = 1; - Negotiate_packet_debug_enabled = 1; - break; - case 'h': - usage(); - exit(0); - case '?': - opt = optopt; - /* fall thru to default */ - default: - fprintf(stderr, "unknown option: -%c. Exiting\n", opt); - usage(); - had_error = 1; - } + switch (opt) { + case 'd': + debug_enabled = 1; + break; + case 'v': + debug_enabled = 1; + Negotiate_packet_debug_enabled = 1; + break; + case 'h': + usage(); + exit(0); + case '?': + opt = optopt; + /* fall thru to default */ + default: + fprintf(stderr, "unknown option: -%c. Exiting\n", opt); + usage(); + had_error = 1; + } } if (had_error) - exit(1); + exit(1); } int @@ -147,21 +147,21 @@ manage_request() BOOL Done = FALSE; try_again: - if (fgets(buf, BUFFER_SIZE, stdin) == NULL) + if (fgets(buf, BUFFER_SIZE, stdin) == NULL) return 0; c = memchr(buf, '\n', BUFFER_SIZE); /* safer against overrun than strchr */ if (c) { - if (oversized) { - helperfail("illegal request received"); - fprintf(stderr, "Illegal request received: '%s'\n", buf); - return 1; - } - *c = '\0'; + if (oversized) { + helperfail("illegal request received"); + fprintf(stderr, "Illegal request received: '%s'\n", buf); + return 1; + } + *c = '\0'; } else { - fprintf(stderr, "No newline in '%s'\n", buf); - oversized = 1; - goto try_again; + fprintf(stderr, "No newline in '%s'\n", buf); + oversized = 1; + goto try_again; } if ((strlen(buf) > 3) && Negotiate_packet_debug_enabled) { @@ -173,28 +173,28 @@ try_again: debug("Got '%s' from Squid\n", buf); if (memcmp(buf, "YR ", 3) == 0) { /* refresh-request */ - /* figure out what we got */ + /* figure out what we got */ decoded = base64_decode(buf + 3); - /* Note: we don't need to manage memory at this point, since - * base64_decode returns a pointer to static storage. - */ - if (!decoded) { /* decoding failure, return error */ - SEND("NA * Packet format error, couldn't base64-decode"); - return 1; - } - /* Obtain server blob against SSPI */ + /* Note: we don't need to manage memory at this point, since + * base64_decode returns a pointer to static storage. + */ + if (!decoded) { /* decoding failure, return error */ + SEND("NA * Packet format error, couldn't base64-decode"); + return 1; + } + /* Obtain server blob against SSPI */ plen = (strlen(buf) - 3) * 3 / 4; /* we only need it here. Optimization */ c = (char *) SSP_MakeNegotiateBlob(decoded, plen, &Done, &status, cred); if (status == SSP_OK) { if (Done) { - lc(cred); /* let's lowercase them for our convenience */ + lc(cred); /* let's lowercase them for our convenience */ have_serverblob = 0; Done = FALSE; if (Negotiate_packet_debug_enabled) { printf("AF %s %s\n",c,cred); decoded = base64_decode(c); - debug("sending 'AF' %s to squid with data:\n", cred); + debug("sending 'AF' %s to squid with data:\n", cred); hex_dump(decoded, (strlen(c) * 3) / 4); } else SEND3("AF %s %s", c, cred); @@ -202,7 +202,7 @@ try_again: if (Negotiate_packet_debug_enabled) { printf("TT %s\n",c); decoded = base64_decode(c); - debug("sending 'TT' to squid with data:\n"); + debug("sending 'TT' to squid with data:\n"); hex_dump(decoded, (strlen(c) * 3) / 4); } else { SEND2("TT %s", c); @@ -211,33 +211,33 @@ try_again: } } else helperfail("can't obtain server blob"); - return 1; + return 1; } if (memcmp(buf, "KK ", 3) == 0) { /* authenticate-request */ if (!have_serverblob) { - helperfail("invalid server blob"); - return 1; + helperfail("invalid server blob"); + return 1; + } + /* figure out what we got */ + decoded = base64_decode(buf + 3); + /* Note: we don't need to manage memory at this point, since + * base64_decode returns a pointer to static storage. + */ + if (!decoded) { /* decoding failure, return error */ + SEND("NA * Packet format error, couldn't base64-decode"); + return 1; } - /* figure out what we got */ - decoded = base64_decode(buf + 3); - /* Note: we don't need to manage memory at this point, since - * base64_decode returns a pointer to static storage. - */ - if (!decoded) { /* decoding failure, return error */ - SEND("NA * Packet format error, couldn't base64-decode"); - return 1; - } /* check against SSPI */ - plen = (strlen(buf) - 3) * 3 / 4; /* we only need it here. Optimization */ + plen = (strlen(buf) - 3) * 3 / 4; /* we only need it here. Optimization */ c = (char *) SSP_ValidateNegotiateCredentials(decoded, plen, &Done, &status, cred); - + if (status == SSP_ERROR) { #if FAIL_DEBUG fail_debug_enabled = 1; #endif - FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | + FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), @@ -249,43 +249,43 @@ try_again: ErrorMessage[strlen(ErrorMessage) - 1] = '\0'; if (ErrorMessage[strlen(ErrorMessage) - 1] == '\r') ErrorMessage[strlen(ErrorMessage) - 1] = '\0'; - SEND2("NA * %s", ErrorMessage); + SEND2("NA * %s", ErrorMessage); LocalFree(ErrorMessage); - return 1; - } + return 1; + } if (Done) { - lc(cred); /* let's lowercase them for our convenience */ + lc(cred); /* let's lowercase them for our convenience */ have_serverblob = 0; Done = FALSE; if (Negotiate_packet_debug_enabled) { printf("AF %s %s\n",c,cred); decoded = base64_decode(c); - debug("sending 'AF' %s to squid with data:\n", cred); + debug("sending 'AF' %s to squid with data:\n", cred); hex_dump(decoded, (strlen(c) * 3) / 4); } else { SEND3("AF %s %s", c, cred); } - return 1; + return 1; } else { if (Negotiate_packet_debug_enabled) { printf("TT %s\n",c); decoded = base64_decode(c); - debug("sending 'TT' to squid with data:\n"); + debug("sending 'TT' to squid with data:\n"); hex_dump(decoded, (strlen(c) * 3) / 4); } else - SEND2("TT %s", c); - return 1; + SEND2("TT %s", c); + return 1; } } else { /* not an auth-request */ - helperfail("illegal request received"); - fprintf(stderr, "Illegal request received: '%s'\n", buf); - return 1; + helperfail("illegal request received"); + fprintf(stderr, "Illegal request received: '%s'\n", buf); + return 1; } helperfail("detected protocol error"); return 1; -/********* END ********/ + /********* END ********/ } int @@ -296,10 +296,10 @@ main(int argc, char *argv[]) process_options(argc, argv); debug("%s build " __DATE__ ", " __TIME__ " starting up...\n", my_program_name); - + if (LoadSecurityDll(SSP_NTLM, NEGOTIATE_PACKAGE_NAME) == NULL) { - fprintf(stderr, "FATAL, can't initialize SSPI, exiting.\n"); - exit(1); + fprintf(stderr, "FATAL, can't initialize SSPI, exiting.\n"); + exit(1); } debug("SSPI initialized OK\n"); @@ -310,7 +310,7 @@ main(int argc, char *argv[]) setbuf(stderr, NULL); while (manage_request()) { - /* everything is done within manage_request */ + /* everything is done within manage_request */ } exit(0); } diff --git a/helpers/negotiate_auth/squid_kerb_auth/base64.c b/helpers/negotiate_auth/squid_kerb_auth/base64.c index 97467e8f1e..3c1574bc05 100644 --- a/helpers/negotiate_auth/squid_kerb_auth/base64.c +++ b/helpers/negotiate_auth/squid_kerb_auth/base64.c @@ -22,10 +22,10 @@ ska_base64_init(void) int i; for (i = 0; i < BASE64_VALUE_SZ; i++) - base64_value[i] = -1; + base64_value[i] = -1; for (i = 0; i < 64; i++) - base64_value[(int) base64_code[i]] = i; + base64_value[(int) base64_code[i]] = i; base64_value['='] = 0; base64_initialized = 1; @@ -37,30 +37,30 @@ void ska_base64_decode(char* result, const char *data, int result_size) int c; long val; if (!data) - return; + return; if (!base64_initialized) - ska_base64_init(); + ska_base64_init(); val = c = 0; - + for (j = 0; *data ;data++) { - unsigned int k = ((unsigned char) *data) % BASE64_VALUE_SZ; - if (base64_value[k] < 0) - continue; - val <<= 6; - val += base64_value[k]; - if (++c < 4) - continue; - /* One quantum of four encoding characters/24 bit */ + unsigned int k = ((unsigned char) *data) % BASE64_VALUE_SZ; + if (base64_value[k] < 0) + continue; + val <<= 6; + val += base64_value[k]; + if (++c < 4) + continue; + /* One quantum of four encoding characters/24 bit */ if (j >= result_size) - break; - result[j++] = val >> 16; /* High 8 bits */ + break; + result[j++] = val >> 16; /* High 8 bits */ if (j >= result_size) - break; - result[j++] = (val >> 8) & 0xff; /* Mid 8 bits */ + break; + result[j++] = (val >> 8) & 0xff; /* Mid 8 bits */ if (j >= result_size) - break; - result[j++] = val & 0xff; /* Low 8 bits */ - val = c = 0; + break; + result[j++] = val & 0xff; /* Low 8 bits */ + val = c = 0; } return; } @@ -73,80 +73,80 @@ void ska_base64_encode(char* result, const char *data, int result_size, int data int out_cnt = 0; if (!data) - return; + return; if (!base64_initialized) - ska_base64_init(); + ska_base64_init(); while (data_size--) { int c = (unsigned char) *data++; - bits += c; - char_count++; - if (char_count == 3) { + bits += c; + char_count++; + if (char_count == 3) { if (out_cnt >= result_size) - break; - result[out_cnt++] = base64_code[bits >> 18]; + break; + result[out_cnt++] = base64_code[bits >> 18]; if (out_cnt >= result_size) - break; - result[out_cnt++] = base64_code[(bits >> 12) & 0x3f]; + break; + result[out_cnt++] = base64_code[(bits >> 12) & 0x3f]; if (out_cnt >= result_size) - break; - result[out_cnt++] = base64_code[(bits >> 6) & 0x3f]; + break; + result[out_cnt++] = base64_code[(bits >> 6) & 0x3f]; if (out_cnt >= result_size) - break; - result[out_cnt++] = base64_code[bits & 0x3f]; - bits = 0; - char_count = 0; - } else { - bits <<= 8; - } + break; + result[out_cnt++] = base64_code[bits & 0x3f]; + bits = 0; + char_count = 0; + } else { + bits <<= 8; + } } if (char_count != 0) { - bits <<= 16 - (8 * char_count); + bits <<= 16 - (8 * char_count); if (out_cnt >= result_size) - goto end; - result[out_cnt++] = base64_code[bits >> 18]; + goto end; + result[out_cnt++] = base64_code[bits >> 18]; if (out_cnt >= result_size) - goto end; - result[out_cnt++] = base64_code[(bits >> 12) & 0x3f]; - if (char_count == 1) { + goto end; + result[out_cnt++] = base64_code[(bits >> 12) & 0x3f]; + if (char_count == 1) { if (out_cnt >= result_size) - goto end; - result[out_cnt++] = '='; + goto end; + result[out_cnt++] = '='; if (out_cnt >= result_size) - goto end; - result[out_cnt++] = '='; - } else { + goto end; + result[out_cnt++] = '='; + } else { if (out_cnt >= result_size) - goto end; - result[out_cnt++] = base64_code[(bits >> 6) & 0x3f]; + goto end; + result[out_cnt++] = base64_code[(bits >> 6) & 0x3f]; if (out_cnt >= result_size) - goto end; - result[out_cnt++] = '='; - } + goto end; + result[out_cnt++] = '='; + } } end: if (out_cnt >= result_size) { - result[result_size-1] = '\0'; /* terminate */ + result[result_size-1] = '\0'; /* terminate */ } else { - result[out_cnt] = '\0'; /* terminate */ + result[out_cnt] = '\0'; /* terminate */ } return; } int ska_base64_encode_len(int len) { - return ((len+2)/3*4)+1; + return ((len+2)/3*4)+1; } int ska_base64_decode_len(const char *data) { - int i,j; - - j=0; - for (i=strlen(data)-1;i>=0;i--) { - if (data[i] == '=') j++; - if (data[i] != '=') break; - } - return strlen(data)/4*3-j; + int i,j; + + j=0; + for (i=strlen(data)-1;i>=0;i--) { + if (data[i] == '=') j++; + if (data[i] != '=') break; + } + return strlen(data)/4*3-j; } diff --git a/helpers/negotiate_auth/squid_kerb_auth/spnegohelp/derparse.c b/helpers/negotiate_auth/squid_kerb_auth/spnegohelp/derparse.c index 8af877dae6..668c4b58aa 100644 --- a/helpers/negotiate_auth/squid_kerb_auth/spnegohelp/derparse.c +++ b/helpers/negotiate_auth/squid_kerb_auth/spnegohelp/derparse.c @@ -32,12 +32,11 @@ // The GSS Mechanism OID enumeration values (SPNEGO_MECH_OID) control which offset in // the array below, that a mechanism can be found. // -MECH_OID g_stcMechOIDList [] = -{ - { (unsigned char*) "\x06\x09\x2a\x86\x48\x82\xf7\x12\x01\x02\x02", 11, 9, spnego_mech_oid_Kerberos_V5_Legacy }, // 1.2.840.48018.1.2.2 - { (unsigned char*) "\x06\x09\x2a\x86\x48\x86\xf7\x12\x01\x02\x02", 11, 9, spnego_mech_oid_Kerberos_V5 }, // 1.2.840.113554.1.2.2 - { (unsigned char*) "\x06\x06\x2b\x06\x01\x05\x05\x02", 8, 6, spnego_mech_oid_Spnego }, // 1.3.6.1.1.5.5.2 - { (unsigned char*) "", 0, 0, spnego_mech_oid_NotUsed } // Placeholder +MECH_OID g_stcMechOIDList [] = { + { (unsigned char*) "\x06\x09\x2a\x86\x48\x82\xf7\x12\x01\x02\x02", 11, 9, spnego_mech_oid_Kerberos_V5_Legacy }, // 1.2.840.48018.1.2.2 + { (unsigned char*) "\x06\x09\x2a\x86\x48\x86\xf7\x12\x01\x02\x02", 11, 9, spnego_mech_oid_Kerberos_V5 }, // 1.2.840.113554.1.2.2 + { (unsigned char*) "\x06\x06\x2b\x06\x01\x05\x05\x02", 8, 6, spnego_mech_oid_Spnego }, // 1.3.6.1.1.5.5.2 + { (unsigned char*) "", 0, 0, spnego_mech_oid_NotUsed } // Placeholder }; ///////////////////////////////////////////////////////////////////////////// @@ -66,100 +65,91 @@ MECH_OID g_stcMechOIDList [] = int ASNDerGetLength( unsigned char* pbLengthData, long nBoundaryLength, long* pnLength, long* pnNumLengthBytes ) { - int nReturn = SPNEGO_E_INVALID_LENGTH; - int nNumLengthBytes = 0; - - // First check if the extended length bit is set - - if ( *pbLengthData & LEN_XTND ) - { - // Lower 7 bits contain the number of trailing bytes that describe the length - nNumLengthBytes = *pbLengthData & LEN_MASK; - - // Check that the number of bytes we are about to read is within our boundary - // constraints - - if ( nNumLengthBytes <= nBoundaryLength - 1 ) - { - - // For now, our handler won't deal with lengths greater than 4 bytes - if ( nNumLengthBytes >= 1 && nNumLengthBytes <= 4 ) - { - // 0 out the initial length - *pnLength = 0L; - - // Bump by 1 byte - pbLengthData++; - - #if defined(__LITTLE_ENDIAN__) || !defined(WORDS_BIGENDIAN) - - // There may be a cleaner way to do this, but for now, this seems to be - // an easy way to do the transformation - switch ( nNumLengthBytes ) - { - case 1: - { - *( ( (unsigned char*) pnLength ) ) = *pbLengthData; - break; - } - - case 2: - { - *( ( (unsigned char*) pnLength ) ) = *(pbLengthData + 1); - *( ( (unsigned char*) pnLength ) + 1 ) = *(pbLengthData); - - break; - } - - case 3: - { - *( ( (unsigned char*) pnLength ) ) = *(pbLengthData + 2); - *( ( (unsigned char*) pnLength ) + 2 ) = *(pbLengthData + 1); - *( ( (unsigned char*) pnLength ) + 3 ) = *(pbLengthData); - break; - } - - case 4: - { - *( ( (unsigned char*) pnLength ) ) = *(pbLengthData + 3); - *( ( (unsigned char*) pnLength ) + 1 ) = *(pbLengthData + 2); - *( ( (unsigned char*) pnLength ) + 2 ) = *(pbLengthData + 1); - *( ( (unsigned char*) pnLength ) + 3 ) = *(pbLengthData); - break; - } - - } // SWITCH ( nNumLengthBytes ) - - #else - // We are Big-Endian, so the length can be copied in from the source - // as is. Ensure that we adjust for the number of bytes we actually - // copy. - - memcpy( ( (unsigned char *) pnLength ) + ( 4 - nNumLengthBytes ), - pbLengthData, nNumLengthBytes ); - #endif - - // Account for the initial length byte - *pnNumLengthBytes = nNumLengthBytes + 1; - nReturn = SPNEGO_E_SUCCESS; - - } // IF Valid Length - - } // IF num bytes to read is within the boundary length - - } // IF xtended length - else - { - - // Extended bit is not set, so the length is in the value and the one - // byte describes the length - *pnLength = *pbLengthData & LEN_MASK; - *pnNumLengthBytes = 1; - nReturn = SPNEGO_E_SUCCESS; - - } - LOG(("ASNDerGetLength returned %d\n",nReturn)); - return nReturn; + int nReturn = SPNEGO_E_INVALID_LENGTH; + int nNumLengthBytes = 0; + + // First check if the extended length bit is set + + if ( *pbLengthData & LEN_XTND ) { + // Lower 7 bits contain the number of trailing bytes that describe the length + nNumLengthBytes = *pbLengthData & LEN_MASK; + + // Check that the number of bytes we are about to read is within our boundary + // constraints + + if ( nNumLengthBytes <= nBoundaryLength - 1 ) { + + // For now, our handler won't deal with lengths greater than 4 bytes + if ( nNumLengthBytes >= 1 && nNumLengthBytes <= 4 ) { + // 0 out the initial length + *pnLength = 0L; + + // Bump by 1 byte + pbLengthData++; + +#if defined(__LITTLE_ENDIAN__) || !defined(WORDS_BIGENDIAN) + + // There may be a cleaner way to do this, but for now, this seems to be + // an easy way to do the transformation + switch ( nNumLengthBytes ) { + case 1: { + *( ( (unsigned char*) pnLength ) ) = *pbLengthData; + break; + } + + case 2: { + *( ( (unsigned char*) pnLength ) ) = *(pbLengthData + 1); + *( ( (unsigned char*) pnLength ) + 1 ) = *(pbLengthData); + + break; + } + + case 3: { + *( ( (unsigned char*) pnLength ) ) = *(pbLengthData + 2); + *( ( (unsigned char*) pnLength ) + 2 ) = *(pbLengthData + 1); + *( ( (unsigned char*) pnLength ) + 3 ) = *(pbLengthData); + break; + } + + case 4: { + *( ( (unsigned char*) pnLength ) ) = *(pbLengthData + 3); + *( ( (unsigned char*) pnLength ) + 1 ) = *(pbLengthData + 2); + *( ( (unsigned char*) pnLength ) + 2 ) = *(pbLengthData + 1); + *( ( (unsigned char*) pnLength ) + 3 ) = *(pbLengthData); + break; + } + + } // SWITCH ( nNumLengthBytes ) + +#else + // We are Big-Endian, so the length can be copied in from the source + // as is. Ensure that we adjust for the number of bytes we actually + // copy. + + memcpy( ( (unsigned char *) pnLength ) + ( 4 - nNumLengthBytes ), + pbLengthData, nNumLengthBytes ); +#endif + + // Account for the initial length byte + *pnNumLengthBytes = nNumLengthBytes + 1; + nReturn = SPNEGO_E_SUCCESS; + + } // IF Valid Length + + } // IF num bytes to read is within the boundary length + + } // IF xtended length + else { + + // Extended bit is not set, so the length is in the value and the one + // byte describes the length + *pnLength = *pbLengthData & LEN_MASK; + *pnNumLengthBytes = 1; + nReturn = SPNEGO_E_SUCCESS; + + } + LOG(("ASNDerGetLength returned %d\n",nReturn)); + return nReturn; } @@ -174,7 +164,7 @@ int ASNDerGetLength( unsigned char* pbLengthData, long nBoundaryLength, long* pn // [in] nLengthWithToken - Expected token length (with data) // [in] nBoundaryLength - Length that value must not exceed. // [out] pnLength - Filled out with data length -// [out] pnTokenLength - Filled out with number of bytes +// [out] pnTokenLength - Filled out with number of bytes // consumed by token identifier and length. // // Returns: @@ -190,67 +180,59 @@ int ASNDerGetLength( unsigned char* pbLengthData, long nBoundaryLength, long* pn //////////////////////////////////////////////////////////////////////////// int ASNDerCheckToken( unsigned char* pbTokenData, unsigned char nToken, - long nLengthWithToken, long nBoundaryLength, - long* pnLength, long* pnTokenLength ) + long nLengthWithToken, long nBoundaryLength, + long* pnLength, long* pnTokenLength ) { - int nReturn = SPNEGO_E_INVALID_LENGTH; - long nNumLengthBytes = 0L; + int nReturn = SPNEGO_E_INVALID_LENGTH; + long nNumLengthBytes = 0L; - // Make sure that we've at least got 2 bytes of room to work with + // Make sure that we've at least got 2 bytes of room to work with - if ( nBoundaryLength >= 2 ) - { - // The first byte of the token data MUST match the specified token - if ( *pbTokenData == nToken ) - { - // Next byte indicates the length - pbTokenData++; + if ( nBoundaryLength >= 2 ) { + // The first byte of the token data MUST match the specified token + if ( *pbTokenData == nToken ) { + // Next byte indicates the length + pbTokenData++; - // Get the length described by the token - if ( ( nReturn = ASNDerGetLength( pbTokenData, nBoundaryLength, pnLength, - &nNumLengthBytes ) ) == SPNEGO_E_SUCCESS ) - { - // Verify that the length is LESS THAN the boundary length - // (this should prevent us walking out of our buffer) - if ( ( nBoundaryLength - ( nNumLengthBytes + 1 ) < *pnLength ) ) - { + // Get the length described by the token + if ( ( nReturn = ASNDerGetLength( pbTokenData, nBoundaryLength, pnLength, + &nNumLengthBytes ) ) == SPNEGO_E_SUCCESS ) { + // Verify that the length is LESS THAN the boundary length + // (this should prevent us walking out of our buffer) + if ( ( nBoundaryLength - ( nNumLengthBytes + 1 ) < *pnLength ) ) { - nReturn = SPNEGO_E_INVALID_LENGTH; + nReturn = SPNEGO_E_INVALID_LENGTH; - } + } - // If we were passed a length to check, do so now - if ( nLengthWithToken > 0L ) - { + // If we were passed a length to check, do so now + if ( nLengthWithToken > 0L ) { - // Check that the expected length matches - if ( ( nLengthWithToken - ( nNumLengthBytes + 1 ) ) != *pnLength ) - { + // Check that the expected length matches + if ( ( nLengthWithToken - ( nNumLengthBytes + 1 ) ) != *pnLength ) { - nReturn = SPNEGO_E_INVALID_LENGTH; + nReturn = SPNEGO_E_INVALID_LENGTH; - } + } - } // IF need to validate length + } // IF need to validate length - if ( SPNEGO_E_SUCCESS == nReturn ) - { - *pnTokenLength = nNumLengthBytes + 1; - } + if ( SPNEGO_E_SUCCESS == nReturn ) { + *pnTokenLength = nNumLengthBytes + 1; + } - } // IF ASNDerGetLength + } // IF ASNDerGetLength - } // IF token matches - else - { - nReturn = SPNEGO_E_TOKEN_NOT_FOUND; - } + } // IF token matches + else { + nReturn = SPNEGO_E_TOKEN_NOT_FOUND; + } - } // IF Boundary Length is at least 2 bytes + } // IF Boundary Length is at least 2 bytes - LOG(("ASNDerCheckToken returned %d\n",nReturn)); - return nReturn; + LOG(("ASNDerCheckToken returned %d\n",nReturn)); + return nReturn; } ///////////////////////////////////////////////////////////////////////////// @@ -275,39 +257,34 @@ int ASNDerCheckToken( unsigned char* pbTokenData, unsigned char nToken, //////////////////////////////////////////////////////////////////////////// int ASNDerCheckOID( unsigned char* pbTokenData, SPNEGO_MECH_OID nMechOID, long nBoundaryLength, - long* pnTokenLength ) + long* pnTokenLength ) { - int nReturn = 0L; - long nLength = 0L; - - // Verify that we have an OID token - if ( ( nReturn = ASNDerCheckToken( pbTokenData, OID, 0L, nBoundaryLength, - &nLength, pnTokenLength ) ) == SPNEGO_E_SUCCESS ) - { - // Add the data length to the Token Length - *pnTokenLength += nLength; - - // Token Lengths plus the actual length must match the length in our OID list element. - // If it doesn't, we're done - if ( *pnTokenLength == g_stcMechOIDList[nMechOID].iLen ) - { - // Memcompare the token and the expected field - if ( memcmp( pbTokenData, g_stcMechOIDList[nMechOID].ucOid, *pnTokenLength ) != 0 ) - { - LOG(("ASNDerCheckOID memcmp failed\n")); + int nReturn = 0L; + long nLength = 0L; + + // Verify that we have an OID token + if ( ( nReturn = ASNDerCheckToken( pbTokenData, OID, 0L, nBoundaryLength, + &nLength, pnTokenLength ) ) == SPNEGO_E_SUCCESS ) { + // Add the data length to the Token Length + *pnTokenLength += nLength; + + // Token Lengths plus the actual length must match the length in our OID list element. + // If it doesn't, we're done + if ( *pnTokenLength == g_stcMechOIDList[nMechOID].iLen ) { + // Memcompare the token and the expected field + if ( memcmp( pbTokenData, g_stcMechOIDList[nMechOID].ucOid, *pnTokenLength ) != 0 ) { + LOG(("ASNDerCheckOID memcmp failed\n")); + nReturn = SPNEGO_E_UNEXPECTED_OID; + } + } else { + LOG(("ASNDerCheckOID token length failed\n")); nReturn = SPNEGO_E_UNEXPECTED_OID; - } - } - else - { - LOG(("ASNDerCheckOID token length failed\n")); - nReturn = SPNEGO_E_UNEXPECTED_OID; - } - - } // IF OID Token CHecks - - LOG(("ASNDerCheckOID returned %d\n",nReturn)); - return nReturn; + } + + } // IF OID Token CHecks + + LOG(("ASNDerCheckOID returned %d\n",nReturn)); + return nReturn; } ///////////////////////////////////////////////////////////////////////////// @@ -330,36 +307,27 @@ int ASNDerCheckOID( unsigned char* pbTokenData, SPNEGO_MECH_OID nMechOID, long n int ASNDerCalcNumLengthBytes( long nLength ) { - if ( nLength <= 0x7F ) - { - // A single byte will be sufficient for describing this length. - // The byte will simply contain the length - return 1; - } - else if ( nLength <= 0xFF ) - { - // Two bytes are necessary, one to say how many following bytes - // describe the length, and one to give the length - return 2; - } - else if ( nLength <= 0xFFFF ) - { - // Three bytes are necessary, one to say how many following bytes - // describe the length, and two to give the length - return 3; - } - else if ( nLength <= 0xFFFFFF ) - { - // Four bytes are necessary, one to say how many following bytes - // describe the length, and three to give the length - return 4; - } - else - { - // Five bytes are necessary, one to say how many following bytes - // describe the length, and four to give the length - return 5; - } + if ( nLength <= 0x7F ) { + // A single byte will be sufficient for describing this length. + // The byte will simply contain the length + return 1; + } else if ( nLength <= 0xFF ) { + // Two bytes are necessary, one to say how many following bytes + // describe the length, and one to give the length + return 2; + } else if ( nLength <= 0xFFFF ) { + // Three bytes are necessary, one to say how many following bytes + // describe the length, and two to give the length + return 3; + } else if ( nLength <= 0xFFFFFF ) { + // Four bytes are necessary, one to say how many following bytes + // describe the length, and three to give the length + return 4; + } else { + // Five bytes are necessary, one to say how many following bytes + // describe the length, and four to give the length + return 5; + } } @@ -384,11 +352,11 @@ int ASNDerCalcNumLengthBytes( long nLength ) long ASNDerCalcTokenLength( long nLength, long nDataLength ) { - // Add a byte to the length size to account for a single byte to - // hold the token type. - long nTotalLength = ASNDerCalcNumLengthBytes( nLength ) + 1; + // Add a byte to the length size to account for a single byte to + // hold the token type. + long nTotalLength = ASNDerCalcNumLengthBytes( nLength ) + 1; - return nTotalLength + nDataLength; + return nTotalLength + nDataLength; } @@ -413,20 +381,19 @@ long ASNDerCalcTokenLength( long nLength, long nDataLength ) long ASNDerCalcElementLength( long nDataLength, long* pnInternalLength ) { - // First the type token and the actual data - long nTotalLength = ASNDerCalcTokenLength( nDataLength, nDataLength ); + // First the type token and the actual data + long nTotalLength = ASNDerCalcTokenLength( nDataLength, nDataLength ); - // Internal length is the length without the element sequence token - if ( NULL != pnInternalLength ) - { - *pnInternalLength = nTotalLength; - } + // Internal length is the length without the element sequence token + if ( NULL != pnInternalLength ) { + *pnInternalLength = nTotalLength; + } - // Next add in the element's sequence token (remember that its - // length is the total length of the type token and data) - nTotalLength += ASNDerCalcTokenLength( nTotalLength, 0L ); + // Next add in the element's sequence token (remember that its + // length is the total length of the type token and data) + nTotalLength += ASNDerCalcTokenLength( nTotalLength, 0L ); - return nTotalLength; + return nTotalLength; } ///////////////////////////////////////////////////////////////////////////// @@ -452,22 +419,21 @@ long ASNDerCalcElementLength( long nDataLength, long* pnInternalLength ) long ASNDerCalcMechListLength( SPNEGO_MECH_OID mechoid, long* pnInternalLength ) { - // First the OID - long nTotalLength = g_stcMechOIDList[mechoid].iLen; + // First the OID + long nTotalLength = g_stcMechOIDList[mechoid].iLen; - // Next add in a sequence token - nTotalLength += ASNDerCalcTokenLength( nTotalLength, 0L ); + // Next add in a sequence token + nTotalLength += ASNDerCalcTokenLength( nTotalLength, 0L ); - // Internal length is the length without the element sequence token - if ( NULL != pnInternalLength ) - { - *pnInternalLength = nTotalLength; - } + // Internal length is the length without the element sequence token + if ( NULL != pnInternalLength ) { + *pnInternalLength = nTotalLength; + } - // Finally add in the element's sequence token - nTotalLength += ASNDerCalcTokenLength( nTotalLength, 0L ); + // Finally add in the element's sequence token + nTotalLength += ASNDerCalcTokenLength( nTotalLength, 0L ); - return nTotalLength; + return nTotalLength; } @@ -490,79 +456,72 @@ long ASNDerCalcMechListLength( SPNEGO_MECH_OID mechoid, long* pnInternalLength ) int ASNDerWriteLength( unsigned char* pbData, long nLength ) { - int nNumBytesRequired = ASNDerCalcNumLengthBytes( nLength ); - int nNumLengthBytes = nNumBytesRequired - 1; + int nNumBytesRequired = ASNDerCalcNumLengthBytes( nLength ); + int nNumLengthBytes = nNumBytesRequired - 1; - if ( nNumBytesRequired > 1 ) - { + if ( nNumBytesRequired > 1 ) { - // Write out the number of bytes following which will be used - *pbData = (unsigned char ) ( LEN_XTND | nNumLengthBytes ); + // Write out the number of bytes following which will be used + *pbData = (unsigned char ) ( LEN_XTND | nNumLengthBytes ); - // Point to where we'll actually write the length - pbData++; + // Point to where we'll actually write the length + pbData++; -#if defined(__LITTLE_ENDIAN__) || !defined(WORDS_BIGENDIAN) +#if defined(__LITTLE_ENDIAN__) || !defined(WORDS_BIGENDIAN) - // There may be a cleaner way to do this, but for now, this seems to be - // an easy way to do the transformation - switch ( nNumLengthBytes ) - { - case 1: - { + // There may be a cleaner way to do this, but for now, this seems to be + // an easy way to do the transformation + switch ( nNumLengthBytes ) { + case 1: { // Cast the length to a single byte, since we know that it // is 0x7F or less (or we wouldn't only need a single byte). - + *pbData = (unsigned char) nLength; break; - } + } - case 2: - { + case 2: { *pbData = *( ( (unsigned char*) &nLength ) + 1 ); *( pbData + 1) = *( ( (unsigned char*) &nLength ) ); break; - } + } - case 3: - { + case 3: { *pbData = *( ( (unsigned char*) &nLength ) + 3 ); *( pbData + 1) = *( ( (unsigned char*) &nLength ) + 2 ); *( pbData + 2) = *( ( (unsigned char*) &nLength ) ); break; - } + } - case 4: - { + case 4: { *pbData = *( ( (unsigned char*) &nLength ) + 3 ); *( pbData + 1) = *( ( (unsigned char*) &nLength ) + 2 ); *( pbData + 2) = *( ( (unsigned char*) &nLength ) + 1 ); *( pbData + 3) = *( ( (unsigned char*) &nLength ) ); break; - } + } - } // SWITCH ( nNumLengthBytes ) + } // SWITCH ( nNumLengthBytes ) #else - // We are Big-Endian, so the length can be copied in from the source - // as is. Ensure that we adjust for the number of bytes we actually - // copy. + // We are Big-Endian, so the length can be copied in from the source + // as is. Ensure that we adjust for the number of bytes we actually + // copy. - memcpy( pbData, - ( (unsigned char *) &nLength ) + ( 4 - nNumLengthBytes ), nNumLengthBytes ); + memcpy( pbData, + ( (unsigned char *) &nLength ) + ( 4 - nNumLengthBytes ), nNumLengthBytes ); #endif - } // IF > 1 byte for length - else - { - // Cast the length to a single byte, since we know that it - // is 0x7F or less (or we wouldn't only need a single byte). - - *pbData = (unsigned char) nLength; - } + } // IF > 1 byte for length + else { + // Cast the length to a single byte, since we know that it + // is 0x7F or less (or we wouldn't only need a single byte). + + *pbData = (unsigned char) nLength; + } - return nNumBytesRequired; + return nNumBytesRequired; } ///////////////////////////////////////////////////////////////////////////// @@ -587,34 +546,33 @@ int ASNDerWriteLength( unsigned char* pbData, long nLength ) //////////////////////////////////////////////////////////////////////////// int ASNDerWriteToken( unsigned char* pbData, unsigned char ucType, - unsigned char* pbTokenValue, long nLength ) + unsigned char* pbTokenValue, long nLength ) { - int nTotalBytesWrittenOut = 0L; - int nNumLengthBytesWritten = 0L; + int nTotalBytesWrittenOut = 0L; + int nNumLengthBytesWritten = 0L; - // Write out the type - *pbData = ucType; + // Write out the type + *pbData = ucType; - // Wrote 1 byte, and move data pointer - nTotalBytesWrittenOut++; - pbData++; + // Wrote 1 byte, and move data pointer + nTotalBytesWrittenOut++; + pbData++; - // Now write out the length and adjust the number of bytes written out - nNumLengthBytesWritten = ASNDerWriteLength( pbData, nLength ); + // Now write out the length and adjust the number of bytes written out + nNumLengthBytesWritten = ASNDerWriteLength( pbData, nLength ); - nTotalBytesWrittenOut += nNumLengthBytesWritten; - pbData += nNumLengthBytesWritten; + nTotalBytesWrittenOut += nNumLengthBytesWritten; + pbData += nNumLengthBytesWritten; - // Write out the token value if we got one. The assumption is that the - // nLength value indicates how many bytes are in pbTokenValue. + // Write out the token value if we got one. The assumption is that the + // nLength value indicates how many bytes are in pbTokenValue. - if ( NULL != pbTokenValue ) - { - memcpy( pbData, pbTokenValue, nLength ); - nTotalBytesWrittenOut += nLength; - } + if ( NULL != pbTokenValue ) { + memcpy( pbData, pbTokenValue, nLength ); + nTotalBytesWrittenOut += nLength; + } - return nTotalBytesWrittenOut; + return nTotalBytesWrittenOut; } @@ -640,9 +598,9 @@ int ASNDerWriteToken( unsigned char* pbData, unsigned char ucType, int ASNDerWriteOID( unsigned char* pbData, SPNEGO_MECH_OID eMechOID ) { - memcpy( pbData, g_stcMechOIDList[eMechOID].ucOid, g_stcMechOIDList[eMechOID].iLen ); + memcpy( pbData, g_stcMechOIDList[eMechOID].ucOid, g_stcMechOIDList[eMechOID].iLen ); - return g_stcMechOIDList[eMechOID].iLen; + return g_stcMechOIDList[eMechOID].iLen; } @@ -667,25 +625,25 @@ int ASNDerWriteOID( unsigned char* pbData, SPNEGO_MECH_OID eMechOID ) long ASNDerWriteMechList( unsigned char* pbData, SPNEGO_MECH_OID mechoid ) { - // First get the length - long nInternalLength = 0L; - long nMechListLength = ASNDerCalcMechListLength( mechoid, &nInternalLength ); - long nTempLength = 0L; + // First get the length + long nInternalLength = 0L; + long nMechListLength = ASNDerCalcMechListLength( mechoid, &nInternalLength ); + long nTempLength = 0L; - nTempLength = ASNDerWriteToken( pbData, SPNEGO_NEGINIT_ELEMENT_MECHTYPES, + nTempLength = ASNDerWriteToken( pbData, SPNEGO_NEGINIT_ELEMENT_MECHTYPES, NULL, nInternalLength ); - // Adjust the data pointer - pbData += nTempLength; + // Adjust the data pointer + pbData += nTempLength; - // Now write the Sequence token and the OID (the OID is a BLOB in the global - // structure. + // Now write the Sequence token and the OID (the OID is a BLOB in the global + // structure. - nTempLength = ASNDerWriteToken( pbData, SPNEGO_CONSTRUCTED_SEQUENCE, + nTempLength = ASNDerWriteToken( pbData, SPNEGO_CONSTRUCTED_SEQUENCE, g_stcMechOIDList[mechoid].ucOid, g_stcMechOIDList[mechoid].iLen ); - return nMechListLength; + return nMechListLength; } @@ -713,20 +671,20 @@ long ASNDerWriteMechList( unsigned char* pbData, SPNEGO_MECH_OID mechoid ) int ASNDerWriteElement( unsigned char* pbData, unsigned char ucElementSequence, unsigned char ucType, unsigned char* pbTokenValue, long nLength ) { - // First get the length - long nInternalLength = 0L; - long nElementLength = ASNDerCalcElementLength( nLength, &nInternalLength ); - long nTempLength = 0L; + // First get the length + long nInternalLength = 0L; + long nElementLength = ASNDerCalcElementLength( nLength, &nInternalLength ); + long nTempLength = 0L; - // Write out the sequence byte and the length of the type and data - nTempLength = ASNDerWriteToken( pbData, ucElementSequence, NULL, nInternalLength ); + // Write out the sequence byte and the length of the type and data + nTempLength = ASNDerWriteToken( pbData, ucElementSequence, NULL, nInternalLength ); - // Adjust the data pointer - pbData += nTempLength; + // Adjust the data pointer + pbData += nTempLength; - // Now write the type and the data. - nTempLength = ASNDerWriteToken( pbData, ucType, pbTokenValue, nLength ); + // Now write the type and the data. + nTempLength = ASNDerWriteToken( pbData, ucType, pbTokenValue, nLength ); - return nElementLength; + return nElementLength; } diff --git a/helpers/negotiate_auth/squid_kerb_auth/spnegohelp/derparse.h b/helpers/negotiate_auth/squid_kerb_auth/spnegohelp/derparse.h index cdca9b45cb..6bbdad2b29 100644 --- a/helpers/negotiate_auth/squid_kerb_auth/spnegohelp/derparse.h +++ b/helpers/negotiate_auth/squid_kerb_auth/spnegohelp/derparse.h @@ -30,20 +30,20 @@ extern "C" { #endif -/* Identifier Types */ + /* Identifier Types */ #define IDENTIFIER_MASK 0xC0 // Bits 7 and 8 #define IDENTIFIER_UNIVERSAL 0x00 // 00 = universal #define IDENTIFIER_APPLICATION 0x40 // 01 = application #define IDENTIFIER_CONTEXT_SPECIFIC 0x80 // 10 = context specific #define IDENTIFIER_PRIVATE 0xC0 // 11 = Private -/* Encoding type */ + /* Encoding type */ #define FORM_MASK 0x20 /* Bit 6 */ #define PRIMITIVE 0x00 /* 0 = primitive */ #define CONSTRUCTED 0x20 /* 1 = constructed */ -/* Universal tags */ + /* Universal tags */ #define TAG_MASK 0x1F /* Bits 5 - 1 */ #define BOOLEAN 0x01 /* 1: TRUE or FALSE */ @@ -72,7 +72,7 @@ extern "C" #define UNIVERSALSTR 0x1C /* 28: Universal String */ #define BMPSTR 0x1E /* 30: Basic Multilingual Plane String */ -/* Length encoding */ + /* Length encoding */ #define LEN_XTND 0x80 /* Indefinite or long form */ #define LEN_MASK 0x7f /* Bits 7 - 1 */ @@ -165,40 +165,39 @@ extern "C" // of these which we'll use for validation/searches/parsing. // -typedef struct _mechOID -{ - unsigned char* ucOid; // Byte representation of OID - int iLen; // Length of the OID, length and identifier - int iActualDataLen; // Length of the actual OID - SPNEGO_MECH_OID eMechanismOID; // Which OID is this? -} MECH_OID; + typedef struct _mechOID { + unsigned char* ucOid; // Byte representation of OID + int iLen; // Length of the OID, length and identifier + int iActualDataLen; // Length of the actual OID + SPNEGO_MECH_OID eMechanismOID; // Which OID is this? + } MECH_OID; // // ASN Der functions // -int ASNDerGetLength( unsigned char* pbLengthData, long nBoundaryLength, long* pnLength, - long* pnNumLengthBytes ); -int ASNDerCheckToken( unsigned char* pbTokenData, unsigned char nToken, - long nCheckLength, long nBoundaryLength, long* pnLength, + int ASNDerGetLength( unsigned char* pbLengthData, long nBoundaryLength, long* pnLength, + long* pnNumLengthBytes ); + int ASNDerCheckToken( unsigned char* pbTokenData, unsigned char nToken, + long nCheckLength, long nBoundaryLength, long* pnLength, + long* pnTokenLength ); + int ASNDerCheckOID( unsigned char* pbTokenData, SPNEGO_MECH_OID nMechOID, long nBoundaryLength, long* pnTokenLength ); -int ASNDerCheckOID( unsigned char* pbTokenData, SPNEGO_MECH_OID nMechOID, long nBoundaryLength, - long* pnTokenLength ); -int ASNDerCalcNumLengthBytes( long nLength ); -long ASNDerCalcTokenLength( long nLength, long nDataLength ); -long ASNDerCalcElementLength( long nDataLength, long* pnInternalLength ); -long ASNDerCalcMechListLength( SPNEGO_MECH_OID mechoid, long* pnInternalLength ); -int ASNDerWriteLength( unsigned char* pbData, long nLength ); -int ASNDerWriteToken( unsigned char* pbData, unsigned char ucType, - unsigned char* pbTokenValue, long nLength ); -int ASNDerWriteOID( unsigned char* pbData, SPNEGO_MECH_OID eMechOID ); -long ASNDerWriteMechList( unsigned char* pbData, SPNEGO_MECH_OID mechoid ); -int ASNDerWriteElement( unsigned char* pbData, unsigned char ucElementSequence, - unsigned char ucType, unsigned char* pbTokenValue, long nLength ); - - - // C++ Specific + int ASNDerCalcNumLengthBytes( long nLength ); + long ASNDerCalcTokenLength( long nLength, long nDataLength ); + long ASNDerCalcElementLength( long nDataLength, long* pnInternalLength ); + long ASNDerCalcMechListLength( SPNEGO_MECH_OID mechoid, long* pnInternalLength ); + int ASNDerWriteLength( unsigned char* pbData, long nLength ); + int ASNDerWriteToken( unsigned char* pbData, unsigned char ucType, + unsigned char* pbTokenValue, long nLength ); + int ASNDerWriteOID( unsigned char* pbData, SPNEGO_MECH_OID eMechOID ); + long ASNDerWriteMechList( unsigned char* pbData, SPNEGO_MECH_OID mechoid ); + int ASNDerWriteElement( unsigned char* pbData, unsigned char ucElementSequence, + unsigned char ucType, unsigned char* pbTokenValue, long nLength ); + + + // C++ Specific #if defined(__cplusplus) } #endif diff --git a/helpers/negotiate_auth/squid_kerb_auth/spnegohelp/spnego.c b/helpers/negotiate_auth/squid_kerb_auth/spnegohelp/spnego.c index deb4cd3e31..5f26261ddf 100644 --- a/helpers/negotiate_auth/squid_kerb_auth/spnegohelp/spnego.c +++ b/helpers/negotiate_auth/squid_kerb_auth/spnegohelp/spnego.c @@ -71,18 +71,18 @@ extern MECH_OID g_stcMechOIDList []; int spnegoInitFromBinary( unsigned char* pbTokenData, unsigned long ulLength, SPNEGO_TOKEN_HANDLE* phSpnegoToken ) { - int nReturn = SPNEGO_E_INVALID_PARAMETER; - SPNEGO_TOKEN** ppSpnegoToken = (SPNEGO_TOKEN**) phSpnegoToken; - - // Pass off to a handler function that allows tighter control over how the token structure - // is handled. In this case, we want the token data copied and we want the associated buffer - // freed. - nReturn = InitTokenFromBinary( SPNEGO_TOKEN_INTERNAL_COPYDATA, - SPNEGO_TOKEN_INTERNAL_FLAGS_FREEDATA, pbTokenData, - ulLength, ppSpnegoToken ); - - LOG(("spnegoInitFromBinary returned %d\n",nReturn)); - return nReturn; + int nReturn = SPNEGO_E_INVALID_PARAMETER; + SPNEGO_TOKEN** ppSpnegoToken = (SPNEGO_TOKEN**) phSpnegoToken; + + // Pass off to a handler function that allows tighter control over how the token structure + // is handled. In this case, we want the token data copied and we want the associated buffer + // freed. + nReturn = InitTokenFromBinary( SPNEGO_TOKEN_INTERNAL_COPYDATA, + SPNEGO_TOKEN_INTERNAL_FLAGS_FREEDATA, pbTokenData, + ulLength, ppSpnegoToken ); + + LOG(("spnegoInitFromBinary returned %d\n",nReturn)); + return nReturn; } ///////////////////////////////////////////////////////////////////////////// @@ -113,68 +113,62 @@ int spnegoInitFromBinary( unsigned char* pbTokenData, unsigned long ulLength, SP //////////////////////////////////////////////////////////////////////////// int spnegoCreateNegTokenInit( SPNEGO_MECH_OID MechType, - unsigned char ucContextFlags, unsigned char* pbMechToken, - unsigned long ulMechTokenLen, unsigned char* pbMechListMIC, - unsigned long ulMechListMICLen, SPNEGO_TOKEN_HANDLE* phSpnegoToken ) + unsigned char ucContextFlags, unsigned char* pbMechToken, + unsigned long ulMechTokenLen, unsigned char* pbMechListMIC, + unsigned long ulMechListMICLen, SPNEGO_TOKEN_HANDLE* phSpnegoToken ) { - int nReturn = SPNEGO_E_INVALID_PARAMETER; - long nTokenLength = 0L; - long nInternalTokenLength = 0L; - unsigned char* pbTokenData = NULL; - SPNEGO_TOKEN** ppSpnegoToken = (SPNEGO_TOKEN**) phSpnegoToken; - - if ( NULL != ppSpnegoToken && - IsValidMechOid( MechType ) && - IsValidContextFlags( ucContextFlags ) ) - { - // Get the actual token size - - if ( ( nReturn = CalculateMinSpnegoInitTokenSize( ulMechTokenLen, ulMechListMICLen, - MechType, ( ucContextFlags != 0L ), - &nTokenLength, &nInternalTokenLength ) ) - == SPNEGO_E_SUCCESS ) - { - // Allocate a buffer to hold the data. - pbTokenData = calloc( 1, nTokenLength ); - - if ( NULL != pbTokenData ) - { - - // Now write the token - if ( ( nReturn = CreateSpnegoInitToken( MechType, - ucContextFlags, pbMechToken, - ulMechTokenLen, pbMechListMIC, - ulMechListMICLen, pbTokenData, - nTokenLength, nInternalTokenLength ) ) - == SPNEGO_E_SUCCESS ) - { - - // This will copy our allocated pointer, and ensure that the sructure cleans - // up the data later - nReturn = InitTokenFromBinary( SPNEGO_TOKEN_INTERNAL_COPYPTR, - SPNEGO_TOKEN_INTERNAL_FLAGS_FREEDATA, - pbTokenData, nTokenLength, ppSpnegoToken ); - - } - - // Cleanup on failure - if ( SPNEGO_E_SUCCESS != nReturn ) - { - free( pbTokenData ); + int nReturn = SPNEGO_E_INVALID_PARAMETER; + long nTokenLength = 0L; + long nInternalTokenLength = 0L; + unsigned char* pbTokenData = NULL; + SPNEGO_TOKEN** ppSpnegoToken = (SPNEGO_TOKEN**) phSpnegoToken; + + if ( NULL != ppSpnegoToken && + IsValidMechOid( MechType ) && + IsValidContextFlags( ucContextFlags ) ) { + // Get the actual token size + + if ( ( nReturn = CalculateMinSpnegoInitTokenSize( ulMechTokenLen, ulMechListMICLen, + MechType, ( ucContextFlags != 0L ), + &nTokenLength, &nInternalTokenLength ) ) + == SPNEGO_E_SUCCESS ) { + // Allocate a buffer to hold the data. + pbTokenData = calloc( 1, nTokenLength ); + + if ( NULL != pbTokenData ) { + + // Now write the token + if ( ( nReturn = CreateSpnegoInitToken( MechType, + ucContextFlags, pbMechToken, + ulMechTokenLen, pbMechListMIC, + ulMechListMICLen, pbTokenData, + nTokenLength, nInternalTokenLength ) ) + == SPNEGO_E_SUCCESS ) { + + // This will copy our allocated pointer, and ensure that the sructure cleans + // up the data later + nReturn = InitTokenFromBinary( SPNEGO_TOKEN_INTERNAL_COPYPTR, + SPNEGO_TOKEN_INTERNAL_FLAGS_FREEDATA, + pbTokenData, nTokenLength, ppSpnegoToken ); + + } + + // Cleanup on failure + if ( SPNEGO_E_SUCCESS != nReturn ) { + free( pbTokenData ); + } + + } // IF alloc succeeded + else { + nReturn = SPNEGO_E_OUT_OF_MEMORY; } - } // IF alloc succeeded - else - { - nReturn = SPNEGO_E_OUT_OF_MEMORY; - } + } // If calculated token size - } // If calculated token size + } // IF Valid Parameters - } // IF Valid Parameters - - LOG(("spnegoCreateNegTokenInit returned %d\n",nReturn)); - return nReturn; + LOG(("spnegoCreateNegTokenInit returned %d\n",nReturn)); + return nReturn; } ///////////////////////////////////////////////////////////////////////////// @@ -203,85 +197,79 @@ int spnegoCreateNegTokenInit( SPNEGO_MECH_OID MechType, // //////////////////////////////////////////////////////////////////////////// -int spnegoCreateNegTokenTarg( SPNEGO_MECH_OID MechType, - SPNEGO_NEGRESULT spnegoNegResult, unsigned char* pbMechToken, - unsigned long ulMechTokenLen, unsigned char* pbMechListMIC, - unsigned long ulMechListMICLen, SPNEGO_TOKEN_HANDLE* phSpnegoToken ) +int spnegoCreateNegTokenTarg( SPNEGO_MECH_OID MechType, + SPNEGO_NEGRESULT spnegoNegResult, unsigned char* pbMechToken, + unsigned long ulMechTokenLen, unsigned char* pbMechListMIC, + unsigned long ulMechListMICLen, SPNEGO_TOKEN_HANDLE* phSpnegoToken ) { - int nReturn = SPNEGO_E_INVALID_PARAMETER; - long nTokenLength = 0L; - long nInternalTokenLength = 0L; - unsigned char* pbTokenData = NULL; - SPNEGO_TOKEN** ppSpnegoToken = (SPNEGO_TOKEN**) phSpnegoToken; - - // - // spnego_mech_oid_NotUsed and spnego_negresult_NotUsed - // are okay here, however a valid MechOid is required - // if spnego_negresult_success or spnego_negresult_incomplete - // is specified. - // - - if ( NULL != ppSpnegoToken && - - ( IsValidMechOid( MechType ) || - spnego_mech_oid_NotUsed == MechType ) && - - ( IsValidNegResult( spnegoNegResult ) || - spnego_negresult_NotUsed == spnegoNegResult ) && - - !( !IsValidMechOid( MechType ) && - ( spnego_negresult_success == spnegoNegResult || - spnego_negresult_incomplete == spnegoNegResult ) ) ) - { - - // Get the actual token size - - if ( ( nReturn = CalculateMinSpnegoTargTokenSize( MechType, spnegoNegResult, ulMechTokenLen, - ulMechListMICLen, &nTokenLength, - &nInternalTokenLength ) ) - == SPNEGO_E_SUCCESS ) - { - // Allocate a buffer to hold the data. - pbTokenData = calloc( 1, nTokenLength ); - - if ( NULL != pbTokenData ) - { - - // Now write the token - if ( ( nReturn = CreateSpnegoTargToken( MechType, - spnegoNegResult, pbMechToken, - ulMechTokenLen, pbMechListMIC, - ulMechListMICLen, pbTokenData, - nTokenLength, nInternalTokenLength ) ) - == SPNEGO_E_SUCCESS ) - { - - // This will copy our allocated pointer, and ensure that the sructure cleans - // up the data later - nReturn = InitTokenFromBinary( SPNEGO_TOKEN_INTERNAL_COPYPTR, - SPNEGO_TOKEN_INTERNAL_FLAGS_FREEDATA, - pbTokenData, nTokenLength, ppSpnegoToken ); - + int nReturn = SPNEGO_E_INVALID_PARAMETER; + long nTokenLength = 0L; + long nInternalTokenLength = 0L; + unsigned char* pbTokenData = NULL; + SPNEGO_TOKEN** ppSpnegoToken = (SPNEGO_TOKEN**) phSpnegoToken; + + // + // spnego_mech_oid_NotUsed and spnego_negresult_NotUsed + // are okay here, however a valid MechOid is required + // if spnego_negresult_success or spnego_negresult_incomplete + // is specified. + // + + if ( NULL != ppSpnegoToken && + + ( IsValidMechOid( MechType ) || + spnego_mech_oid_NotUsed == MechType ) && + + ( IsValidNegResult( spnegoNegResult ) || + spnego_negresult_NotUsed == spnegoNegResult ) && + + !( !IsValidMechOid( MechType ) && + ( spnego_negresult_success == spnegoNegResult || + spnego_negresult_incomplete == spnegoNegResult ) ) ) { + + // Get the actual token size + + if ( ( nReturn = CalculateMinSpnegoTargTokenSize( MechType, spnegoNegResult, ulMechTokenLen, + ulMechListMICLen, &nTokenLength, + &nInternalTokenLength ) ) + == SPNEGO_E_SUCCESS ) { + // Allocate a buffer to hold the data. + pbTokenData = calloc( 1, nTokenLength ); + + if ( NULL != pbTokenData ) { + + // Now write the token + if ( ( nReturn = CreateSpnegoTargToken( MechType, + spnegoNegResult, pbMechToken, + ulMechTokenLen, pbMechListMIC, + ulMechListMICLen, pbTokenData, + nTokenLength, nInternalTokenLength ) ) + == SPNEGO_E_SUCCESS ) { + + // This will copy our allocated pointer, and ensure that the sructure cleans + // up the data later + nReturn = InitTokenFromBinary( SPNEGO_TOKEN_INTERNAL_COPYPTR, + SPNEGO_TOKEN_INTERNAL_FLAGS_FREEDATA, + pbTokenData, nTokenLength, ppSpnegoToken ); + + } + + // Cleanup on failure + if ( SPNEGO_E_SUCCESS != nReturn ) { + free( pbTokenData ); + } + + } // IF alloc succeeded + else { + nReturn = SPNEGO_E_OUT_OF_MEMORY; } - // Cleanup on failure - if ( SPNEGO_E_SUCCESS != nReturn ) - { - free( pbTokenData ); - } - - } // IF alloc succeeded - else - { - nReturn = SPNEGO_E_OUT_OF_MEMORY; - } - - } // If calculated token size + } // If calculated token size - } // IF Valid Parameters + } // IF Valid Parameters - LOG(("spnegoCreateNegTokenTarg returned %d\n",nReturn)); - return nReturn; + LOG(("spnegoCreateNegTokenTarg returned %d\n",nReturn)); + return nReturn; } ///////////////////////////////////////////////////////////////////////////// @@ -308,34 +296,30 @@ int spnegoCreateNegTokenTarg( SPNEGO_MECH_OID MechType, //////////////////////////////////////////////////////////////////////////// int spnegoTokenGetBinary( SPNEGO_TOKEN_HANDLE hSpnegoToken, unsigned char* pbTokenData, - unsigned long * pulDataLen ) + unsigned long * pulDataLen ) { - int nReturn = SPNEGO_E_INVALID_PARAMETER; - SPNEGO_TOKEN* pSpnegoToken = (SPNEGO_TOKEN*) hSpnegoToken; - - // Check parameters - pbTokenData is optional - if ( IsValidSpnegoToken( pSpnegoToken ) && - NULL != pulDataLen ) - { - - // Check for Buffer too small conditions - if ( NULL == pbTokenData || - pSpnegoToken->ulBinaryDataLen > *pulDataLen ) - { - *pulDataLen = pSpnegoToken->ulBinaryDataLen; - nReturn = SPNEGO_E_BUFFER_TOO_SMALL; - } - else - { - memcpy( pbTokenData, pSpnegoToken->pbBinaryData, pSpnegoToken->ulBinaryDataLen ); - *pulDataLen = pSpnegoToken->ulBinaryDataLen; - nReturn = SPNEGO_E_SUCCESS; - } - - } // IF parameters OK - - LOG(("spnegoTokenGetBinary returned %d\n",nReturn)); - return nReturn;; + int nReturn = SPNEGO_E_INVALID_PARAMETER; + SPNEGO_TOKEN* pSpnegoToken = (SPNEGO_TOKEN*) hSpnegoToken; + + // Check parameters - pbTokenData is optional + if ( IsValidSpnegoToken( pSpnegoToken ) && + NULL != pulDataLen ) { + + // Check for Buffer too small conditions + if ( NULL == pbTokenData || + pSpnegoToken->ulBinaryDataLen > *pulDataLen ) { + *pulDataLen = pSpnegoToken->ulBinaryDataLen; + nReturn = SPNEGO_E_BUFFER_TOO_SMALL; + } else { + memcpy( pbTokenData, pSpnegoToken->pbBinaryData, pSpnegoToken->ulBinaryDataLen ); + *pulDataLen = pSpnegoToken->ulBinaryDataLen; + nReturn = SPNEGO_E_SUCCESS; + } + + } // IF parameters OK + + LOG(("spnegoTokenGetBinary returned %d\n",nReturn)); + return nReturn;; } ///////////////////////////////////////////////////////////////////////////// @@ -357,8 +341,8 @@ int spnegoTokenGetBinary( SPNEGO_TOKEN_HANDLE hSpnegoToken, unsigned char* pbTok void spnegoFreeData( SPNEGO_TOKEN_HANDLE hSpnegoToken ) { - FreeSpnegoToken( (SPNEGO_TOKEN*) hSpnegoToken); - return; + FreeSpnegoToken( (SPNEGO_TOKEN*) hSpnegoToken); + return; } ///////////////////////////////////////////////////////////////////////////// @@ -382,27 +366,25 @@ void spnegoFreeData( SPNEGO_TOKEN_HANDLE hSpnegoToken ) int spnegoGetTokenType( SPNEGO_TOKEN_HANDLE hSpnegoToken, int * piTokenType ) { - int nReturn = SPNEGO_E_INVALID_PARAMETER; - SPNEGO_TOKEN* pSpnegoToken = (SPNEGO_TOKEN*) hSpnegoToken; - - // Check parameters - if ( IsValidSpnegoToken( pSpnegoToken ) && - NULL != piTokenType && - pSpnegoToken) - { - - // Check that the type in the structure makes sense - if ( SPNEGO_TOKEN_INIT == pSpnegoToken->ucTokenType || - SPNEGO_TOKEN_TARG == pSpnegoToken->ucTokenType ) - { - *piTokenType = pSpnegoToken->ucTokenType; - nReturn = SPNEGO_E_SUCCESS; - } - - } // IF parameters OK - - LOG(("spnegoGetTokenType returned %d\n",nReturn)); - return nReturn; + int nReturn = SPNEGO_E_INVALID_PARAMETER; + SPNEGO_TOKEN* pSpnegoToken = (SPNEGO_TOKEN*) hSpnegoToken; + + // Check parameters + if ( IsValidSpnegoToken( pSpnegoToken ) && + NULL != piTokenType && + pSpnegoToken) { + + // Check that the type in the structure makes sense + if ( SPNEGO_TOKEN_INIT == pSpnegoToken->ucTokenType || + SPNEGO_TOKEN_TARG == pSpnegoToken->ucTokenType ) { + *piTokenType = pSpnegoToken->ucTokenType; + nReturn = SPNEGO_E_SUCCESS; + } + + } // IF parameters OK + + LOG(("spnegoGetTokenType returned %d\n",nReturn)); + return nReturn; } ///////////////////////////////////////////////////////////////////////////// @@ -431,34 +413,30 @@ int spnegoGetTokenType( SPNEGO_TOKEN_HANDLE hSpnegoToken, int * piTokenType ) // Returns the Initial Mech Type in the MechList element in the NegInitToken. int spnegoIsMechTypeAvailable( SPNEGO_TOKEN_HANDLE hSpnegoToken, SPNEGO_MECH_OID MechOID, int * piMechTypeIndex ) { - int nReturn = SPNEGO_E_INVALID_PARAMETER; - SPNEGO_TOKEN* pSpnegoToken = (SPNEGO_TOKEN*) hSpnegoToken; - - // Check parameters - if ( IsValidSpnegoToken( pSpnegoToken ) && - NULL != piMechTypeIndex && - IsValidMechOid( MechOID ) && - SPNEGO_TOKEN_INIT == pSpnegoToken->ucTokenType ) - { - - // Check if MechList is available - if ( pSpnegoToken->aElementArray[SPNEGO_INIT_MECHTYPES_ELEMENT].iElementPresent - == SPNEGO_TOKEN_ELEMENT_AVAILABLE ) - { - // Locate the MechOID in the list element - nReturn = FindMechOIDInMechList( - &pSpnegoToken->aElementArray[SPNEGO_INIT_MECHTYPES_ELEMENT], - MechOID, piMechTypeIndex ); - } - else - { - nReturn = SPNEGO_E_ELEMENT_UNAVAILABLE; - } - - } // IF parameters OK - - LOG(("spnegoIsMechTypeAvailable returned %d\n",nReturn)); - return nReturn;; + int nReturn = SPNEGO_E_INVALID_PARAMETER; + SPNEGO_TOKEN* pSpnegoToken = (SPNEGO_TOKEN*) hSpnegoToken; + + // Check parameters + if ( IsValidSpnegoToken( pSpnegoToken ) && + NULL != piMechTypeIndex && + IsValidMechOid( MechOID ) && + SPNEGO_TOKEN_INIT == pSpnegoToken->ucTokenType ) { + + // Check if MechList is available + if ( pSpnegoToken->aElementArray[SPNEGO_INIT_MECHTYPES_ELEMENT].iElementPresent + == SPNEGO_TOKEN_ELEMENT_AVAILABLE ) { + // Locate the MechOID in the list element + nReturn = FindMechOIDInMechList( + &pSpnegoToken->aElementArray[SPNEGO_INIT_MECHTYPES_ELEMENT], + MechOID, piMechTypeIndex ); + } else { + nReturn = SPNEGO_E_ELEMENT_UNAVAILABLE; + } + + } // IF parameters OK + + LOG(("spnegoIsMechTypeAvailable returned %d\n",nReturn)); + return nReturn;; } ///////////////////////////////////////////////////////////////////////////// @@ -484,43 +462,36 @@ int spnegoIsMechTypeAvailable( SPNEGO_TOKEN_HANDLE hSpnegoToken, SPNEGO_MECH_OID int spnegoGetContextFlags( SPNEGO_TOKEN_HANDLE hSpnegoToken, unsigned char* pucContextFlags ) { - int nReturn = SPNEGO_E_INVALID_PARAMETER; - SPNEGO_TOKEN* pSpnegoToken = (SPNEGO_TOKEN*) hSpnegoToken; - - // Check parameters - if ( IsValidSpnegoToken( pSpnegoToken ) && - NULL != pucContextFlags && - SPNEGO_TOKEN_INIT == pSpnegoToken->ucTokenType ) - { - - // Check if ContextFlags is available - if ( pSpnegoToken->aElementArray[SPNEGO_INIT_REQFLAGS_ELEMENT].iElementPresent - == SPNEGO_TOKEN_ELEMENT_AVAILABLE ) - { - // The length should be two, the value should show a 1 bit difference in the difference byte, and - // the value must be valid - if ( pSpnegoToken->aElementArray[SPNEGO_INIT_REQFLAGS_ELEMENT].nDatalength == SPNEGO_NEGINIT_MAXLEN_REQFLAGS && - pSpnegoToken->aElementArray[SPNEGO_INIT_REQFLAGS_ELEMENT].pbData[0] == SPNEGO_NEGINIT_REQFLAGS_BITDIFF && - IsValidContextFlags( pSpnegoToken->aElementArray[SPNEGO_INIT_REQFLAGS_ELEMENT].pbData[1] ) ) - { - *pucContextFlags = pSpnegoToken->aElementArray[SPNEGO_INIT_REQFLAGS_ELEMENT].pbData[1]; - nReturn = SPNEGO_E_SUCCESS; - } - else - { - nReturn = SPNEGO_E_INVALID_ELEMENT; - } - - } - else - { - nReturn = SPNEGO_E_ELEMENT_UNAVAILABLE; - } - - } // IF parameters OK - - LOG(("spnegoGetContextFlags returned %d\n",nReturn)); - return nReturn;; + int nReturn = SPNEGO_E_INVALID_PARAMETER; + SPNEGO_TOKEN* pSpnegoToken = (SPNEGO_TOKEN*) hSpnegoToken; + + // Check parameters + if ( IsValidSpnegoToken( pSpnegoToken ) && + NULL != pucContextFlags && + SPNEGO_TOKEN_INIT == pSpnegoToken->ucTokenType ) { + + // Check if ContextFlags is available + if ( pSpnegoToken->aElementArray[SPNEGO_INIT_REQFLAGS_ELEMENT].iElementPresent + == SPNEGO_TOKEN_ELEMENT_AVAILABLE ) { + // The length should be two, the value should show a 1 bit difference in the difference byte, and + // the value must be valid + if ( pSpnegoToken->aElementArray[SPNEGO_INIT_REQFLAGS_ELEMENT].nDatalength == SPNEGO_NEGINIT_MAXLEN_REQFLAGS && + pSpnegoToken->aElementArray[SPNEGO_INIT_REQFLAGS_ELEMENT].pbData[0] == SPNEGO_NEGINIT_REQFLAGS_BITDIFF && + IsValidContextFlags( pSpnegoToken->aElementArray[SPNEGO_INIT_REQFLAGS_ELEMENT].pbData[1] ) ) { + *pucContextFlags = pSpnegoToken->aElementArray[SPNEGO_INIT_REQFLAGS_ELEMENT].pbData[1]; + nReturn = SPNEGO_E_SUCCESS; + } else { + nReturn = SPNEGO_E_INVALID_ELEMENT; + } + + } else { + nReturn = SPNEGO_E_ELEMENT_UNAVAILABLE; + } + + } // IF parameters OK + + LOG(("spnegoGetContextFlags returned %d\n",nReturn)); + return nReturn;; } ///////////////////////////////////////////////////////////////////////////// @@ -546,40 +517,33 @@ int spnegoGetContextFlags( SPNEGO_TOKEN_HANDLE hSpnegoToken, unsigned char* pucC int spnegoGetNegotiationResult( SPNEGO_TOKEN_HANDLE hSpnegoToken, SPNEGO_NEGRESULT* pnegResult ) { - int nReturn = SPNEGO_E_INVALID_PARAMETER; - SPNEGO_TOKEN* pSpnegoToken = (SPNEGO_TOKEN*) hSpnegoToken; - - // Check parameters - if ( IsValidSpnegoToken( pSpnegoToken ) && - NULL != pnegResult && - SPNEGO_TOKEN_TARG == pSpnegoToken->ucTokenType ) - { - - // Check if NegResult is available - if ( pSpnegoToken->aElementArray[SPNEGO_TARG_NEGRESULT_ELEMENT].iElementPresent - == SPNEGO_TOKEN_ELEMENT_AVAILABLE ) - { - // Must be 1 byte long and a valid value - if ( pSpnegoToken->aElementArray[SPNEGO_TARG_NEGRESULT_ELEMENT].nDatalength == SPNEGO_NEGTARG_MAXLEN_NEGRESULT && - IsValidNegResult( *pSpnegoToken->aElementArray[SPNEGO_TARG_NEGRESULT_ELEMENT].pbData ) ) - { - *pnegResult = *pSpnegoToken->aElementArray[SPNEGO_TARG_NEGRESULT_ELEMENT].pbData; - nReturn = SPNEGO_E_SUCCESS; - } - else - { - nReturn = SPNEGO_E_INVALID_ELEMENT; - } - } - else - { - nReturn = SPNEGO_E_ELEMENT_UNAVAILABLE; - } - - } // IF parameters OK - - LOG(("spnegoGetNegotiationResult returned %d\n",nReturn)); - return nReturn;; + int nReturn = SPNEGO_E_INVALID_PARAMETER; + SPNEGO_TOKEN* pSpnegoToken = (SPNEGO_TOKEN*) hSpnegoToken; + + // Check parameters + if ( IsValidSpnegoToken( pSpnegoToken ) && + NULL != pnegResult && + SPNEGO_TOKEN_TARG == pSpnegoToken->ucTokenType ) { + + // Check if NegResult is available + if ( pSpnegoToken->aElementArray[SPNEGO_TARG_NEGRESULT_ELEMENT].iElementPresent + == SPNEGO_TOKEN_ELEMENT_AVAILABLE ) { + // Must be 1 byte long and a valid value + if ( pSpnegoToken->aElementArray[SPNEGO_TARG_NEGRESULT_ELEMENT].nDatalength == SPNEGO_NEGTARG_MAXLEN_NEGRESULT && + IsValidNegResult( *pSpnegoToken->aElementArray[SPNEGO_TARG_NEGRESULT_ELEMENT].pbData ) ) { + *pnegResult = *pSpnegoToken->aElementArray[SPNEGO_TARG_NEGRESULT_ELEMENT].pbData; + nReturn = SPNEGO_E_SUCCESS; + } else { + nReturn = SPNEGO_E_INVALID_ELEMENT; + } + } else { + nReturn = SPNEGO_E_ELEMENT_UNAVAILABLE; + } + + } // IF parameters OK + + LOG(("spnegoGetNegotiationResult returned %d\n",nReturn)); + return nReturn;; } ///////////////////////////////////////////////////////////////////////////// @@ -606,50 +570,44 @@ int spnegoGetNegotiationResult( SPNEGO_TOKEN_HANDLE hSpnegoToken, SPNEGO_NEGRESU int spnegoGetSupportedMechType( SPNEGO_TOKEN_HANDLE hSpnegoToken, SPNEGO_MECH_OID* pMechOID ) { - int nReturn = SPNEGO_E_INVALID_PARAMETER; - int nCtr = 0L; - long nLength = 0L; - SPNEGO_TOKEN* pSpnegoToken = (SPNEGO_TOKEN*) hSpnegoToken; - - // Check parameters - if ( IsValidSpnegoToken( pSpnegoToken ) && - NULL != pMechOID && - SPNEGO_TOKEN_TARG == pSpnegoToken->ucTokenType ) - { - - // Check if MechList is available - if ( pSpnegoToken->aElementArray[SPNEGO_TARG_SUPPMECH_ELEMENT].iElementPresent - == SPNEGO_TOKEN_ELEMENT_AVAILABLE ) - { - - for ( nCtr = 0; - nReturn != SPNEGO_E_SUCCESS && - g_stcMechOIDList[nCtr].eMechanismOID != spnego_mech_oid_NotUsed; - nCtr++ ) - { - - if ( ( nReturn = ASNDerCheckOID( - pSpnegoToken->aElementArray[SPNEGO_TARG_SUPPMECH_ELEMENT].pbData, - nCtr, - pSpnegoToken->aElementArray[SPNEGO_TARG_SUPPMECH_ELEMENT].nDatalength, - &nLength ) ) == SPNEGO_E_SUCCESS ) - { - *pMechOID = nCtr; - } + int nReturn = SPNEGO_E_INVALID_PARAMETER; + int nCtr = 0L; + long nLength = 0L; + SPNEGO_TOKEN* pSpnegoToken = (SPNEGO_TOKEN*) hSpnegoToken; + + // Check parameters + if ( IsValidSpnegoToken( pSpnegoToken ) && + NULL != pMechOID && + SPNEGO_TOKEN_TARG == pSpnegoToken->ucTokenType ) { - } // For enum MechOIDs + // Check if MechList is available + if ( pSpnegoToken->aElementArray[SPNEGO_TARG_SUPPMECH_ELEMENT].iElementPresent + == SPNEGO_TOKEN_ELEMENT_AVAILABLE ) { + for ( nCtr = 0; + nReturn != SPNEGO_E_SUCCESS && + g_stcMechOIDList[nCtr].eMechanismOID != spnego_mech_oid_NotUsed; + nCtr++ ) { - } - else - { - nReturn = SPNEGO_E_ELEMENT_UNAVAILABLE; - } + if ( ( nReturn = ASNDerCheckOID( + pSpnegoToken->aElementArray[SPNEGO_TARG_SUPPMECH_ELEMENT].pbData, + nCtr, + pSpnegoToken->aElementArray[SPNEGO_TARG_SUPPMECH_ELEMENT].nDatalength, + &nLength ) ) == SPNEGO_E_SUCCESS ) { + *pMechOID = nCtr; + } - } // IF parameters OK + } // For enum MechOIDs - LOG(("spnegoGetSupportedMechType returned %d\n",nReturn)); - return nReturn;; + + } else { + nReturn = SPNEGO_E_ELEMENT_UNAVAILABLE; + } + + } // IF parameters OK + + LOG(("spnegoGetSupportedMechType returned %d\n",nReturn)); + return nReturn;; } ///////////////////////////////////////////////////////////////////////////// @@ -681,52 +639,42 @@ int spnegoGetSupportedMechType( SPNEGO_TOKEN_HANDLE hSpnegoToken, SPNEGO_MECH_OI int spnegoGetMechToken( SPNEGO_TOKEN_HANDLE hSpnegoToken, unsigned char* pbTokenData, unsigned long* pulDataLen ) { - int nReturn = SPNEGO_E_INVALID_PARAMETER; - SPNEGO_TOKEN* pSpnegoToken = (SPNEGO_TOKEN*) hSpnegoToken; - SPNEGO_ELEMENT* pSpnegoElement = NULL; - - // Check parameters - if ( IsValidSpnegoToken( pSpnegoToken ) && - NULL != pulDataLen ) - { - - // Point at the proper Element - if ( SPNEGO_TOKEN_INIT == pSpnegoToken->ucTokenType ) - { - pSpnegoElement = &pSpnegoToken->aElementArray[SPNEGO_INIT_MECHTOKEN_ELEMENT]; - } - else - { - pSpnegoElement = &pSpnegoToken->aElementArray[SPNEGO_TARG_RESPTOKEN_ELEMENT]; - } - - // Check if MechType is available - if ( SPNEGO_TOKEN_ELEMENT_AVAILABLE == pSpnegoElement->iElementPresent ) - { - // Check for Buffer too small conditions - if ( NULL == pbTokenData || - pSpnegoElement->nDatalength > *pulDataLen ) - { - *pulDataLen = pSpnegoElement->nDatalength; - nReturn = SPNEGO_E_BUFFER_TOO_SMALL; - } - else - { - // Copy Memory - memcpy( pbTokenData, pSpnegoElement->pbData, pSpnegoElement->nDatalength ); - *pulDataLen = pSpnegoElement->nDatalength; - nReturn = SPNEGO_E_SUCCESS; - } - } - else - { - nReturn = SPNEGO_E_ELEMENT_UNAVAILABLE; - } + int nReturn = SPNEGO_E_INVALID_PARAMETER; + SPNEGO_TOKEN* pSpnegoToken = (SPNEGO_TOKEN*) hSpnegoToken; + SPNEGO_ELEMENT* pSpnegoElement = NULL; + + // Check parameters + if ( IsValidSpnegoToken( pSpnegoToken ) && + NULL != pulDataLen ) { + + // Point at the proper Element + if ( SPNEGO_TOKEN_INIT == pSpnegoToken->ucTokenType ) { + pSpnegoElement = &pSpnegoToken->aElementArray[SPNEGO_INIT_MECHTOKEN_ELEMENT]; + } else { + pSpnegoElement = &pSpnegoToken->aElementArray[SPNEGO_TARG_RESPTOKEN_ELEMENT]; + } + + // Check if MechType is available + if ( SPNEGO_TOKEN_ELEMENT_AVAILABLE == pSpnegoElement->iElementPresent ) { + // Check for Buffer too small conditions + if ( NULL == pbTokenData || + pSpnegoElement->nDatalength > *pulDataLen ) { + *pulDataLen = pSpnegoElement->nDatalength; + nReturn = SPNEGO_E_BUFFER_TOO_SMALL; + } else { + // Copy Memory + memcpy( pbTokenData, pSpnegoElement->pbData, pSpnegoElement->nDatalength ); + *pulDataLen = pSpnegoElement->nDatalength; + nReturn = SPNEGO_E_SUCCESS; + } + } else { + nReturn = SPNEGO_E_ELEMENT_UNAVAILABLE; + } - } // IF parameters OK + } // IF parameters OK - LOG(("spnegoGetMechToken returned %d\n",nReturn)); - return nReturn;; + LOG(("spnegoGetMechToken returned %d\n",nReturn)); + return nReturn;; } ///////////////////////////////////////////////////////////////////////////// @@ -756,51 +704,41 @@ int spnegoGetMechToken( SPNEGO_TOKEN_HANDLE hSpnegoToken, unsigned char* pbToken int spnegoGetMechListMIC( SPNEGO_TOKEN_HANDLE hSpnegoToken, unsigned char* pbMICData, unsigned long* pulDataLen ) { - int nReturn = SPNEGO_E_INVALID_PARAMETER; - SPNEGO_TOKEN* pSpnegoToken = (SPNEGO_TOKEN*) hSpnegoToken; - SPNEGO_ELEMENT* pSpnegoElement = NULL; - - // Check parameters - if ( IsValidSpnegoToken( pSpnegoToken ) && - NULL != pulDataLen ) - { - - // Point at the proper Element - if ( SPNEGO_TOKEN_INIT == pSpnegoToken->ucTokenType ) - { - pSpnegoElement = &pSpnegoToken->aElementArray[SPNEGO_INIT_MECHLISTMIC_ELEMENT]; - } - else - { - pSpnegoElement = &pSpnegoToken->aElementArray[SPNEGO_TARG_MECHLISTMIC_ELEMENT]; - } - - // Check if MechType is available - if ( SPNEGO_TOKEN_ELEMENT_AVAILABLE == pSpnegoElement->iElementPresent ) - { - // Check for Buffer too small conditions - if ( NULL == pbMICData || - pSpnegoElement->nDatalength > *pulDataLen ) - { - *pulDataLen = pSpnegoElement->nDatalength; - nReturn = SPNEGO_E_BUFFER_TOO_SMALL; - } - else - { - // Copy Memory - memcpy( pbMICData, pSpnegoElement->pbData, pSpnegoElement->nDatalength ); - *pulDataLen = pSpnegoElement->nDatalength; - nReturn = SPNEGO_E_SUCCESS; - } - } - else - { - nReturn = SPNEGO_E_ELEMENT_UNAVAILABLE; - } + int nReturn = SPNEGO_E_INVALID_PARAMETER; + SPNEGO_TOKEN* pSpnegoToken = (SPNEGO_TOKEN*) hSpnegoToken; + SPNEGO_ELEMENT* pSpnegoElement = NULL; + + // Check parameters + if ( IsValidSpnegoToken( pSpnegoToken ) && + NULL != pulDataLen ) { + + // Point at the proper Element + if ( SPNEGO_TOKEN_INIT == pSpnegoToken->ucTokenType ) { + pSpnegoElement = &pSpnegoToken->aElementArray[SPNEGO_INIT_MECHLISTMIC_ELEMENT]; + } else { + pSpnegoElement = &pSpnegoToken->aElementArray[SPNEGO_TARG_MECHLISTMIC_ELEMENT]; + } + + // Check if MechType is available + if ( SPNEGO_TOKEN_ELEMENT_AVAILABLE == pSpnegoElement->iElementPresent ) { + // Check for Buffer too small conditions + if ( NULL == pbMICData || + pSpnegoElement->nDatalength > *pulDataLen ) { + *pulDataLen = pSpnegoElement->nDatalength; + nReturn = SPNEGO_E_BUFFER_TOO_SMALL; + } else { + // Copy Memory + memcpy( pbMICData, pSpnegoElement->pbData, pSpnegoElement->nDatalength ); + *pulDataLen = pSpnegoElement->nDatalength; + nReturn = SPNEGO_E_SUCCESS; + } + } else { + nReturn = SPNEGO_E_ELEMENT_UNAVAILABLE; + } - } // IF parameters OK + } // IF parameters OK - LOG(("spnegoGetMechListMIC returned %d\n",nReturn)); - return nReturn;; + LOG(("spnegoGetMechListMIC returned %d\n",nReturn)); + return nReturn;; } diff --git a/helpers/negotiate_auth/squid_kerb_auth/spnegohelp/spnego.h b/helpers/negotiate_auth/squid_kerb_auth/spnegohelp/spnego.h index a49b220cdf..3c2c9dc194 100644 --- a/helpers/negotiate_auth/squid_kerb_auth/spnegohelp/spnego.h +++ b/helpers/negotiate_auth/squid_kerb_auth/spnegohelp/spnego.h @@ -37,32 +37,31 @@ extern "C" // Users of SPNEGO Token Handler API will request // these as well as free them, // -typedef void* SPNEGO_TOKEN_HANDLE; + typedef void* SPNEGO_TOKEN_HANDLE; // // Defines the element types that are found // in each of the tokens. // -typedef enum spnego_element_type -{ - spnego_element_min, // Lower bound + typedef enum spnego_element_type { + spnego_element_min, // Lower bound - // Init token elements - spnego_init_mechtypes, - spnego_init_reqFlags, - spnego_init_mechToken, - spnego_init_mechListMIC, + // Init token elements + spnego_init_mechtypes, + spnego_init_reqFlags, + spnego_init_mechToken, + spnego_init_mechListMIC, - // Targ token elements - spnego_targ_negResult, - spnego_targ_supportedMech, - spnego_targ_responseToken, - spnego_targ_mechListMIC, + // Targ token elements + spnego_targ_negResult, + spnego_targ_supportedMech, + spnego_targ_responseToken, + spnego_targ_mechListMIC, - spnego_element_max // Upper bound + spnego_element_max // Upper bound -} SPNEGO_ELEMENT_TYPE; + } SPNEGO_ELEMENT_TYPE; // // Token Element Availability. Elements in both @@ -89,27 +88,25 @@ typedef enum spnego_element_type // defined in the parsing code. // -typedef enum spnego_mech_oid -{ - // Init token elements - spnego_mech_oid_Kerberos_V5_Legacy, // Really V5, but OID off by 1 bit - spnego_mech_oid_Kerberos_V5, - spnego_mech_oid_Spnego, - spnego_mech_oid_NotUsed = -1 + typedef enum spnego_mech_oid { + // Init token elements + spnego_mech_oid_Kerberos_V5_Legacy, // Really V5, but OID off by 1 bit + spnego_mech_oid_Kerberos_V5, + spnego_mech_oid_Spnego, + spnego_mech_oid_NotUsed = -1 -} SPNEGO_MECH_OID; + } SPNEGO_MECH_OID; // // Defines the negResult values. // -typedef enum spnego_negResult -{ - spnego_negresult_success, - spnego_negresult_incomplete, - spnego_negresult_rejected, - spnego_negresult_NotUsed = -1 -} SPNEGO_NEGRESULT; + typedef enum spnego_negResult { + spnego_negresult_success, + spnego_negresult_incomplete, + spnego_negresult_rejected, + spnego_negresult_NotUsed = -1 + } SPNEGO_NEGRESULT; // // Context Flags in NegTokenInit @@ -180,58 +177,58 @@ typedef enum spnego_negResult // A Token Element was invalid (e.g. improper length or value) #define SPNEGO_E_INVALID_ELEMENT -13 -/* Miscelaneous API Functions */ + /* Miscelaneous API Functions */ // Frees opaque data -void spnegoFreeData( SPNEGO_TOKEN_HANDLE hSpnegoToken ); + void spnegoFreeData( SPNEGO_TOKEN_HANDLE hSpnegoToken ); // Initializes SPNEGO_TOKEN structure from DER encoded binary data -int spnegoInitFromBinary( unsigned char* pbTokenData, unsigned long ulLength, SPNEGO_TOKEN_HANDLE* phSpnegoToken ); + int spnegoInitFromBinary( unsigned char* pbTokenData, unsigned long ulLength, SPNEGO_TOKEN_HANDLE* phSpnegoToken ); // Initializes SPNEGO_TOKEN structure for a NegTokenInit type using the // supplied parameters -int spnegoCreateNegTokenInit( SPNEGO_MECH_OID MechType, - unsigned char ucContextFlags, unsigned char* pbMechToken, - unsigned long ulMechTokenLen, unsigned char* pbMechTokenMIC, - unsigned long ulMechTokenMIC, SPNEGO_TOKEN_HANDLE* phSpnegoToken ); + int spnegoCreateNegTokenInit( SPNEGO_MECH_OID MechType, + unsigned char ucContextFlags, unsigned char* pbMechToken, + unsigned long ulMechTokenLen, unsigned char* pbMechTokenMIC, + unsigned long ulMechTokenMIC, SPNEGO_TOKEN_HANDLE* phSpnegoToken ); // Initializes SPNEGO_TOKEN structure for a NegTokenTarg type using the // supplied parameters -int spnegoCreateNegTokenTarg( SPNEGO_MECH_OID MechType, - SPNEGO_NEGRESULT spnegoNegResult, unsigned char* pbMechToken, - unsigned long ulMechTokenLen, unsigned char* pbMechListMIC, - unsigned long ulMechListMICLen, SPNEGO_TOKEN_HANDLE* phSpnegoToken ); + int spnegoCreateNegTokenTarg( SPNEGO_MECH_OID MechType, + SPNEGO_NEGRESULT spnegoNegResult, unsigned char* pbMechToken, + unsigned long ulMechTokenLen, unsigned char* pbMechListMIC, + unsigned long ulMechListMICLen, SPNEGO_TOKEN_HANDLE* phSpnegoToken ); // Copies binary representation of SPNEGO Data into user supplied buffer -int spnegoTokenGetBinary( SPNEGO_TOKEN_HANDLE hSpnegoToken, unsigned char* pbTokenData, - unsigned long * pulDataLen ); + int spnegoTokenGetBinary( SPNEGO_TOKEN_HANDLE hSpnegoToken, unsigned char* pbTokenData, + unsigned long * pulDataLen ); // Returns SPNEGO Token Type -int spnegoGetTokenType( SPNEGO_TOKEN_HANDLE hSpnegoToken, int * piTokenType ); + int spnegoGetTokenType( SPNEGO_TOKEN_HANDLE hSpnegoToken, int * piTokenType ); -/* Reading an Init Token */ + /* Reading an Init Token */ // Returns the Initial Mech Type in the MechList element in the NegInitToken. -int spnegoIsMechTypeAvailable( SPNEGO_TOKEN_HANDLE hSpnegoToken, SPNEGO_MECH_OID MechOID, int * piMechTypeIndex ); + int spnegoIsMechTypeAvailable( SPNEGO_TOKEN_HANDLE hSpnegoToken, SPNEGO_MECH_OID MechOID, int * piMechTypeIndex ); // Returns the value from the context flags element in the NegInitToken as an unsigned long -int spnegoGetContextFlags( SPNEGO_TOKEN_HANDLE hSpnegoToken, unsigned char* pucContextFlags ); + int spnegoGetContextFlags( SPNEGO_TOKEN_HANDLE hSpnegoToken, unsigned char* pucContextFlags ); -/* Reading a Response Token */ + /* Reading a Response Token */ // Returns the value from the negResult element (Status code of GSS call - 0,1,2) -int spnegoGetNegotiationResult( SPNEGO_TOKEN_HANDLE hSpnegoToken, SPNEGO_NEGRESULT* pnegResult ); + int spnegoGetNegotiationResult( SPNEGO_TOKEN_HANDLE hSpnegoToken, SPNEGO_NEGRESULT* pnegResult ); // Returns the Supported Mech Type from the NegTokenTarg. -int spnegoGetSupportedMechType( SPNEGO_TOKEN_HANDLE hSpnegoToken, SPNEGO_MECH_OID* pMechOID ); + int spnegoGetSupportedMechType( SPNEGO_TOKEN_HANDLE hSpnegoToken, SPNEGO_MECH_OID* pMechOID ); -/* Reading either Token Type */ + /* Reading either Token Type */ // Returns the actual Mechanism data from the token (this is what is passed into GSS-API functions -int spnegoGetMechToken( SPNEGO_TOKEN_HANDLE hSpnegoToken, unsigned char* pbTokenData, unsigned long* pulDataLen ); + int spnegoGetMechToken( SPNEGO_TOKEN_HANDLE hSpnegoToken, unsigned char* pbTokenData, unsigned long* pulDataLen ); // Returns the Message Integrity BLOB in the token -int spnegoGetMechListMIC( SPNEGO_TOKEN_HANDLE hSpnegoToken, unsigned char* pbMICData, unsigned long* pulDataLen ); + int spnegoGetMechListMIC( SPNEGO_TOKEN_HANDLE hSpnegoToken, unsigned char* pbMICData, unsigned long* pulDataLen ); // C++ Specific #if defined(__cplusplus) @@ -239,9 +236,9 @@ int spnegoGetMechListMIC( SPNEGO_TOKEN_HANDLE hSpnegoToken, unsigned char* pbMIC #endif #ifdef DEBUG #include - #define PRERR(...) fprintf(stderr, __VA_ARGS__) - #define LOG(x) PRERR x +#define PRERR(...) fprintf(stderr, __VA_ARGS__) +#define LOG(x) PRERR x #else - #define LOG(x) +#define LOG(x) #endif #endif diff --git a/helpers/negotiate_auth/squid_kerb_auth/spnegohelp/spnegohelp.c b/helpers/negotiate_auth/squid_kerb_auth/spnegohelp/spnegohelp.c index a10bc25c92..465819510c 100644 --- a/helpers/negotiate_auth/squid_kerb_auth/spnegohelp/spnegohelp.c +++ b/helpers/negotiate_auth/squid_kerb_auth/spnegohelp/spnegohelp.c @@ -39,8 +39,8 @@ int makeNegTokenTarg (const unsigned char * kerberosToken, /* Check arguments. */ if (!kerberosToken || - !negTokenTarg || - !negTokenTargLength) + !negTokenTarg || + !negTokenTargLength) return 10; /* Does IIS reply with 1.2.840.48018.1.2.2 or 1.2.840.113554.1.2.2? */ @@ -57,8 +57,7 @@ int makeNegTokenTarg (const unsigned char * kerberosToken, 0, &hSpnegoToken); - if (rc2 != SPNEGO_E_SUCCESS) - { + if (rc2 != SPNEGO_E_SUCCESS) { rc1 = abs(rc2)+100; goto cleanup; } @@ -69,16 +68,14 @@ int makeNegTokenTarg (const unsigned char * kerberosToken, NULL, (unsigned long*) negTokenTargLength); - if (rc2 != SPNEGO_E_BUFFER_TOO_SMALL) - { + if (rc2 != SPNEGO_E_BUFFER_TOO_SMALL) { rc1 = abs(rc2)+200; goto cleanup; } *negTokenTarg = malloc (*negTokenTargLength); - if (!*negTokenTarg) - { + if (!*negTokenTarg) { rc1 = abs(rc2)+300; goto cleanup; } @@ -86,12 +83,11 @@ int makeNegTokenTarg (const unsigned char * kerberosToken, /* Get NegTokenTarg data. */ rc2 = spnegoTokenGetBinary (hSpnegoToken, - (unsigned char *) *negTokenTarg, - (unsigned long*) negTokenTargLength); + (unsigned char *) *negTokenTarg, + (unsigned long*) negTokenTargLength); - if (rc2 != SPNEGO_E_SUCCESS) - { + if (rc2 != SPNEGO_E_SUCCESS) { rc1 = abs(rc2)+400; goto error; } @@ -102,8 +98,7 @@ int makeNegTokenTarg (const unsigned char * kerberosToken, error: - if (*negTokenTarg) - { + if (*negTokenTarg) { free ((unsigned char *) *negTokenTarg); *negTokenTarg = NULL; *negTokenTargLength = 0; @@ -133,8 +128,8 @@ int parseNegTokenInit (const unsigned char * negTokenInit, /* Check arguments. */ if (!negTokenInit || - !kerberosToken || - !kerberosTokenLength) + !kerberosToken || + !kerberosTokenLength) return 10; /* Decode SPNEGO token. */ @@ -143,8 +138,7 @@ int parseNegTokenInit (const unsigned char * negTokenInit, negTokenInitLength, &hSpnegoToken); - if (rc2 != SPNEGO_E_SUCCESS) - { + if (rc2 != SPNEGO_E_SUCCESS) { rc1 = abs(rc2)+100; goto cleanup; } @@ -154,40 +148,36 @@ int parseNegTokenInit (const unsigned char * negTokenInit, rc2 = spnegoGetTokenType (hSpnegoToken, &tokenType); - if (rc2 != SPNEGO_E_SUCCESS) - { + if (rc2 != SPNEGO_E_SUCCESS) { rc1 = abs(rc2)+200; goto cleanup; } - if (tokenType != SPNEGO_TOKEN_INIT) - { + if (tokenType != SPNEGO_TOKEN_INIT) { rc1 = abs(rc2)+300; goto cleanup; } - /* - Check that first mechType is 1.2.840.113554.1.2.2 or 1.2.840.48018.1.2.2. - */ + /* + Check that first mechType is 1.2.840.113554.1.2.2 or 1.2.840.48018.1.2.2. + */ - /* - IE seems to reply with 1.2.840.48018.1.2.2 and then 1.2.840.113554.1.2.2. - */ + /* + IE seems to reply with 1.2.840.48018.1.2.2 and then 1.2.840.113554.1.2.2. + */ rc2 = spnegoIsMechTypeAvailable (hSpnegoToken, spnego_mech_oid_Kerberos_V5_Legacy, &pindex); if (rc2 != SPNEGO_E_SUCCESS || - pindex != 0) - { + pindex != 0) { rc2 = spnegoIsMechTypeAvailable (hSpnegoToken, spnego_mech_oid_Kerberos_V5, &pindex); if (rc2 != SPNEGO_E_SUCCESS || - pindex != 0) - { + pindex != 0) { rc1 = abs(rc2)+400; goto cleanup; } @@ -200,8 +190,7 @@ int parseNegTokenInit (const unsigned char * negTokenInit, rc2 = spnegoGetContextFlags (hSpnegoToken, &reqFlags); - if (rc2 == SPNEGO_E_SUCCESS) - { + if (rc2 == SPNEGO_E_SUCCESS) { rc1 = abs(rc2)+500; goto cleanup; } @@ -212,16 +201,14 @@ int parseNegTokenInit (const unsigned char * negTokenInit, NULL, (unsigned long*) kerberosTokenLength); - if (rc2 != SPNEGO_E_BUFFER_TOO_SMALL) - { + if (rc2 != SPNEGO_E_BUFFER_TOO_SMALL) { rc1 = abs(rc2)+600; goto cleanup; } *kerberosToken = malloc (*kerberosTokenLength); - if (!*kerberosToken) - { + if (!*kerberosToken) { rc1 = abs(rc2)+700; goto cleanup; } @@ -232,8 +219,7 @@ int parseNegTokenInit (const unsigned char * negTokenInit, (unsigned char *) *kerberosToken, (unsigned long*) kerberosTokenLength); - if (rc2 != SPNEGO_E_SUCCESS) - { + if (rc2 != SPNEGO_E_SUCCESS) { rc1 = abs(rc2)+800; goto error; } @@ -246,8 +232,7 @@ int parseNegTokenInit (const unsigned char * negTokenInit, error: - if (*kerberosToken) - { + if (*kerberosToken) { free ((unsigned char *) *kerberosToken); *kerberosToken = NULL; *kerberosTokenLength = 0; diff --git a/helpers/negotiate_auth/squid_kerb_auth/spnegohelp/spnegohelp.h b/helpers/negotiate_auth/squid_kerb_auth/spnegohelp/spnegohelp.h index 5bcbabea64..35030fcd71 100644 --- a/helpers/negotiate_auth/squid_kerb_auth/spnegohelp/spnegohelp.h +++ b/helpers/negotiate_auth/squid_kerb_auth/spnegohelp/spnegohelp.h @@ -8,51 +8,53 @@ */ #ifndef SPNEGOHELP_H -#define SPNEGOHELP_H + #define SPNEGOHELP_H #ifdef __cplusplus -extern "C" { + extern "C" +{ #endif - + #include -/* ----------------------------------------------------------------------------- - * makeNegTokenTarg makes an RFC 2478 SPNEGO NegTokenTarg (token) from an - * RFC 1964 Kerberos GSS-API token. - * - * If makeNegTokenTarg is successful, call free (*negTokenTarg) to free the - * memory allocated by parseNegTokenInit. - * - * Returns 0 if successful, 1 otherwise. - * ----------------------------------------------------------------------------- - */ - -int makeNegTokenTarg (const unsigned char * kerberosToken, - size_t kerberosTokenLength, - const unsigned char ** negTokenTarg, - size_t * negTokenTargLength); - -/* ----------------------------------------------------------------------------- - * parseNegTokenInit parses an RFC 2478 SPNEGO NegTokenInit (token) to extract - * an RFC 1964 Kerberos GSS-API token. - * - * If the NegTokenInit does cotain a Kerberos GSS-API token, parseNegTokenInit - * returns an error. - * - * If parseNegTokenInit is successful, call free (*kerberosToken) to - * free the memory allocated by parseNegTokenInit. - * - * Returns 0 if successful, 1 otherwise. - * ----------------------------------------------------------------------------- - */ - -int parseNegTokenInit (const unsigned char * negTokenInit, - size_t negTokenInitLength, - const unsigned char ** kerberosToken, - size_t * kerberosTokenLength); + /* ----------------------------------------------------------------------------- + * makeNegTokenTarg makes an RFC 2478 SPNEGO NegTokenTarg (token) from an + * RFC 1964 Kerberos GSS-API token. + * + * If makeNegTokenTarg is successful, call free (*negTokenTarg) to free the + * memory allocated by parseNegTokenInit. + * + * Returns 0 if successful, 1 otherwise. + * ----------------------------------------------------------------------------- + */ + + int makeNegTokenTarg (const unsigned char * kerberosToken, + size_t kerberosTokenLength, + const unsigned char ** negTokenTarg, + size_t * negTokenTargLength); + + /* ----------------------------------------------------------------------------- + * parseNegTokenInit parses an RFC 2478 SPNEGO NegTokenInit (token) to extract + * an RFC 1964 Kerberos GSS-API token. + * + * If the NegTokenInit does cotain a Kerberos GSS-API token, parseNegTokenInit + * returns an error. + * + * If parseNegTokenInit is successful, call free (*kerberosToken) to + * free the memory allocated by parseNegTokenInit. + * + * Returns 0 if successful, 1 otherwise. + * ----------------------------------------------------------------------------- + */ + + int parseNegTokenInit (const unsigned char * negTokenInit, + size_t negTokenInitLength, + const unsigned char ** kerberosToken, + size_t * kerberosTokenLength); #ifdef __cplusplus -} + } #endif - + #endif /* SPNEGOHELP_H */ + \ No newline at end of file diff --git a/helpers/negotiate_auth/squid_kerb_auth/spnegohelp/spnegoparse.c b/helpers/negotiate_auth/squid_kerb_auth/spnegohelp/spnegoparse.c index e300af5be6..785b225b94 100644 --- a/helpers/negotiate_auth/squid_kerb_auth/spnegohelp/spnegoparse.c +++ b/helpers/negotiate_auth/squid_kerb_auth/spnegohelp/spnegoparse.c @@ -75,128 +75,117 @@ extern MECH_OID g_stcMechOIDList []; //////////////////////////////////////////////////////////////////////////// int CalculateMinSpnegoInitTokenSize( long nMechTokenLength, - long nMechListMICLength, SPNEGO_MECH_OID mechOid, - int nReqFlagsAvailable, long* pnTokenSize, - long* pnInternalTokenLength ) + long nMechListMICLength, SPNEGO_MECH_OID mechOid, + int nReqFlagsAvailable, long* pnTokenSize, + long* pnInternalTokenLength ) { - int nReturn = SPNEGO_E_INVALID_LENGTH; + int nReturn = SPNEGO_E_INVALID_LENGTH; - // Start at 0. - long nTotalLength = 0; - long nTempLength= 0L; + // Start at 0. + long nTotalLength = 0; + long nTempLength= 0L; - // We will calculate this by walking the token backwards + // We will calculate this by walking the token backwards - // Start with MIC Element - if ( nMechListMICLength > 0L ) - { - nTempLength = ASNDerCalcElementLength( nMechListMICLength, NULL ); + // Start with MIC Element + if ( nMechListMICLength > 0L ) { + nTempLength = ASNDerCalcElementLength( nMechListMICLength, NULL ); - // Check for rollover error - if ( nTempLength < nMechListMICLength ) - { - goto xEndTokenInitLength; - } + // Check for rollover error + if ( nTempLength < nMechListMICLength ) { + goto xEndTokenInitLength; + } - nTotalLength += nTempLength; - } + nTotalLength += nTempLength; + } - // Next is the MechToken - if ( nMechTokenLength > 0L ) - { - nTempLength += ASNDerCalcElementLength( nMechTokenLength, NULL ); + // Next is the MechToken + if ( nMechTokenLength > 0L ) { + nTempLength += ASNDerCalcElementLength( nMechTokenLength, NULL ); - // Check for rollover error - if ( nTempLength < nTotalLength ) - { - goto xEndTokenInitLength; - } + // Check for rollover error + if ( nTempLength < nTotalLength ) { + goto xEndTokenInitLength; + } - nTotalLength = nTempLength; - } + nTotalLength = nTempLength; + } - // Next is the ReqFlags - if ( nReqFlagsAvailable ) - { - nTempLength += ASNDerCalcElementLength( SPNEGO_NEGINIT_MAXLEN_REQFLAGS, NULL ); + // Next is the ReqFlags + if ( nReqFlagsAvailable ) { + nTempLength += ASNDerCalcElementLength( SPNEGO_NEGINIT_MAXLEN_REQFLAGS, NULL ); - // Check for rollover error - if ( nTempLength < nTotalLength ) - { - goto xEndTokenInitLength; - } + // Check for rollover error + if ( nTempLength < nTotalLength ) { + goto xEndTokenInitLength; + } - nTotalLength = nTempLength; - } + nTotalLength = nTempLength; + } - // Next is the MechList - This is REQUIRED - nTempLength += ASNDerCalcMechListLength( mechOid, NULL ); + // Next is the MechList - This is REQUIRED + nTempLength += ASNDerCalcMechListLength( mechOid, NULL ); - // Check for rollover error - if ( nTempLength < nTotalLength ) - { - goto xEndTokenInitLength; - } + // Check for rollover error + if ( nTempLength < nTotalLength ) { + goto xEndTokenInitLength; + } - nTotalLength = nTempLength; + nTotalLength = nTempLength; - // Following four fields are the basic header tokens + // Following four fields are the basic header tokens - // Sequence Token - nTempLength += ASNDerCalcTokenLength( nTotalLength, 0L ); + // Sequence Token + nTempLength += ASNDerCalcTokenLength( nTotalLength, 0L ); - // Check for rollover error - if ( nTempLength < nTotalLength ) - { - goto xEndTokenInitLength; - } + // Check for rollover error + if ( nTempLength < nTotalLength ) { + goto xEndTokenInitLength; + } - nTotalLength = nTempLength; + nTotalLength = nTempLength; - // Neg Token Identifier Token - nTempLength += ASNDerCalcTokenLength( nTotalLength, 0L ); + // Neg Token Identifier Token + nTempLength += ASNDerCalcTokenLength( nTotalLength, 0L ); - // Check for rollover error - if ( nTempLength < nTotalLength ) - { - goto xEndTokenInitLength; - } + // Check for rollover error + if ( nTempLength < nTotalLength ) { + goto xEndTokenInitLength; + } - nTotalLength = nTempLength; + nTotalLength = nTempLength; - // SPNEGO OID Token - nTempLength += g_stcMechOIDList[spnego_mech_oid_Spnego].iLen; + // SPNEGO OID Token + nTempLength += g_stcMechOIDList[spnego_mech_oid_Spnego].iLen; - // Check for rollover error - if ( nTempLength < nTotalLength ) - { - goto xEndTokenInitLength; - } + // Check for rollover error + if ( nTempLength < nTotalLength ) { + goto xEndTokenInitLength; + } - nTotalLength = nTempLength; + nTotalLength = nTempLength; - // App Constructed Token - nTempLength += ASNDerCalcTokenLength( nTotalLength, 0L ); + // App Constructed Token + nTempLength += ASNDerCalcTokenLength( nTotalLength, 0L ); - // Check for rollover error - if ( nTempLength < nTotalLength ) - { - goto xEndTokenInitLength; - } + // Check for rollover error + if ( nTempLength < nTotalLength ) { + goto xEndTokenInitLength; + } - // The internal length doesn't include the number of bytes - // for the initial token - *pnInternalTokenLength = nTotalLength; - nTotalLength = nTempLength; + // The internal length doesn't include the number of bytes + // for the initial token + *pnInternalTokenLength = nTotalLength; + nTotalLength = nTempLength; - // We're done - *pnTokenSize = nTotalLength; - nReturn = SPNEGO_E_SUCCESS; + // We're done + *pnTokenSize = nTotalLength; + nReturn = SPNEGO_E_SUCCESS; xEndTokenInitLength: - LOG(("CalculateMinSpnegoInitTokenSize returned %d\n",nReturn)); - return nReturn; + LOG(("CalculateMinSpnegoInitTokenSize returned %d\n",nReturn)); + return nReturn; } @@ -231,201 +220,190 @@ xEndTokenInitLength: //////////////////////////////////////////////////////////////////////////// int CreateSpnegoInitToken( SPNEGO_MECH_OID MechType, - unsigned char ucContextFlags, unsigned char* pbMechToken, - unsigned long ulMechTokenLen, unsigned char* pbMechListMIC, - unsigned long ulMechListMICLen, unsigned char* pbTokenData, - long nTokenLength, long nInternalTokenLength ) + unsigned char ucContextFlags, unsigned char* pbMechToken, + unsigned long ulMechTokenLen, unsigned char* pbMechListMIC, + unsigned long ulMechListMICLen, unsigned char* pbTokenData, + long nTokenLength, long nInternalTokenLength ) { - int nReturn = SPNEGO_E_INVALID_LENGTH; + int nReturn = SPNEGO_E_INVALID_LENGTH; - // Start at 0. - long nTempLength= 0L; - long nTotalBytesWritten = 0L; - long nInternalLength = 0L; + // Start at 0. + long nTempLength= 0L; + long nTotalBytesWritten = 0L; + long nInternalLength = 0L; - unsigned char* pbWriteTokenData = pbTokenData + nTokenLength; + unsigned char* pbWriteTokenData = pbTokenData + nTokenLength; - // Temporary buffer to hold the REQ Flags as BIT String Data - unsigned char abTempReqFlags[SPNEGO_NEGINIT_MAXLEN_REQFLAGS]; + // Temporary buffer to hold the REQ Flags as BIT String Data + unsigned char abTempReqFlags[SPNEGO_NEGINIT_MAXLEN_REQFLAGS]; - // We will write the token out backwards to properly handle the cases - // where the length bytes become adjustable + // We will write the token out backwards to properly handle the cases + // where the length bytes become adjustable - // Start with MIC Element - if ( ulMechListMICLen > 0L ) - { - nTempLength = ASNDerCalcElementLength( ulMechListMICLen, &nInternalLength ); + // Start with MIC Element + if ( ulMechListMICLen > 0L ) { + nTempLength = ASNDerCalcElementLength( ulMechListMICLen, &nInternalLength ); - // Decrease the pbWriteTokenData, now we know the length and - // write it out. + // Decrease the pbWriteTokenData, now we know the length and + // write it out. - pbWriteTokenData -= nTempLength; - nTempLength = ASNDerWriteElement( pbWriteTokenData, SPNEGO_NEGINIT_ELEMENT_MECHLISTMIC, - OCTETSTRING, pbMechListMIC, ulMechListMICLen ); + pbWriteTokenData -= nTempLength; + nTempLength = ASNDerWriteElement( pbWriteTokenData, SPNEGO_NEGINIT_ELEMENT_MECHLISTMIC, + OCTETSTRING, pbMechListMIC, ulMechListMICLen ); - // Adjust Values and sanity check - nTotalBytesWritten += nTempLength; - nInternalTokenLength -= nTempLength; + // Adjust Values and sanity check + nTotalBytesWritten += nTempLength; + nInternalTokenLength -= nTempLength; - if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 ) - { - goto xEndWriteNegTokenInit; - } + if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 ) { + goto xEndWriteNegTokenInit; + } - } // IF MechListMIC is present + } // IF MechListMIC is present - // Next is the MechToken - if ( ulMechTokenLen > 0L ) - { - nTempLength = ASNDerCalcElementLength( ulMechTokenLen, &nInternalLength ); + // Next is the MechToken + if ( ulMechTokenLen > 0L ) { + nTempLength = ASNDerCalcElementLength( ulMechTokenLen, &nInternalLength ); - // Decrease the pbWriteTokenData, now we know the length and - // write it out. - pbWriteTokenData -= nTempLength; - nTempLength = ASNDerWriteElement( pbWriteTokenData, SPNEGO_NEGINIT_ELEMENT_MECHTOKEN, - OCTETSTRING, pbMechToken, ulMechTokenLen ); - // Adjust Values and sanity check - nTotalBytesWritten += nTempLength; - nInternalTokenLength -= nTempLength; + // Decrease the pbWriteTokenData, now we know the length and + // write it out. + pbWriteTokenData -= nTempLength; + nTempLength = ASNDerWriteElement( pbWriteTokenData, SPNEGO_NEGINIT_ELEMENT_MECHTOKEN, + OCTETSTRING, pbMechToken, ulMechTokenLen ); + // Adjust Values and sanity check + nTotalBytesWritten += nTempLength; + nInternalTokenLength -= nTempLength; - if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 ) - { - goto xEndWriteNegTokenInit; - } - - } // IF MechToken Length is present + if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 ) { + goto xEndWriteNegTokenInit; + } - // Next is the ReqFlags - if ( ucContextFlags > 0L ) - { + } // IF MechToken Length is present - nTempLength = ASNDerCalcElementLength( SPNEGO_NEGINIT_MAXLEN_REQFLAGS, &nInternalLength ); + // Next is the ReqFlags + if ( ucContextFlags > 0L ) { - // We need a byte that indicates how many bits difference between the number - // of bits used in final octet (we only have one) and the max (8) + nTempLength = ASNDerCalcElementLength( SPNEGO_NEGINIT_MAXLEN_REQFLAGS, &nInternalLength ); - abTempReqFlags[0] = SPNEGO_NEGINIT_REQFLAGS_BITDIFF; - abTempReqFlags[1] = ucContextFlags; + // We need a byte that indicates how many bits difference between the number + // of bits used in final octet (we only have one) and the max (8) - // Decrease the pbWriteTokenData, now we know the length and - // write it out. - pbWriteTokenData -= nTempLength; - nTempLength = ASNDerWriteElement( pbWriteTokenData, SPNEGO_NEGINIT_ELEMENT_REQFLAGS, - BITSTRING, abTempReqFlags, SPNEGO_NEGINIT_MAXLEN_REQFLAGS ); + abTempReqFlags[0] = SPNEGO_NEGINIT_REQFLAGS_BITDIFF; + abTempReqFlags[1] = ucContextFlags; - // Adjust Values and sanity check - nTotalBytesWritten += nTempLength; - nInternalTokenLength -= nTempLength; + // Decrease the pbWriteTokenData, now we know the length and + // write it out. + pbWriteTokenData -= nTempLength; + nTempLength = ASNDerWriteElement( pbWriteTokenData, SPNEGO_NEGINIT_ELEMENT_REQFLAGS, + BITSTRING, abTempReqFlags, SPNEGO_NEGINIT_MAXLEN_REQFLAGS ); - if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 ) - { - goto xEndWriteNegTokenInit; - } + // Adjust Values and sanity check + nTotalBytesWritten += nTempLength; + nInternalTokenLength -= nTempLength; - } // IF ContextFlags + if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 ) { + goto xEndWriteNegTokenInit; + } - // Next is the MechList - This is REQUIRED - nTempLength = ASNDerCalcMechListLength( MechType, &nInternalLength ); + } // IF ContextFlags - // Decrease the pbWriteTokenData, now we know the length and - // write it out. - pbWriteTokenData -= nTempLength; - nTempLength = ASNDerWriteMechList( pbWriteTokenData, MechType ); + // Next is the MechList - This is REQUIRED + nTempLength = ASNDerCalcMechListLength( MechType, &nInternalLength ); - // Adjust Values and sanity check - nTotalBytesWritten += nTempLength; - nInternalTokenLength -= nTempLength; + // Decrease the pbWriteTokenData, now we know the length and + // write it out. + pbWriteTokenData -= nTempLength; + nTempLength = ASNDerWriteMechList( pbWriteTokenData, MechType ); - if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 ) - { - goto xEndWriteNegTokenInit; - } + // Adjust Values and sanity check + nTotalBytesWritten += nTempLength; + nInternalTokenLength -= nTempLength; - // The next tokens we're writing out reflect the total number of bytes - // we have actually written out. + if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 ) { + goto xEndWriteNegTokenInit; + } - // Sequence Token - nTempLength = ASNDerCalcTokenLength( nTotalBytesWritten, 0L ); + // The next tokens we're writing out reflect the total number of bytes + // we have actually written out. - // Decrease the pbWriteTokenData, now we know the length and - // write it out. - pbWriteTokenData -= nTempLength; - nTempLength = ASNDerWriteToken( pbWriteTokenData, SPNEGO_CONSTRUCTED_SEQUENCE, + // Sequence Token + nTempLength = ASNDerCalcTokenLength( nTotalBytesWritten, 0L ); + + // Decrease the pbWriteTokenData, now we know the length and + // write it out. + pbWriteTokenData -= nTempLength; + nTempLength = ASNDerWriteToken( pbWriteTokenData, SPNEGO_CONSTRUCTED_SEQUENCE, NULL, nTotalBytesWritten ); - // Adjust Values and sanity check - nTotalBytesWritten += nTempLength; - nInternalTokenLength -= nTempLength; + // Adjust Values and sanity check + nTotalBytesWritten += nTempLength; + nInternalTokenLength -= nTempLength; - if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 ) - { - goto xEndWriteNegTokenInit; - } + if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 ) { + goto xEndWriteNegTokenInit; + } - // Neg Init Token Identifier Token - nTempLength = ASNDerCalcTokenLength( nTotalBytesWritten, 0L ); + // Neg Init Token Identifier Token + nTempLength = ASNDerCalcTokenLength( nTotalBytesWritten, 0L ); - // Decrease the pbWriteTokenData, now we know the length and - // write it out. - pbWriteTokenData -= nTempLength; - nTempLength = ASNDerWriteToken( pbWriteTokenData, SPNEGO_NEGINIT_TOKEN_IDENTIFIER, + // Decrease the pbWriteTokenData, now we know the length and + // write it out. + pbWriteTokenData -= nTempLength; + nTempLength = ASNDerWriteToken( pbWriteTokenData, SPNEGO_NEGINIT_TOKEN_IDENTIFIER, NULL, nTotalBytesWritten ); - // Adjust Values and sanity check - nTotalBytesWritten += nTempLength; - nInternalTokenLength -= nTempLength; - - if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 ) - { - goto xEndWriteNegTokenInit; - } - - // SPNEGO OID Token - nTempLength = g_stcMechOIDList[spnego_mech_oid_Spnego].iLen; - - // Decrease the pbWriteTokenData, now we know the length and - // write it out. - pbWriteTokenData -= nTempLength; - nTempLength = ASNDerWriteOID( pbWriteTokenData, spnego_mech_oid_Spnego ); - - // Adjust Values and sanity check - nTotalBytesWritten += nTempLength; - nInternalTokenLength -= nTempLength; - - if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 ) - { - goto xEndWriteNegTokenInit; - } - - // App Constructed Token - nTempLength = ASNDerCalcTokenLength( nTotalBytesWritten, 0L ); - - // Decrease the pbWriteTokenData, now we know the length and - // write it out. - pbWriteTokenData -= nTempLength; - nTempLength = ASNDerWriteToken( pbWriteTokenData, SPNEGO_NEGINIT_APP_CONSTRUCT, + // Adjust Values and sanity check + nTotalBytesWritten += nTempLength; + nInternalTokenLength -= nTempLength; + + if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 ) { + goto xEndWriteNegTokenInit; + } + + // SPNEGO OID Token + nTempLength = g_stcMechOIDList[spnego_mech_oid_Spnego].iLen; + + // Decrease the pbWriteTokenData, now we know the length and + // write it out. + pbWriteTokenData -= nTempLength; + nTempLength = ASNDerWriteOID( pbWriteTokenData, spnego_mech_oid_Spnego ); + + // Adjust Values and sanity check + nTotalBytesWritten += nTempLength; + nInternalTokenLength -= nTempLength; + + if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 ) { + goto xEndWriteNegTokenInit; + } + + // App Constructed Token + nTempLength = ASNDerCalcTokenLength( nTotalBytesWritten, 0L ); + + // Decrease the pbWriteTokenData, now we know the length and + // write it out. + pbWriteTokenData -= nTempLength; + nTempLength = ASNDerWriteToken( pbWriteTokenData, SPNEGO_NEGINIT_APP_CONSTRUCT, NULL, nTotalBytesWritten ); - // Adjust Values and sanity check - nTotalBytesWritten += nTempLength; + // Adjust Values and sanity check + nTotalBytesWritten += nTempLength; - // Don't adjust the internal token length here, it doesn't account - // the initial bytes written out (we really don't need to keep - // a running count here, but for debugging, it helps to be able - // to see the total number of bytes written out as well as the - // number of bytes left to write). + // Don't adjust the internal token length here, it doesn't account + // the initial bytes written out (we really don't need to keep + // a running count here, but for debugging, it helps to be able + // to see the total number of bytes written out as well as the + // number of bytes left to write). - if ( nTotalBytesWritten == nTokenLength && nInternalTokenLength == 0 && - pbWriteTokenData == pbTokenData ) - { - nReturn = SPNEGO_E_SUCCESS; - } + if ( nTotalBytesWritten == nTokenLength && nInternalTokenLength == 0 && + pbWriteTokenData == pbTokenData ) { + nReturn = SPNEGO_E_SUCCESS; + } xEndWriteNegTokenInit: - LOG(("CreateSpnegoInitToken returned %d\n",nReturn)); - return nReturn; + LOG(("CreateSpnegoInitToken returned %d\n",nReturn)); + return nReturn; } @@ -458,114 +436,104 @@ xEndWriteNegTokenInit: //////////////////////////////////////////////////////////////////////////// int CalculateMinSpnegoTargTokenSize( SPNEGO_MECH_OID MechType, - SPNEGO_NEGRESULT spnegoNegResult, long nMechTokenLen, - long nMechListMICLen, long* pnTokenSize, - long* pnInternalTokenLength ) + SPNEGO_NEGRESULT spnegoNegResult, long nMechTokenLen, + long nMechListMICLen, long* pnTokenSize, + long* pnInternalTokenLength ) { - int nReturn = SPNEGO_E_INVALID_LENGTH; + int nReturn = SPNEGO_E_INVALID_LENGTH; - // Start at 0. - long nTotalLength = 0; - long nTempLength= 0L; + // Start at 0. + long nTotalLength = 0; + long nTempLength= 0L; - // We will calculate this by walking the token backwards + // We will calculate this by walking the token backwards - // Start with MIC Element - if ( nMechListMICLen > 0L ) - { - nTempLength = ASNDerCalcElementLength( nMechListMICLen, NULL ); + // Start with MIC Element + if ( nMechListMICLen > 0L ) { + nTempLength = ASNDerCalcElementLength( nMechListMICLen, NULL ); - // Check for rollover error - if ( nTempLength < nMechListMICLen ) - { - goto xEndTokenTargLength; - } + // Check for rollover error + if ( nTempLength < nMechListMICLen ) { + goto xEndTokenTargLength; + } - nTotalLength += nTempLength; - } + nTotalLength += nTempLength; + } - // Next is the MechToken - if ( nMechTokenLen > 0L ) - { - nTempLength += ASNDerCalcElementLength( nMechTokenLen, NULL ); + // Next is the MechToken + if ( nMechTokenLen > 0L ) { + nTempLength += ASNDerCalcElementLength( nMechTokenLen, NULL ); - // Check for rollover error - if ( nTempLength < nTotalLength ) - { - goto xEndTokenTargLength; - } + // Check for rollover error + if ( nTempLength < nTotalLength ) { + goto xEndTokenTargLength; + } - nTotalLength = nTempLength; - } + nTotalLength = nTempLength; + } - // Supported MechType - if ( spnego_mech_oid_NotUsed != MechType ) - { - // Supported MechOID element - we use the token function since - // we already know the size of the OID token and value - nTempLength += ASNDerCalcElementLength( g_stcMechOIDList[MechType].iActualDataLen, - NULL ); + // Supported MechType + if ( spnego_mech_oid_NotUsed != MechType ) { + // Supported MechOID element - we use the token function since + // we already know the size of the OID token and value + nTempLength += ASNDerCalcElementLength( g_stcMechOIDList[MechType].iActualDataLen, + NULL ); - // Check for rollover error - if ( nTempLength < nTotalLength ) - { - goto xEndTokenTargLength; - } + // Check for rollover error + if ( nTempLength < nTotalLength ) { + goto xEndTokenTargLength; + } - nTotalLength = nTempLength; + nTotalLength = nTempLength; - } // IF MechType is available + } // IF MechType is available - // NegResult Element - if ( spnego_negresult_NotUsed != spnegoNegResult ) - { - nTempLength += ASNDerCalcElementLength( SPNEGO_NEGTARG_MAXLEN_NEGRESULT, NULL ); + // NegResult Element + if ( spnego_negresult_NotUsed != spnegoNegResult ) { + nTempLength += ASNDerCalcElementLength( SPNEGO_NEGTARG_MAXLEN_NEGRESULT, NULL ); - // Check for rollover error - if ( nTempLength < nTotalLength ) - { - goto xEndTokenTargLength; - } + // Check for rollover error + if ( nTempLength < nTotalLength ) { + goto xEndTokenTargLength; + } - nTotalLength = nTempLength; + nTotalLength = nTempLength; - } // IF negResult is available + } // IF negResult is available - // Following two fields are the basic header tokens + // Following two fields are the basic header tokens - // Sequence Token - nTempLength += ASNDerCalcTokenLength( nTotalLength, 0L ); + // Sequence Token + nTempLength += ASNDerCalcTokenLength( nTotalLength, 0L ); - // Check for rollover error - if ( nTempLength < nTotalLength ) - { - goto xEndTokenTargLength; - } + // Check for rollover error + if ( nTempLength < nTotalLength ) { + goto xEndTokenTargLength; + } - nTotalLength = nTempLength; + nTotalLength = nTempLength; - // Neg Token Identifier Token - nTempLength += ASNDerCalcTokenLength( nTotalLength, 0L ); + // Neg Token Identifier Token + nTempLength += ASNDerCalcTokenLength( nTotalLength, 0L ); - // Check for rollover error - if ( nTempLength < nTotalLength ) - { - goto xEndTokenTargLength; - } + // Check for rollover error + if ( nTempLength < nTotalLength ) { + goto xEndTokenTargLength; + } - // The internal length doesn't include the number of bytes - // for the initial token - *pnInternalTokenLength = nTotalLength; - nTotalLength = nTempLength; + // The internal length doesn't include the number of bytes + // for the initial token + *pnInternalTokenLength = nTotalLength; + nTotalLength = nTempLength; - // We're done - *pnTokenSize = nTotalLength; - nReturn = SPNEGO_E_SUCCESS; + // We're done + *pnTokenSize = nTotalLength; + nReturn = SPNEGO_E_SUCCESS; xEndTokenTargLength: - LOG(("CalculateMinSpnegoTargTokenSize returned %d\n",nReturn)); - return nReturn; + LOG(("CalculateMinSpnegoTargTokenSize returned %d\n",nReturn)); + return nReturn; } @@ -600,171 +568,161 @@ xEndTokenTargLength: //////////////////////////////////////////////////////////////////////////// int CreateSpnegoTargToken( SPNEGO_MECH_OID MechType, - SPNEGO_NEGRESULT eNegResult, unsigned char* pbMechToken, - unsigned long ulMechTokenLen, unsigned char* pbMechListMIC, - unsigned long ulMechListMICLen, unsigned char* pbTokenData, - long nTokenLength, long nInternalTokenLength ) + SPNEGO_NEGRESULT eNegResult, unsigned char* pbMechToken, + unsigned long ulMechTokenLen, unsigned char* pbMechListMIC, + unsigned long ulMechListMICLen, unsigned char* pbTokenData, + long nTokenLength, long nInternalTokenLength ) { - int nReturn = SPNEGO_E_INVALID_LENGTH; - - // Start at 0. - long nTempLength= 0L; - long nTotalBytesWritten = 0L; - long nInternalLength = 0L; - - unsigned char ucTemp = 0; - - // We will write the token out backwards to properly handle the cases - // where the length bytes become adjustable, so the write location - // is initialized to point *just* past the end of the buffer. + int nReturn = SPNEGO_E_INVALID_LENGTH; + + // Start at 0. + long nTempLength= 0L; + long nTotalBytesWritten = 0L; + long nInternalLength = 0L; + + unsigned char ucTemp = 0; + + // We will write the token out backwards to properly handle the cases + // where the length bytes become adjustable, so the write location + // is initialized to point *just* past the end of the buffer. + + unsigned char* pbWriteTokenData = pbTokenData + nTokenLength; + + + // Start with MIC Element + if ( ulMechListMICLen > 0L ) { + nTempLength = ASNDerCalcElementLength( ulMechListMICLen, &nInternalLength ); + + // Decrease the pbWriteTokenData, now we know the length and + // write it out. + + pbWriteTokenData -= nTempLength; + nTempLength = ASNDerWriteElement( pbWriteTokenData, SPNEGO_NEGTARG_ELEMENT_MECHLISTMIC, + OCTETSTRING, pbMechListMIC, ulMechListMICLen ); + + // Adjust Values and sanity check + nTotalBytesWritten += nTempLength; + nInternalTokenLength -= nTempLength; + + if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 ) { + goto xEndWriteNegTokenTarg; + } + + } // IF MechListMIC is present + + // Next is the MechToken + if ( ulMechTokenLen > 0L ) { + nTempLength = ASNDerCalcElementLength( ulMechTokenLen, &nInternalLength ); + + // Decrease the pbWriteTokenData, now we know the length and + // write it out. + pbWriteTokenData -= nTempLength; + nTempLength = ASNDerWriteElement( pbWriteTokenData, SPNEGO_NEGTARG_ELEMENT_RESPONSETOKEN, + OCTETSTRING, pbMechToken, ulMechTokenLen ); + // Adjust Values and sanity check + nTotalBytesWritten += nTempLength; + nInternalTokenLength -= nTempLength; + + if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 ) { + goto xEndWriteNegTokenTarg; + } - unsigned char* pbWriteTokenData = pbTokenData + nTokenLength; + } // IF MechToken Length is present + // Supported Mech Type + if ( spnego_mech_oid_NotUsed != MechType ) { - // Start with MIC Element - if ( ulMechListMICLen > 0L ) - { - nTempLength = ASNDerCalcElementLength( ulMechListMICLen, &nInternalLength ); - - // Decrease the pbWriteTokenData, now we know the length and - // write it out. - - pbWriteTokenData -= nTempLength; - nTempLength = ASNDerWriteElement( pbWriteTokenData, SPNEGO_NEGTARG_ELEMENT_MECHLISTMIC, - OCTETSTRING, pbMechListMIC, ulMechListMICLen ); - - // Adjust Values and sanity check - nTotalBytesWritten += nTempLength; - nInternalTokenLength -= nTempLength; - - if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 ) - { - goto xEndWriteNegTokenTarg; - } - - } // IF MechListMIC is present - - // Next is the MechToken - if ( ulMechTokenLen > 0L ) - { - nTempLength = ASNDerCalcElementLength( ulMechTokenLen, &nInternalLength ); - - // Decrease the pbWriteTokenData, now we know the length and - // write it out. - pbWriteTokenData -= nTempLength; - nTempLength = ASNDerWriteElement( pbWriteTokenData, SPNEGO_NEGTARG_ELEMENT_RESPONSETOKEN, - OCTETSTRING, pbMechToken, ulMechTokenLen ); - // Adjust Values and sanity check - nTotalBytesWritten += nTempLength; - nInternalTokenLength -= nTempLength; - - if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 ) - { - goto xEndWriteNegTokenTarg; - } - - } // IF MechToken Length is present - - // Supported Mech Type - if ( spnego_mech_oid_NotUsed != MechType ) - { - - nTempLength = ASNDerCalcElementLength( g_stcMechOIDList[MechType].iActualDataLen, - &nInternalLength ); - - // Decrease the pbWriteTokenData, now we know the length and - // write it out. - pbWriteTokenData -= nTempLength; - nTempLength = ASNDerWriteToken( pbWriteTokenData, SPNEGO_NEGTARG_ELEMENT_SUPPORTEDMECH, - g_stcMechOIDList[MechType].ucOid, - g_stcMechOIDList[MechType].iLen ); - - // Adjust Values and sanity check - nTotalBytesWritten += nTempLength; - nInternalTokenLength -= nTempLength; - - if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 ) - { - goto xEndWriteNegTokenTarg; - } - - } // IF MechType is present - - // Neg Result - // NegResult Element - if ( spnego_negresult_NotUsed != eNegResult ) - { - ucTemp = (unsigned char) eNegResult; - - nTempLength = ASNDerCalcElementLength( SPNEGO_NEGTARG_MAXLEN_NEGRESULT, &nInternalLength ); - - // Decrease the pbWriteTokenData, now we know the length and - // write it out. - pbWriteTokenData -= nTempLength; - nTempLength = ASNDerWriteElement( pbWriteTokenData, SPNEGO_NEGTARG_ELEMENT_NEGRESULT, - ENUMERATED, &ucTemp, SPNEGO_NEGTARG_MAXLEN_NEGRESULT ); - - // Adjust Values and sanity check - nTotalBytesWritten += nTempLength; - nInternalTokenLength -= nTempLength; - - if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 ) - { - goto xEndWriteNegTokenTarg; - } - - } // If eNegResult is available - - // The next tokens we're writing out reflect the total number of bytes - // we have actually written out. - - // Sequence Token - nTempLength = ASNDerCalcTokenLength( nTotalBytesWritten, 0L ); - - // Decrease the pbWriteTokenData, now we know the length and - // write it out. - pbWriteTokenData -= nTempLength; - nTempLength = ASNDerWriteToken( pbWriteTokenData, SPNEGO_CONSTRUCTED_SEQUENCE, + nTempLength = ASNDerCalcElementLength( g_stcMechOIDList[MechType].iActualDataLen, + &nInternalLength ); + + // Decrease the pbWriteTokenData, now we know the length and + // write it out. + pbWriteTokenData -= nTempLength; + nTempLength = ASNDerWriteToken( pbWriteTokenData, SPNEGO_NEGTARG_ELEMENT_SUPPORTEDMECH, + g_stcMechOIDList[MechType].ucOid, + g_stcMechOIDList[MechType].iLen ); + + // Adjust Values and sanity check + nTotalBytesWritten += nTempLength; + nInternalTokenLength -= nTempLength; + + if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 ) { + goto xEndWriteNegTokenTarg; + } + + } // IF MechType is present + + // Neg Result + // NegResult Element + if ( spnego_negresult_NotUsed != eNegResult ) { + ucTemp = (unsigned char) eNegResult; + + nTempLength = ASNDerCalcElementLength( SPNEGO_NEGTARG_MAXLEN_NEGRESULT, &nInternalLength ); + + // Decrease the pbWriteTokenData, now we know the length and + // write it out. + pbWriteTokenData -= nTempLength; + nTempLength = ASNDerWriteElement( pbWriteTokenData, SPNEGO_NEGTARG_ELEMENT_NEGRESULT, + ENUMERATED, &ucTemp, SPNEGO_NEGTARG_MAXLEN_NEGRESULT ); + + // Adjust Values and sanity check + nTotalBytesWritten += nTempLength; + nInternalTokenLength -= nTempLength; + + if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 ) { + goto xEndWriteNegTokenTarg; + } + + } // If eNegResult is available + + // The next tokens we're writing out reflect the total number of bytes + // we have actually written out. + + // Sequence Token + nTempLength = ASNDerCalcTokenLength( nTotalBytesWritten, 0L ); + + // Decrease the pbWriteTokenData, now we know the length and + // write it out. + pbWriteTokenData -= nTempLength; + nTempLength = ASNDerWriteToken( pbWriteTokenData, SPNEGO_CONSTRUCTED_SEQUENCE, NULL, nTotalBytesWritten ); - // Adjust Values and sanity check - nTotalBytesWritten += nTempLength; - nInternalTokenLength -= nTempLength; + // Adjust Values and sanity check + nTotalBytesWritten += nTempLength; + nInternalTokenLength -= nTempLength; - if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 ) - { - goto xEndWriteNegTokenTarg; - } + if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 ) { + goto xEndWriteNegTokenTarg; + } - // Neg Targ Token Identifier Token - nTempLength = ASNDerCalcTokenLength( nTotalBytesWritten, 0L ); + // Neg Targ Token Identifier Token + nTempLength = ASNDerCalcTokenLength( nTotalBytesWritten, 0L ); - // Decrease the pbWriteTokenData, now we know the length and - // write it out. - pbWriteTokenData -= nTempLength; - nTempLength = ASNDerWriteToken( pbWriteTokenData, SPNEGO_NEGTARG_TOKEN_IDENTIFIER, + // Decrease the pbWriteTokenData, now we know the length and + // write it out. + pbWriteTokenData -= nTempLength; + nTempLength = ASNDerWriteToken( pbWriteTokenData, SPNEGO_NEGTARG_TOKEN_IDENTIFIER, NULL, nTotalBytesWritten ); - // Adjust Values and sanity check - nTotalBytesWritten += nTempLength; + // Adjust Values and sanity check + nTotalBytesWritten += nTempLength; - // Don't adjust the internal token length here, it doesn't account - // the initial bytes written out (we really don't need to keep - // a running count here, but for debugging, it helps to be able - // to see the total number of bytes written out as well as the - // number of bytes left to write). + // Don't adjust the internal token length here, it doesn't account + // the initial bytes written out (we really don't need to keep + // a running count here, but for debugging, it helps to be able + // to see the total number of bytes written out as well as the + // number of bytes left to write). - if ( nTotalBytesWritten == nTokenLength && nInternalTokenLength == 0 && - pbWriteTokenData == pbTokenData ) - { - nReturn = SPNEGO_E_SUCCESS; - } + if ( nTotalBytesWritten == nTokenLength && nInternalTokenLength == 0 && + pbWriteTokenData == pbTokenData ) { + nReturn = SPNEGO_E_SUCCESS; + } xEndWriteNegTokenTarg: - LOG(("CreateSpnegoTargToken returned %d\n",nReturn)); - return nReturn; + LOG(("CreateSpnegoTargToken returned %d\n",nReturn)); + return nReturn; } @@ -794,60 +752,54 @@ xEndWriteNegTokenTarg: //////////////////////////////////////////////////////////////////////////// SPNEGO_TOKEN* AllocEmptySpnegoToken( unsigned char ucCopyData, unsigned long ulFlags, - unsigned char * pbTokenData, unsigned long ulTokenSize ) + unsigned char * pbTokenData, unsigned long ulTokenSize ) { - SPNEGO_TOKEN* pSpnegoToken = (SPNEGO_TOKEN*) calloc( 1, sizeof(SPNEGO_TOKEN) ); - - if ( NULL != pSpnegoToken ) - { - // Set the token size - pSpnegoToken->nStructSize = SPNEGO_TOKEN_SIZE; - - // Initialize the element array - InitSpnegoTokenElementArray( pSpnegoToken ); - - // Assign the flags value - pSpnegoToken->ulFlags = ulFlags; + SPNEGO_TOKEN* pSpnegoToken = (SPNEGO_TOKEN*) calloc( 1, sizeof(SPNEGO_TOKEN) ); + + if ( NULL != pSpnegoToken ) { + // Set the token size + pSpnegoToken->nStructSize = SPNEGO_TOKEN_SIZE; + + // Initialize the element array + InitSpnegoTokenElementArray( pSpnegoToken ); + + // Assign the flags value + pSpnegoToken->ulFlags = ulFlags; + + // + // IF ucCopyData is TRUE, we will allocate a buffer and copy data into it. + // Otherwise, we will just copy the pointer and the length. This is so we + // can cut out additional allocations for performance reasons + // + + if ( SPNEGO_TOKEN_INTERNAL_FLAGS_FREEDATA == ucCopyData ) { + // Alloc the internal buffer. Cleanup on failure. + pSpnegoToken->pbBinaryData = (unsigned char*) calloc( ulTokenSize, sizeof(unsigned char) ); + + if ( NULL != pSpnegoToken->pbBinaryData ) { + // We must ALWAYS free this buffer + pSpnegoToken->ulFlags |= SPNEGO_TOKEN_INTERNAL_FLAGS_FREEDATA; + + // Copy the data locally + memcpy( pSpnegoToken->pbBinaryData, pbTokenData, ulTokenSize ); + pSpnegoToken->ulBinaryDataLen = ulTokenSize; + } else { + free( pSpnegoToken ); + pSpnegoToken = NULL; + } - // - // IF ucCopyData is TRUE, we will allocate a buffer and copy data into it. - // Otherwise, we will just copy the pointer and the length. This is so we - // can cut out additional allocations for performance reasons - // + } // IF ucCopyData + else { + // Copy the pointer and the length directly - ulFlags will control whether or not + // we are allowed to free the value - if ( SPNEGO_TOKEN_INTERNAL_FLAGS_FREEDATA == ucCopyData ) - { - // Alloc the internal buffer. Cleanup on failure. - pSpnegoToken->pbBinaryData = (unsigned char*) calloc( ulTokenSize, sizeof(unsigned char) ); + pSpnegoToken->pbBinaryData = pbTokenData; + pSpnegoToken->ulBinaryDataLen = ulTokenSize; + } - if ( NULL != pSpnegoToken->pbBinaryData ) - { - // We must ALWAYS free this buffer - pSpnegoToken->ulFlags |= SPNEGO_TOKEN_INTERNAL_FLAGS_FREEDATA; + } - // Copy the data locally - memcpy( pSpnegoToken->pbBinaryData, pbTokenData, ulTokenSize ); - pSpnegoToken->ulBinaryDataLen = ulTokenSize; - } - else - { - free( pSpnegoToken ); - pSpnegoToken = NULL; - } - - } // IF ucCopyData - else - { - // Copy the pointer and the length directly - ulFlags will control whether or not - // we are allowed to free the value - - pSpnegoToken->pbBinaryData = pbTokenData; - pSpnegoToken->ulBinaryDataLen = ulTokenSize; - } - - } - - return pSpnegoToken; + return pSpnegoToken; } ///////////////////////////////////////////////////////////////////////////// @@ -869,19 +821,17 @@ SPNEGO_TOKEN* AllocEmptySpnegoToken( unsigned char ucCopyData, unsigned long ulF void FreeSpnegoToken( SPNEGO_TOKEN* pSpnegoToken ) { - if ( NULL != pSpnegoToken ) - { - - // Cleanup internal allocation per the flags - if ( pSpnegoToken->ulFlags & SPNEGO_TOKEN_INTERNAL_FLAGS_FREEDATA && - NULL != pSpnegoToken->pbBinaryData ) - { - free( pSpnegoToken->pbBinaryData ); - pSpnegoToken->pbBinaryData = NULL; - } - - free ( pSpnegoToken ); - } + if ( NULL != pSpnegoToken ) { + + // Cleanup internal allocation per the flags + if ( pSpnegoToken->ulFlags & SPNEGO_TOKEN_INTERNAL_FLAGS_FREEDATA && + NULL != pSpnegoToken->pbBinaryData ) { + free( pSpnegoToken->pbBinaryData ); + pSpnegoToken->pbBinaryData = NULL; + } + + free ( pSpnegoToken ); + } } ///////////////////////////////////////////////////////////////////////////// @@ -903,22 +853,21 @@ void FreeSpnegoToken( SPNEGO_TOKEN* pSpnegoToken ) void InitSpnegoTokenElementArray( SPNEGO_TOKEN* pSpnegoToken ) { - int nCtr; - - // Set the number of elemnts - pSpnegoToken->nNumElements = MAX_NUM_TOKEN_ELEMENTS; - - // - // Initially, all elements are unavailable - // - - for ( nCtr = 0; nCtr < MAX_NUM_TOKEN_ELEMENTS; nCtr++ ) - { - // Set the element size as well - pSpnegoToken->aElementArray[ nCtr ].nStructSize = SPNEGO_ELEMENT_SIZE; - pSpnegoToken->aElementArray[ nCtr ].iElementPresent = SPNEGO_TOKEN_ELEMENT_UNAVAILABLE; - } - + int nCtr; + + // Set the number of elemnts + pSpnegoToken->nNumElements = MAX_NUM_TOKEN_ELEMENTS; + + // + // Initially, all elements are unavailable + // + + for ( nCtr = 0; nCtr < MAX_NUM_TOKEN_ELEMENTS; nCtr++ ) { + // Set the element size as well + pSpnegoToken->aElementArray[ nCtr ].nStructSize = SPNEGO_ELEMENT_SIZE; + pSpnegoToken->aElementArray[ nCtr ].iElementPresent = SPNEGO_TOKEN_ELEMENT_UNAVAILABLE; + } + } ///////////////////////////////////////////////////////////////////////////// @@ -946,121 +895,112 @@ void InitSpnegoTokenElementArray( SPNEGO_TOKEN* pSpnegoToken ) //////////////////////////////////////////////////////////////////////////// int InitSpnegoTokenType( SPNEGO_TOKEN* pSpnegoToken, long* pnTokenLength, - long* pnRemainingTokenLength, unsigned char** ppbFirstElement ) + long* pnRemainingTokenLength, unsigned char** ppbFirstElement ) { - int nReturn = SPNEGO_E_INVALID_TOKEN; - long nActualTokenLength = 0L; - long nBoundaryLength = pSpnegoToken->ulBinaryDataLen; - unsigned char* pbTokenData = pSpnegoToken->pbBinaryData; - - // - // First byte MUST be either an APP_CONSTRUCT or the NEGTARG_TOKEN_TARG - // - - if ( SPNEGO_NEGINIT_APP_CONSTRUCT == *pbTokenData ) - { - // Validate the above token - this will tell us the actual length of the token - // per the encoding (minus the actual token bytes) - if ( ( nReturn = ASNDerCheckToken( pbTokenData, SPNEGO_NEGINIT_APP_CONSTRUCT, 0L, nBoundaryLength, - pnTokenLength, &nActualTokenLength ) ) - == SPNEGO_E_SUCCESS ) - { - // Initialize the remaining token length value. This will be used - // to tell the caller how much token there is left once we've parsed - // the header (they could calculate it from the other values, but this - // is a bit friendlier) - *pnRemainingTokenLength = *pnTokenLength; - - // Make adjustments to next token - pbTokenData += nActualTokenLength; - nBoundaryLength -= nActualTokenLength; - - // The next token should be an OID - if ( ( nReturn = ASNDerCheckOID( pbTokenData, spnego_mech_oid_Spnego, nBoundaryLength, - &nActualTokenLength ) ) == SPNEGO_E_SUCCESS ) - { + int nReturn = SPNEGO_E_INVALID_TOKEN; + long nActualTokenLength = 0L; + long nBoundaryLength = pSpnegoToken->ulBinaryDataLen; + unsigned char* pbTokenData = pSpnegoToken->pbBinaryData; + + // + // First byte MUST be either an APP_CONSTRUCT or the NEGTARG_TOKEN_TARG + // + + if ( SPNEGO_NEGINIT_APP_CONSTRUCT == *pbTokenData ) { + // Validate the above token - this will tell us the actual length of the token + // per the encoding (minus the actual token bytes) + if ( ( nReturn = ASNDerCheckToken( pbTokenData, SPNEGO_NEGINIT_APP_CONSTRUCT, 0L, nBoundaryLength, + pnTokenLength, &nActualTokenLength ) ) + == SPNEGO_E_SUCCESS ) { + // Initialize the remaining token length value. This will be used + // to tell the caller how much token there is left once we've parsed + // the header (they could calculate it from the other values, but this + // is a bit friendlier) + *pnRemainingTokenLength = *pnTokenLength; + // Make adjustments to next token pbTokenData += nActualTokenLength; nBoundaryLength -= nActualTokenLength; - *pnRemainingTokenLength -= nActualTokenLength; - - // The next token should specify the NegTokenInit - if ( ( nReturn = ASNDerCheckToken( pbTokenData, SPNEGO_NEGINIT_TOKEN_IDENTIFIER, - *pnRemainingTokenLength, nBoundaryLength, pnTokenLength, - &nActualTokenLength ) ) - == SPNEGO_E_SUCCESS ) - { - // Make adjustments to next token - pbTokenData += nActualTokenLength; - nBoundaryLength -= nActualTokenLength; - *pnRemainingTokenLength -= nActualTokenLength; - - // The next token should specify the start of a sequence - if ( ( nReturn = ASNDerCheckToken( pbTokenData, SPNEGO_CONSTRUCTED_SEQUENCE, + + // The next token should be an OID + if ( ( nReturn = ASNDerCheckOID( pbTokenData, spnego_mech_oid_Spnego, nBoundaryLength, + &nActualTokenLength ) ) == SPNEGO_E_SUCCESS ) { + // Make adjustments to next token + pbTokenData += nActualTokenLength; + nBoundaryLength -= nActualTokenLength; + *pnRemainingTokenLength -= nActualTokenLength; + + // The next token should specify the NegTokenInit + if ( ( nReturn = ASNDerCheckToken( pbTokenData, SPNEGO_NEGINIT_TOKEN_IDENTIFIER, *pnRemainingTokenLength, nBoundaryLength, pnTokenLength, &nActualTokenLength ) ) - == SPNEGO_E_SUCCESS ) - { - // NegTokenInit header is now checked out! + == SPNEGO_E_SUCCESS ) { + // Make adjustments to next token + pbTokenData += nActualTokenLength; + nBoundaryLength -= nActualTokenLength; + *pnRemainingTokenLength -= nActualTokenLength; - // Make adjustments to next token - *pnRemainingTokenLength -= nActualTokenLength; + // The next token should specify the start of a sequence + if ( ( nReturn = ASNDerCheckToken( pbTokenData, SPNEGO_CONSTRUCTED_SEQUENCE, + *pnRemainingTokenLength, nBoundaryLength, pnTokenLength, + &nActualTokenLength ) ) + == SPNEGO_E_SUCCESS ) { + // NegTokenInit header is now checked out! - // Store pointer to first element - *ppbFirstElement = pbTokenData + nActualTokenLength; - pSpnegoToken->ucTokenType = SPNEGO_TOKEN_INIT; - } // IF Check Sequence Token + // Make adjustments to next token + *pnRemainingTokenLength -= nActualTokenLength; - } // IF Check NegTokenInit token + // Store pointer to first element + *ppbFirstElement = pbTokenData + nActualTokenLength; + pSpnegoToken->ucTokenType = SPNEGO_TOKEN_INIT; + } // IF Check Sequence Token + } // IF Check NegTokenInit token - } // IF Check for SPNEGO OID + } // IF Check for SPNEGO OID - } // IF check app construct token - } - else if ( SPNEGO_NEGTARG_TOKEN_IDENTIFIER == *pbTokenData ) - { + } // IF check app construct token - // The next token should specify the NegTokenInit - if ( ( nReturn = ASNDerCheckToken( pbTokenData, SPNEGO_NEGTARG_TOKEN_IDENTIFIER, - *pnRemainingTokenLength, nBoundaryLength, pnTokenLength, - &nActualTokenLength ) ) - == SPNEGO_E_SUCCESS ) - { - // Initialize the remaining token length value. This will be used - // to tell the caller how much token there is left once we've parsed - // the header (they could calculate it from the other values, but this - // is a bit friendlier) - *pnRemainingTokenLength = *pnTokenLength; + } else if ( SPNEGO_NEGTARG_TOKEN_IDENTIFIER == *pbTokenData ) { - // Make adjustments to next token - pbTokenData += nActualTokenLength; - nBoundaryLength -= nActualTokenLength; - - // The next token should specify the start of a sequence - if ( ( nReturn = ASNDerCheckToken( pbTokenData, SPNEGO_CONSTRUCTED_SEQUENCE, - *pnRemainingTokenLength, nBoundaryLength, pnTokenLength, - &nActualTokenLength ) ) - == SPNEGO_E_SUCCESS ) - { - // NegTokenInit header is now checked out! + // The next token should specify the NegTokenInit + if ( ( nReturn = ASNDerCheckToken( pbTokenData, SPNEGO_NEGTARG_TOKEN_IDENTIFIER, + *pnRemainingTokenLength, nBoundaryLength, pnTokenLength, + &nActualTokenLength ) ) + == SPNEGO_E_SUCCESS ) { + // Initialize the remaining token length value. This will be used + // to tell the caller how much token there is left once we've parsed + // the header (they could calculate it from the other values, but this + // is a bit friendlier) + *pnRemainingTokenLength = *pnTokenLength; // Make adjustments to next token - *pnRemainingTokenLength -= nActualTokenLength; + pbTokenData += nActualTokenLength; + nBoundaryLength -= nActualTokenLength; + + // The next token should specify the start of a sequence + if ( ( nReturn = ASNDerCheckToken( pbTokenData, SPNEGO_CONSTRUCTED_SEQUENCE, + *pnRemainingTokenLength, nBoundaryLength, pnTokenLength, + &nActualTokenLength ) ) + == SPNEGO_E_SUCCESS ) { + // NegTokenInit header is now checked out! + + // Make adjustments to next token + *pnRemainingTokenLength -= nActualTokenLength; - // Store pointer to first element - *ppbFirstElement = pbTokenData + nActualTokenLength; - pSpnegoToken->ucTokenType = SPNEGO_TOKEN_TARG; - } // IF Check Sequence Token + // Store pointer to first element + *ppbFirstElement = pbTokenData + nActualTokenLength; + pSpnegoToken->ucTokenType = SPNEGO_TOKEN_TARG; + } // IF Check Sequence Token - } // IF Check NegTokenInit token + } // IF Check NegTokenInit token - } // ELSE IF it's a NegTokenTarg + } // ELSE IF it's a NegTokenTarg - LOG(("InitSpnegoTokenType returned %d\n",nReturn)); - return nReturn; + LOG(("InitSpnegoTokenType returned %d\n",nReturn)); + return nReturn; } @@ -1088,39 +1028,37 @@ int InitSpnegoTokenType( SPNEGO_TOKEN* pSpnegoToken, long* pnTokenLength, //////////////////////////////////////////////////////////////////////////// int GetSpnegoInitTokenMechList( unsigned char* pbTokenData, int nMechListLength, - SPNEGO_ELEMENT* pSpnegoElement ) + SPNEGO_ELEMENT* pSpnegoElement ) { - int nReturn = SPNEGO_E_INVALID_TOKEN; - long nLength = 0L; - long nActualTokenLength = 0L; + int nReturn = SPNEGO_E_INVALID_TOKEN; + long nLength = 0L; + long nActualTokenLength = 0L; - // Actual MechList is prepended by a Constructed Sequence Token - if ( ( nReturn = ASNDerCheckToken( pbTokenData, SPNEGO_CONSTRUCTED_SEQUENCE, + // Actual MechList is prepended by a Constructed Sequence Token + if ( ( nReturn = ASNDerCheckToken( pbTokenData, SPNEGO_CONSTRUCTED_SEQUENCE, nMechListLength, nMechListLength, &nLength, &nActualTokenLength ) ) - == SPNEGO_E_SUCCESS ) - { - // Adjust for this token - nMechListLength -= nActualTokenLength; - pbTokenData += nActualTokenLength; - - // Perform simple validation of the actual MechList (i.e. ensure that - // the OIDs in the MechList are reasonable). - - if ( ( nReturn = ValidateMechList( pbTokenData, nLength ) ) == SPNEGO_E_SUCCESS ) - { - // Initialize the element now - pSpnegoElement->eElementType = spnego_init_mechtypes; - pSpnegoElement->iElementPresent = SPNEGO_TOKEN_ELEMENT_AVAILABLE; - pSpnegoElement->type = SPNEGO_MECHLIST_TYPE; - pSpnegoElement->nDatalength = nLength; - pSpnegoElement->pbData = pbTokenData; - } - - } // IF Check Token - - LOG(("GetSpnegoInitTokenMechList returned %d\n",nReturn)); - return nReturn; + == SPNEGO_E_SUCCESS ) { + // Adjust for this token + nMechListLength -= nActualTokenLength; + pbTokenData += nActualTokenLength; + + // Perform simple validation of the actual MechList (i.e. ensure that + // the OIDs in the MechList are reasonable). + + if ( ( nReturn = ValidateMechList( pbTokenData, nLength ) ) == SPNEGO_E_SUCCESS ) { + // Initialize the element now + pSpnegoElement->eElementType = spnego_init_mechtypes; + pSpnegoElement->iElementPresent = SPNEGO_TOKEN_ELEMENT_AVAILABLE; + pSpnegoElement->type = SPNEGO_MECHLIST_TYPE; + pSpnegoElement->nDatalength = nLength; + pSpnegoElement->pbData = pbTokenData; + } + + } // IF Check Token + + LOG(("GetSpnegoInitTokenMechList returned %d\n",nReturn)); + return nReturn; } ///////////////////////////////////////////////////////////////////////////// @@ -1142,46 +1080,44 @@ int GetSpnegoInitTokenMechList( unsigned char* pbTokenData, int nMechListLength, // // Comments : // Checks that pbTokenData is pointing at the specified DER type. If so, -// then we verify that lengths are proper and then fill out the +// then we verify that lengths are proper and then fill out the // SPNEGO_ELEMENT data structure. // //////////////////////////////////////////////////////////////////////////// int InitSpnegoTokenElementFromBasicType( unsigned char* pbTokenData, int nElementLength, - unsigned char ucExpectedType, - SPNEGO_ELEMENT_TYPE spnegoElementType, - SPNEGO_ELEMENT* pSpnegoElement ) + unsigned char ucExpectedType, + SPNEGO_ELEMENT_TYPE spnegoElementType, + SPNEGO_ELEMENT* pSpnegoElement ) { - int nReturn = SPNEGO_E_UNEXPECTED_TYPE; - long nLength = 0L; - long nActualTokenLength = 0L; - - // The type BYTE must match our token data or something is badly wrong - if ( *pbTokenData == ucExpectedType ) - { - - // Check that we are pointing at the specified type - if ( ( nReturn = ASNDerCheckToken( pbTokenData, ucExpectedType, - nElementLength, nElementLength, - &nLength, &nActualTokenLength ) ) - == SPNEGO_E_SUCCESS ) - { - // Adjust for this token - nElementLength -= nActualTokenLength; - pbTokenData += nActualTokenLength; - - // Initialize the element now - pSpnegoElement->eElementType = spnegoElementType; - pSpnegoElement->iElementPresent = SPNEGO_TOKEN_ELEMENT_AVAILABLE; - pSpnegoElement->type = ucExpectedType; - pSpnegoElement->nDatalength = nLength; - pSpnegoElement->pbData = pbTokenData; - } - - } // IF type makes sense - - LOG(("InitSpnegoTokenElementFromBasicType returned %d\n",nReturn)); - return nReturn; + int nReturn = SPNEGO_E_UNEXPECTED_TYPE; + long nLength = 0L; + long nActualTokenLength = 0L; + + // The type BYTE must match our token data or something is badly wrong + if ( *pbTokenData == ucExpectedType ) { + + // Check that we are pointing at the specified type + if ( ( nReturn = ASNDerCheckToken( pbTokenData, ucExpectedType, + nElementLength, nElementLength, + &nLength, &nActualTokenLength ) ) + == SPNEGO_E_SUCCESS ) { + // Adjust for this token + nElementLength -= nActualTokenLength; + pbTokenData += nActualTokenLength; + + // Initialize the element now + pSpnegoElement->eElementType = spnegoElementType; + pSpnegoElement->iElementPresent = SPNEGO_TOKEN_ELEMENT_AVAILABLE; + pSpnegoElement->type = ucExpectedType; + pSpnegoElement->nDatalength = nLength; + pSpnegoElement->pbData = pbTokenData; + } + + } // IF type makes sense + + LOG(("InitSpnegoTokenElementFromBasicType returned %d\n",nReturn)); + return nReturn; } @@ -1213,34 +1149,32 @@ int InitSpnegoTokenElementFromOID( unsigned char* pbTokenData, int nElementLengt SPNEGO_ELEMENT_TYPE spnegoElementType, SPNEGO_ELEMENT* pSpnegoElement ) { - int nReturn = SPNEGO_E_UNEXPECTED_TYPE; - long nLength = 0L; - long nActualTokenLength = 0L; - - // The type BYTE must match our token data or something is badly wrong - if ( *pbTokenData == OID ) - { - - // Check that we are pointing at an OID type - if ( ( nReturn = ASNDerCheckToken( pbTokenData, OID, - nElementLength, nElementLength, - &nLength, &nActualTokenLength ) ) - == SPNEGO_E_SUCCESS ) - { - // Don't adjust any values for this function - - // Initialize the element now - pSpnegoElement->eElementType = spnegoElementType; - pSpnegoElement->iElementPresent = SPNEGO_TOKEN_ELEMENT_AVAILABLE; - pSpnegoElement->type = OID; - pSpnegoElement->nDatalength = nElementLength; - pSpnegoElement->pbData = pbTokenData; - } - - } // IF type makes sense - - LOG(("InitSpnegoTokenElementFromBasicType returned %d\n",nReturn)); - return nReturn; + int nReturn = SPNEGO_E_UNEXPECTED_TYPE; + long nLength = 0L; + long nActualTokenLength = 0L; + + // The type BYTE must match our token data or something is badly wrong + if ( *pbTokenData == OID ) { + + // Check that we are pointing at an OID type + if ( ( nReturn = ASNDerCheckToken( pbTokenData, OID, + nElementLength, nElementLength, + &nLength, &nActualTokenLength ) ) + == SPNEGO_E_SUCCESS ) { + // Don't adjust any values for this function + + // Initialize the element now + pSpnegoElement->eElementType = spnegoElementType; + pSpnegoElement->iElementPresent = SPNEGO_TOKEN_ELEMENT_AVAILABLE; + pSpnegoElement->type = OID; + pSpnegoElement->nDatalength = nElementLength; + pSpnegoElement->pbData = pbTokenData; + } + + } // IF type makes sense + + LOG(("InitSpnegoTokenElementFromBasicType returned %d\n",nReturn)); + return nReturn; } @@ -1268,220 +1202,200 @@ int InitSpnegoTokenElementFromOID( unsigned char* pbTokenData, int nElementLengt //////////////////////////////////////////////////////////////////////////// int InitSpnegoTokenElements( SPNEGO_TOKEN* pSpnegoToken, unsigned char* pbTokenData, - long nRemainingTokenLength ) + long nRemainingTokenLength ) { - // - // The following arrays contain the token identifiers for the elements - // comprising the actual token. All values are optional, and there are - // no defaults. - // - - static unsigned char abNegTokenInitElements[] = - { SPNEGO_NEGINIT_ELEMENT_MECHTYPES, SPNEGO_NEGINIT_ELEMENT_REQFLAGS, - SPNEGO_NEGINIT_ELEMENT_MECHTOKEN, SPNEGO_NEGINIT_ELEMENT_MECHLISTMIC }; - - static unsigned char abNegTokenTargElements[] = - { SPNEGO_NEGTARG_ELEMENT_NEGRESULT, SPNEGO_NEGTARG_ELEMENT_SUPPORTEDMECH, - SPNEGO_NEGTARG_ELEMENT_RESPONSETOKEN, SPNEGO_NEGTARG_ELEMENT_MECHLISTMIC }; - - int nReturn = SPNEGO_E_SUCCESS; - int nCtr = 0L; - long nElementLength = 0L; - long nActualTokenLength = 0L; - unsigned char* pbElements = NULL; - - // Point to the correct array - switch( pSpnegoToken->ucTokenType ) - { - case SPNEGO_TOKEN_INIT: - { - pbElements = abNegTokenInitElements; - } - break; - - case SPNEGO_TOKEN_TARG: - { - pbElements = abNegTokenTargElements; - } - break; - - } // SWITCH tokentype - - // - // Enumerate the element arrays and look for the tokens at our current location - // - - for ( nCtr = 0L; - SPNEGO_E_SUCCESS == nReturn && - nCtr < MAX_NUM_TOKEN_ELEMENTS && - nRemainingTokenLength > 0L; - nCtr++ ) - { - - // Check if the token exists - if ( ( nReturn = ASNDerCheckToken( pbTokenData, pbElements[nCtr], - 0L, nRemainingTokenLength, - &nElementLength, &nActualTokenLength ) ) - == SPNEGO_E_SUCCESS ) - { - - // Token data should skip over the sequence token and then - // call the appropriate function to initialize the element - pbTokenData += nActualTokenLength; - - // Lengths in the elements should NOT go beyond the element - // length - - // Different tokens mean different elements - if ( SPNEGO_TOKEN_INIT == pSpnegoToken->ucTokenType ) - { - - // Handle each element as appropriate - switch( pbElements[nCtr] ) - { - - case SPNEGO_NEGINIT_ELEMENT_MECHTYPES: - { - // - // This is a Mech List that specifies which OIDs the - // originator of the Init Token supports. - // - - nReturn = GetSpnegoInitTokenMechList( pbTokenData, nElementLength, - &pSpnegoToken->aElementArray[nCtr] ); - - } - break; - - case SPNEGO_NEGINIT_ELEMENT_REQFLAGS: - { - // - // This is a BITSTRING which specifies the flags that the receiver - // pass to the gss_accept_sec_context() function. - // - - nReturn = InitSpnegoTokenElementFromBasicType( pbTokenData, nElementLength, - BITSTRING, spnego_init_reqFlags, - &pSpnegoToken->aElementArray[nCtr] ); - } - break; - - case SPNEGO_NEGINIT_ELEMENT_MECHTOKEN: - { - // - // This is an OCTETSTRING which contains a GSSAPI token corresponding - // to the first OID in the MechList. - // - - nReturn = InitSpnegoTokenElementFromBasicType( pbTokenData, nElementLength, - OCTETSTRING, spnego_init_mechToken, - &pSpnegoToken->aElementArray[nCtr] ); - } - break; - - case SPNEGO_NEGINIT_ELEMENT_MECHLISTMIC: - { - // - // This is an OCTETSTRING which contains a message integrity BLOB. - // - - nReturn = InitSpnegoTokenElementFromBasicType( pbTokenData, nElementLength, - OCTETSTRING, spnego_init_mechListMIC, - &pSpnegoToken->aElementArray[nCtr] ); - } - break; - - } // SWITCH Element - } - else - { - - switch( pbElements[nCtr] ) - { - - case SPNEGO_NEGTARG_ELEMENT_NEGRESULT: - { - // - // This is an ENUMERATION which specifies result of the last GSS - // token negotiation call. - // - - nReturn = InitSpnegoTokenElementFromBasicType( pbTokenData, nElementLength, - ENUMERATED, spnego_targ_negResult, - &pSpnegoToken->aElementArray[nCtr] ); - } - break; - - case SPNEGO_NEGTARG_ELEMENT_SUPPORTEDMECH: - { - // - // This is an OID which specifies a supported mechanism. - // - - nReturn = InitSpnegoTokenElementFromOID( pbTokenData, nElementLength, - spnego_targ_mechListMIC, - &pSpnegoToken->aElementArray[nCtr] ); - } - break; - - case SPNEGO_NEGTARG_ELEMENT_RESPONSETOKEN: - { - // - // This is an OCTETSTRING which specifies results of the last GSS - // token negotiation call. - // - - nReturn = InitSpnegoTokenElementFromBasicType( pbTokenData, nElementLength, - OCTETSTRING, spnego_targ_responseToken, - &pSpnegoToken->aElementArray[nCtr] ); - } - break; - - case SPNEGO_NEGTARG_ELEMENT_MECHLISTMIC: - { - // - // This is an OCTETSTRING which specifies a message integrity BLOB. - // - - nReturn = InitSpnegoTokenElementFromBasicType( pbTokenData, nElementLength, - OCTETSTRING, spnego_targ_mechListMIC, - &pSpnegoToken->aElementArray[nCtr] ); - } - break; - - } // SWITCH Element - - } // ELSE !NegTokenInit - - // Account for the entire token and following data - nRemainingTokenLength -= ( nActualTokenLength + nElementLength ); - - // Token data should skip past the element length now - pbTokenData += nElementLength; - - } // IF Token found - else if ( SPNEGO_E_TOKEN_NOT_FOUND == nReturn ) - { - // For now, this is a benign error (remember, all elements are optional, so - // if we don't find one, it's okay). - - nReturn = SPNEGO_E_SUCCESS; - } - - } // FOR enum elements - - // - // We should always run down to 0 remaining bytes in the token. If not, we've got - // a bad token. - // - - if ( SPNEGO_E_SUCCESS == nReturn && nRemainingTokenLength != 0L ) - { - nReturn = SPNEGO_E_INVALID_TOKEN; - } - - LOG(("InitSpnegoTokenElements returned %d\n",nReturn)); - return nReturn; + // + // The following arrays contain the token identifiers for the elements + // comprising the actual token. All values are optional, and there are + // no defaults. + // + + static unsigned char abNegTokenInitElements[] = { SPNEGO_NEGINIT_ELEMENT_MECHTYPES, SPNEGO_NEGINIT_ELEMENT_REQFLAGS, + SPNEGO_NEGINIT_ELEMENT_MECHTOKEN, SPNEGO_NEGINIT_ELEMENT_MECHLISTMIC + }; + + static unsigned char abNegTokenTargElements[] = { SPNEGO_NEGTARG_ELEMENT_NEGRESULT, SPNEGO_NEGTARG_ELEMENT_SUPPORTEDMECH, + SPNEGO_NEGTARG_ELEMENT_RESPONSETOKEN, SPNEGO_NEGTARG_ELEMENT_MECHLISTMIC + }; + + int nReturn = SPNEGO_E_SUCCESS; + int nCtr = 0L; + long nElementLength = 0L; + long nActualTokenLength = 0L; + unsigned char* pbElements = NULL; + + // Point to the correct array + switch ( pSpnegoToken->ucTokenType ) { + case SPNEGO_TOKEN_INIT: { + pbElements = abNegTokenInitElements; + } + break; + + case SPNEGO_TOKEN_TARG: { + pbElements = abNegTokenTargElements; + } + break; + + } // SWITCH tokentype + + // + // Enumerate the element arrays and look for the tokens at our current location + // + + for ( nCtr = 0L; + SPNEGO_E_SUCCESS == nReturn && + nCtr < MAX_NUM_TOKEN_ELEMENTS && + nRemainingTokenLength > 0L; + nCtr++ ) { + + // Check if the token exists + if ( ( nReturn = ASNDerCheckToken( pbTokenData, pbElements[nCtr], + 0L, nRemainingTokenLength, + &nElementLength, &nActualTokenLength ) ) + == SPNEGO_E_SUCCESS ) { + + // Token data should skip over the sequence token and then + // call the appropriate function to initialize the element + pbTokenData += nActualTokenLength; + + // Lengths in the elements should NOT go beyond the element + // length + + // Different tokens mean different elements + if ( SPNEGO_TOKEN_INIT == pSpnegoToken->ucTokenType ) { + + // Handle each element as appropriate + switch ( pbElements[nCtr] ) { + + case SPNEGO_NEGINIT_ELEMENT_MECHTYPES: { + // + // This is a Mech List that specifies which OIDs the + // originator of the Init Token supports. + // + + nReturn = GetSpnegoInitTokenMechList( pbTokenData, nElementLength, + &pSpnegoToken->aElementArray[nCtr] ); + + } + break; + + case SPNEGO_NEGINIT_ELEMENT_REQFLAGS: { + // + // This is a BITSTRING which specifies the flags that the receiver + // pass to the gss_accept_sec_context() function. + // + + nReturn = InitSpnegoTokenElementFromBasicType( pbTokenData, nElementLength, + BITSTRING, spnego_init_reqFlags, + &pSpnegoToken->aElementArray[nCtr] ); + } + break; + + case SPNEGO_NEGINIT_ELEMENT_MECHTOKEN: { + // + // This is an OCTETSTRING which contains a GSSAPI token corresponding + // to the first OID in the MechList. + // + + nReturn = InitSpnegoTokenElementFromBasicType( pbTokenData, nElementLength, + OCTETSTRING, spnego_init_mechToken, + &pSpnegoToken->aElementArray[nCtr] ); + } + break; + + case SPNEGO_NEGINIT_ELEMENT_MECHLISTMIC: { + // + // This is an OCTETSTRING which contains a message integrity BLOB. + // + + nReturn = InitSpnegoTokenElementFromBasicType( pbTokenData, nElementLength, + OCTETSTRING, spnego_init_mechListMIC, + &pSpnegoToken->aElementArray[nCtr] ); + } + break; + + } // SWITCH Element + } else { + + switch ( pbElements[nCtr] ) { + + case SPNEGO_NEGTARG_ELEMENT_NEGRESULT: { + // + // This is an ENUMERATION which specifies result of the last GSS + // token negotiation call. + // + + nReturn = InitSpnegoTokenElementFromBasicType( pbTokenData, nElementLength, + ENUMERATED, spnego_targ_negResult, + &pSpnegoToken->aElementArray[nCtr] ); + } + break; + + case SPNEGO_NEGTARG_ELEMENT_SUPPORTEDMECH: { + // + // This is an OID which specifies a supported mechanism. + // + + nReturn = InitSpnegoTokenElementFromOID( pbTokenData, nElementLength, + spnego_targ_mechListMIC, + &pSpnegoToken->aElementArray[nCtr] ); + } + break; + + case SPNEGO_NEGTARG_ELEMENT_RESPONSETOKEN: { + // + // This is an OCTETSTRING which specifies results of the last GSS + // token negotiation call. + // + + nReturn = InitSpnegoTokenElementFromBasicType( pbTokenData, nElementLength, + OCTETSTRING, spnego_targ_responseToken, + &pSpnegoToken->aElementArray[nCtr] ); + } + break; + + case SPNEGO_NEGTARG_ELEMENT_MECHLISTMIC: { + // + // This is an OCTETSTRING which specifies a message integrity BLOB. + // + + nReturn = InitSpnegoTokenElementFromBasicType( pbTokenData, nElementLength, + OCTETSTRING, spnego_targ_mechListMIC, + &pSpnegoToken->aElementArray[nCtr] ); + } + break; + + } // SWITCH Element + + } // ELSE !NegTokenInit + + // Account for the entire token and following data + nRemainingTokenLength -= ( nActualTokenLength + nElementLength ); + + // Token data should skip past the element length now + pbTokenData += nElementLength; + + } // IF Token found + else if ( SPNEGO_E_TOKEN_NOT_FOUND == nReturn ) { + // For now, this is a benign error (remember, all elements are optional, so + // if we don't find one, it's okay). + + nReturn = SPNEGO_E_SUCCESS; + } + + } // FOR enum elements + + // + // We should always run down to 0 remaining bytes in the token. If not, we've got + // a bad token. + // + + if ( SPNEGO_E_SUCCESS == nReturn && nRemainingTokenLength != 0L ) { + nReturn = SPNEGO_E_INVALID_TOKEN; + } + + LOG(("InitSpnegoTokenElements returned %d\n",nReturn)); + return nReturn; } @@ -1507,33 +1421,31 @@ int InitSpnegoTokenElements( SPNEGO_TOKEN* pSpnegoToken, unsigned char* pbTokenD //////////////////////////////////////////////////////////////////////////// int FindMechOIDInMechList( SPNEGO_ELEMENT* pSpnegoElement, SPNEGO_MECH_OID MechOID, - int * piMechTypeIndex ) + int * piMechTypeIndex ) { - int nReturn = SPNEGO_E_NOT_FOUND; - int nCtr = 0; - long nLength = 0L; - long nBoundaryLength = pSpnegoElement->nDatalength; - unsigned char* pbMechListData = pSpnegoElement->pbData; - - while( SPNEGO_E_SUCCESS != nReturn && nBoundaryLength > 0L ) - { - - // Use the helper function to check the OID - if ( ( nReturn = ASNDerCheckOID( pbMechListData, MechOID, nBoundaryLength, &nLength ) ) - == SPNEGO_E_SUCCESS ) - { - *piMechTypeIndex = nCtr; - } - - // Adjust for the current OID - pbMechListData += nLength; - nBoundaryLength -= nLength; - nCtr++; - - } // WHILE enuming OIDs - - LOG(("FindMechOIDInMechList returned %d\n",nReturn)); - return nReturn; + int nReturn = SPNEGO_E_NOT_FOUND; + int nCtr = 0; + long nLength = 0L; + long nBoundaryLength = pSpnegoElement->nDatalength; + unsigned char* pbMechListData = pSpnegoElement->pbData; + + while ( SPNEGO_E_SUCCESS != nReturn && nBoundaryLength > 0L ) { + + // Use the helper function to check the OID + if ( ( nReturn = ASNDerCheckOID( pbMechListData, MechOID, nBoundaryLength, &nLength ) ) + == SPNEGO_E_SUCCESS ) { + *piMechTypeIndex = nCtr; + } + + // Adjust for the current OID + pbMechListData += nLength; + nBoundaryLength -= nLength; + nCtr++; + + } // WHILE enuming OIDs + + LOG(("FindMechOIDInMechList returned %d\n",nReturn)); + return nReturn; } @@ -1560,26 +1472,25 @@ int FindMechOIDInMechList( SPNEGO_ELEMENT* pSpnegoElement, SPNEGO_MECH_OID MechO int ValidateMechList( unsigned char* pbMechListData, long nBoundaryLength ) { - int nReturn = SPNEGO_E_SUCCESS; - long nLength = 0L; - long nTokenLength = 0L; - - while( SPNEGO_E_SUCCESS == nReturn && nBoundaryLength > 0L ) - { - // Verify that we have something that at least *looks* like an OID - in other - // words it has an OID identifier and specifies a length that doesn't go beyond - // the size of the list. - nReturn = ASNDerCheckToken( pbMechListData, OID, 0L, nBoundaryLength, - &nLength, &nTokenLength ); - - // Adjust for the current OID - pbMechListData += ( nLength + nTokenLength ); - nBoundaryLength -= ( nLength + nTokenLength ); - - } // WHILE enuming OIDs - - LOG(("ValidateMechList returned %d\n",nReturn)); - return nReturn; + int nReturn = SPNEGO_E_SUCCESS; + long nLength = 0L; + long nTokenLength = 0L; + + while ( SPNEGO_E_SUCCESS == nReturn && nBoundaryLength > 0L ) { + // Verify that we have something that at least *looks* like an OID - in other + // words it has an OID identifier and specifies a length that doesn't go beyond + // the size of the list. + nReturn = ASNDerCheckToken( pbMechListData, OID, 0L, nBoundaryLength, + &nLength, &nTokenLength ); + + // Adjust for the current OID + pbMechListData += ( nLength + nTokenLength ); + nBoundaryLength -= ( nLength + nTokenLength ); + + } // WHILE enuming OIDs + + LOG(("ValidateMechList returned %d\n",nReturn)); + return nReturn; } @@ -1602,10 +1513,10 @@ int ValidateMechList( unsigned char* pbMechListData, long nBoundaryLength ) int IsValidMechOid( SPNEGO_MECH_OID mechOid ) { - LOG(("IsValidMechOid returned %d\n",mechOid >= spnego_mech_oid_Kerberos_V5_Legacy && - mechOid <= spnego_mech_oid_Spnego)); - return ( mechOid >= spnego_mech_oid_Kerberos_V5_Legacy && - mechOid <= spnego_mech_oid_Spnego ); + LOG(("IsValidMechOid returned %d\n",mechOid >= spnego_mech_oid_Kerberos_V5_Legacy && + mechOid <= spnego_mech_oid_Spnego)); + return ( mechOid >= spnego_mech_oid_Kerberos_V5_Legacy && + mechOid <= spnego_mech_oid_Spnego ); } ///////////////////////////////////////////////////////////////////////////// @@ -1627,10 +1538,10 @@ int IsValidMechOid( SPNEGO_MECH_OID mechOid ) int IsValidContextFlags( unsigned char ucContextFlags ) { - // Mask out our valid bits. If there is anything leftover, this - // is not a valid value for Context Flags - LOG(("IsValidContextFlags returned %d\n",(( ucContextFlags & ~SPNEGO_NEGINIT_CONTEXT_MASK ) == 0))); - return ( ( ucContextFlags & ~SPNEGO_NEGINIT_CONTEXT_MASK ) == 0 ); + // Mask out our valid bits. If there is anything leftover, this + // is not a valid value for Context Flags + LOG(("IsValidContextFlags returned %d\n",(( ucContextFlags & ~SPNEGO_NEGINIT_CONTEXT_MASK ) == 0))); + return ( ( ucContextFlags & ~SPNEGO_NEGINIT_CONTEXT_MASK ) == 0 ); } ///////////////////////////////////////////////////////////////////////////// @@ -1652,10 +1563,10 @@ int IsValidContextFlags( unsigned char ucContextFlags ) int IsValidNegResult( SPNEGO_NEGRESULT negResult ) { - LOG(("IsValidNegResult returned %d\n",negResult >= spnego_negresult_success && - negResult <= spnego_negresult_rejected )); - return ( negResult >= spnego_negresult_success && - negResult <= spnego_negresult_rejected ); + LOG(("IsValidNegResult returned %d\n",negResult >= spnego_negresult_success && + negResult <= spnego_negresult_rejected )); + return ( negResult >= spnego_negresult_success && + negResult <= spnego_negresult_rejected ); } ///////////////////////////////////////////////////////////////////////////// @@ -1677,32 +1588,28 @@ int IsValidNegResult( SPNEGO_NEGRESULT negResult ) int IsValidSpnegoToken( SPNEGO_TOKEN* pSpnegoToken ) { - int nReturn = 0; - - // Parameter should be non-NULL - if ( NULL != pSpnegoToken ) - { - // Length should be at least the size defined in the header - if ( pSpnegoToken->nStructSize >= SPNEGO_TOKEN_SIZE ) - { - // Number of elements should be >= our maximum - if it's greater, that's - // okay, since we'll only be accessing the elements up to MAX_NUM_TOKEN_ELEMENTS - if ( pSpnegoToken->nNumElements >= MAX_NUM_TOKEN_ELEMENTS ) - { - // Check for proper token type - if ( SPNEGO_TOKEN_INIT == pSpnegoToken->ucTokenType || - SPNEGO_TOKEN_TARG == pSpnegoToken->ucTokenType ) - { - nReturn = 1; + int nReturn = 0; + + // Parameter should be non-NULL + if ( NULL != pSpnegoToken ) { + // Length should be at least the size defined in the header + if ( pSpnegoToken->nStructSize >= SPNEGO_TOKEN_SIZE ) { + // Number of elements should be >= our maximum - if it's greater, that's + // okay, since we'll only be accessing the elements up to MAX_NUM_TOKEN_ELEMENTS + if ( pSpnegoToken->nNumElements >= MAX_NUM_TOKEN_ELEMENTS ) { + // Check for proper token type + if ( SPNEGO_TOKEN_INIT == pSpnegoToken->ucTokenType || + SPNEGO_TOKEN_TARG == pSpnegoToken->ucTokenType ) { + nReturn = 1; + } } - } - } // IF struct size makes sense + } // IF struct size makes sense - } // IF non-NULL spnego Token + } // IF non-NULL spnego Token - LOG(("IsValidSpnegoToken returned %d\n",nReturn)); - return nReturn; + LOG(("IsValidSpnegoToken returned %d\n",nReturn)); + return nReturn; } ///////////////////////////////////////////////////////////////////////////// @@ -1726,29 +1633,25 @@ int IsValidSpnegoToken( SPNEGO_TOKEN* pSpnegoToken ) int IsValidSpnegoElement( SPNEGO_TOKEN* pSpnegoToken,SPNEGO_ELEMENT_TYPE spnegoElement ) { - int nReturn = 0; - - // Check boundaries - if ( spnegoElement > spnego_element_min && - spnegoElement < spnego_element_max ) - { - - // Check for appropriateness to token type - if ( SPNEGO_TOKEN_INIT == pSpnegoToken->ucTokenType ) - { - nReturn = ( spnegoElement >= spnego_init_mechtypes && - spnegoElement <= spnego_init_mechListMIC ); - } - else - { - nReturn = ( spnegoElement >= spnego_targ_negResult && - spnegoElement <= spnego_targ_mechListMIC ); - } - - } // IF boundary conditions are met - - LOG(("IsValidSpnegoElement returned %d\n",nReturn)); - return nReturn; + int nReturn = 0; + + // Check boundaries + if ( spnegoElement > spnego_element_min && + spnegoElement < spnego_element_max ) { + + // Check for appropriateness to token type + if ( SPNEGO_TOKEN_INIT == pSpnegoToken->ucTokenType ) { + nReturn = ( spnegoElement >= spnego_init_mechtypes && + spnegoElement <= spnego_init_mechListMIC ); + } else { + nReturn = ( spnegoElement >= spnego_targ_negResult && + spnegoElement <= spnego_targ_mechListMIC ); + } + + } // IF boundary conditions are met + + LOG(("IsValidSpnegoElement returned %d\n",nReturn)); + return nReturn; } ///////////////////////////////////////////////////////////////////////////// @@ -1772,22 +1675,19 @@ int IsValidSpnegoElement( SPNEGO_TOKEN* pSpnegoToken,SPNEGO_ELEMENT_TYPE spnegoE int CalculateElementArrayIndex( SPNEGO_TOKEN* pSpnegoToken,SPNEGO_ELEMENT_TYPE spnegoElement ) { - int nReturn = 0; - - // Offset is difference between value and initial element identifier - // (these differ based on ucTokenType) - - if ( SPNEGO_TOKEN_INIT == pSpnegoToken->ucTokenType ) - { - nReturn = spnegoElement - spnego_init_mechtypes; - } - else - { - nReturn = spnegoElement - spnego_targ_negResult; - } - - LOG(("CalculateElementArrayIndex returned %d\n",nReturn)); - return nReturn; + int nReturn = 0; + + // Offset is difference between value and initial element identifier + // (these differ based on ucTokenType) + + if ( SPNEGO_TOKEN_INIT == pSpnegoToken->ucTokenType ) { + nReturn = spnegoElement - spnego_init_mechtypes; + } else { + nReturn = spnegoElement - spnego_targ_negResult; + } + + LOG(("CalculateElementArrayIndex returned %d\n",nReturn)); + return nReturn; } ///////////////////////////////////////////////////////////////////////////// @@ -1816,65 +1716,58 @@ int CalculateElementArrayIndex( SPNEGO_TOKEN* pSpnegoToken,SPNEGO_ELEMENT_TYPE s // Initializes SPNEGO_TOKEN structure from DER encoded binary data int InitTokenFromBinary( unsigned char ucCopyData, unsigned long ulFlags, - unsigned char* pbTokenData, unsigned long ulLength, - SPNEGO_TOKEN** ppSpnegoToken ) + unsigned char* pbTokenData, unsigned long ulLength, + SPNEGO_TOKEN** ppSpnegoToken ) { - int nReturn = SPNEGO_E_INVALID_PARAMETER; - SPNEGO_TOKEN* pSpnegoToken = NULL; - unsigned char* pbFirstElement = NULL; - long nTokenLength = 0L; - long nRemainingTokenLength = 0L; - - // Basic Parameter Validation - - if ( NULL != pbTokenData && - NULL != ppSpnegoToken && - 0L != ulLength ) - { - - // - // Allocate the empty token, then initialize the data structure. - // - - pSpnegoToken = AllocEmptySpnegoToken( ucCopyData, ulFlags, pbTokenData, ulLength ); - - if ( NULL != pSpnegoToken ) - { - - // Copy the binary data locally - - - // Initialize the token type - if ( ( nReturn = InitSpnegoTokenType( pSpnegoToken, &nTokenLength, - &nRemainingTokenLength, &pbFirstElement ) ) - == SPNEGO_E_SUCCESS ) - { - - // Initialize the element array - if ( ( nReturn = InitSpnegoTokenElements( pSpnegoToken, pbFirstElement, - nRemainingTokenLength ) ) - == SPNEGO_E_SUCCESS ) - { - *ppSpnegoToken = pSpnegoToken; - } + int nReturn = SPNEGO_E_INVALID_PARAMETER; + SPNEGO_TOKEN* pSpnegoToken = NULL; + unsigned char* pbFirstElement = NULL; + long nTokenLength = 0L; + long nRemainingTokenLength = 0L; + + // Basic Parameter Validation + + if ( NULL != pbTokenData && + NULL != ppSpnegoToken && + 0L != ulLength ) { + + // + // Allocate the empty token, then initialize the data structure. + // + + pSpnegoToken = AllocEmptySpnegoToken( ucCopyData, ulFlags, pbTokenData, ulLength ); + + if ( NULL != pSpnegoToken ) { - } // IF Init Token Type + // Copy the binary data locally - // Cleanup on error condition - if ( SPNEGO_E_SUCCESS != nReturn ) - { - spnegoFreeData( pSpnegoToken ); - } - } - else - { - nReturn = SPNEGO_E_OUT_OF_MEMORY; - } + // Initialize the token type + if ( ( nReturn = InitSpnegoTokenType( pSpnegoToken, &nTokenLength, + &nRemainingTokenLength, &pbFirstElement ) ) + == SPNEGO_E_SUCCESS ) { + + // Initialize the element array + if ( ( nReturn = InitSpnegoTokenElements( pSpnegoToken, pbFirstElement, + nRemainingTokenLength ) ) + == SPNEGO_E_SUCCESS ) { + *ppSpnegoToken = pSpnegoToken; + } + + } // IF Init Token Type + + // Cleanup on error condition + if ( SPNEGO_E_SUCCESS != nReturn ) { + spnegoFreeData( pSpnegoToken ); + } + + } else { + nReturn = SPNEGO_E_OUT_OF_MEMORY; + } - } // IF Valid parameters + } // IF Valid parameters - LOG(("InitTokenFromBinary returned %d\n",nReturn)); - return nReturn; + LOG(("InitTokenFromBinary returned %d\n",nReturn)); + return nReturn; } diff --git a/helpers/negotiate_auth/squid_kerb_auth/spnegohelp/spnegoparse.h b/helpers/negotiate_auth/squid_kerb_auth/spnegohelp/spnegoparse.h index c60ec60493..44c456bd21 100644 --- a/helpers/negotiate_auth/squid_kerb_auth/spnegohelp/spnegoparse.h +++ b/helpers/negotiate_auth/squid_kerb_auth/spnegohelp/spnegoparse.h @@ -38,7 +38,7 @@ extern "C" // the SPNEG_TOKEN structure is destroyed #define SPNEGO_TOKEN_INTERNAL_FLAGS_FREEDATA 0x1 - // + // // Each SPNEGO Token Type can be broken down into a // maximum of 4 separate elements. // @@ -65,22 +65,21 @@ extern "C" // Defines an individual SPNEGO Token Element. // -typedef struct SpnegoElement -{ - size_t nStructSize; // Size of the element structure - int iElementPresent; // Is the field present? Must be either - // SPNEGO_TOKEN_ELEMENT_UNAVAILABLE or - // SPNEGO_TOKEN_ELEMENT_AVAILABLE + typedef struct SpnegoElement { + size_t nStructSize; // Size of the element structure + int iElementPresent; // Is the field present? Must be either + // SPNEGO_TOKEN_ELEMENT_UNAVAILABLE or + // SPNEGO_TOKEN_ELEMENT_AVAILABLE + + SPNEGO_ELEMENT_TYPE eElementType; // The Element Type - SPNEGO_ELEMENT_TYPE eElementType; // The Element Type + unsigned char type; // Data Type - unsigned char type; // Data Type + unsigned char* pbData; // Points to actual Data - unsigned char* pbData; // Points to actual Data + unsigned long nDatalength; // Actual Data Length - unsigned long nDatalength; // Actual Data Length - -} SPNEGO_ELEMENT; + } SPNEGO_ELEMENT; // Structure size in case we later choose to extend the structure #define SPNEGO_ELEMENT_SIZE sizeof(SPNEGO_ELEMENT) @@ -91,20 +90,19 @@ typedef struct SpnegoElement // contain up to four distinct, optional elements. // -typedef struct SpnegoToken -{ - size_t nStructSize; // Size of the Token structure - unsigned long ulFlags; // Internal Structure Flags - Reserved! - int ucTokenType; // Token Type - Must be - // SPNEGO_TOKEN_INIT or - // SPNEGO_TOKEN_TARG + typedef struct SpnegoToken { + size_t nStructSize; // Size of the Token structure + unsigned long ulFlags; // Internal Structure Flags - Reserved! + int ucTokenType; // Token Type - Must be + // SPNEGO_TOKEN_INIT or + // SPNEGO_TOKEN_TARG - unsigned char* pbBinaryData; // Points to binary token data + unsigned char* pbBinaryData; // Points to binary token data - unsigned long ulBinaryDataLen; // Length of the actual binary data - int nNumElements; // Number of elements - SPNEGO_ELEMENT aElementArray [MAX_NUM_TOKEN_ELEMENTS]; // Holds the elements for the token -} SPNEGO_TOKEN; + unsigned long ulBinaryDataLen; // Length of the actual binary data + int nNumElements; // Number of elements + SPNEGO_ELEMENT aElementArray [MAX_NUM_TOKEN_ELEMENTS]; // Holds the elements for the token + } SPNEGO_TOKEN; // Structure size in case we later choose to extend the structure #define SPNEGO_TOKEN_SIZE sizeof(SPNEGO_TOKEN) @@ -113,54 +111,54 @@ typedef struct SpnegoToken // Function definitions // -SPNEGO_TOKEN* AllocEmptySpnegoToken( unsigned char ucCopyData, unsigned long ulFlags, - unsigned char * pbTokenData, unsigned long ulTokenSize ); -void FreeSpnegoToken( SPNEGO_TOKEN* pSpnegoToken ); -void InitSpnegoTokenElementArray( SPNEGO_TOKEN* pSpnegoToken ); -int InitSpnegoTokenType( SPNEGO_TOKEN* pSpnegoToken, long* pnTokenLength, - long* pnRemainingTokenLength, unsigned char** ppbFirstElement ); -int InitSpnegoTokenElements( SPNEGO_TOKEN* pSpnegoToken, unsigned char* pbTokenData, - long nRemainingTokenLength ); -int GetSpnegoInitTokenMechList( unsigned char* pbTokenData, int nMechListLength, - SPNEGO_ELEMENT* pSpnegoElement ); -int InitSpnegoTokenElementFromBasicType( unsigned char* pbTokenData, int nElementLength, - unsigned char ucExpectedType, - SPNEGO_ELEMENT_TYPE spnegoElementType, - SPNEGO_ELEMENT* pSpnegoElement ); -int InitSpnegoTokenElementFromOID( unsigned char* pbTokenData, int nElementLength, - SPNEGO_ELEMENT_TYPE spnegoElementType, - SPNEGO_ELEMENT* pSpnegoElement ); -int FindMechOIDInMechList( SPNEGO_ELEMENT* pSpnegoElement, SPNEGO_MECH_OID MechOID, - int * piMechTypeIndex ); -int ValidateMechList( unsigned char* pbMechListData, long nBoundaryLength ); -int CalculateMinSpnegoInitTokenSize( long nMechTokenLength, long nMechListMICLength, - SPNEGO_MECH_OID mechOid, int nReqFlagsAvailable, - long* plTokenSize, long* plInternalLength ); -int CalculateMinSpnegoTargTokenSize( SPNEGO_MECH_OID MechType, SPNEGO_NEGRESULT spnegoNegResult, - long nMechTokenLen, - long nMechTokenMIC, long* pnTokenSize, - long* pnInternalTokenLength ); -int CreateSpnegoInitToken( SPNEGO_MECH_OID MechType, - unsigned char ucContextFlags, unsigned char* pbMechToken, - unsigned long ulMechTokenLen, unsigned char* pbMechListMIC, - unsigned long ulMechListMICLen, unsigned char* pbTokenData, - long nTokenLength, long nInternalTokenLength ); -int CreateSpnegoTargToken( SPNEGO_MECH_OID MechType, - SPNEGO_NEGRESULT eNegResult, unsigned char* pbMechToken, - unsigned long ulMechTokenLen, unsigned char* pbMechListMIC, - unsigned long ulMechListMICLen, unsigned char* pbTokenData, - long nTokenLength, long nInternalTokenLength ); -int IsValidMechOid( SPNEGO_MECH_OID mechOid ); -int IsValidContextFlags( unsigned char ucContextFlags ); -int IsValidNegResult( SPNEGO_NEGRESULT negResult ); -int IsValidSpnegoToken( SPNEGO_TOKEN* pSpnegoToken ); -int IsValidSpnegoElement( SPNEGO_TOKEN* pSpnegoToken,SPNEGO_ELEMENT_TYPE spnegoElement ); -int CalculateElementArrayIndex( SPNEGO_TOKEN* pSpnegoToken,SPNEGO_ELEMENT_TYPE spnegoElement ); -int InitTokenFromBinary( unsigned char ucCopyData, unsigned long ulFlags, - unsigned char* pbTokenData, unsigned long ulLength, - SPNEGO_TOKEN** ppSpnegoToken ); - - // C++ Specific + SPNEGO_TOKEN* AllocEmptySpnegoToken( unsigned char ucCopyData, unsigned long ulFlags, + unsigned char * pbTokenData, unsigned long ulTokenSize ); + void FreeSpnegoToken( SPNEGO_TOKEN* pSpnegoToken ); + void InitSpnegoTokenElementArray( SPNEGO_TOKEN* pSpnegoToken ); + int InitSpnegoTokenType( SPNEGO_TOKEN* pSpnegoToken, long* pnTokenLength, + long* pnRemainingTokenLength, unsigned char** ppbFirstElement ); + int InitSpnegoTokenElements( SPNEGO_TOKEN* pSpnegoToken, unsigned char* pbTokenData, + long nRemainingTokenLength ); + int GetSpnegoInitTokenMechList( unsigned char* pbTokenData, int nMechListLength, + SPNEGO_ELEMENT* pSpnegoElement ); + int InitSpnegoTokenElementFromBasicType( unsigned char* pbTokenData, int nElementLength, + unsigned char ucExpectedType, + SPNEGO_ELEMENT_TYPE spnegoElementType, + SPNEGO_ELEMENT* pSpnegoElement ); + int InitSpnegoTokenElementFromOID( unsigned char* pbTokenData, int nElementLength, + SPNEGO_ELEMENT_TYPE spnegoElementType, + SPNEGO_ELEMENT* pSpnegoElement ); + int FindMechOIDInMechList( SPNEGO_ELEMENT* pSpnegoElement, SPNEGO_MECH_OID MechOID, + int * piMechTypeIndex ); + int ValidateMechList( unsigned char* pbMechListData, long nBoundaryLength ); + int CalculateMinSpnegoInitTokenSize( long nMechTokenLength, long nMechListMICLength, + SPNEGO_MECH_OID mechOid, int nReqFlagsAvailable, + long* plTokenSize, long* plInternalLength ); + int CalculateMinSpnegoTargTokenSize( SPNEGO_MECH_OID MechType, SPNEGO_NEGRESULT spnegoNegResult, + long nMechTokenLen, + long nMechTokenMIC, long* pnTokenSize, + long* pnInternalTokenLength ); + int CreateSpnegoInitToken( SPNEGO_MECH_OID MechType, + unsigned char ucContextFlags, unsigned char* pbMechToken, + unsigned long ulMechTokenLen, unsigned char* pbMechListMIC, + unsigned long ulMechListMICLen, unsigned char* pbTokenData, + long nTokenLength, long nInternalTokenLength ); + int CreateSpnegoTargToken( SPNEGO_MECH_OID MechType, + SPNEGO_NEGRESULT eNegResult, unsigned char* pbMechToken, + unsigned long ulMechTokenLen, unsigned char* pbMechListMIC, + unsigned long ulMechListMICLen, unsigned char* pbTokenData, + long nTokenLength, long nInternalTokenLength ); + int IsValidMechOid( SPNEGO_MECH_OID mechOid ); + int IsValidContextFlags( unsigned char ucContextFlags ); + int IsValidNegResult( SPNEGO_NEGRESULT negResult ); + int IsValidSpnegoToken( SPNEGO_TOKEN* pSpnegoToken ); + int IsValidSpnegoElement( SPNEGO_TOKEN* pSpnegoToken,SPNEGO_ELEMENT_TYPE spnegoElement ); + int CalculateElementArrayIndex( SPNEGO_TOKEN* pSpnegoToken,SPNEGO_ELEMENT_TYPE spnegoElement ); + int InitTokenFromBinary( unsigned char ucCopyData, unsigned long ulFlags, + unsigned char* pbTokenData, unsigned long ulLength, + SPNEGO_TOKEN** ppSpnegoToken ); + + // C++ Specific #if defined(__cplusplus) } #endif diff --git a/helpers/negotiate_auth/squid_kerb_auth/squid_kerb_auth.c b/helpers/negotiate_auth/squid_kerb_auth/squid_kerb_auth.c old mode 100755 new mode 100644 index efd5466473..bdf04332b0 --- a/helpers/negotiate_auth/squid_kerb_auth/squid_kerb_auth.c +++ b/helpers/negotiate_auth/squid_kerb_auth/squid_kerb_auth.c @@ -92,7 +92,7 @@ #undef VERSION #endif /* - * Reset varibles + * Reset varibles */ #include "config.h" #endif @@ -152,458 +152,459 @@ static const char *LogTime() return buf; } -char *gethost_name(void) { - char hostname[sysconf(_SC_HOST_NAME_MAX)]; - struct addrinfo *hres=NULL, *hres_list; - int rc,count; - - rc = gethostname(hostname,sysconf(_SC_HOST_NAME_MAX)); - if (rc) - { - fprintf(stderr, "%s| %s: error while resolving hostname '%s'\n", LogTime(), PROGRAM, hostname); - return NULL; +char *gethost_name(void) +{ + char hostname[sysconf(_SC_HOST_NAME_MAX)]; + struct addrinfo *hres=NULL, *hres_list; + int rc,count; + + rc = gethostname(hostname,sysconf(_SC_HOST_NAME_MAX)); + if (rc) { + fprintf(stderr, "%s| %s: error while resolving hostname '%s'\n", LogTime(), PROGRAM, hostname); + return NULL; + } + rc = xgetaddrinfo(hostname,NULL,NULL,&hres); + if (rc != 0) { + fprintf(stderr, "%s| %s: error while resolving hostname with getaddrinfo: %s\n", LogTime(), PROGRAM, xgai_strerror(rc)); + return NULL; + } + hres_list=hres; + count=0; + while (hres_list) { + count++; + hres_list=hres_list->ai_next; + } + rc = xgetnameinfo (hres->ai_addr, hres->ai_addrlen,hostname, sizeof (hostname), NULL, 0, 0); + if (rc != 0) { + fprintf(stderr, "%s| %s: error while resolving ip address with getnameinfo: %s\n", LogTime(), PROGRAM, xgai_strerror(rc)); + xfreeaddrinfo(hres); + return NULL ; } - rc = xgetaddrinfo(hostname,NULL,NULL,&hres); - if (rc != 0) { - fprintf(stderr, "%s| %s: error while resolving hostname with getaddrinfo: %s\n", LogTime(), PROGRAM, xgai_strerror(rc)); - return NULL; - } - hres_list=hres; - count=0; - while (hres_list) { - count++; - hres_list=hres_list->ai_next; - } - rc = xgetnameinfo (hres->ai_addr, hres->ai_addrlen,hostname, sizeof (hostname), NULL, 0, 0); - if (rc != 0) { - fprintf(stderr, "%s| %s: error while resolving ip address with getnameinfo: %s\n", LogTime(), PROGRAM, xgai_strerror(rc)); - xfreeaddrinfo(hres); - return NULL ; - } - xfreeaddrinfo(hres); - hostname[sysconf(_SC_HOST_NAME_MAX)-1]='\0'; - return(xstrdup(hostname)); + xfreeaddrinfo(hres); + hostname[sysconf(_SC_HOST_NAME_MAX)-1]='\0'; + return(xstrdup(hostname)); } -int check_gss_err(OM_uint32 major_status, OM_uint32 minor_status, const char* function, int debug, int log) { - if (GSS_ERROR(major_status)) { - OM_uint32 maj_stat,min_stat; - OM_uint32 msg_ctx = 0; - gss_buffer_desc status_string; - char buf[1024]; - size_t len; - - len = 0; - msg_ctx = 0; - while (!msg_ctx) { - /* convert major status code (GSS-API error) to text */ - maj_stat = gss_display_status(&min_stat, major_status, - GSS_C_GSS_CODE, - GSS_C_NULL_OID, - &msg_ctx, &status_string); - if (maj_stat == GSS_S_COMPLETE) { - if (sizeof(buf) > len + status_string.length + 1) { - sprintf(buf+len, "%s", (char*) status_string.value); - len += status_string.length; - } - gss_release_buffer(&min_stat, &status_string); - break; - } - gss_release_buffer(&min_stat, &status_string); - } - if (sizeof(buf) > len + 2) { - sprintf(buf+len, "%s", ". "); - len += 2; - } - msg_ctx = 0; - while (!msg_ctx) { - /* convert minor status code (underlying routine error) to text */ - maj_stat = gss_display_status(&min_stat, minor_status, - GSS_C_MECH_CODE, - GSS_C_NULL_OID, - &msg_ctx, &status_string); - if (maj_stat == GSS_S_COMPLETE) { - if (sizeof(buf) > len + status_string.length ) { - sprintf(buf+len, "%s", (char*) status_string.value); - len += status_string.length; - } - gss_release_buffer(&min_stat, &status_string); - break; - } - gss_release_buffer(&min_stat, &status_string); +int check_gss_err(OM_uint32 major_status, OM_uint32 minor_status, const char* function, int debug, int log) +{ + if (GSS_ERROR(major_status)) { + OM_uint32 maj_stat,min_stat; + OM_uint32 msg_ctx = 0; + gss_buffer_desc status_string; + char buf[1024]; + size_t len; + + len = 0; + msg_ctx = 0; + while (!msg_ctx) { + /* convert major status code (GSS-API error) to text */ + maj_stat = gss_display_status(&min_stat, major_status, + GSS_C_GSS_CODE, + GSS_C_NULL_OID, + &msg_ctx, &status_string); + if (maj_stat == GSS_S_COMPLETE) { + if (sizeof(buf) > len + status_string.length + 1) { + sprintf(buf+len, "%s", (char*) status_string.value); + len += status_string.length; + } + gss_release_buffer(&min_stat, &status_string); + break; + } + gss_release_buffer(&min_stat, &status_string); + } + if (sizeof(buf) > len + 2) { + sprintf(buf+len, "%s", ". "); + len += 2; + } + msg_ctx = 0; + while (!msg_ctx) { + /* convert minor status code (underlying routine error) to text */ + maj_stat = gss_display_status(&min_stat, minor_status, + GSS_C_MECH_CODE, + GSS_C_NULL_OID, + &msg_ctx, &status_string); + if (maj_stat == GSS_S_COMPLETE) { + if (sizeof(buf) > len + status_string.length ) { + sprintf(buf+len, "%s", (char*) status_string.value); + len += status_string.length; + } + gss_release_buffer(&min_stat, &status_string); + break; + } + gss_release_buffer(&min_stat, &status_string); + } + if (debug) + fprintf(stderr, "%s| %s: %s failed: %s\n", LogTime(), PROGRAM, function, buf); + fprintf(stdout, "BH %s failed: %s\n",function, buf); + if (log) + fprintf(stderr, "%s| %s: User not authenticated\n", LogTime(), PROGRAM); + return(1); } - if (debug) - fprintf(stderr, "%s| %s: %s failed: %s\n", LogTime(), PROGRAM, function, buf); - fprintf(stdout, "BH %s failed: %s\n",function, buf); - if (log) - fprintf(stderr, "%s| %s: User not authenticated\n", LogTime(), PROGRAM); - return(1); - } - return(0); + return(0); } int main(int argc, char * const argv[]) { - char buf[MAX_AUTHTOKEN_LEN]; - char *c; - int length=0; - static int err=0; - int opt, debug=0, log=0; + char buf[MAX_AUTHTOKEN_LEN]; + char *c; + int length=0; + static int err=0; + int opt, debug=0, log=0; #ifndef HAVE_SPNEGO - int rc; + int rc; #endif - OM_uint32 ret_flags=0, spnego_flag=0; - char *service_name=(char *)"HTTP",*host_name=NULL; - char *token = NULL; - char *service_principal = NULL; - OM_uint32 major_status, minor_status; - gss_ctx_id_t gss_context = GSS_C_NO_CONTEXT; - gss_name_t client_name = GSS_C_NO_NAME; - gss_name_t server_name = GSS_C_NO_NAME; - gss_cred_id_t server_creds = GSS_C_NO_CREDENTIAL; - gss_buffer_desc service = GSS_C_EMPTY_BUFFER; - gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; - gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; - const unsigned char *kerberosToken = NULL; + OM_uint32 ret_flags=0, spnego_flag=0; + char *service_name=(char *)"HTTP",*host_name=NULL; + char *token = NULL; + char *service_principal = NULL; + OM_uint32 major_status, minor_status; + gss_ctx_id_t gss_context = GSS_C_NO_CONTEXT; + gss_name_t client_name = GSS_C_NO_NAME; + gss_name_t server_name = GSS_C_NO_NAME; + gss_cred_id_t server_creds = GSS_C_NO_CREDENTIAL; + gss_buffer_desc service = GSS_C_EMPTY_BUFFER; + gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; + gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; + const unsigned char *kerberosToken = NULL; #ifndef HAVE_SPNEGO - size_t kerberosTokenLength = 0; + size_t kerberosTokenLength = 0; #endif - const unsigned char *spnegoToken = NULL ; - size_t spnegoTokenLength = 0; - - setbuf(stdout,NULL); - setbuf(stdin,NULL); - - while (-1 != (opt = getopt(argc, argv, "dis:h"))) { - switch (opt) { - case 'd': - debug = 1; - break; - case 'i': - log = 1; - break; - case 's': - service_principal = xstrdup(optarg); - break; - case 'h': - fprintf(stderr, "Usage: \n"); - fprintf(stderr, "squid_kerb_auth [-d] [-i] [-s SPN] [-h]\n"); - fprintf(stderr, "-d full debug\n"); - fprintf(stderr, "-i informational messages\n"); - fprintf(stderr, "-s service principal name\n"); - fprintf(stderr, "-h help\n"); - fprintf(stderr, "The SPN can be set to GSS_C_NO_NAME to allow any entry from keytab\n"); - fprintf(stderr, "default SPN is HTTP/fqdn@DEFAULT_REALM\n"); - exit(0); - default: - fprintf(stderr, "%s| %s: unknown option: -%c.\n", LogTime(), PROGRAM, opt); - } - } - - if (debug) - fprintf(stderr, "%s| %s: Starting version %s\n", LogTime(), PROGRAM, VERSION); - if (service_principal && strcasecmp(service_principal,"GSS_C_NO_NAME") ) { - service.value = service_principal; - service.length = strlen((char *)service.value); - } else { - host_name=gethost_name(); - if ( !host_name ) { - fprintf(stderr, "%s| %s: Local hostname could not be determined. Please specify the service principal\n", LogTime(), PROGRAM); - fprintf(stdout, "BH hostname error\n"); - exit(-1); - } - service.value = xmalloc(strlen(service_name)+strlen(host_name)+2); - snprintf(service.value,strlen(service_name)+strlen(host_name)+2,"%s@%s",service_name,host_name); - service.length = strlen((char *)service.value); - } - - while (1) { - if (fgets(buf, sizeof(buf)-1, stdin) == NULL) { - if (ferror(stdin)) { - if (debug) - fprintf(stderr, "%s| %s: fgets() failed! dying..... errno=%d (%s)\n", LogTime(), PROGRAM, ferror(stdin), - strerror(ferror(stdin))); - - fprintf(stdout, "BH input error\n"); - exit(1); /* BIIG buffer */ - } - fprintf(stdout, "BH input error\n"); - exit(0); - } - - c=memchr(buf,'\n',sizeof(buf)-1); - if (c) { - *c = '\0'; - length = c-buf; - } else { - err = 1; - } - if (err) { - if (debug) - fprintf(stderr, "%s| %s: Oversized message\n", LogTime(), PROGRAM); - fprintf(stdout, "BH Oversized message\n"); - err = 0; - continue; + const unsigned char *spnegoToken = NULL ; + size_t spnegoTokenLength = 0; + + setbuf(stdout,NULL); + setbuf(stdin,NULL); + + while (-1 != (opt = getopt(argc, argv, "dis:h"))) { + switch (opt) { + case 'd': + debug = 1; + break; + case 'i': + log = 1; + break; + case 's': + service_principal = xstrdup(optarg); + break; + case 'h': + fprintf(stderr, "Usage: \n"); + fprintf(stderr, "squid_kerb_auth [-d] [-i] [-s SPN] [-h]\n"); + fprintf(stderr, "-d full debug\n"); + fprintf(stderr, "-i informational messages\n"); + fprintf(stderr, "-s service principal name\n"); + fprintf(stderr, "-h help\n"); + fprintf(stderr, "The SPN can be set to GSS_C_NO_NAME to allow any entry from keytab\n"); + fprintf(stderr, "default SPN is HTTP/fqdn@DEFAULT_REALM\n"); + exit(0); + default: + fprintf(stderr, "%s| %s: unknown option: -%c.\n", LogTime(), PROGRAM, opt); + } } if (debug) - fprintf(stderr, "%s| %s: Got '%s' from squid (length: %d).\n", LogTime(), PROGRAM, buf,length); - - if (buf[0] == '\0') { - if (debug) - fprintf(stderr, "%s| %s: Invalid request\n", LogTime(), PROGRAM); - fprintf(stdout, "BH Invalid request\n"); - continue; - } - - if (strlen(buf) < 2) { - if (debug) - fprintf(stderr, "%s| %s: Invalid request [%s]\n", LogTime(), PROGRAM, buf); - fprintf(stdout, "BH Invalid request\n"); - continue; - } - - if ( !strncmp(buf, "QQ", 2) ) { - gss_release_buffer(&minor_status, &input_token); - gss_release_buffer(&minor_status, &output_token); - gss_release_buffer(&minor_status, &service); - gss_release_cred(&minor_status, &server_creds); - if (server_name) - gss_release_name(&minor_status, &server_name); - if (client_name) - gss_release_name(&minor_status, &client_name); - if (gss_context != GSS_C_NO_CONTEXT ) - gss_delete_sec_context(&minor_status, &gss_context, NULL); - if (kerberosToken) { - /* Allocated by parseNegTokenInit, but no matching free function exists.. */ - if (!spnego_flag) - xfree((char *)kerberosToken); - kerberosToken=NULL; - } - if (spnego_flag) { - /* Allocated by makeNegTokenTarg, but no matching free function exists.. */ - if (spnegoToken) - xfree((char *)spnegoToken); - spnegoToken=NULL; - } - if (token) { - xfree(token); - token=NULL; - } - if (host_name) { - xfree(host_name); - host_name=NULL; - } - fprintf(stdout, "BH quit command\n"); - exit(0); - } - - if ( strncmp(buf, "YR", 2) && strncmp(buf, "KK", 2) ) { - if (debug) - fprintf(stderr, "%s| %s: Invalid request [%s]\n", LogTime(), PROGRAM, buf); - fprintf(stdout, "BH Invalid request\n"); - continue; - } - if ( !strncmp(buf, "YR", 2) ){ - if (gss_context != GSS_C_NO_CONTEXT ) - gss_delete_sec_context(&minor_status, &gss_context, NULL); - gss_context = GSS_C_NO_CONTEXT; + fprintf(stderr, "%s| %s: Starting version %s\n", LogTime(), PROGRAM, VERSION); + if (service_principal && strcasecmp(service_principal,"GSS_C_NO_NAME") ) { + service.value = service_principal; + service.length = strlen((char *)service.value); + } else { + host_name=gethost_name(); + if ( !host_name ) { + fprintf(stderr, "%s| %s: Local hostname could not be determined. Please specify the service principal\n", LogTime(), PROGRAM); + fprintf(stdout, "BH hostname error\n"); + exit(-1); + } + service.value = xmalloc(strlen(service_name)+strlen(host_name)+2); + snprintf(service.value,strlen(service_name)+strlen(host_name)+2,"%s@%s",service_name,host_name); + service.length = strlen((char *)service.value); } - if (strlen(buf) <= 3) { - if (debug) - fprintf(stderr, "%s| %s: Invalid negotiate request [%s]\n", LogTime(), PROGRAM, buf); - fprintf(stdout, "BH Invalid negotiate request\n"); - continue; - } - - input_token.length = ska_base64_decode_len(buf+3); - if (debug) - fprintf(stderr, "%s| %s: Decode '%s' (decoded length: %d).\n", LogTime(), PROGRAM, buf+3,(int)input_token.length); - input_token.value = xmalloc(input_token.length); + while (1) { + if (fgets(buf, sizeof(buf)-1, stdin) == NULL) { + if (ferror(stdin)) { + if (debug) + fprintf(stderr, "%s| %s: fgets() failed! dying..... errno=%d (%s)\n", LogTime(), PROGRAM, ferror(stdin), + strerror(ferror(stdin))); + + fprintf(stdout, "BH input error\n"); + exit(1); /* BIIG buffer */ + } + fprintf(stdout, "BH input error\n"); + exit(0); + } + + c=memchr(buf,'\n',sizeof(buf)-1); + if (c) { + *c = '\0'; + length = c-buf; + } else { + err = 1; + } + if (err) { + if (debug) + fprintf(stderr, "%s| %s: Oversized message\n", LogTime(), PROGRAM); + fprintf(stdout, "BH Oversized message\n"); + err = 0; + continue; + } + + if (debug) + fprintf(stderr, "%s| %s: Got '%s' from squid (length: %d).\n", LogTime(), PROGRAM, buf,length); + + if (buf[0] == '\0') { + if (debug) + fprintf(stderr, "%s| %s: Invalid request\n", LogTime(), PROGRAM); + fprintf(stdout, "BH Invalid request\n"); + continue; + } + + if (strlen(buf) < 2) { + if (debug) + fprintf(stderr, "%s| %s: Invalid request [%s]\n", LogTime(), PROGRAM, buf); + fprintf(stdout, "BH Invalid request\n"); + continue; + } + + if ( !strncmp(buf, "QQ", 2) ) { + gss_release_buffer(&minor_status, &input_token); + gss_release_buffer(&minor_status, &output_token); + gss_release_buffer(&minor_status, &service); + gss_release_cred(&minor_status, &server_creds); + if (server_name) + gss_release_name(&minor_status, &server_name); + if (client_name) + gss_release_name(&minor_status, &client_name); + if (gss_context != GSS_C_NO_CONTEXT ) + gss_delete_sec_context(&minor_status, &gss_context, NULL); + if (kerberosToken) { + /* Allocated by parseNegTokenInit, but no matching free function exists.. */ + if (!spnego_flag) + xfree((char *)kerberosToken); + kerberosToken=NULL; + } + if (spnego_flag) { + /* Allocated by makeNegTokenTarg, but no matching free function exists.. */ + if (spnegoToken) + xfree((char *)spnegoToken); + spnegoToken=NULL; + } + if (token) { + xfree(token); + token=NULL; + } + if (host_name) { + xfree(host_name); + host_name=NULL; + } + fprintf(stdout, "BH quit command\n"); + exit(0); + } + + if ( strncmp(buf, "YR", 2) && strncmp(buf, "KK", 2) ) { + if (debug) + fprintf(stderr, "%s| %s: Invalid request [%s]\n", LogTime(), PROGRAM, buf); + fprintf(stdout, "BH Invalid request\n"); + continue; + } + if ( !strncmp(buf, "YR", 2) ) { + if (gss_context != GSS_C_NO_CONTEXT ) + gss_delete_sec_context(&minor_status, &gss_context, NULL); + gss_context = GSS_C_NO_CONTEXT; + } + + if (strlen(buf) <= 3) { + if (debug) + fprintf(stderr, "%s| %s: Invalid negotiate request [%s]\n", LogTime(), PROGRAM, buf); + fprintf(stdout, "BH Invalid negotiate request\n"); + continue; + } + + input_token.length = ska_base64_decode_len(buf+3); + if (debug) + fprintf(stderr, "%s| %s: Decode '%s' (decoded length: %d).\n", LogTime(), PROGRAM, buf+3,(int)input_token.length); + input_token.value = xmalloc(input_token.length); + + ska_base64_decode(input_token.value,buf+3,input_token.length); - ska_base64_decode(input_token.value,buf+3,input_token.length); - #ifndef HAVE_SPNEGO - if (( rc=parseNegTokenInit (input_token.value, - input_token.length, - &kerberosToken, - &kerberosTokenLength))!=0 ){ - if (debug) - fprintf(stderr, "%s| %s: parseNegTokenInit failed with rc=%d\n", LogTime(), PROGRAM, rc); - - /* if between 100 and 200 it might be a GSSAPI token and not a SPNEGO token */ - if ( rc < 100 || rc > 199 ) { - if (debug) - fprintf(stderr, "%s| %s: Invalid GSS-SPNEGO query [%s]\n", LogTime(), PROGRAM, buf); - fprintf(stdout, "BH Invalid GSS-SPNEGO query\n"); - goto cleanup; - } - if ((input_token.length >= sizeof ntlmProtocol + 1) && - (!memcmp (input_token.value, ntlmProtocol, sizeof ntlmProtocol))) { - if (debug) - fprintf(stderr, "%s| %s: received type %d NTLM token\n", LogTime(), PROGRAM, (int) *((unsigned char *)input_token.value + sizeof ntlmProtocol)); - fprintf(stdout, "BH received type %d NTLM token\n",(int) *((unsigned char *)input_token.value + sizeof ntlmProtocol)); - goto cleanup; - } - if (debug) - fprintf(stderr, "%s| %s: Token is possibly a GSSAPI token\n", LogTime(), PROGRAM); - spnego_flag=0; - } else { - gss_release_buffer(&minor_status, &input_token); - input_token.length=kerberosTokenLength; - input_token.value=(void *)kerberosToken; - spnego_flag=1; - } + if (( rc=parseNegTokenInit (input_token.value, + input_token.length, + &kerberosToken, + &kerberosTokenLength))!=0 ) { + if (debug) + fprintf(stderr, "%s| %s: parseNegTokenInit failed with rc=%d\n", LogTime(), PROGRAM, rc); + + /* if between 100 and 200 it might be a GSSAPI token and not a SPNEGO token */ + if ( rc < 100 || rc > 199 ) { + if (debug) + fprintf(stderr, "%s| %s: Invalid GSS-SPNEGO query [%s]\n", LogTime(), PROGRAM, buf); + fprintf(stdout, "BH Invalid GSS-SPNEGO query\n"); + goto cleanup; + } + if ((input_token.length >= sizeof ntlmProtocol + 1) && + (!memcmp (input_token.value, ntlmProtocol, sizeof ntlmProtocol))) { + if (debug) + fprintf(stderr, "%s| %s: received type %d NTLM token\n", LogTime(), PROGRAM, (int) *((unsigned char *)input_token.value + sizeof ntlmProtocol)); + fprintf(stdout, "BH received type %d NTLM token\n",(int) *((unsigned char *)input_token.value + sizeof ntlmProtocol)); + goto cleanup; + } + if (debug) + fprintf(stderr, "%s| %s: Token is possibly a GSSAPI token\n", LogTime(), PROGRAM); + spnego_flag=0; + } else { + gss_release_buffer(&minor_status, &input_token); + input_token.length=kerberosTokenLength; + input_token.value=(void *)kerberosToken; + spnego_flag=1; + } #else - if ((input_token.length >= sizeof ntlmProtocol + 1) && - (!memcmp (input_token.value, ntlmProtocol, sizeof ntlmProtocol))) { - if (debug) - fprintf(stderr, "%s| %s: received type %d NTLM token\n", LogTime(), PROGRAM, (int) *((unsigned char *)input_token.value + sizeof ntlmProtocol)); - fprintf(stdout, "BH received type %d NTLM token\n",(int) *((unsigned char *)input_token.value + sizeof ntlmProtocol)); - goto cleanup; - } + if ((input_token.length >= sizeof ntlmProtocol + 1) && + (!memcmp (input_token.value, ntlmProtocol, sizeof ntlmProtocol))) { + if (debug) + fprintf(stderr, "%s| %s: received type %d NTLM token\n", LogTime(), PROGRAM, (int) *((unsigned char *)input_token.value + sizeof ntlmProtocol)); + fprintf(stdout, "BH received type %d NTLM token\n",(int) *((unsigned char *)input_token.value + sizeof ntlmProtocol)); + goto cleanup; + } #endif - - if ( service_principal ) { - if ( strcasecmp(service_principal,"GSS_C_NO_NAME") ){ - major_status = gss_import_name(&minor_status, &service, - (gss_OID) GSS_C_NULL_OID, &server_name); - - } else { - server_name = GSS_C_NO_NAME; - major_status = GSS_S_COMPLETE; - } - } else { - major_status = gss_import_name(&minor_status, &service, - gss_nt_service_name, &server_name); - } - if ( check_gss_err(major_status,minor_status,"gss_import_name()",debug,log) ) - goto cleanup; - - major_status = gss_acquire_cred(&minor_status, server_name, GSS_C_INDEFINITE, - GSS_C_NO_OID_SET, GSS_C_ACCEPT, &server_creds, - NULL, NULL); - if (check_gss_err(major_status,minor_status,"gss_acquire_cred()",debug,log) ) - goto cleanup; - - major_status = gss_accept_sec_context(&minor_status, - &gss_context, - server_creds, - &input_token, - GSS_C_NO_CHANNEL_BINDINGS, - &client_name, - NULL, - &output_token, - &ret_flags, - NULL, - NULL); - - - if (output_token.length) { + if ( service_principal ) { + if ( strcasecmp(service_principal,"GSS_C_NO_NAME") ) { + major_status = gss_import_name(&minor_status, &service, + (gss_OID) GSS_C_NULL_OID, &server_name); + + } else { + server_name = GSS_C_NO_NAME; + major_status = GSS_S_COMPLETE; + } + } else { + major_status = gss_import_name(&minor_status, &service, + gss_nt_service_name, &server_name); + } + + if ( check_gss_err(major_status,minor_status,"gss_import_name()",debug,log) ) + goto cleanup; + + major_status = gss_acquire_cred(&minor_status, server_name, GSS_C_INDEFINITE, + GSS_C_NO_OID_SET, GSS_C_ACCEPT, &server_creds, + NULL, NULL); + if (check_gss_err(major_status,minor_status,"gss_acquire_cred()",debug,log) ) + goto cleanup; + + major_status = gss_accept_sec_context(&minor_status, + &gss_context, + server_creds, + &input_token, + GSS_C_NO_CHANNEL_BINDINGS, + &client_name, + NULL, + &output_token, + &ret_flags, + NULL, + NULL); + + + if (output_token.length) { #ifndef HAVE_SPNEGO - if (spnego_flag) { - if ((rc=makeNegTokenTarg (output_token.value, - output_token.length, - &spnegoToken, - &spnegoTokenLength))!=0 ) { - if (debug) - fprintf(stderr, "%s| %s: makeNegTokenTarg failed with rc=%d\n", LogTime(), PROGRAM, rc); - fprintf(stdout, "BH makeNegTokenTarg failed with rc=%d\n",rc); - goto cleanup; - } - } else { - spnegoToken = output_token.value; - spnegoTokenLength = output_token.length; - } + if (spnego_flag) { + if ((rc=makeNegTokenTarg (output_token.value, + output_token.length, + &spnegoToken, + &spnegoTokenLength))!=0 ) { + if (debug) + fprintf(stderr, "%s| %s: makeNegTokenTarg failed with rc=%d\n", LogTime(), PROGRAM, rc); + fprintf(stdout, "BH makeNegTokenTarg failed with rc=%d\n",rc); + goto cleanup; + } + } else { + spnegoToken = output_token.value; + spnegoTokenLength = output_token.length; + } #else - spnegoToken = output_token.value; - spnegoTokenLength = output_token.length; + spnegoToken = output_token.value; + spnegoTokenLength = output_token.length; #endif - token = xmalloc(ska_base64_encode_len(spnegoTokenLength)); - if (token == NULL) { - if (debug) - fprintf(stderr, "%s| %s: Not enough memory\n", LogTime(), PROGRAM); - fprintf(stdout, "BH Not enough memory\n"); - goto cleanup; - } - - ska_base64_encode(token,(const char *)spnegoToken,ska_base64_encode_len(spnegoTokenLength),spnegoTokenLength); - - if (check_gss_err(major_status,minor_status,"gss_accept_sec_context()",debug,log) ) - goto cleanup; - if (major_status & GSS_S_CONTINUE_NEEDED) { - if (debug) - fprintf(stderr, "%s| %s: continuation needed\n", LogTime(), PROGRAM); - fprintf(stdout, "TT %s\n",token); - goto cleanup; - } - gss_release_buffer(&minor_status, &output_token); - major_status = gss_display_name(&minor_status, client_name, &output_token, - NULL); - - if (check_gss_err(major_status,minor_status,"gss_display_name()",debug,log) ) - goto cleanup; - fprintf(stdout, "AF %s %s\n",token,(char *)output_token.value); - if (debug) - fprintf(stderr, "%s| %s: AF %s %s\n", LogTime(), PROGRAM, token,(char *)output_token.value); - if (log) - fprintf(stderr, "%s| %s: User %s authenticated\n", LogTime(), PROGRAM, (char *)output_token.value); - goto cleanup; - } else { - if (check_gss_err(major_status,minor_status,"gss_accept_sec_context()",debug,log) ) - goto cleanup; - if (major_status & GSS_S_CONTINUE_NEEDED) { - if (debug) - fprintf(stderr, "%s| %s: continuation needed\n", LogTime(), PROGRAM); - fprintf(stdout, "NA %s\n",token); - goto cleanup; - } - gss_release_buffer(&minor_status, &output_token); - major_status = gss_display_name(&minor_status, client_name, &output_token, - NULL); - - if (check_gss_err(major_status,minor_status,"gss_display_name()",debug,log) ) - goto cleanup; - /* - * Return dummy token AA. May need an extra return tag then AF - */ - fprintf(stdout, "AF %s %s\n","AA==",(char *)output_token.value); - if (debug) - fprintf(stderr, "%s| %s: AF %s %s\n", LogTime(), PROGRAM, "AA==", (char *)output_token.value); - if (log) - fprintf(stderr, "%s| %s: User %s authenticated\n", LogTime(), PROGRAM, (char *)output_token.value); + token = xmalloc(ska_base64_encode_len(spnegoTokenLength)); + if (token == NULL) { + if (debug) + fprintf(stderr, "%s| %s: Not enough memory\n", LogTime(), PROGRAM); + fprintf(stdout, "BH Not enough memory\n"); + goto cleanup; + } + + ska_base64_encode(token,(const char *)spnegoToken,ska_base64_encode_len(spnegoTokenLength),spnegoTokenLength); + + if (check_gss_err(major_status,minor_status,"gss_accept_sec_context()",debug,log) ) + goto cleanup; + if (major_status & GSS_S_CONTINUE_NEEDED) { + if (debug) + fprintf(stderr, "%s| %s: continuation needed\n", LogTime(), PROGRAM); + fprintf(stdout, "TT %s\n",token); + goto cleanup; + } + gss_release_buffer(&minor_status, &output_token); + major_status = gss_display_name(&minor_status, client_name, &output_token, + NULL); + + if (check_gss_err(major_status,minor_status,"gss_display_name()",debug,log) ) + goto cleanup; + fprintf(stdout, "AF %s %s\n",token,(char *)output_token.value); + if (debug) + fprintf(stderr, "%s| %s: AF %s %s\n", LogTime(), PROGRAM, token,(char *)output_token.value); + if (log) + fprintf(stderr, "%s| %s: User %s authenticated\n", LogTime(), PROGRAM, (char *)output_token.value); + goto cleanup; + } else { + if (check_gss_err(major_status,minor_status,"gss_accept_sec_context()",debug,log) ) + goto cleanup; + if (major_status & GSS_S_CONTINUE_NEEDED) { + if (debug) + fprintf(stderr, "%s| %s: continuation needed\n", LogTime(), PROGRAM); + fprintf(stdout, "NA %s\n",token); + goto cleanup; + } + gss_release_buffer(&minor_status, &output_token); + major_status = gss_display_name(&minor_status, client_name, &output_token, + NULL); + + if (check_gss_err(major_status,minor_status,"gss_display_name()",debug,log) ) + goto cleanup; + /* + * Return dummy token AA. May need an extra return tag then AF + */ + fprintf(stdout, "AF %s %s\n","AA==",(char *)output_token.value); + if (debug) + fprintf(stderr, "%s| %s: AF %s %s\n", LogTime(), PROGRAM, "AA==", (char *)output_token.value); + if (log) + fprintf(stderr, "%s| %s: User %s authenticated\n", LogTime(), PROGRAM, (char *)output_token.value); cleanup: - gss_release_buffer(&minor_status, &input_token); - gss_release_buffer(&minor_status, &output_token); - gss_release_cred(&minor_status, &server_creds); - if (server_name) - gss_release_name(&minor_status, &server_name); - if (client_name) - gss_release_name(&minor_status, &client_name); - if (kerberosToken) { - /* Allocated by parseNegTokenInit, but no matching free function exists.. */ - if (!spnego_flag) - xfree((char *)kerberosToken); - kerberosToken=NULL; - } - if (spnego_flag) { - /* Allocated by makeNegTokenTarg, but no matching free function exists.. */ - if (spnegoToken) - xfree((char *)spnegoToken); - spnegoToken=NULL; - } - if (token) { - xfree(token); - token=NULL; - } - continue; + gss_release_buffer(&minor_status, &input_token); + gss_release_buffer(&minor_status, &output_token); + gss_release_cred(&minor_status, &server_creds); + if (server_name) + gss_release_name(&minor_status, &server_name); + if (client_name) + gss_release_name(&minor_status, &client_name); + if (kerberosToken) { + /* Allocated by parseNegTokenInit, but no matching free function exists.. */ + if (!spnego_flag) + xfree((char *)kerberosToken); + kerberosToken=NULL; + } + if (spnego_flag) { + /* Allocated by makeNegTokenTarg, but no matching free function exists.. */ + if (spnegoToken) + xfree((char *)spnegoToken); + spnegoToken=NULL; + } + if (token) { + xfree(token); + token=NULL; + } + continue; + } } - } } diff --git a/helpers/negotiate_auth/squid_kerb_auth/squid_kerb_auth_test.c b/helpers/negotiate_auth/squid_kerb_auth/squid_kerb_auth_test.c index 2318326dd4..ef4157c13e 100644 --- a/helpers/negotiate_auth/squid_kerb_auth/squid_kerb_auth_test.c +++ b/helpers/negotiate_auth/squid_kerb_auth/squid_kerb_auth_test.c @@ -127,134 +127,137 @@ gss_OID gss_mech_spnego = &_gss_mech_spnego; #endif #endif -int check_gss_err(OM_uint32 major_status, OM_uint32 minor_status, const char* function){ - if (GSS_ERROR(major_status)) { - OM_uint32 maj_stat,min_stat; - OM_uint32 msg_ctx = 0; - gss_buffer_desc status_string; - char buf[1024]; - size_t len; +int check_gss_err(OM_uint32 major_status, OM_uint32 minor_status, const char* function) +{ + if (GSS_ERROR(major_status)) { + OM_uint32 maj_stat,min_stat; + OM_uint32 msg_ctx = 0; + gss_buffer_desc status_string; + char buf[1024]; + size_t len; - len = 0; - msg_ctx = 0; - while (!msg_ctx) { - /* convert major status code (GSS-API error) to text */ - maj_stat = gss_display_status(&min_stat, major_status, - GSS_C_GSS_CODE, - GSS_C_NULL_OID, - &msg_ctx, &status_string); - if (maj_stat == GSS_S_COMPLETE) { - if (sizeof(buf) > len + status_string.length + 1) { - sprintf(buf+len, "%s", (char*) status_string.value); - len += status_string.length; + len = 0; + msg_ctx = 0; + while (!msg_ctx) { + /* convert major status code (GSS-API error) to text */ + maj_stat = gss_display_status(&min_stat, major_status, + GSS_C_GSS_CODE, + GSS_C_NULL_OID, + &msg_ctx, &status_string); + if (maj_stat == GSS_S_COMPLETE) { + if (sizeof(buf) > len + status_string.length + 1) { + sprintf(buf+len, "%s", (char*) status_string.value); + len += status_string.length; + } + gss_release_buffer(&min_stat, &status_string); + break; + } + gss_release_buffer(&min_stat, &status_string); } - gss_release_buffer(&min_stat, &status_string); - break; - } - gss_release_buffer(&min_stat, &status_string); - } - if (sizeof(buf) > len + 2) { - sprintf(buf+len, "%s", ". "); - len += 2; - } - msg_ctx = 0; - while (!msg_ctx) { - /* convert minor status code (underlying routine error) to text */ - maj_stat = gss_display_status(&min_stat, minor_status, - GSS_C_MECH_CODE, - GSS_C_NULL_OID, - &msg_ctx, &status_string); - if (maj_stat == GSS_S_COMPLETE) { - if (sizeof(buf) > len + status_string.length ) { - sprintf(buf+len, "%s", (char*) status_string.value); - len += status_string.length; + if (sizeof(buf) > len + 2) { + sprintf(buf+len, "%s", ". "); + len += 2; } - gss_release_buffer(&min_stat, &status_string); - break; - } - gss_release_buffer(&min_stat, &status_string); + msg_ctx = 0; + while (!msg_ctx) { + /* convert minor status code (underlying routine error) to text */ + maj_stat = gss_display_status(&min_stat, minor_status, + GSS_C_MECH_CODE, + GSS_C_NULL_OID, + &msg_ctx, &status_string); + if (maj_stat == GSS_S_COMPLETE) { + if (sizeof(buf) > len + status_string.length ) { + sprintf(buf+len, "%s", (char*) status_string.value); + len += status_string.length; + } + gss_release_buffer(&min_stat, &status_string); + break; + } + gss_release_buffer(&min_stat, &status_string); + } + fprintf(stderr, "%s| %s: %s failed: %s\n", LogTime(), PROGRAM, function, buf); + return(1); } - fprintf(stderr, "%s| %s: %s failed: %s\n", LogTime(), PROGRAM, function, buf); - return(1); - } - return(0); + return(0); } -const char *squid_kerb_proxy_auth(char *proxy) { - OM_uint32 major_status, minor_status; - gss_ctx_id_t gss_context = GSS_C_NO_CONTEXT; - gss_name_t server_name = GSS_C_NO_NAME; - gss_buffer_desc service = GSS_C_EMPTY_BUFFER; - gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; - gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; - char *token = NULL; +const char *squid_kerb_proxy_auth(char *proxy) +{ + OM_uint32 major_status, minor_status; + gss_ctx_id_t gss_context = GSS_C_NO_CONTEXT; + gss_name_t server_name = GSS_C_NO_NAME; + gss_buffer_desc service = GSS_C_EMPTY_BUFFER; + gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; + gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; + char *token = NULL; + + setbuf(stdout,NULL); + setbuf(stdin,NULL); - setbuf(stdout,NULL); - setbuf(stdin,NULL); + if (!proxy ) { + fprintf(stderr, "%s| %s: Error: No proxy server name\n", LogTime(), PROGRAM); + return NULL; + } + + service.value = xmalloc(strlen("HTTP")+strlen(proxy)+2); + snprintf(service.value,strlen("HTTP")+strlen(proxy)+2,"%s@%s","HTTP",proxy); + service.length = strlen((char *)service.value); - if (!proxy ) { - fprintf(stderr, "%s| %s: Error: No proxy server name\n", LogTime(), PROGRAM); - return NULL; - } + major_status = gss_import_name(&minor_status, &service, + gss_nt_service_name, &server_name); - service.value = xmalloc(strlen("HTTP")+strlen(proxy)+2); - snprintf(service.value,strlen("HTTP")+strlen(proxy)+2,"%s@%s","HTTP",proxy); - service.length = strlen((char *)service.value); - - major_status = gss_import_name(&minor_status, &service, - gss_nt_service_name, &server_name); - - if (check_gss_err(major_status,minor_status,"gss_import_name()") ) - goto cleanup; + if (check_gss_err(major_status,minor_status,"gss_import_name()") ) + goto cleanup; - major_status = gss_init_sec_context(&minor_status, - GSS_C_NO_CREDENTIAL, - &gss_context, - server_name, + major_status = gss_init_sec_context(&minor_status, + GSS_C_NO_CREDENTIAL, + &gss_context, + server_name, #ifdef HAVE_SPNEGO - gss_mech_spnego, + gss_mech_spnego, #else - 0, + 0, #endif - 0, - 0, - GSS_C_NO_CHANNEL_BINDINGS, - &input_token, - NULL, - &output_token, - NULL, - NULL); + 0, + 0, + GSS_C_NO_CHANNEL_BINDINGS, + &input_token, + NULL, + &output_token, + NULL, + NULL); - if (check_gss_err(major_status,minor_status,"gss_init_sec_context()") ) - goto cleanup; + if (check_gss_err(major_status,minor_status,"gss_init_sec_context()") ) + goto cleanup; - if (output_token.length) { - token=xmalloc(ska_base64_encode_len(output_token.length)); - ska_base64_encode(token,(const char*)output_token.value,ska_base64_encode_len(output_token.length),output_token.length); - } + if (output_token.length) { + token=xmalloc(ska_base64_encode_len(output_token.length)); + ska_base64_encode(token,(const char*)output_token.value,ska_base64_encode_len(output_token.length),output_token.length); + } cleanup: - gss_delete_sec_context(&minor_status, &gss_context, NULL); - gss_release_buffer(&minor_status, &service); - gss_release_buffer(&minor_status, &input_token); - gss_release_buffer(&minor_status, &output_token); - gss_release_name(&minor_status, &server_name); + gss_delete_sec_context(&minor_status, &gss_context, NULL); + gss_release_buffer(&minor_status, &service); + gss_release_buffer(&minor_status, &input_token); + gss_release_buffer(&minor_status, &output_token); + gss_release_name(&minor_status, &server_name); - return token; + return token; } -int main(int argc, char *argv[]) { +int main(int argc, char *argv[]) +{ + + const char *Token; - const char *Token; - - if (argc < 1) { - fprintf(stderr, "%s| %s: Error: No proxy server name given\n", LogTime(), PROGRAM); - exit(99); - } - Token = (const char *)squid_kerb_proxy_auth(argv[1]); - fprintf(stdout,"Token: %s\n",Token?Token:"NULL"); + if (argc < 1) { + fprintf(stderr, "%s| %s: Error: No proxy server name given\n", LogTime(), PROGRAM); + exit(99); + } + Token = (const char *)squid_kerb_proxy_auth(argv[1]); + fprintf(stdout,"Token: %s\n",Token?Token:"NULL"); - exit(0); + exit(0); } diff --git a/helpers/ntlm_auth/SMB/libntlmssp.c b/helpers/ntlm_auth/SMB/libntlmssp.c index 09a9d5dfa5..f8d0b28fcc 100644 --- a/helpers/ntlm_auth/SMB/libntlmssp.c +++ b/helpers/ntlm_auth/SMB/libntlmssp.c @@ -7,7 +7,7 @@ * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - + * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -42,21 +42,20 @@ SMB_Handle_Type SMB_Connect_Server(SMB_Handle_Type Con_Handle, char *server, cha /* this one is reallllly haackiish. We really should be using anything from smblib-priv.h */ -static char *SMB_Prots[] = -{"PC NETWORK PROGRAM 1.0", - "MICROSOFT NETWORKS 1.03", - "MICROSOFT NETWORKS 3.0", - "DOS LANMAN1.0", - "LANMAN1.0", - "DOS LM1.2X002", - "LM1.2X002", - "DOS LANMAN2.1", - "LANMAN2.1", - "Samba", - "NT LM 0.12", - "NT LANMAN 1.0", - NULL -}; +static char *SMB_Prots[] = {"PC NETWORK PROGRAM 1.0", + "MICROSOFT NETWORKS 1.03", + "MICROSOFT NETWORKS 3.0", + "DOS LANMAN1.0", + "LANMAN1.0", + "DOS LM1.2X002", + "LM1.2X002", + "DOS LANMAN2.1", + "LANMAN2.1", + "Samba", + "NT LM 0.12", + "NT LANMAN 1.0", + NULL + }; #if 0 int SMB_Discon(SMB_Handle_Type Con_Handle, BOOL KeepHandle); @@ -74,7 +73,7 @@ int SMB_Logon_Server(SMB_Handle_Type Con_Handle, char *UserName, char *PassWord, #define ENCODED_PASS_LEN 24 static unsigned char challenge[NONCE_LEN]; static unsigned char lmencoded_empty_pass[ENCODED_PASS_LEN], - ntencoded_empty_pass[ENCODED_PASS_LEN]; +ntencoded_empty_pass[ENCODED_PASS_LEN]; SMB_Handle_Type handle = NULL; /* Disconnects from the DC. A reconnection will be done upon the next request @@ -83,7 +82,7 @@ void dc_disconnect() { if (handle != NULL) - SMB_Discon(handle, 0); + SMB_Discon(handle, 0); handle = NULL; } @@ -100,7 +99,7 @@ is_dc_ok(char *domain, char *domain_controller) { SMB_Handle_Type h = SMB_Connect_Server(NULL, domain_controller, domain); if (h == NULL) - return 0; + return 0; SMB_Discon(h, 0); return 1; } @@ -114,7 +113,7 @@ init_challenge(char *domain, char *domain_controller) int smberr; if (handle != NULL) { - return 0; + return 0; } debug("Connecting to server %s domain %s\n", domain_controller, domain); handle = SMB_Connect_Server(NULL, domain_controller, domain); @@ -123,24 +122,24 @@ init_challenge(char *domain, char *domain_controller) if (handle == NULL) { /* couldn't connect */ - debug("Couldn't connect to SMB Server. Error:%s\n", errstr); - return 1; + debug("Couldn't connect to SMB Server. Error:%s\n", errstr); + return 1; } if (SMB_Negotiate(handle, SMB_Prots) < 0) { /* An error */ - debug("Error negotiating protocol with SMB Server\n"); - SMB_Discon(handle, 0); - handle = NULL; - return 2; + debug("Error negotiating protocol with SMB Server\n"); + SMB_Discon(handle, 0); + handle = NULL; + return 2; } if (handle->Security == 0) { /* share-level security, unuseable */ - debug("SMB Server uses share-level security .. we need user security.\n"); - SMB_Discon(handle, 0); - handle = NULL; - return 3; + debug("SMB Server uses share-level security .. we need user security.\n"); + SMB_Discon(handle, 0); + handle = NULL; + return 3; } memcpy(challenge, handle->Encrypt_Key, NONCE_LEN); - SMBencrypt((unsigned char *)"",challenge,lmencoded_empty_pass); - SMBNTencrypt((unsigned char *)"",challenge,ntencoded_empty_pass); + SMBencrypt((unsigned char *)"",challenge,lmencoded_empty_pass); + SMBNTencrypt((unsigned char *)"",challenge,ntencoded_empty_pass); return 0; } @@ -148,12 +147,12 @@ static char my_domain[100], my_domain_controller[100]; const char * make_challenge(char *domain, char *domain_controller) { - /* trying to circumvent some strange problem wih pointers in SMBLib */ - /* Ugly as hell, but the lib is going to be dropped... */ - strcpy(my_domain,domain); - strcpy(my_domain_controller,domain_controller); + /* trying to circumvent some strange problem wih pointers in SMBLib */ + /* Ugly as hell, but the lib is going to be dropped... */ + strcpy(my_domain,domain); + strcpy(my_domain_controller,domain_controller); if (init_challenge(my_domain, my_domain_controller) > 0) { - return NULL; + return NULL; } return ntlm_make_challenge(my_domain, my_domain_controller, (char *)challenge, NONCE_LEN); } @@ -180,14 +179,14 @@ fetch_credentials(ntlm_authenticate * auth, int auth_length) tmp = ntlm_fetch_string((char *) auth, auth_length, &auth->domain); *p = '\0'; if (tmp.str == NULL) - return NULL; + return NULL; memcpy(p, tmp.str, tmp.l); p += tmp.l; *p++ = '\\'; *p = '\0'; tmp = ntlm_fetch_string((char *) auth, auth_length, &auth->user); if (tmp.str == NULL) - return NULL; + return NULL; memcpy(p, tmp.str, tmp.l); *(p + tmp.l) = '\0'; return credentials; @@ -209,86 +208,86 @@ ntlm_check_auth(ntlm_authenticate * auth, int auth_length) lstring tmp; if (handle == NULL) { /*if null we aren't connected, but it shouldn't happen */ - debug("Weird, we've been disconnected\n"); - ntlm_errno = NTLM_NOT_CONNECTED; - return NULL; + debug("Weird, we've been disconnected\n"); + ntlm_errno = NTLM_NOT_CONNECTED; + return NULL; } -/* debug("fetching domain\n"); */ + /* debug("fetching domain\n"); */ tmp = ntlm_fetch_string((char *) auth, auth_length, &auth->domain); if (tmp.str == NULL || tmp.l == 0) { - debug("No domain supplied. Returning no-auth\n"); - ntlm_errno = NTLM_LOGON_ERROR; - return NULL; + debug("No domain supplied. Returning no-auth\n"); + ntlm_errno = NTLM_LOGON_ERROR; + return NULL; } if (tmp.l > MAX_DOMAIN_LEN) { - debug("Domain string exceeds %d bytes, rejecting\n", MAX_DOMAIN_LEN); - ntlm_errno = NTLM_LOGON_ERROR; - return NULL; + debug("Domain string exceeds %d bytes, rejecting\n", MAX_DOMAIN_LEN); + ntlm_errno = NTLM_LOGON_ERROR; + return NULL; } memcpy(domain, tmp.str, tmp.l); user = domain + tmp.l; *user++ = '\0'; -/* debug("fetching user name\n"); */ + /* debug("fetching user name\n"); */ tmp = ntlm_fetch_string((char *) auth, auth_length, &auth->user); if (tmp.str == NULL || tmp.l == 0) { - debug("No username supplied. Returning no-auth\n"); - ntlm_errno = NTLM_LOGON_ERROR; - return NULL; + debug("No username supplied. Returning no-auth\n"); + ntlm_errno = NTLM_LOGON_ERROR; + return NULL; } if (tmp.l > MAX_USERNAME_LEN) { - debug("Username string exceeds %d bytes, rejecting\n", MAX_USERNAME_LEN); - ntlm_errno = NTLM_LOGON_ERROR; - return NULL; + debug("Username string exceeds %d bytes, rejecting\n", MAX_USERNAME_LEN); + ntlm_errno = NTLM_LOGON_ERROR; + return NULL; } memcpy(user, tmp.str, tmp.l); *(user + tmp.l) = '\0'; - + /* Authenticating against the NT response doesn't seem to work... */ tmp = ntlm_fetch_string((char *) auth, auth_length, &auth->lmresponse); if (tmp.str == NULL || tmp.l == 0) { - fprintf(stderr, "No auth at all. Returning no-auth\n"); - ntlm_errno = NTLM_LOGON_ERROR; - return NULL; + fprintf(stderr, "No auth at all. Returning no-auth\n"); + ntlm_errno = NTLM_LOGON_ERROR; + return NULL; } if (tmp.l > MAX_PASSWD_LEN) { - debug("Password string exceeds %d bytes, rejecting\n", MAX_PASSWD_LEN); - ntlm_errno = NTLM_LOGON_ERROR; - return NULL; + debug("Password string exceeds %d bytes, rejecting\n", MAX_PASSWD_LEN); + ntlm_errno = NTLM_LOGON_ERROR; + return NULL; } memcpy(pass, tmp.str, tmp.l); pass[min(MAX_PASSWD_LEN,tmp.l)] = '\0'; #if 1 - debug ("Empty LM pass detection: user: '%s', ours:'%s', his: '%s'" - "(length: %d)\n", - user,lmencoded_empty_pass,tmp.str,tmp.l); - if (memcmp(tmp.str,lmencoded_empty_pass,ENCODED_PASS_LEN)==0) { - fprintf(stderr,"Empty LM password supplied for user %s\\%s. " - "No-auth\n",domain,user); - ntlm_errno=NTLM_LOGON_ERROR; - return NULL; - } - - tmp = ntlm_fetch_string ((char *) auth, auth_length, &auth->ntresponse); - if (tmp.str != NULL && tmp.l != 0) { - debug ("Empty NT pass detection: user: '%s', ours:'%s', his: '%s'" - "(length: %d)\n", - user,ntencoded_empty_pass,tmp.str,tmp.l); - if (memcmp(tmp.str,lmencoded_empty_pass,ENCODED_PASS_LEN)==0) { - fprintf(stderr,"Empty NT password supplied for user %s\\%s. " - "No-auth\n",domain,user); - ntlm_errno=NTLM_LOGON_ERROR; - return NULL; - } - } + debug ("Empty LM pass detection: user: '%s', ours:'%s', his: '%s'" + "(length: %d)\n", + user,lmencoded_empty_pass,tmp.str,tmp.l); + if (memcmp(tmp.str,lmencoded_empty_pass,ENCODED_PASS_LEN)==0) { + fprintf(stderr,"Empty LM password supplied for user %s\\%s. " + "No-auth\n",domain,user); + ntlm_errno=NTLM_LOGON_ERROR; + return NULL; + } + + tmp = ntlm_fetch_string ((char *) auth, auth_length, &auth->ntresponse); + if (tmp.str != NULL && tmp.l != 0) { + debug ("Empty NT pass detection: user: '%s', ours:'%s', his: '%s'" + "(length: %d)\n", + user,ntencoded_empty_pass,tmp.str,tmp.l); + if (memcmp(tmp.str,lmencoded_empty_pass,ENCODED_PASS_LEN)==0) { + fprintf(stderr,"Empty NT password supplied for user %s\\%s. " + "No-auth\n",domain,user); + ntlm_errno=NTLM_LOGON_ERROR; + return NULL; + } + } #endif - /* TODO: check against empty password!!!!! */ - + /* TODO: check against empty password!!!!! */ + debug("checking domain: '%s', user: '%s', pass='%s'\n", domain, user, pass); @@ -297,8 +296,8 @@ ntlm_check_auth(ntlm_authenticate * auth, int auth_length) debug("Login attempt had result %d\n", rv); if (rv != NTV_NO_ERROR) { /* failed */ - ntlm_errno = rv; - return NULL; + ntlm_errno = rv; + return NULL; } *(user - 1) = '\\'; /* hack. Performing, but ugly. */ diff --git a/helpers/ntlm_auth/SMB/ntlm.h b/helpers/ntlm_auth/SMB/ntlm.h index 5a2128a82b..de63809b05 100644 --- a/helpers/ntlm_auth/SMB/ntlm.h +++ b/helpers/ntlm_auth/SMB/ntlm.h @@ -9,7 +9,7 @@ * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - + * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/helpers/ntlm_auth/SMB/ntlm_auth.c b/helpers/ntlm_auth/SMB/ntlm_auth.c index aedfc240fb..a66ddf920b 100644 --- a/helpers/ntlm_auth/SMB/ntlm_auth.c +++ b/helpers/ntlm_auth/SMB/ntlm_auth.c @@ -7,7 +7,7 @@ * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - + * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -84,8 +84,8 @@ uc(char *string) { char *p = string, c; while ((c = *p)) { - *p = xtoupper(c); - p++; + *p = xtoupper(c); + p++; } } @@ -95,8 +95,8 @@ lc(char *string) { char *p = string, c; while ((c = *p)) { - *p = xtolower(c); - p++; + *p = xtolower(c); + p++; } } @@ -107,16 +107,16 @@ send_bh_or_ld(char *bhmessage, ntlm_authenticate * failedauth, int authlen) #ifdef NTLM_FAIL_OPEN char *creds = NULL; if (last_ditch_enabled) { - creds = fetch_credentials(failedauth, authlen); - if (creds) { - lc(creds); - SEND2("LD %s", creds); - } else { - SEND("NA last-ditch on, but no credentials"); - } + creds = fetch_credentials(failedauth, authlen); + if (creds) { + lc(creds); + SEND2("LD %s", creds); + } else { + SEND("NA last-ditch on, but no credentials"); + } } else { #endif - SEND2("BH %s", bhmessage); + SEND2("BH %s", bhmessage); #ifdef NTLM_FAIL_OPEN } #endif @@ -136,15 +136,15 @@ void usage() { fprintf(stderr, - "%s usage:\n%s [-b] [-f] [-d] [-l] domain\\controller [domain\\controller ...]\n" - "-b enables load-balancing among controllers\n" - "-f enables failover among controllers (DEPRECATED and always active)\n" - "-l changes behavior on domain controller failyures to last-ditch.\n" - "-d enables debugging statements if DEBUG was defined at build-time.\n\n" - "You MUST specify at least one Domain Controller.\n" - "You can use either \\ or / as separator between the domain name \n" - "and the controller name\n", - my_program_name, my_program_name); + "%s usage:\n%s [-b] [-f] [-d] [-l] domain\\controller [domain\\controller ...]\n" + "-b enables load-balancing among controllers\n" + "-f enables failover among controllers (DEPRECATED and always active)\n" + "-l changes behavior on domain controller failyures to last-ditch.\n" + "-d enables debugging statements if DEBUG was defined at build-time.\n\n" + "You MUST specify at least one Domain Controller.\n" + "You can use either \\ or / as separator between the domain name \n" + "and the controller name\n", + my_program_name, my_program_name); } char debug_enabled=0; @@ -155,76 +155,76 @@ process_options(int argc, char *argv[]) int opt, j, had_error = 0; dc *new_dc = NULL, *last_dc = NULL; while (-1 != (opt = getopt(argc, argv, "bfld"))) { - switch (opt) { - case 'b': - load_balance = 1; - break; - case 'f': - fprintf(stderr, - "WARNING. The -f flag is DEPRECATED and always active.\n"); - break; + switch (opt) { + case 'b': + load_balance = 1; + break; + case 'f': + fprintf(stderr, + "WARNING. The -f flag is DEPRECATED and always active.\n"); + break; #ifdef NTLM_FAIL_OPEN - case 'l': - last_ditch_enabled = 1; - break; + case 'l': + last_ditch_enabled = 1; + break; #endif - case 'd': - debug_enabled=1; - break; - default: - fprintf(stderr, "unknown option: -%c. Exiting\n", opt); - usage(); - had_error = 1; - } + case 'd': + debug_enabled=1; + break; + default: + fprintf(stderr, "unknown option: -%c. Exiting\n", opt); + usage(); + had_error = 1; + } } if (had_error) - exit(1); + exit(1); /* Okay, now begin filling controllers up */ /* we can avoid memcpy-ing, and just reuse argv[] */ for (j = optind; j < argc; j++) { - char *d, *c; - /* d will not be freed in case of non-error. Since we don't reconfigure, - * it's going to live as long as the process anyways */ - d = malloc(strlen(argv[j]) + 1); - strcpy(d, argv[j]); - debug("Adding domain-controller %s\n", d); - if (NULL == (c = strchr(d, '\\')) && NULL == (c = strchr(d, '/'))) { - fprintf(stderr, "Couldn't grok domain-controller %s\n", d); - free(d); - continue; - } - /* more than one delimiter is not allowed */ - if (NULL != strchr(c + 1, '\\') || NULL != strchr(c + 1, '/')) { - fprintf(stderr, "Broken domain-controller %s\n", d); - free(d); - continue; - } - *c++ = '\0'; - new_dc = (dc *) malloc(sizeof(dc)); - if (!new_dc) { - fprintf(stderr, "Malloc error while parsing DC options\n"); - free(d); - continue; - } - /* capitalize */ - uc(c); - uc(d); - numcontrollers++; - new_dc->domain = d; - new_dc->controller = c; - new_dc->dead = 0; - if (controllers == NULL) { /* first controller */ - controllers = new_dc; - last_dc = new_dc; - } else { - last_dc->next = new_dc; /* can't be null */ - last_dc = new_dc; - } + char *d, *c; + /* d will not be freed in case of non-error. Since we don't reconfigure, + * it's going to live as long as the process anyways */ + d = malloc(strlen(argv[j]) + 1); + strcpy(d, argv[j]); + debug("Adding domain-controller %s\n", d); + if (NULL == (c = strchr(d, '\\')) && NULL == (c = strchr(d, '/'))) { + fprintf(stderr, "Couldn't grok domain-controller %s\n", d); + free(d); + continue; + } + /* more than one delimiter is not allowed */ + if (NULL != strchr(c + 1, '\\') || NULL != strchr(c + 1, '/')) { + fprintf(stderr, "Broken domain-controller %s\n", d); + free(d); + continue; + } + *c++ = '\0'; + new_dc = (dc *) malloc(sizeof(dc)); + if (!new_dc) { + fprintf(stderr, "Malloc error while parsing DC options\n"); + free(d); + continue; + } + /* capitalize */ + uc(c); + uc(d); + numcontrollers++; + new_dc->domain = d; + new_dc->controller = c; + new_dc->dead = 0; + if (controllers == NULL) { /* first controller */ + controllers = new_dc; + last_dc = new_dc; + } else { + last_dc->next = new_dc; /* can't be null */ + last_dc = new_dc; + } } if (numcontrollers == 0) { - fprintf(stderr, "You must specify at least one domain-controller!\n"); - usage(); - exit(1); + fprintf(stderr, "You must specify at least one domain-controller!\n"); + usage(); + exit(1); } last_dc->next = controllers; /* close the queue, now it's circular */ } @@ -238,32 +238,32 @@ obtain_challenge() int j = 0; const char *ch = NULL; for (j = 0; j < numcontrollers; j++) { - debug("obtain_challenge: selecting %s\\%s (attempt #%d)\n", - current_dc->domain, current_dc->controller, j + 1); - if (current_dc->dead != 0) { - if (time(NULL) - current_dc->dead >= DEAD_DC_RETRY_INTERVAL) { - /* mark helper as retry-worthy if it's so. */ - debug("Reviving DC\n"); - current_dc->dead = 0; - } else { /* skip it */ - debug("Skipping it\n"); - continue; - } - } - /* else branch. Here we KNOW that the DC is fine */ - debug("attempting challenge retrieval\n"); - ch = make_challenge(current_dc->domain, current_dc->controller); - debug("make_challenge retuned %p\n", ch); - if (ch) { - debug("Got it\n"); - return ch; /* All went OK, returning */ - } - /* Huston, we've got a problem. Take this DC out of the loop */ - debug("Marking DC as DEAD\n"); - current_dc->dead = time(NULL); - /* Try with the next */ - debug("moving on to next controller\n"); - current_dc = current_dc->next; + debug("obtain_challenge: selecting %s\\%s (attempt #%d)\n", + current_dc->domain, current_dc->controller, j + 1); + if (current_dc->dead != 0) { + if (time(NULL) - current_dc->dead >= DEAD_DC_RETRY_INTERVAL) { + /* mark helper as retry-worthy if it's so. */ + debug("Reviving DC\n"); + current_dc->dead = 0; + } else { /* skip it */ + debug("Skipping it\n"); + continue; + } + } + /* else branch. Here we KNOW that the DC is fine */ + debug("attempting challenge retrieval\n"); + ch = make_challenge(current_dc->domain, current_dc->controller); + debug("make_challenge retuned %p\n", ch); + if (ch) { + debug("Got it\n"); + return ch; /* All went OK, returning */ + } + /* Huston, we've got a problem. Take this DC out of the loop */ + debug("Marking DC as DEAD\n"); + current_dc->dead = time(NULL); + /* Try with the next */ + debug("moving on to next controller\n"); + current_dc = current_dc->next; } /* all DCs failed. */ return NULL; @@ -280,170 +280,170 @@ manage_request() int plen; if (fgets(buf, BUFFER_SIZE, stdin) == NULL) { - fprintf(stderr, "fgets() failed! dying..... errno=%d (%s)\n", errno, - strerror(errno)); - exit(1); /* BIIG buffer */ + fprintf(stderr, "fgets() failed! dying..... errno=%d (%s)\n", errno, + strerror(errno)); + exit(1); /* BIIG buffer */ } debug("managing request\n"); ch2 = memchr(buf, '\n', BUFFER_SIZE); /* safer against overrun than strchr */ if (ch2) { - *ch2 = '\0'; /* terminate the string at newline. */ - ch = ch2; + *ch2 = '\0'; /* terminate the string at newline. */ + ch = ch2; } debug("ntlm authenticator. Got '%s' from Squid\n", buf); if (memcmp(buf, "KK ", 3) == 0) { /* authenticate-request */ - /* figure out what we got */ - decoded = base64_decode(buf + 3); - /* Note: we don't need to manage memory at this point, since - * base64_decode returns a pointer to static storage. - */ - - if (!decoded) { /* decoding failure, return error */ - SEND("NA Packet format error, couldn't base64-decode"); - return; - } - /* fast-track-decode request type. */ - fast_header = (struct _ntlmhdr *) decoded; - - /* sanity-check: it IS a NTLMSSP packet, isn't it? */ - if (memcmp(fast_header->signature, "NTLMSSP", 8) != 0) { - SEND("NA Broken authentication packet"); - return; - } - switch (le32toh(fast_header->type)) { - case NTLM_NEGOTIATE: - SEND("NA Invalid negotiation request received"); - return; - /* notreached */ - case NTLM_CHALLENGE: - SEND - ("NA Got a challenge. We refuse to have our authority disputed"); - return; - /* notreached */ - case NTLM_AUTHENTICATE: - /* check against the DC */ - plen = strlen(buf) * 3 / 4; /* we only need it here. Optimization */ - signal(SIGALRM, timeout_during_auth); - alarm(30); - cred = ntlm_check_auth((ntlm_authenticate *) decoded, plen); - alarm(0); - signal(SIGALRM, SIG_DFL); - if (got_timeout != 0) { - fprintf(stderr, "ntlm-auth[%ld]: Timeout during authentication.\n", (long)getpid()); - SEND("BH Timeout during authentication"); - got_timeout = 0; - return; - } - if (cred == NULL) { - int smblib_err, smb_errorclass, smb_errorcode, nb_error; - if (ntlm_errno == NTLM_LOGON_ERROR) { /* hackish */ - SEND("NA Logon Failure"); - return; - } - /* there was an error. We have two errno's to look at. - * libntlmssp's erno is insufficient, we'll have to look at - * the actual SMB library error codes, to acually figure - * out what's happening. The thing has braindamaged interfacess..*/ - smblib_err = SMB_Get_Last_Error(); - smb_errorclass = SMBlib_Error_Class(SMB_Get_Last_SMB_Err()); - smb_errorcode = SMBlib_Error_Code(SMB_Get_Last_SMB_Err()); - nb_error = RFCNB_Get_Last_Error(); - debug("No creds. SMBlib error %d, SMB error class %d, SMB error code %d, NB error %d\n", - smblib_err, smb_errorclass, smb_errorcode, nb_error); - /* Should I use smblib_err? Actually it seems I can do as well - * without it.. */ - if (nb_error != 0) { /* netbios-level error */ - send_bh_or_ld("NetBios error!", - (ntlm_authenticate *) decoded, plen); - fprintf(stderr, "NetBios error code %d (%s)\n", nb_error, - RFCNB_Error_Strings[abs(nb_error)]); - return; - } - switch (smb_errorclass) { - case SMBC_SUCCESS: - debug("Huh? Got a SMB success code but could check auth.."); - SEND("NA Authentication failed"); - /* - * send_bh_or_ld("SMB success, but no creds. Internal error?", - * (ntlm_authenticate *) decoded, plen); - */ - return; - case SMBC_ERRDOS: - /*this is the most important one for errors */ - debug("DOS error\n"); - switch (smb_errorcode) { - /* two categories matter to us: those which could be - * server errors, and those which are auth errors */ - case SMBD_noaccess: /* 5 */ - SEND("NA Access denied"); - return; - case SMBD_badformat: - SEND("NA bad format in authentication packet"); - return; - case SMBD_badaccess: - SEND("NA Bad access request"); - return; - case SMBD_baddata: - SEND("NA Bad Data"); - return; - default: - send_bh_or_ld("DOS Error", - (ntlm_authenticate *) decoded, plen); - return; - } - case SMBC_ERRSRV: /* server errors */ - debug("Server error"); - switch (smb_errorcode) { - /* mostly same as above */ - case SMBV_badpw: - SEND("NA Bad password"); - return; - case SMBV_access: - SEND("NA Server access error"); - return; - default: - send_bh_or_ld("Server Error", - (ntlm_authenticate *) decoded, plen); - return; - } - case SMBC_ERRHRD: /* hardware errors don't really matter */ - send_bh_or_ld("Domain Controller Hardware error", - (ntlm_authenticate *) decoded, plen); - return; - case SMBC_ERRCMD: - send_bh_or_ld("Domain Controller Command Error", - (ntlm_authenticate *) decoded, plen); - return; - } - } + /* figure out what we got */ + decoded = base64_decode(buf + 3); + /* Note: we don't need to manage memory at this point, since + * base64_decode returns a pointer to static storage. + */ + + if (!decoded) { /* decoding failure, return error */ + SEND("NA Packet format error, couldn't base64-decode"); + return; + } + /* fast-track-decode request type. */ + fast_header = (struct _ntlmhdr *) decoded; + + /* sanity-check: it IS a NTLMSSP packet, isn't it? */ + if (memcmp(fast_header->signature, "NTLMSSP", 8) != 0) { + SEND("NA Broken authentication packet"); + return; + } + switch (le32toh(fast_header->type)) { + case NTLM_NEGOTIATE: + SEND("NA Invalid negotiation request received"); + return; + /* notreached */ + case NTLM_CHALLENGE: + SEND + ("NA Got a challenge. We refuse to have our authority disputed"); + return; + /* notreached */ + case NTLM_AUTHENTICATE: + /* check against the DC */ + plen = strlen(buf) * 3 / 4; /* we only need it here. Optimization */ + signal(SIGALRM, timeout_during_auth); + alarm(30); + cred = ntlm_check_auth((ntlm_authenticate *) decoded, plen); + alarm(0); + signal(SIGALRM, SIG_DFL); + if (got_timeout != 0) { + fprintf(stderr, "ntlm-auth[%ld]: Timeout during authentication.\n", (long)getpid()); + SEND("BH Timeout during authentication"); + got_timeout = 0; + return; + } + if (cred == NULL) { + int smblib_err, smb_errorclass, smb_errorcode, nb_error; + if (ntlm_errno == NTLM_LOGON_ERROR) { /* hackish */ + SEND("NA Logon Failure"); + return; + } + /* there was an error. We have two errno's to look at. + * libntlmssp's erno is insufficient, we'll have to look at + * the actual SMB library error codes, to acually figure + * out what's happening. The thing has braindamaged interfacess..*/ + smblib_err = SMB_Get_Last_Error(); + smb_errorclass = SMBlib_Error_Class(SMB_Get_Last_SMB_Err()); + smb_errorcode = SMBlib_Error_Code(SMB_Get_Last_SMB_Err()); + nb_error = RFCNB_Get_Last_Error(); + debug("No creds. SMBlib error %d, SMB error class %d, SMB error code %d, NB error %d\n", + smblib_err, smb_errorclass, smb_errorcode, nb_error); + /* Should I use smblib_err? Actually it seems I can do as well + * without it.. */ + if (nb_error != 0) { /* netbios-level error */ + send_bh_or_ld("NetBios error!", + (ntlm_authenticate *) decoded, plen); + fprintf(stderr, "NetBios error code %d (%s)\n", nb_error, + RFCNB_Error_Strings[abs(nb_error)]); + return; + } + switch (smb_errorclass) { + case SMBC_SUCCESS: + debug("Huh? Got a SMB success code but could check auth.."); + SEND("NA Authentication failed"); + /* + * send_bh_or_ld("SMB success, but no creds. Internal error?", + * (ntlm_authenticate *) decoded, plen); + */ + return; + case SMBC_ERRDOS: + /*this is the most important one for errors */ + debug("DOS error\n"); + switch (smb_errorcode) { + /* two categories matter to us: those which could be + * server errors, and those which are auth errors */ + case SMBD_noaccess: /* 5 */ + SEND("NA Access denied"); + return; + case SMBD_badformat: + SEND("NA bad format in authentication packet"); + return; + case SMBD_badaccess: + SEND("NA Bad access request"); + return; + case SMBD_baddata: + SEND("NA Bad Data"); + return; + default: + send_bh_or_ld("DOS Error", + (ntlm_authenticate *) decoded, plen); + return; + } + case SMBC_ERRSRV: /* server errors */ + debug("Server error"); + switch (smb_errorcode) { + /* mostly same as above */ + case SMBV_badpw: + SEND("NA Bad password"); + return; + case SMBV_access: + SEND("NA Server access error"); + return; + default: + send_bh_or_ld("Server Error", + (ntlm_authenticate *) decoded, plen); + return; + } + case SMBC_ERRHRD: /* hardware errors don't really matter */ + send_bh_or_ld("Domain Controller Hardware error", + (ntlm_authenticate *) decoded, plen); + return; + case SMBC_ERRCMD: + send_bh_or_ld("Domain Controller Command Error", + (ntlm_authenticate *) decoded, plen); + return; + } + } assert(cred != NULL); - lc(cred); /* let's lowercase them for our convenience */ - SEND2("AF %s", cred); - return; - default: - SEND("BH unknown authentication packet type"); - return; - } + lc(cred); /* let's lowercase them for our convenience */ + SEND2("AF %s", cred); + return; + default: + SEND("BH unknown authentication packet type"); + return; + } - return; + return; } if (memcmp(buf, "YR", 2) == 0) { /* refresh-request */ - dc_disconnect(); - ch = obtain_challenge(); - /* Robert says we can afford to wait forever. I'll trust him on this - * one */ - while (ch == NULL) { - sleep(30); - ch = obtain_challenge(); - } - SEND2("TT %s", ch); - return; + dc_disconnect(); + ch = obtain_challenge(); + /* Robert says we can afford to wait forever. I'll trust him on this + * one */ + while (ch == NULL) { + sleep(30); + ch = obtain_challenge(); + } + SEND2("TT %s", ch); + return; } SEND("BH Helper detected protocol error"); return; -/********* END ********/ + /********* END ********/ } @@ -470,17 +470,17 @@ main(int argc, char *argv[]) /* select the first domain controller we're going to use */ current_dc = controllers; if (load_balance != 0 && numcontrollers > 1) { - int n; - pid_t pid = getpid(); - n = pid % numcontrollers; - debug("load balancing. Selected controller #%d\n", n); - while (n > 0) { - current_dc = current_dc->next; - n--; - } + int n; + pid_t pid = getpid(); + n = pid % numcontrollers; + debug("load balancing. Selected controller #%d\n", n); + while (n > 0) { + current_dc = current_dc->next; + n--; + } } while (1) { - manage_request(); + manage_request(); } return 0; } diff --git a/helpers/ntlm_auth/SMB/smbval/byteorder.h b/helpers/ntlm_auth/SMB/smbval/byteorder.h index ab2578ce4c..de91c4574f 100644 --- a/helpers/ntlm_auth/SMB/smbval/byteorder.h +++ b/helpers/ntlm_auth/SMB/smbval/byteorder.h @@ -1,32 +1,32 @@ -/* +/* * Unix SMB/Netbios implementation. * Version 1.9. * SMB Byte handling * Copyright (C) Andrew Tridgell 1992-1995 - * + * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* - * This file implements macros for machine independent short and + * This file implements macros for machine independent short and * int manipulation */ #undef CAREFUL_ALIGNMENT -/* we know that the 386 can handle misalignment and has the "right" +/* we know that the 386 can handle misalignment and has the "right" * byteorder */ #ifdef __i386__ #define CAREFUL_ALIGNMENT 0 @@ -57,7 +57,7 @@ * alignment errors */ /* * WARNING: This section is dependent on the length of int16 and int32 - * being correct + * being correct */ #define SVAL(buf,pos) (*(uint16 *)((char *)(buf) + (pos))) #define IVAL(buf,pos) (*(uint32 *)((char *)(buf) + (pos))) diff --git a/helpers/ntlm_auth/SMB/smbval/md4.c b/helpers/ntlm_auth/SMB/smbval/md4.c index 9622aca51d..5318045029 100644 --- a/helpers/ntlm_auth/SMB/smbval/md4.c +++ b/helpers/ntlm_auth/SMB/smbval/md4.c @@ -1,27 +1,27 @@ -/* +/* * Unix SMB/Netbios implementation. * Version 1.9. * a implementation of MD4 designed for use in the SMB authentication protocol * Copyright (C) Andrew Tridgell 1997 - * + * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ -/* NOTE: This code makes no attempt to be fast! - * +/* NOTE: This code makes no attempt to be fast! + * * It assumes that a int is at least 32 bits long */ #include @@ -67,7 +67,7 @@ mdfour64(uint32 * M) uint32 X[16]; for (j = 0; j < 16; j++) - X[j] = M[j]; + X[j] = M[j]; AA = A; BB = B; @@ -136,7 +136,7 @@ mdfour64(uint32 * M) D &= 0xFFFFFFFF; for (j = 0; j < 16; j++) - X[j] = 0; + X[j] = 0; } static void @@ -145,8 +145,8 @@ copy64(uint32 * M, unsigned char *in) int i; for (i = 0; i < 16; i++) - M[i] = (in[i * 4 + 3] << 24) | (in[i * 4 + 2] << 16) | - (in[i * 4 + 1] << 8) | (in[i * 4 + 0] << 0); + M[i] = (in[i * 4 + 3] << 24) | (in[i * 4 + 2] << 16) | + (in[i * 4 + 1] << 8) | (in[i * 4 + 0] << 0); } static void @@ -173,31 +173,31 @@ mdfour(unsigned char *out, unsigned char *in, int n) D = 0x10325476; while (n > 64) { - copy64(M, in); - mdfour64(M); - in += 64; - n -= 64; + copy64(M, in); + mdfour64(M); + in += 64; + n -= 64; } for (i = 0; i < 128; i++) - buf[i] = 0; + buf[i] = 0; memcpy(buf, in, n); buf[n] = 0x80; if (n <= 55) { - copy4(buf + 56, b); - copy64(M, buf); - mdfour64(M); + copy4(buf + 56, b); + copy64(M, buf); + mdfour64(M); } else { - copy4(buf + 120, b); - copy64(M, buf); - mdfour64(M); - copy64(M, buf + 64); - mdfour64(M); + copy4(buf + 120, b); + copy64(M, buf); + mdfour64(M); + copy64(M, buf + 64); + mdfour64(M); } for (i = 0; i < 128; i++) - buf[i] = 0; + buf[i] = 0; copy64(M, buf); copy4(out, A); diff --git a/helpers/ntlm_auth/SMB/smbval/md4.h b/helpers/ntlm_auth/SMB/smbval/md4.h index 015b84997c..91733de761 100644 --- a/helpers/ntlm_auth/SMB/smbval/md4.h +++ b/helpers/ntlm_auth/SMB/smbval/md4.h @@ -1 +1 @@ -void mdfour(unsigned char *out, unsigned char *in, int n); +void mdfour(unsigned char *out, unsigned char *in, int n); diff --git a/helpers/ntlm_auth/SMB/smbval/rfcnb-common.h b/helpers/ntlm_auth/SMB/smbval/rfcnb-common.h index a56a539523..84f5a3dfe8 100644 --- a/helpers/ntlm_auth/SMB/smbval/rfcnb-common.h +++ b/helpers/ntlm_auth/SMB/smbval/rfcnb-common.h @@ -1,10 +1,10 @@ /* UNIX RFCNB (RFC1001/RFC1002) NetBIOS implementation - * + * * Version 1.0 * RFCNB Common Structures etc Defines - * + * * Copyright (C) Richard Sharpe 1996 - * + * */ /* @@ -12,12 +12,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. diff --git a/helpers/ntlm_auth/SMB/smbval/rfcnb-error.h b/helpers/ntlm_auth/SMB/smbval/rfcnb-error.h index 14eb6c614a..e03ca5d992 100644 --- a/helpers/ntlm_auth/SMB/smbval/rfcnb-error.h +++ b/helpers/ntlm_auth/SMB/smbval/rfcnb-error.h @@ -1,10 +1,10 @@ /* UNIX RFCNB (RFC1001/RFC1002) NetBIOS implementation - * + * * Version 1.0 * RFCNB Error Response Defines - * + * * Copyright (C) Richard Sharpe 1996 - * + * */ /* @@ -12,12 +12,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -51,7 +51,7 @@ extern char *RFCNB_Error_Strings[]; /* * static char *RFCNB_Error_Strings[] = { - * + * * "RFCNBE_OK: Routine completed successfully.", * "RFCNBE_NoSpace: No space available for a malloc call.", * "RFCNBE_BadName: NetBIOS name could not be translated to IP address.", @@ -69,6 +69,6 @@ extern char *RFCNB_Error_Strings[]; * "RFCNBE_CallRejUnSpec: Call rejected. Unspecified error.", * "RFCNBE_BadParam: Bad parameters passed to a routine.", * "RFCNBE_Timeout: IO Operation timed out ..." - * + * * }; */ diff --git a/helpers/ntlm_auth/SMB/smbval/rfcnb-io.c b/helpers/ntlm_auth/SMB/smbval/rfcnb-io.c index 06ed1ee398..e51956e8f5 100644 --- a/helpers/ntlm_auth/SMB/smbval/rfcnb-io.c +++ b/helpers/ntlm_auth/SMB/smbval/rfcnb-io.c @@ -1,10 +1,10 @@ /* UNIX RFCNB (RFC1001/RFC1002) NEtBIOS implementation - * + * * Version 1.0 * RFCNB IO Routines ... - * + * * Copyright (C) Richard Sharpe 1996 - * + * */ /* @@ -12,12 +12,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -59,19 +59,19 @@ RFCNB_Set_Timeout(int seconds) if (RFCNB_Timeout > 0) { /* Set up handler to ignore but not restart */ #if HAVE_SIGACTION - inact.sa_handler = (void (*)()) rfcnb_alarm; - sigemptyset(&inact.sa_mask); - inact.sa_flags = 0; /* Don't restart */ + inact.sa_handler = (void (*)()) rfcnb_alarm; + sigemptyset(&inact.sa_mask); + inact.sa_flags = 0; /* Don't restart */ - if (sigaction(SIGALRM, &inact, &outact) < 0) - return (-1); + if (sigaction(SIGALRM, &inact, &outact) < 0) + return (-1); #else - invec.sv_handler = (void (*)()) rfcnb_alarm; - invec.sv_mask = 0; - invec.sv_flags = SV_INTERRUPT; + invec.sv_handler = (void (*)()) rfcnb_alarm; + invec.sv_mask = 0; + invec.sv_flags = SV_INTERRUPT; - if (sigvec(SIGALRM, &invec, &outvec) < 0) - return (-1); + if (sigvec(SIGALRM, &invec, &outvec) < 0) + return (-1); #endif } @@ -98,22 +98,22 @@ RFCNB_Discard_Rest(struct RFCNB_Con *con, int len) while (rest > 0) { - this_read = (rest > sizeof(temp) ? sizeof(temp) : rest); + this_read = (rest > sizeof(temp) ? sizeof(temp) : rest); - bytes_read = read(con->fd, temp, this_read); + bytes_read = read(con->fd, temp, this_read); - if (bytes_read <= 0) { /* Error so return */ + if (bytes_read <= 0) { /* Error so return */ - if (bytes_read < 0) - RFCNB_errno = RFCNBE_BadRead; - else - RFCNB_errno = RFCNBE_ConGone; + if (bytes_read < 0) + RFCNB_errno = RFCNBE_BadRead; + else + RFCNB_errno = RFCNBE_ConGone; - RFCNB_saved_errno = errno; - return (RFCNBE_Bad); + RFCNB_saved_errno = errno; + return (RFCNBE_Bad); - } - rest = rest - bytes_read; + } + rest = rest - bytes_read; } @@ -123,11 +123,11 @@ RFCNB_Discard_Rest(struct RFCNB_Con *con, int len) /* Send an RFCNB packet to the connection. - * - * We just send each of the blocks linked together ... - * - * If we can, try to send it as one iovec ... - * + * + * We just send each of the blocks linked together ... + * + * If we can, try to send it as one iovec ... + * */ int @@ -150,23 +150,23 @@ RFCNB_Put_Pkt(struct RFCNB_Con *con, struct RFCNB_Pkt *pkt, int len) while ((pkt_ptr != NULL) & (i < 10)) { /* Watch that magic number! */ - this_len = pkt_ptr->len; - this_data = pkt_ptr->data; - if ((tot_sent + this_len) > len) - this_len = len - tot_sent; /* Adjust so we don't send too much */ + this_len = pkt_ptr->len; + this_data = pkt_ptr->data; + if ((tot_sent + this_len) > len) + this_len = len - tot_sent; /* Adjust so we don't send too much */ - /* Now plug into the iovec ... */ + /* Now plug into the iovec ... */ - io_list[i].iov_len = this_len; - io_list[i].iov_base = this_data; - i++; + io_list[i].iov_len = this_len; + io_list[i].iov_base = this_data; + i++; - tot_sent += this_len; + tot_sent += this_len; - if (tot_sent == len) - break; /* Let's not send too much */ + if (tot_sent == len) + break; /* Let's not send too much */ - pkt_ptr = pkt_ptr->next; + pkt_ptr = pkt_ptr->next; } @@ -177,29 +177,29 @@ RFCNB_Put_Pkt(struct RFCNB_Con *con, struct RFCNB_Pkt *pkt, int len) /* Set up an alarm if timeouts are set ... */ if (RFCNB_Timeout > 0) - alarm(RFCNB_Timeout); + alarm(RFCNB_Timeout); if ((len_sent = writev(con->fd, io_list, i)) < 0) { /* An error */ - con->rfc_errno = errno; - if (errno == EINTR) /* We were interrupted ... */ - RFCNB_errno = RFCNBE_Timeout; - else - RFCNB_errno = RFCNBE_BadWrite; - RFCNB_saved_errno = errno; - return (RFCNBE_Bad); + con->rfc_errno = errno; + if (errno == EINTR) /* We were interrupted ... */ + RFCNB_errno = RFCNBE_Timeout; + else + RFCNB_errno = RFCNBE_BadWrite; + RFCNB_saved_errno = errno; + return (RFCNBE_Bad); } if (len_sent < tot_sent) { /* Less than we wanted */ - if (errno == EINTR) /* We were interrupted */ - RFCNB_errno = RFCNBE_Timeout; - else - RFCNB_errno = RFCNBE_BadWrite; - RFCNB_saved_errno = errno; - return (RFCNBE_Bad); + if (errno == EINTR) /* We were interrupted */ + RFCNB_errno = RFCNBE_Timeout; + else + RFCNB_errno = RFCNBE_BadWrite; + RFCNB_saved_errno = errno; + return (RFCNBE_Bad); } if (RFCNB_Timeout > 0) - alarm(0); /* Reset that sucker */ + alarm(0); /* Reset that sucker */ #ifdef RFCNB_DEBUG @@ -212,11 +212,11 @@ RFCNB_Put_Pkt(struct RFCNB_Con *con, struct RFCNB_Pkt *pkt, int len) } -/* Read an RFCNB packet off the connection. - * +/* Read an RFCNB packet off the connection. + * * We read the first 4 bytes, that tells us the length, then read the - * rest. We should implement a timeout, but we don't just yet - * + * rest. We should implement a timeout, but we don't just yet + * */ @@ -234,58 +234,58 @@ RFCNB_Get_Pkt(struct RFCNB_Con *con, struct RFCNB_Pkt *pkt, int len) if (len < RFCNB_Pkt_Hdr_Len) { /* What a bozo */ #ifdef RFCNB_DEBUG - fprintf(stderr, "Trying to read less than a packet:"); - perror(""); + fprintf(stderr, "Trying to read less than a packet:"); + perror(""); #endif - RFCNB_errno = RFCNBE_BadParam; - return (RFCNBE_Bad); + RFCNB_errno = RFCNBE_BadParam; + return (RFCNBE_Bad); } /* We discard keep alives here ... */ if (RFCNB_Timeout > 0) - alarm(RFCNB_Timeout); + alarm(RFCNB_Timeout); while (seen_keep_alive) { - if ((read_len = read(con->fd, hdr, sizeof(hdr))) < 0) { /* Problems */ + if ((read_len = read(con->fd, hdr, sizeof(hdr))) < 0) { /* Problems */ #ifdef RFCNB_DEBUG - fprintf(stderr, "Reading the packet, we got:"); - perror(""); + fprintf(stderr, "Reading the packet, we got:"); + perror(""); #endif - if (errno == EINTR) - RFCNB_errno = RFCNBE_Timeout; - else - RFCNB_errno = RFCNBE_BadRead; - RFCNB_saved_errno = errno; - return (RFCNBE_Bad); + if (errno == EINTR) + RFCNB_errno = RFCNBE_Timeout; + else + RFCNB_errno = RFCNBE_BadRead; + RFCNB_saved_errno = errno; + return (RFCNBE_Bad); - } - /* Now we check out what we got */ + } + /* Now we check out what we got */ - if (read_len == 0) { /* Connection closed, send back eof? */ + if (read_len == 0) { /* Connection closed, send back eof? */ #ifdef RFCNB_DEBUG - fprintf(stderr, "Connection closed reading\n"); + fprintf(stderr, "Connection closed reading\n"); #endif - if (errno == EINTR) - RFCNB_errno = RFCNBE_Timeout; - else - RFCNB_errno = RFCNBE_ConGone; - RFCNB_saved_errno = errno; - return (RFCNBE_Bad); + if (errno == EINTR) + RFCNB_errno = RFCNBE_Timeout; + else + RFCNB_errno = RFCNBE_ConGone; + RFCNB_saved_errno = errno; + return (RFCNBE_Bad); - } - if (RFCNB_Pkt_Type(hdr) == RFCNB_SESSION_KEEP_ALIVE) { + } + if (RFCNB_Pkt_Type(hdr) == RFCNB_SESSION_KEEP_ALIVE) { #ifdef RFCNB_DEBUG - fprintf(stderr, "RFCNB KEEP ALIVE received\n"); + fprintf(stderr, "RFCNB KEEP ALIVE received\n"); #endif - } else { - seen_keep_alive = FALSE; - } + } else { + seen_keep_alive = FALSE; + } } @@ -293,15 +293,15 @@ RFCNB_Get_Pkt(struct RFCNB_Con *con, struct RFCNB_Pkt *pkt, int len) if (read_len < sizeof(hdr)) { /* We got a small packet */ - /* Now we need to copy the hdr portion we got into the supplied packet */ + /* Now we need to copy the hdr portion we got into the supplied packet */ - memcpy(pkt->data, hdr, read_len); /*Copy data */ + memcpy(pkt->data, hdr, read_len); /*Copy data */ #ifdef RFCNB_DEBUG - RFCNB_Print_Pkt(stderr, "rcvd", pkt, read_len); + RFCNB_Print_Pkt(stderr, "rcvd", pkt, read_len); #endif - return (read_len); + return (read_len); } /* Now, if we got at least a hdr size, alloc space for rest, if we need it */ @@ -321,65 +321,65 @@ RFCNB_Get_Pkt(struct RFCNB_Con *con, struct RFCNB_Pkt *pkt, int len) /* use an iovec ... */ if (len < pkt_len) /* Only get as much as we have space for */ - more = len - RFCNB_Pkt_Hdr_Len; + more = len - RFCNB_Pkt_Hdr_Len; else - more = pkt_len; + more = pkt_len; this_time = 0; /* We read for each fragment ... */ if (pkt->len == read_len) { /* If this frag was exact size */ - pkt_frag = pkt->next; /* Stick next lot in next frag */ - offset = 0; /* then we start at 0 in next */ + pkt_frag = pkt->next; /* Stick next lot in next frag */ + offset = 0; /* then we start at 0 in next */ } else { - pkt_frag = pkt; /* Otherwise use rest of this frag */ - offset = RFCNB_Pkt_Hdr_Len; /* Otherwise skip the header */ + pkt_frag = pkt; /* Otherwise use rest of this frag */ + offset = RFCNB_Pkt_Hdr_Len; /* Otherwise skip the header */ } frag_len = pkt_frag->len; if (more <= frag_len) /* If len left to get less than frag space */ - this_len = more; /* Get the rest ... */ + this_len = more; /* Get the rest ... */ else - this_len = frag_len - offset; + this_len = frag_len - offset; while (more > 0) { - if ((this_time = read(con->fd, (pkt_frag->data) + offset, this_len)) <= 0) { /* Problems */ + if ((this_time = read(con->fd, (pkt_frag->data) + offset, this_len)) <= 0) { /* Problems */ - if (errno == EINTR) { + if (errno == EINTR) { - RFCNB_errno = RFCNB_Timeout; + RFCNB_errno = RFCNB_Timeout; - } else { - if (this_time < 0) - RFCNB_errno = RFCNBE_BadRead; - else - RFCNB_errno = RFCNBE_ConGone; - } + } else { + if (this_time < 0) + RFCNB_errno = RFCNBE_BadRead; + else + RFCNB_errno = RFCNBE_ConGone; + } - RFCNB_saved_errno = errno; - return (RFCNBE_Bad); + RFCNB_saved_errno = errno; + return (RFCNBE_Bad); - } + } #ifdef RFCNB_DEBUG - fprintf(stderr, "Frag_Len = %i, this_time = %i, this_len = %i, more = %i\n", frag_len, - this_time, this_len, more); + fprintf(stderr, "Frag_Len = %i, this_time = %i, this_len = %i, more = %i\n", frag_len, + this_time, this_len, more); #endif - read_len = read_len + this_time; /* How much have we read ... */ + read_len = read_len + this_time; /* How much have we read ... */ - /* Now set up the next part */ + /* Now set up the next part */ - if (pkt_frag->next == NULL) - break; /* That's it here */ + if (pkt_frag->next == NULL) + break; /* That's it here */ - pkt_frag = pkt_frag->next; - this_len = pkt_frag->len; - offset = 0; + pkt_frag = pkt_frag->next; + this_len = pkt_frag->len; + offset = 0; - more = more - this_time; + more = more - this_time; } @@ -390,11 +390,11 @@ RFCNB_Get_Pkt(struct RFCNB_Con *con, struct RFCNB_Pkt *pkt, int len) if (read_len < (pkt_len + sizeof(hdr))) { /* Discard the rest */ - return (RFCNB_Discard_Rest(con, (pkt_len + sizeof(hdr)) - read_len)); + return (RFCNB_Discard_Rest(con, (pkt_len + sizeof(hdr)) - read_len)); } if (RFCNB_Timeout > 0) - alarm(0); /* Reset that sucker */ + alarm(0); /* Reset that sucker */ return (read_len + sizeof(RFCNB_Hdr)); } diff --git a/helpers/ntlm_auth/SMB/smbval/rfcnb-io.h b/helpers/ntlm_auth/SMB/smbval/rfcnb-io.h index 40a96b3629..46180d0030 100644 --- a/helpers/ntlm_auth/SMB/smbval/rfcnb-io.h +++ b/helpers/ntlm_auth/SMB/smbval/rfcnb-io.h @@ -1,10 +1,10 @@ /* UNIX RFCNB (RFC1001/RFC1002) NetBIOS implementation - * + * * Version 1.0 * RFCNB IO Routines Defines - * + * * Copyright (C) Richard Sharpe 1996 - * + * */ /* @@ -12,12 +12,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. diff --git a/helpers/ntlm_auth/SMB/smbval/rfcnb-priv.h b/helpers/ntlm_auth/SMB/smbval/rfcnb-priv.h index 766a66fb92..f7587e7f7e 100644 --- a/helpers/ntlm_auth/SMB/smbval/rfcnb-priv.h +++ b/helpers/ntlm_auth/SMB/smbval/rfcnb-priv.h @@ -2,12 +2,12 @@ #define __RFCNB_H__ /* UNIX RFCNB (RFC1001/RFC1002) NetBIOS implementation - * + * * Version 1.0 * RFCNB Defines - * + * * Copyright (C) Richard Sharpe 1996 - * + * */ /* @@ -15,12 +15,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -77,8 +77,8 @@ typedef struct RFCNB_Con { } RFCNB_Con; typedef char RFCNB_Hdr[4]; /* The header is 4 bytes long with */ - /* char[0] as the type, char[1] the */ - /* flags, and char[2..3] the length */ +/* char[0] as the type, char[1] the */ +/* flags, and char[2..3] the length */ /* Macros to extract things from the header. These are for portability * between architecture types where we are worried about byte order */ @@ -111,13 +111,13 @@ typedef char RFCNB_Hdr[4]; /* The header is 4 bytes long with */ #define RFCNB_Pkt_Type(p) (CVAL(p, RFCNB_Pkt_Type_Offset)) /*typedef struct RFCNB_Hdr { - * + * * unsigned char type; * unsigned char flags; * int16 len; - * + * * } RFCNB_Hdr; - * + * * typedef struct RFCNB_Sess_Pkt { * unsigned char type; * unsigned char flags; @@ -127,21 +127,21 @@ typedef char RFCNB_Hdr[4]; /* The header is 4 bytes long with */ * unsigned char n2_len; * char calling_name[33]; * } RFCNB_Sess_Pkt; - * - * + * + * * typedef struct RFCNB_Nack_Pkt { - * + * * struct RFCNB_Hdr hdr; * unsigned char error; - * + * * } RFCNB_Nack_Pkt; - * + * * typedef struct RFCNB_Retarget_Pkt { - * + * * struct RFCNB_Hdr hdr; * int dest_ip; * unsigned char port; - * + * * } RFCNB_Redir_Pkt; */ /* Static variables */ diff --git a/helpers/ntlm_auth/SMB/smbval/rfcnb-util.c b/helpers/ntlm_auth/SMB/smbval/rfcnb-util.c index a203462dbf..7fcde49ae7 100644 --- a/helpers/ntlm_auth/SMB/smbval/rfcnb-util.c +++ b/helpers/ntlm_auth/SMB/smbval/rfcnb-util.c @@ -1,10 +1,10 @@ /* UNIX RFCNB (RFC1001/RFC1002) NetBIOS implementation - * + * * Version 1.0 * RFCNB Utility Routines ... - * + * * Copyright (C) Richard Sharpe 1996 - * + * */ /* @@ -12,12 +12,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -49,20 +49,20 @@ RFCNB_CvtPad_Name(char *name1, char *name2) for (i = 0; i < 16; i++) { - if (i >= len) { + if (i >= len) { - c1 = 'C'; - c2 = 'A'; /* CA is a space */ + c1 = 'C'; + c2 = 'A'; /* CA is a space */ - } else { + } else { - c = name1[i]; - c1 = (char) ((int) c / 16 + (int) 'A'); - c2 = (char) ((int) c % 16 + (int) 'A'); - } + c = name1[i]; + c1 = (char) ((int) c / 16 + (int) 'A'); + c2 = (char) ((int) c % 16 + (int) 'A'); + } - name2[i * 2] = c1; - name2[i * 2 + 1] = c2; + name2[i * 2] = c1; + name2[i * 2 + 1] = c2; } @@ -73,10 +73,10 @@ RFCNB_CvtPad_Name(char *name1, char *name2) /* Converts an Ascii NB Name (16 chars) to an RFCNB Name (32 chars) * Uses the encoding in RFC1001. Each nibble of byte is added to 'A' * to produce the next byte in the name. - * - * This routine assumes that AName is 16 bytes long and that NBName has - * space for 32 chars, so be careful ... - * + * + * This routine assumes that AName is 16 bytes long and that NBName has + * space for 32 chars, so be careful ... + * */ void @@ -87,13 +87,13 @@ RFCNB_AName_To_NBName(char *AName, char *NBName) for (i = 0; i < 16; i++) { - c = AName[i]; + c = AName[i]; - c1 = (char) ((c >> 4) + 'A'); - c2 = (char) ((c & 0xF) + 'A'); + c1 = (char) ((c >> 4) + 'A'); + c2 = (char) ((c & 0xF) + 'A'); - NBName[i * 2] = c1; - NBName[i * 2 + 1] = c2; + NBName[i * 2] = c1; + NBName[i * 2 + 1] = c2; } NBName[32] = 0; /* Put in a null */ @@ -110,12 +110,12 @@ RFCNB_NBName_To_AName(char *NBName, char *AName) for (i = 0; i < 16; i++) { - c1 = NBName[i * 2]; - c2 = NBName[i * 2 + 1]; + c1 = NBName[i * 2]; + c2 = NBName[i * 2 + 1]; - c = (char) (((int) c1 - (int) 'A') * 16 + ((int) c2 - (int) 'A')); + c = (char) (((int) c1 - (int) 'A') * 16 + ((int) c2 - (int) 'A')); - AName[i] = c; + AName[i] = c; } @@ -140,27 +140,27 @@ RFCNB_Print_Hex(FILE * fd, struct RFCNB_Pkt *pkt, int Offset, int Len) while (pkt_ptr != NULL) { - for (i = 0; - i < ((Len > (pkt_ptr->len) ? pkt_ptr->len : Len) - Offset); - i++) { + for (i = 0; + i < ((Len > (pkt_ptr->len) ? pkt_ptr->len : Len) - Offset); + i++) { - c = pkt_ptr->data[i + Offset]; - c1 = Hex_List[c >> 4]; - c2 = Hex_List[c & 0xF]; + c = pkt_ptr->data[i + Offset]; + c1 = Hex_List[c >> 4]; + c2 = Hex_List[c & 0xF]; - outbuf1[j++] = c1; - outbuf1[j++] = c2; + outbuf1[j++] = c1; + outbuf1[j++] = c2; - if (j == 32) { /* Print and reset */ - outbuf1[j] = 0; - fprintf(fd, " %s\n", outbuf1); - j = 0; - } - } + if (j == 32) { /* Print and reset */ + outbuf1[j] = 0; + fprintf(fd, " %s\n", outbuf1); + j = 0; + } + } - Offset = 0; - Len = Len - pkt_ptr->len; /* Reduce amount by this much */ - pkt_ptr = pkt_ptr->next; + Offset = 0; + Len = Len - pkt_ptr->len; /* Reduce amount by this much */ + pkt_ptr = pkt_ptr->next; } @@ -168,8 +168,8 @@ RFCNB_Print_Hex(FILE * fd, struct RFCNB_Pkt *pkt, int Offset, int Len) if (j > 0) { - outbuf1[j] = 0; - fprintf(fd, " %s\n", outbuf1); + outbuf1[j] = 0; + fprintf(fd, " %s\n", outbuf1); } fprintf(fd, "\n"); @@ -179,29 +179,28 @@ RFCNB_Print_Hex(FILE * fd, struct RFCNB_Pkt *pkt, int Offset, int Len) /* Get a packet of size n */ struct RFCNB_Pkt * -RFCNB_Alloc_Pkt(int n) -{ + RFCNB_Alloc_Pkt(int n) { RFCNB_Pkt *pkt; if ((pkt = (struct RFCNB_Pkt *) malloc(sizeof(struct RFCNB_Pkt))) == NULL) { - RFCNB_errno = RFCNBE_NoSpace; - RFCNB_saved_errno = errno; - return (NULL); + RFCNB_errno = RFCNBE_NoSpace; + RFCNB_saved_errno = errno; + return (NULL); } pkt->next = NULL; pkt->len = n; if (n == 0) - return (pkt); + return (pkt); if ((pkt->data = (char *) malloc(n)) == NULL) { - RFCNB_errno = RFCNBE_NoSpace; - RFCNB_saved_errno = errno; - free(pkt); - return (NULL); + RFCNB_errno = RFCNBE_NoSpace; + RFCNB_saved_errno = errno; + free(pkt); + return (NULL); } return (pkt); @@ -218,16 +217,16 @@ RFCNB_Free_Pkt(struct RFCNB_Pkt *pkt) while (pkt != NULL) { - pkt_next = pkt->next; + pkt_next = pkt->next; - data_ptr = pkt->data; + data_ptr = pkt->data; - if (data_ptr != NULL) - free(data_ptr); + if (data_ptr != NULL) + free(data_ptr); - free(pkt); + free(pkt); - pkt = pkt_next; + pkt = pkt_next; } @@ -249,70 +248,70 @@ RFCNB_Print_Pkt(FILE * fd, char *dirn, struct RFCNB_Pkt *pkt, int len) case RFCNB_SESSION_MESSAGE: - fprintf(fd, "SESSION MESSAGE: Length = %i\n", RFCNB_Pkt_Len(pkt->data)); - RFCNB_Print_Hex(fd, pkt, RFCNB_Pkt_Hdr_Len, + fprintf(fd, "SESSION MESSAGE: Length = %i\n", RFCNB_Pkt_Len(pkt->data)); + RFCNB_Print_Hex(fd, pkt, RFCNB_Pkt_Hdr_Len, #ifdef RFCNB_PRINT_DATA - RFCNB_Pkt_Len(pkt->data) - RFCNB_Pkt_Hdr_Len); + RFCNB_Pkt_Len(pkt->data) - RFCNB_Pkt_Hdr_Len); #else - 40); + 40); #endif - if (Prot_Print_Routine != 0) { /* Print the rest of the packet */ + if (Prot_Print_Routine != 0) { /* Print the rest of the packet */ - Prot_Print_Routine(fd, strcmp(dirn, "sent"), pkt, RFCNB_Pkt_Hdr_Len, - RFCNB_Pkt_Len(pkt->data) - RFCNB_Pkt_Hdr_Len); + Prot_Print_Routine(fd, strcmp(dirn, "sent"), pkt, RFCNB_Pkt_Hdr_Len, + RFCNB_Pkt_Len(pkt->data) - RFCNB_Pkt_Hdr_Len); - } - break; + } + break; case RFCNB_SESSION_REQUEST: - fprintf(fd, "SESSION REQUEST: Length = %i\n", - RFCNB_Pkt_Len(pkt->data)); - RFCNB_NBName_To_AName((char *) (pkt->data + RFCNB_Pkt_Called_Offset), lname); - fprintf(fd, " Called Name: %s\n", lname); - RFCNB_NBName_To_AName((char *) (pkt->data + RFCNB_Pkt_Calling_Offset), lname); - fprintf(fd, " Calling Name: %s\n", lname); + fprintf(fd, "SESSION REQUEST: Length = %i\n", + RFCNB_Pkt_Len(pkt->data)); + RFCNB_NBName_To_AName((char *) (pkt->data + RFCNB_Pkt_Called_Offset), lname); + fprintf(fd, " Called Name: %s\n", lname); + RFCNB_NBName_To_AName((char *) (pkt->data + RFCNB_Pkt_Calling_Offset), lname); + fprintf(fd, " Calling Name: %s\n", lname); - break; + break; case RFCNB_SESSION_ACK: - fprintf(fd, "RFCNB SESSION ACK: Length = %i\n", - RFCNB_Pkt_Len(pkt->data)); + fprintf(fd, "RFCNB SESSION ACK: Length = %i\n", + RFCNB_Pkt_Len(pkt->data)); - break; + break; case RFCNB_SESSION_REJ: - fprintf(fd, "RFCNB SESSION REJECT: Length = %i\n", - RFCNB_Pkt_Len(pkt->data)); + fprintf(fd, "RFCNB SESSION REJECT: Length = %i\n", + RFCNB_Pkt_Len(pkt->data)); - if (RFCNB_Pkt_Len(pkt->data) < 1) { - fprintf(fd, " Protocol Error, short Reject packet!\n"); - } else { - fprintf(fd, " Error = %x\n", CVAL(pkt->data, RFCNB_Pkt_Error_Offset)); - } + if (RFCNB_Pkt_Len(pkt->data) < 1) { + fprintf(fd, " Protocol Error, short Reject packet!\n"); + } else { + fprintf(fd, " Error = %x\n", CVAL(pkt->data, RFCNB_Pkt_Error_Offset)); + } - break; + break; case RFCNB_SESSION_RETARGET: - fprintf(fd, "RFCNB SESSION RETARGET: Length = %i\n", - RFCNB_Pkt_Len(pkt->data)); + fprintf(fd, "RFCNB SESSION RETARGET: Length = %i\n", + RFCNB_Pkt_Len(pkt->data)); - /* Print out the IP address etc and the port? */ + /* Print out the IP address etc and the port? */ - break; + break; case RFCNB_SESSION_KEEP_ALIVE: - fprintf(fd, "RFCNB SESSION KEEP ALIVE: Length = %i\n", - RFCNB_Pkt_Len(pkt->data)); - break; + fprintf(fd, "RFCNB SESSION KEEP ALIVE: Length = %i\n", + RFCNB_Pkt_Len(pkt->data)); + break; default: - break; + break; } } @@ -329,21 +328,21 @@ RFCNB_Name_To_IP(char *host, struct in_addr *Dest_IP) if ((addr = inet_addr(host)) == INADDR_NONE) { /* Oh well, a good try :-) */ - /* Now try a name look up with gethostbyname */ + /* Now try a name look up with gethostbyname */ - if ((hp = gethostbyname(host)) == NULL) { /* Not in DNS */ + if ((hp = gethostbyname(host)) == NULL) { /* Not in DNS */ - /* Try NetBIOS name lookup, how the hell do we do that? */ + /* Try NetBIOS name lookup, how the hell do we do that? */ - RFCNB_errno = RFCNBE_BadName; /* Is this right? */ - RFCNB_saved_errno = errno; - return (RFCNBE_Bad); + RFCNB_errno = RFCNBE_BadName; /* Is this right? */ + RFCNB_saved_errno = errno; + return (RFCNBE_Bad); - } else { /* We got a name */ - Dest_IP->s_addr = (*((struct in_addr*)hp->h_addr_list[0])).s_addr; - } + } else { /* We got a name */ + Dest_IP->s_addr = (*((struct in_addr*)hp->h_addr_list[0])).s_addr; + } } else { /* It was an IP address */ - Dest_IP->s_addr = addr; + Dest_IP->s_addr = addr; } return 0; @@ -377,9 +376,9 @@ RFCNB_IP_Connect(struct in_addr Dest_IP, int port) if ((fd = socket(PF_INET, SOCK_STREAM, 0)) < 0) { /* Handle the error */ - RFCNB_errno = RFCNBE_BadSocket; - RFCNB_saved_errno = errno; - return (RFCNBE_Bad); + RFCNB_errno = RFCNBE_BadSocket; + RFCNB_saved_errno = errno; + return (RFCNBE_Bad); } memset((char *) &Socket, 0, sizeof(Socket)); memcpy((char *) &Socket.sin_addr, (char *) &Dest_IP, sizeof(Dest_IP)); @@ -391,27 +390,27 @@ RFCNB_IP_Connect(struct in_addr Dest_IP, int port) if (connect(fd, (struct sockaddr *) &Socket, sizeof(Socket)) < 0) { /* Error */ - close(fd); - RFCNB_errno = RFCNBE_ConnectFailed; - RFCNB_saved_errno = errno; - return (RFCNBE_Bad); + close(fd); + RFCNB_errno = RFCNBE_ConnectFailed; + RFCNB_saved_errno = errno; + return (RFCNBE_Bad); } return (fd); } -/* handle the details of establishing the RFCNB session with remote - * end - * +/* handle the details of establishing the RFCNB session with remote + * end + * */ int RFCNB_Session_Req(struct RFCNB_Con *con, - char *Called_Name, - char *Calling_Name, - BOOL * redirect, - struct in_addr *Dest_IP, - int *port) + char *Called_Name, + char *Calling_Name, + BOOL * redirect, + struct in_addr *Dest_IP, + int *port) { char *sess_pkt; @@ -427,7 +426,7 @@ RFCNB_Session_Req(struct RFCNB_Con *con, if (pkt == NULL) { - return (RFCNBE_Bad); /* Leave the error that RFCNB_Alloc_Pkt gives) */ + return (RFCNBE_Bad); /* Leave the error that RFCNB_Alloc_Pkt gives) */ } sess_pkt = pkt->data; /* Get pointer to packet proper */ @@ -450,7 +449,7 @@ RFCNB_Session_Req(struct RFCNB_Con *con, if ((len = RFCNB_Put_Pkt(con, pkt, RFCNB_Pkt_Sess_Len)) < 0) { - return (RFCNBE_Bad); /* Should be able to write that lot ... */ + return (RFCNBE_Bad); /* Should be able to write that lot ... */ } #ifdef RFCNB_DEBUG @@ -465,7 +464,7 @@ RFCNB_Session_Req(struct RFCNB_Con *con, if ((len = RFCNB_Get_Pkt(con, &res_pkt, sizeof(resp))) < 0) { - return (RFCNBE_Bad); + return (RFCNBE_Bad); } /* Now analyze the packet ... */ @@ -474,52 +473,52 @@ RFCNB_Session_Req(struct RFCNB_Con *con, case RFCNB_SESSION_REJ: /* Didnt like us ... too bad */ - /* Why did we get rejected ? */ - - switch (CVAL(resp, RFCNB_Pkt_Error_Offset)) { - - case 0x80: - RFCNB_errno = RFCNBE_CallRejNLOCN; - break; - case 0x81: - RFCNB_errno = RFCNBE_CallRejNLFCN; - break; - case 0x82: - RFCNB_errno = RFCNBE_CallRejCNNP; - break; - case 0x83: - RFCNB_errno = RFCNBE_CallRejInfRes; - break; - case 0x8F: - RFCNB_errno = RFCNBE_CallRejUnSpec; - break; - default: - RFCNB_errno = RFCNBE_ProtErr; - break; - } - - return (RFCNBE_Bad); - break; + /* Why did we get rejected ? */ + + switch (CVAL(resp, RFCNB_Pkt_Error_Offset)) { + + case 0x80: + RFCNB_errno = RFCNBE_CallRejNLOCN; + break; + case 0x81: + RFCNB_errno = RFCNBE_CallRejNLFCN; + break; + case 0x82: + RFCNB_errno = RFCNBE_CallRejCNNP; + break; + case 0x83: + RFCNB_errno = RFCNBE_CallRejInfRes; + break; + case 0x8F: + RFCNB_errno = RFCNBE_CallRejUnSpec; + break; + default: + RFCNB_errno = RFCNBE_ProtErr; + break; + } + + return (RFCNBE_Bad); + break; case RFCNB_SESSION_ACK: /* Got what we wanted ... */ - return (0); - break; + return (0); + break; case RFCNB_SESSION_RETARGET: /* Go elsewhere */ - *redirect = TRUE; /* Copy port and ip addr */ + *redirect = TRUE; /* Copy port and ip addr */ - memcpy(Dest_IP, (resp + RFCNB_Pkt_IP_Offset), sizeof(struct in_addr)); - *port = SVAL(resp, RFCNB_Pkt_Port_Offset); + memcpy(Dest_IP, (resp + RFCNB_Pkt_IP_Offset), sizeof(struct in_addr)); + *port = SVAL(resp, RFCNB_Pkt_Port_Offset); - return (0); - break; + return (0); + break; default: /* A protocol error */ - RFCNB_errno = RFCNBE_ProtErr; - return (RFCNBE_Bad); - break; + RFCNB_errno = RFCNBE_ProtErr; + return (RFCNBE_Bad); + break; } } diff --git a/helpers/ntlm_auth/SMB/smbval/rfcnb-util.h b/helpers/ntlm_auth/SMB/smbval/rfcnb-util.h index 123c9cba29..34ab9aa85f 100644 --- a/helpers/ntlm_auth/SMB/smbval/rfcnb-util.h +++ b/helpers/ntlm_auth/SMB/smbval/rfcnb-util.h @@ -1,10 +1,10 @@ /* UNIX RFCNB (RFC1001/RFC1002) NetBIOS implementation - * + * * Version 1.0 * RFCNB Utility Defines - * + * * Copyright (C) Richard Sharpe 1996 - * + * */ /* @@ -12,12 +12,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -45,8 +45,8 @@ int RFCNB_Close(int socket); int RFCNB_IP_Connect(struct in_addr Dest_IP, int port); int RFCNB_Session_Req(struct RFCNB_Con *con, - char *Called_Name, - char *Calling_Name, - BOOL * redirect, - struct in_addr *Dest_IP, - int *port); + char *Called_Name, + char *Calling_Name, + BOOL * redirect, + struct in_addr *Dest_IP, + int *port); diff --git a/helpers/ntlm_auth/SMB/smbval/rfcnb.h b/helpers/ntlm_auth/SMB/smbval/rfcnb.h index cd071f62e4..fb8bc207d0 100644 --- a/helpers/ntlm_auth/SMB/smbval/rfcnb.h +++ b/helpers/ntlm_auth/SMB/smbval/rfcnb.h @@ -1,10 +1,10 @@ /* UNIX RFCNB (RFC1001/RFC1002) NetBIOS implementation - * + * * Version 1.0 * RFCNB Defines - * + * * Copyright (C) Richard Sharpe 1996 - * + * */ /* @@ -12,12 +12,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -36,7 +36,7 @@ /* Definition of routines we define */ void *RFCNB_Call(char *Called_Name, char *Calling_Name, char *Called_Address, - int port); + int port); int RFCNB_Send(void *Con_Handle, struct RFCNB_Pkt *Data, int Length); diff --git a/helpers/ntlm_auth/SMB/smbval/session.c b/helpers/ntlm_auth/SMB/smbval/session.c index 08ef888d42..14a9401165 100644 --- a/helpers/ntlm_auth/SMB/smbval/session.c +++ b/helpers/ntlm_auth/SMB/smbval/session.c @@ -1,10 +1,10 @@ /* UNIX RFCNB (RFC1001/RFC1002) NetBIOS implementation - * + * * Version 1.0 * Session Routines ... - * + * * Copyright (C) Richard Sharpe 1996 - * + * */ /* @@ -12,12 +12,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -38,8 +38,7 @@ int RFCNB_saved_errno = 0; /* global data structures */ -char *RFCNB_Error_Strings[] = -{ +char *RFCNB_Error_Strings[] = { "RFCNBE_OK: Routine completed successfully.", "RFCNBE_NoSpace: No space available for a malloc call.", @@ -68,13 +67,13 @@ void (*Prot_Print_Routine) () = NULL; /* Pointer to print routine */ /* Set up a session with a remote name. We are passed Called_Name as a * string which we convert to a NetBIOS name, ie space terminated, up to * 16 characters only if we need to. If Called_Address is not empty, then - * we use it to connect to the remote end, but put in Called_Name ... Called + * we use it to connect to the remote end, but put in Called_Name ... Called * Address can be a DNS based name, or a TCP/IP address ... */ void * RFCNB_Call(char *Called_Name, char *Calling_Name, char *Called_Address, - int port) + int port) { struct RFCNB_Con *con; struct in_addr Dest_IP; @@ -86,15 +85,15 @@ RFCNB_Call(char *Called_Name, char *Calling_Name, char *Called_Address, /* Now, we really should look up the port in /etc/services ... */ if (port == 0) - port = RFCNB_Default_Port; + port = RFCNB_Default_Port; /* Create a connection structure first */ if ((con = (struct RFCNB_Con *) malloc(sizeof(struct RFCNB_Con))) == NULL) { /* Error in size */ - RFCNB_errno = RFCNBE_NoSpace; - RFCNB_saved_errno = errno; - return (NULL); + RFCNB_errno = RFCNBE_NoSpace; + RFCNB_saved_errno = errno; + return (NULL); } con->fd = -0; /* no descriptor yet */ @@ -107,13 +106,13 @@ RFCNB_Call(char *Called_Name, char *Calling_Name, char *Called_Address, Service_Address = Called_Name; if (strcmp(Called_Address, "") != 0) { /* If the Called Address = "" */ - Service_Address = Called_Address; + Service_Address = Called_Address; } if ((errno = RFCNB_Name_To_IP(Service_Address, &Dest_IP)) < 0) { /* Error */ - /* No need to modify RFCNB_errno as it was done by RFCNB_Name_To_IP */ + /* No need to modify RFCNB_errno as it was done by RFCNB_Name_To_IP */ free(con); - return (NULL); + return (NULL); } /* Now connect to the remote end */ @@ -122,76 +121,76 @@ RFCNB_Call(char *Called_Name, char *Calling_Name, char *Called_Address, while (redirect) { /* Connect and get session info etc */ - redirect = FALSE; /* Assume all OK */ + redirect = FALSE; /* Assume all OK */ - /* Build the redirect info. First one is first addr called */ - /* And tack it onto the list of addresses we called */ + /* Build the redirect info. First one is first addr called */ + /* And tack it onto the list of addresses we called */ - if ((redir_addr = (struct redirect_addr *) malloc(sizeof(struct redirect_addr))) == NULL) { /* Could not get space */ + if ((redir_addr = (struct redirect_addr *) malloc(sizeof(struct redirect_addr))) == NULL) { /* Could not get space */ - RFCNB_errno = RFCNBE_NoSpace; - RFCNB_saved_errno = errno; + RFCNB_errno = RFCNBE_NoSpace; + RFCNB_saved_errno = errno; free(con); - return (NULL); + return (NULL); - } - memcpy((char *) &(redir_addr->ip_addr), (char *) &Dest_IP, sizeof(Dest_IP)); - redir_addr->port = port; - redir_addr->next = NULL; + } + memcpy((char *) &(redir_addr->ip_addr), (char *) &Dest_IP, sizeof(Dest_IP)); + redir_addr->port = port; + redir_addr->next = NULL; - if (con->redirect_list == NULL) { /* Stick on head */ + if (con->redirect_list == NULL) { /* Stick on head */ - con->redirect_list = con->last_addr = redir_addr; + con->redirect_list = con->last_addr = redir_addr; - } else { + } else { - con->last_addr->next = redir_addr; - con->last_addr = redir_addr; + con->last_addr->next = redir_addr; + con->last_addr = redir_addr; - } + } - /* Now, make that connection */ + /* Now, make that connection */ - if ((Client = RFCNB_IP_Connect(Dest_IP, port)) < 0) { /* Error */ + if ((Client = RFCNB_IP_Connect(Dest_IP, port)) < 0) { /* Error */ - /* No need to modify RFCNB_errno as it was done by RFCNB_IP_Connect */ + /* No need to modify RFCNB_errno as it was done by RFCNB_IP_Connect */ free(con); - return (NULL); + return (NULL); - } - con->fd = Client; + } + con->fd = Client; - /* Now send and handle the RFCNB session request */ - /* If we get a redirect, we will comeback with redirect true - * and a new IP address in DEST_IP */ + /* Now send and handle the RFCNB session request */ + /* If we get a redirect, we will comeback with redirect true + * and a new IP address in DEST_IP */ - if ((errno = RFCNB_Session_Req(con, - Called_Name, - Calling_Name, - &redirect, &Dest_IP, &port)) < 0) { + if ((errno = RFCNB_Session_Req(con, + Called_Name, + Calling_Name, + &redirect, &Dest_IP, &port)) < 0) { - /* No need to modify RFCNB_errno as it was done by RFCNB_Session.. */ - RFCNB_Close(con->fd); /* Close it */ + /* No need to modify RFCNB_errno as it was done by RFCNB_Session.. */ + RFCNB_Close(con->fd); /* Close it */ free(con); - return (NULL); + return (NULL); - } - if (redirect) { + } + if (redirect) { - /* We have to close the connection, and then try again */ + /* We have to close the connection, and then try again */ - (con->redirects)++; + (con->redirects)++; - RFCNB_Close(con->fd); /* Close it */ + RFCNB_Close(con->fd); /* Close it */ - } + } } return (con); } -/* We send a packet to the other end ... for the moment, we treat the +/* We send a packet to the other end ... for the moment, we treat the * data as a series of pointers to blocks of data ... we should check the * length ... */ @@ -208,9 +207,9 @@ RFCNB_Send(struct RFCNB_Con *Con_Handle, struct RFCNB_Pkt *udata, int Length) if (pkt == NULL) { - RFCNB_errno = RFCNBE_NoSpace; - RFCNB_saved_errno = errno; - return (RFCNBE_Bad); + RFCNB_errno = RFCNBE_NoSpace; + RFCNB_saved_errno = errno; + return (RFCNBE_Bad); } pkt->next = udata; /* The user data we want to send */ @@ -230,9 +229,9 @@ RFCNB_Send(struct RFCNB_Con *Con_Handle, struct RFCNB_Pkt *udata, int Length) if ((len = RFCNB_Put_Pkt(Con_Handle, pkt, Length + RFCNB_Pkt_Hdr_Len)) < 0) { - /* No need to change RFCNB_errno as it was done by put_pkt ... */ + /* No need to change RFCNB_errno as it was done by put_pkt ... */ - return (RFCNBE_Bad); /* Should be able to write that lot ... */ + return (RFCNBE_Bad); /* Should be able to write that lot ... */ } /* Now we have sent that lot, let's get rid of the RFCNB Header and return */ @@ -245,7 +244,7 @@ RFCNB_Send(struct RFCNB_Con *Con_Handle, struct RFCNB_Pkt *udata, int Length) } -/* We pick up a message from the internet ... We have to worry about +/* We pick up a message from the internet ... We have to worry about * non-message packets ... */ int @@ -256,9 +255,9 @@ RFCNB_Recv(void *con_Handle, struct RFCNB_Pkt *Data, int Length) if (con_Handle == NULL) { - RFCNB_errno = RFCNBE_BadHandle; - RFCNB_saved_errno = errno; - return (RFCNBE_Bad); + RFCNB_errno = RFCNBE_BadHandle; + RFCNB_saved_errno = errno; + return (RFCNBE_Bad); } /* Now get a packet from below. We allocate a header first */ @@ -269,9 +268,9 @@ RFCNB_Recv(void *con_Handle, struct RFCNB_Pkt *Data, int Length) if (pkt == NULL) { - RFCNB_errno = RFCNBE_NoSpace; - RFCNB_saved_errno = errno; - return (RFCNBE_Bad); + RFCNB_errno = RFCNBE_NoSpace; + RFCNB_saved_errno = errno; + return (RFCNBE_Bad); } pkt->next = Data; /* Plug in the data portion */ @@ -279,10 +278,10 @@ RFCNB_Recv(void *con_Handle, struct RFCNB_Pkt *Data, int Length) if ((ret_len = RFCNB_Get_Pkt(con_Handle, pkt, Length + RFCNB_Pkt_Hdr_Len)) < 0) { #ifdef RFCNB_DEBUG - fprintf(stderr, "Bad packet return in RFCNB_Recv... \n"); + fprintf(stderr, "Bad packet return in RFCNB_Recv... \n"); #endif - return (RFCNBE_Bad); + return (RFCNBE_Bad); } /* We should check that we go a message and not a keep alive */ @@ -303,8 +302,8 @@ RFCNB_Hangup(struct RFCNB_Con *con_Handle) { if (con_Handle != NULL) { - RFCNB_Close(con_Handle->fd); /* Could this fail? */ - free(con_Handle); + RFCNB_Close(con_Handle->fd); /* Could this fail? */ + free(con_Handle); } return 0; @@ -318,7 +317,7 @@ RFCNB_Set_Sock_NoDelay(struct RFCNB_Con *con_Handle, BOOL yn) { return (setsockopt(con_Handle->fd, IPPROTO_TCP, TCP_NODELAY, - (char *) &yn, sizeof(yn))); + (char *) &yn, sizeof(yn))); } @@ -341,10 +340,10 @@ RFCNB_Get_Error(char *buffer, int buf_len) { if (RFCNB_saved_errno <= 0) { - sprintf(buffer, "%s", RFCNB_Error_Strings[RFCNB_errno]); + sprintf(buffer, "%s", RFCNB_Error_Strings[RFCNB_errno]); } else { - sprintf(buffer, "%s\n\terrno:%s", RFCNB_Error_Strings[RFCNB_errno], - strerror(RFCNB_saved_errno)); + sprintf(buffer, "%s\n\terrno:%s", RFCNB_Error_Strings[RFCNB_errno], + strerror(RFCNB_saved_errno)); } } diff --git a/helpers/ntlm_auth/SMB/smbval/smbdes.c b/helpers/ntlm_auth/SMB/smbval/smbdes.c index a9ac145c1e..8b0ccdfb7f 100644 --- a/helpers/ntlm_auth/SMB/smbval/smbdes.c +++ b/helpers/ntlm_auth/SMB/smbval/smbdes.c @@ -1,43 +1,43 @@ -/* +/* * Unix SMB/Netbios implementation. * Version 1.9. - * - * a partial implementation of DES designed for use in the + * + * a partial implementation of DES designed for use in the * SMB authentication protocol - * + * * Copyright (C) Andrew Tridgell 1997 - * + * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ -/* NOTES: - * +/* NOTES: + * * This code makes no attempt to be fast! In fact, it is a very - * slow implementation - * + * slow implementation + * * This code is NOT a complete DES implementation. It implements only * the minimum necessary for SMB authentication, as used by all SMB * products (including every copy of Microsoft Windows95 ever sold) - * + * * In particular, it can only do a unchained forward DES pass. This * means it is not possible to use this code for encryption/decryption * of data, instead it is only useful as a "hash" algorithm. - * + * * There is no entry point into this code that allows normal DES operation. - * + * * I believe this means that this code does not come under ITAR * regulations but this is NOT a legal opinion. If you are concerned * about the applicability of ITAR regulations to this code then you @@ -47,127 +47,126 @@ -static int perm1[56] = -{57, 49, 41, 33, 25, 17, 9, - 1, 58, 50, 42, 34, 26, 18, - 10, 2, 59, 51, 43, 35, 27, - 19, 11, 3, 60, 52, 44, 36, - 63, 55, 47, 39, 31, 23, 15, - 7, 62, 54, 46, 38, 30, 22, - 14, 6, 61, 53, 45, 37, 29, - 21, 13, 5, 28, 20, 12, 4}; - -static int perm2[48] = -{14, 17, 11, 24, 1, 5, - 3, 28, 15, 6, 21, 10, - 23, 19, 12, 4, 26, 8, - 16, 7, 27, 20, 13, 2, - 41, 52, 31, 37, 47, 55, - 30, 40, 51, 45, 33, 48, - 44, 49, 39, 56, 34, 53, - 46, 42, 50, 36, 29, 32}; - -static int perm3[64] = -{58, 50, 42, 34, 26, 18, 10, 2, - 60, 52, 44, 36, 28, 20, 12, 4, - 62, 54, 46, 38, 30, 22, 14, 6, - 64, 56, 48, 40, 32, 24, 16, 8, - 57, 49, 41, 33, 25, 17, 9, 1, - 59, 51, 43, 35, 27, 19, 11, 3, - 61, 53, 45, 37, 29, 21, 13, 5, - 63, 55, 47, 39, 31, 23, 15, 7}; - -static int perm4[48] = -{32, 1, 2, 3, 4, 5, - 4, 5, 6, 7, 8, 9, - 8, 9, 10, 11, 12, 13, - 12, 13, 14, 15, 16, 17, - 16, 17, 18, 19, 20, 21, - 20, 21, 22, 23, 24, 25, - 24, 25, 26, 27, 28, 29, - 28, 29, 30, 31, 32, 1}; - -static int perm5[32] = -{16, 7, 20, 21, - 29, 12, 28, 17, - 1, 15, 23, 26, - 5, 18, 31, 10, - 2, 8, 24, 14, - 32, 27, 3, 9, - 19, 13, 30, 6, - 22, 11, 4, 25}; - - -static int perm6[64] = -{40, 8, 48, 16, 56, 24, 64, 32, - 39, 7, 47, 15, 55, 23, 63, 31, - 38, 6, 46, 14, 54, 22, 62, 30, - 37, 5, 45, 13, 53, 21, 61, 29, - 36, 4, 44, 12, 52, 20, 60, 28, - 35, 3, 43, 11, 51, 19, 59, 27, - 34, 2, 42, 10, 50, 18, 58, 26, - 33, 1, 41, 9, 49, 17, 57, 25}; - - -static int sc[16] = -{1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1}; - -static int sbox[8][4][16] = -{ +static int perm1[56] = {57, 49, 41, 33, 25, 17, 9, + 1, 58, 50, 42, 34, 26, 18, + 10, 2, 59, 51, 43, 35, 27, + 19, 11, 3, 60, 52, 44, 36, + 63, 55, 47, 39, 31, 23, 15, + 7, 62, 54, 46, 38, 30, 22, + 14, 6, 61, 53, 45, 37, 29, + 21, 13, 5, 28, 20, 12, 4 + }; + +static int perm2[48] = {14, 17, 11, 24, 1, 5, + 3, 28, 15, 6, 21, 10, + 23, 19, 12, 4, 26, 8, + 16, 7, 27, 20, 13, 2, + 41, 52, 31, 37, 47, 55, + 30, 40, 51, 45, 33, 48, + 44, 49, 39, 56, 34, 53, + 46, 42, 50, 36, 29, 32 + }; + +static int perm3[64] = {58, 50, 42, 34, 26, 18, 10, 2, + 60, 52, 44, 36, 28, 20, 12, 4, + 62, 54, 46, 38, 30, 22, 14, 6, + 64, 56, 48, 40, 32, 24, 16, 8, + 57, 49, 41, 33, 25, 17, 9, 1, + 59, 51, 43, 35, 27, 19, 11, 3, + 61, 53, 45, 37, 29, 21, 13, 5, + 63, 55, 47, 39, 31, 23, 15, 7 + }; + +static int perm4[48] = {32, 1, 2, 3, 4, 5, + 4, 5, 6, 7, 8, 9, + 8, 9, 10, 11, 12, 13, + 12, 13, 14, 15, 16, 17, + 16, 17, 18, 19, 20, 21, + 20, 21, 22, 23, 24, 25, + 24, 25, 26, 27, 28, 29, + 28, 29, 30, 31, 32, 1 + }; + +static int perm5[32] = {16, 7, 20, 21, + 29, 12, 28, 17, + 1, 15, 23, 26, + 5, 18, 31, 10, + 2, 8, 24, 14, + 32, 27, 3, 9, + 19, 13, 30, 6, + 22, 11, 4, 25 + }; + + +static int perm6[64] = {40, 8, 48, 16, 56, 24, 64, 32, + 39, 7, 47, 15, 55, 23, 63, 31, + 38, 6, 46, 14, 54, 22, 62, 30, + 37, 5, 45, 13, 53, 21, 61, 29, + 36, 4, 44, 12, 52, 20, 60, 28, + 35, 3, 43, 11, 51, 19, 59, 27, + 34, 2, 42, 10, 50, 18, 58, 26, + 33, 1, 41, 9, 49, 17, 57, 25 + }; + + +static int sc[16] = {1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1}; + +static int sbox[8][4][16] = { { - {14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7}, - {0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8}, - {4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0}, - {15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13}}, + {14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7}, + {0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8}, + {4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0}, + {15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13}}, { - {15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10}, - {3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5}, - {0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15}, - {13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9}}, + {15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10}, + {3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5}, + {0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15}, + {13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9}}, { - {10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8}, - {13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1}, - {13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7}, - {1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12}}, + {10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8}, + {13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1}, + {13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7}, + {1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12}}, { - {7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15}, - {13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9}, - {10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4}, - {3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14}}, + {7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15}, + {13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9}, + {10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4}, + {3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14}}, { - {2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9}, - {14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6}, - {4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14}, - {11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3}}, + {2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9}, + {14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6}, + {4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14}, + {11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3}}, { - {12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11}, - {10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8}, - {9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6}, - {4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13}}, + {12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11}, + {10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8}, + {9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6}, + {4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13}}, { - {4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1}, - {13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6}, - {1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2}, - {6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12}}, + {4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1}, + {13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6}, + {1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2}, + {6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12}}, { - {13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7}, - {1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2}, - {7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8}, - {2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11}}}; + {13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7}, + {1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2}, + {7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8}, + {2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11}} +}; static void permute(char *out, char *in, int *p, int n) { int i; for (i = 0; i < n; i++) - out[i] = in[p[i] - 1]; + out[i] = in[p[i] - 1]; } static void @@ -176,18 +175,18 @@ lshift(char *d, int count, int n) char out[64]; int i; for (i = 0; i < n; i++) - out[i] = d[(i + count) % n]; + out[i] = d[(i + count) % n]; for (i = 0; i < n; i++) - d[i] = out[i]; + d[i] = out[i]; } static void concat(char *out, char *in1, char *in2, int l1, int l2) { while (l1--) - *out++ = *in1++; + *out++ = *in1++; while (l2--) - *out++ = *in2++; + *out++ = *in2++; } static void @@ -195,7 +194,7 @@ xor(char *out, char *in1, char *in2, int n) { int i; for (i = 0; i < n; i++) - out[i] = in1[i] ^ in2[i]; + out[i] = in1[i] ^ in2[i]; } static void @@ -214,63 +213,63 @@ dohash(char *out, char *in, char *key) permute(pk1, key, perm1, 56); for (i = 0; i < 28; i++) - c[i] = pk1[i]; + c[i] = pk1[i]; for (i = 0; i < 28; i++) - d[i] = pk1[i + 28]; + d[i] = pk1[i + 28]; for (i = 0; i < 16; i++) { - lshift(c, sc[i], 28); - lshift(d, sc[i], 28); + lshift(c, sc[i], 28); + lshift(d, sc[i], 28); - concat(cd, c, d, 28, 28); - permute(ki[i], cd, perm2, 48); + concat(cd, c, d, 28, 28); + permute(ki[i], cd, perm2, 48); } permute(pd1, in, perm3, 64); for (j = 0; j < 32; j++) { - l[j] = pd1[j]; - r[j] = pd1[j + 32]; + l[j] = pd1[j]; + r[j] = pd1[j + 32]; } for (i = 0; i < 16; i++) { - char er[48]; - char erk[48]; - char b[8][6]; - char cb[32]; - char pcb[32]; - char r2[32]; + char er[48]; + char erk[48]; + char b[8][6]; + char cb[32]; + char pcb[32]; + char r2[32]; - permute(er, r, perm4, 48); + permute(er, r, perm4, 48); - xor(erk, er, ki[i], 48); + xor(erk, er, ki[i], 48); - for (j = 0; j < 8; j++) - for (k = 0; k < 6; k++) - b[j][k] = erk[j * 6 + k]; + for (j = 0; j < 8; j++) + for (k = 0; k < 6; k++) + b[j][k] = erk[j * 6 + k]; - for (j = 0; j < 8; j++) { - int m, n; - m = (b[j][0] << 1) | b[j][5]; + for (j = 0; j < 8; j++) { + int m, n; + m = (b[j][0] << 1) | b[j][5]; - n = (b[j][1] << 3) | (b[j][2] << 2) | (b[j][3] << 1) | b[j][4]; + n = (b[j][1] << 3) | (b[j][2] << 2) | (b[j][3] << 1) | b[j][4]; - for (k = 0; k < 4; k++) - b[j][k] = (sbox[j][m][n] & (1 << (3 - k))) ? 1 : 0; - } + for (k = 0; k < 4; k++) + b[j][k] = (sbox[j][m][n] & (1 << (3 - k))) ? 1 : 0; + } - for (j = 0; j < 8; j++) - for (k = 0; k < 4; k++) - cb[j * 4 + k] = b[j][k]; - permute(pcb, cb, perm5, 32); + for (j = 0; j < 8; j++) + for (k = 0; k < 4; k++) + cb[j * 4 + k] = b[j][k]; + permute(pcb, cb, perm5, 32); - xor(r2, l, pcb, 32); + xor(r2, l, pcb, 32); - for (j = 0; j < 32; j++) - l[j] = r[j]; + for (j = 0; j < 32; j++) + l[j] = r[j]; - for (j = 0; j < 32; j++) - r[j] = r2[j]; + for (j = 0; j < 32; j++) + r[j] = r2[j]; } concat(rl, r, l, 32, 32); @@ -292,7 +291,7 @@ str_to_key(unsigned char *str, unsigned char *key) key[6] = ((str[5] & 0x3F) << 1) | (str[6] >> 7); key[7] = str[6] & 0x7F; for (i = 0; i < 8; i++) { - key[i] = (key[i] << 1); + key[i] = (key[i] << 1); } } @@ -309,28 +308,27 @@ smbhash(unsigned char *out, unsigned char *in, unsigned char *key) str_to_key(key, key2); for (i = 0; i < 64; i++) { - inb[i] = (in[i / 8] & (1 << (7 - (i % 8)))) ? 1 : 0; - keyb[i] = (key2[i / 8] & (1 << (7 - (i % 8)))) ? 1 : 0; - outb[i] = 0; + inb[i] = (in[i / 8] & (1 << (7 - (i % 8)))) ? 1 : 0; + keyb[i] = (key2[i / 8] & (1 << (7 - (i % 8)))) ? 1 : 0; + outb[i] = 0; } dohash(outb, inb, keyb); for (i = 0; i < 8; i++) { - out[i] = 0; + out[i] = 0; } for (i = 0; i < 64; i++) { - if (outb[i]) - out[i / 8] |= (1 << (7 - (i % 8))); + if (outb[i]) + out[i / 8] |= (1 << (7 - (i % 8))); } } void E_P16(unsigned char *p14, unsigned char *p16) { - unsigned char sp8[8] = - {0x4b, 0x47, 0x53, 0x21, 0x40, 0x23, 0x24, 0x25}; + unsigned char sp8[8] = {0x4b, 0x47, 0x53, 0x21, 0x40, 0x23, 0x24, 0x25}; smbhash(p16, sp8, p14); smbhash(p16 + 8, sp8, p14 + 7); } diff --git a/helpers/ntlm_auth/SMB/smbval/smbencrypt.c b/helpers/ntlm_auth/SMB/smbval/smbencrypt.c index 41b5cbcbb1..c585cecb93 100644 --- a/helpers/ntlm_auth/SMB/smbval/smbencrypt.c +++ b/helpers/ntlm_auth/SMB/smbval/smbencrypt.c @@ -1,20 +1,20 @@ -/* +/* * Unix SMB/Netbios implementation. * Version 1.9. * SMB parameters and setup * Copyright (C) Andrew Tridgell 1992-1997 * Modified by Jeremy Allison 1995. - * + * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -41,7 +41,7 @@ void strupper(char *s); /* * This implements the X/Open SMB password encryption - * It takes a password, a 8 byte "crypt key" and puts 24 bytes of + * It takes a password, a 8 byte "crypt key" and puts 24 bytes of * encrypted password into p24 */ void SMBencrypt(uchar * passwd, uchar * c8, uchar * p24) @@ -63,13 +63,13 @@ _my_wcslen(int16 * str) { int len = 0; while (*str++ != 0) - len++; + len++; return len; } /* * Convert a string into an NT UNICODE string. - * Note that regardless of processor type + * Note that regardless of processor type * this must be in intel (little-endian) * format. */ @@ -81,17 +81,17 @@ _my_mbstowcs(int16 * dst, uchar * src, int len) int16 val; for (i = 0; i < len; i++) { - val = *src; - SSVAL(dst, 0, val); - dst++; - src++; - if (val == 0) - break; + val = *src; + SSVAL(dst, 0, val); + dst++; + src++; + if (val == 0) + break; } return i; } -/* +/* * Creates the MD4 Hash of the users password in NT UNICODE. */ @@ -104,7 +104,7 @@ E_md4hash(uchar * passwd, uchar * p16) /* Password cannot be longer than 128 characters */ len = strlen((char *) passwd); if (len > 128) - len = 128; + len = 128; /* Password must be converted to NT unicode */ _my_mbstowcs(wpwd, passwd, len); wpwd[len] = 0; /* Ensure string is null terminated */ @@ -160,10 +160,10 @@ StrnCpy(char *dest, char *src, int n) { char *d = dest; if (!dest) - return (NULL); + return (NULL); if (!src) { - *dest = 0; - return (dest); + *dest = 0; + return (dest); } while (n-- && (*d++ = *src++)); *d = 0; @@ -174,34 +174,34 @@ void strupper(char *s) { while (*s) { - /* - * #if !defined(KANJI_WIN95_COMPATIBILITY) - * if(lp_client_code_page() == KANJI_CODEPAGE) - * { - * - * if (is_shift_jis (*s)) - * { - * if (is_sj_lower (s[0], s[1])) - * s[1] = sj_toupper2 (s[1]); - * s += 2; - * } - * else if (is_kana (*s)) - * { - * s++; - * } - * else - * { - * if (islower(*s)) - * *s = toupper(*s); - * s++; - * } - * } - * else - * #endif *//* KANJI_WIN95_COMPATIBILITY */ - { - if (islower((int)(unsigned char)*s)) - *s = xtoupper(*s); - s++; - } + /* + * #if !defined(KANJI_WIN95_COMPATIBILITY) + * if(lp_client_code_page() == KANJI_CODEPAGE) + * { + * + * if (is_shift_jis (*s)) + * { + * if (is_sj_lower (s[0], s[1])) + * s[1] = sj_toupper2 (s[1]); + * s += 2; + * } + * else if (is_kana (*s)) + * { + * s++; + * } + * else + * { + * if (islower(*s)) + * *s = toupper(*s); + * s++; + * } + * } + * else + * #endif *//* KANJI_WIN95_COMPATIBILITY */ + { + if (islower((int)(unsigned char)*s)) + *s = xtoupper(*s); + s++; + } } } diff --git a/helpers/ntlm_auth/SMB/smbval/smblib-common.h b/helpers/ntlm_auth/SMB/smbval/smblib-common.h index f2a4bb234f..678305d426 100644 --- a/helpers/ntlm_auth/SMB/smbval/smblib-common.h +++ b/helpers/ntlm_auth/SMB/smbval/smblib-common.h @@ -2,12 +2,12 @@ #define __SMBLIB_COMMON_H__ /* UNIX SMBlib NetBIOS implementation - * + * * Version 1.0 * SMBlib Common Defines - * + * * Copyright (C) Richard Sharpe 1996 - * + * */ /* @@ -15,12 +15,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. diff --git a/helpers/ntlm_auth/SMB/smbval/smblib-priv.h b/helpers/ntlm_auth/SMB/smbval/smblib-priv.h index 5ed7649891..afdbebe32b 100644 --- a/helpers/ntlm_auth/SMB/smbval/smblib-priv.h +++ b/helpers/ntlm_auth/SMB/smbval/smblib-priv.h @@ -2,12 +2,12 @@ #define __SMBLIB_PRIV_H__ /* UNIX SMBlib NetBIOS implementation - * + * * Version 1.0 * SMBlib private Defines - * + * * Copyright (C) Richard Sharpe 1996 - * + * */ /* @@ -15,12 +15,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -281,8 +281,8 @@ typedef unsigned char UCHAR; #define SMB_openx_axr_offset 34 /* Reserved */ #define SMB_openx_axo_offset 35 /* offset of next wct */ #define SMB_openx_flg_offset 37 /* Flags, bit0 = need more info */ - /* bit1 = exclusive oplock */ - /* bit2 = batch oplock */ +/* bit1 = exclusive oplock */ +/* bit2 = batch oplock */ #define SMB_openx_mod_offset 39 /* mode to open with */ #define SMB_openx_atr_offset 41 /* search attributes */ #define SMB_openx_fat_offset 43 /* File attributes */ @@ -377,7 +377,7 @@ typedef unsigned char UCHAR; #define SMB_ssetpLM_buf_offset 55 #define SMB_ssetpNTLM_mbs_offset 37 /* Max Buffer Size for NT LM 0.12 */ - /* and above */ +/* and above */ #define SMB_ssetpNTLM_mmc_offset 39 /* Max Multiplex count */ #define SMB_ssetpNTLM_vcn_offset 41 /* VC Number */ #define SMB_ssetpNTLM_snk_offset 43 /* Session key */ @@ -501,7 +501,7 @@ typedef enum { extern char *SMB_Prots[]; /* - * static char *SMB_Prots[] = {"PC NETWORK PROGRAM 1.0", + * static char *SMB_Prots[] = {"PC NETWORK PROGRAM 1.0", * "MICROSOFT NETWORKS 1.03", * "MICROSOFT NETWORKS 3.0", * "DOS LANMAN1.0", @@ -537,12 +537,12 @@ extern int SMB_Types[]; typedef struct SMB_Status { union { - struct { - unsigned char ErrorClass; - unsigned char Reserved; - unsigned short Error; - } DosError; - unsigned int NtStatus; + struct { + unsigned char ErrorClass; + unsigned char Reserved; + unsigned short Error; + } DosError; + unsigned int NtStatus; } status; } SMB_Status; @@ -636,7 +636,7 @@ extern int SMBlib_SMB_Error; /* last Error */ #endif SMB_Tree_Handle SMB_TreeConnect(SMB_Handle_Type con, SMB_Tree_Handle tree, - char *path, char *password, char *dev); + char *path, char *password, char *dev); int SMB_Init(); void SMB_Get_My_Name(char *name, int len); @@ -644,7 +644,7 @@ int SMB_Negotiate(SMB_Handle_Type Con_Handle, char *Prots[]); int SMB_Discon(SMB_Handle_Type Con_Handle, BOOL KeepHandle); int SMB_Logon_Server(SMB_Handle_Type Con_Handle, char *UserName, - char *PassWord, char *UserDomain, int precrypted); + char *PassWord, char *UserDomain, int precrypted); int SMB_Get_Error_Msg(int msg, char *msgbuf, int len); diff --git a/helpers/ntlm_auth/SMB/smbval/smblib-util.c b/helpers/ntlm_auth/SMB/smbval/smblib-util.c index e1ae2b1c24..f74b27c390 100644 --- a/helpers/ntlm_auth/SMB/smbval/smblib-util.c +++ b/helpers/ntlm_auth/SMB/smbval/smblib-util.c @@ -1,10 +1,10 @@ /* UNIX SMBlib NetBIOS implementation - * + * * Version 1.0 * SMBlib Utility Routines - * + * * Copyright (C) Richard Sharpe 1996 - * + * */ /* @@ -12,12 +12,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -31,35 +31,35 @@ /* global data structures */ -static int SMB_Types[] = -{SMB_P_Core, - SMB_P_CorePlus, - SMB_P_DOSLanMan1, - SMB_P_DOSLanMan1, - SMB_P_LanMan1, - SMB_P_DOSLanMan2, - SMB_P_LanMan2, - SMB_P_LanMan2_1, - SMB_P_LanMan2_1, - SMB_P_NT1, - SMB_P_NT1, - SMB_P_NT1, - -1}; - -static char *SMB_Prots[] = -{"PC NETWORK PROGRAM 1.0", - "MICROSOFT NETWORKS 1.03", - "MICROSOFT NETWORKS 3.0", - "DOS LANMAN1.0", - "LANMAN1.0", - "DOS LM1.2X002", - "LM1.2X002", - "DOS LANMAN2.1", - "LANMAN2.1", - "Samba", - "NT LM 0.12", - "NT LANMAN 1.0", - NULL}; +static int SMB_Types[] = {SMB_P_Core, + SMB_P_CorePlus, + SMB_P_DOSLanMan1, + SMB_P_DOSLanMan1, + SMB_P_LanMan1, + SMB_P_DOSLanMan2, + SMB_P_LanMan2, + SMB_P_LanMan2_1, + SMB_P_LanMan2_1, + SMB_P_NT1, + SMB_P_NT1, + SMB_P_NT1, + -1 + }; + +static char *SMB_Prots[] = {"PC NETWORK PROGRAM 1.0", + "MICROSOFT NETWORKS 1.03", + "MICROSOFT NETWORKS 3.0", + "DOS LANMAN1.0", + "LANMAN1.0", + "DOS LM1.2X002", + "LM1.2X002", + "DOS LANMAN2.1", + "LANMAN2.1", + "Samba", + "NT LM 0.12", + "NT LANMAN 1.0", + NULL + }; /* Print out an SMB pkt in all its gory detail ... */ @@ -99,14 +99,14 @@ SMB_DOSTimToStr(int DOS_time) DOS_year = ((DOS_time & 0xFE000000) >> 25) + 80; sprintf(SMB_Time_Temp, "%2d/%02d/%2d %2d:%02d:%02d", DOS_day, DOS_month, - DOS_year, DOS_hour, DOS_min, DOS_sec); + DOS_year, DOS_hour, DOS_min, DOS_sec); return (SMB_Time_Temp); } /* Convert an attribute byte/word etc to a string ... We return a pointer - * to a static string which we guarantee is long enough. If verbose is + * to a static string which we guarantee is long enough. If verbose is * true, we print out long form of strings ... */ char * @@ -117,22 +117,22 @@ SMB_AtrToStr(int attribs, BOOL verbose) SMB_Attrib_Temp[0] = 0; if (attribs & SMB_FA_ROF) - strcat(SMB_Attrib_Temp, (verbose ? "Read Only " : "R")); + strcat(SMB_Attrib_Temp, (verbose ? "Read Only " : "R")); if (attribs & SMB_FA_HID) - strcat(SMB_Attrib_Temp, (verbose ? "Hidden " : "H")); + strcat(SMB_Attrib_Temp, (verbose ? "Hidden " : "H")); if (attribs & SMB_FA_SYS) - strcat(SMB_Attrib_Temp, (verbose ? "System " : "S")); + strcat(SMB_Attrib_Temp, (verbose ? "System " : "S")); if (attribs & SMB_FA_VOL) - strcat(SMB_Attrib_Temp, (verbose ? "Volume " : "V")); + strcat(SMB_Attrib_Temp, (verbose ? "Volume " : "V")); if (attribs & SMB_FA_DIR) - strcat(SMB_Attrib_Temp, (verbose ? "Directory " : "D")); + strcat(SMB_Attrib_Temp, (verbose ? "Directory " : "D")); if (attribs & SMB_FA_ARC) - strcat(SMB_Attrib_Temp, (verbose ? "Archive " : "A")); + strcat(SMB_Attrib_Temp, (verbose ? "Archive " : "A")); return (SMB_Attrib_Temp); @@ -144,9 +144,9 @@ int SMB_Get_Tree_MBS(SMB_Tree_Handle tree) { if (tree != NULL) { - return (tree->mbs); + return (tree->mbs); } else { - return (SMBlibE_BAD); + return (SMBlibE_BAD); } } @@ -156,9 +156,9 @@ int SMB_Get_Max_Buf_Siz(SMB_Handle_Type Con_Handle) { if (Con_Handle != NULL) { - return (Con_Handle->max_xmit); + return (Con_Handle->max_xmit); } else { - return (SMBlibE_BAD); + return (SMBlibE_BAD); } } @@ -168,9 +168,9 @@ int SMB_Get_Protocol_IDX(SMB_Handle_Type Con_Handle) { if (Con_Handle != NULL) { - return (Con_Handle->prot_IDX); + return (Con_Handle->prot_IDX); } else { - return (0xFFFF); /* Invalid protocol */ + return (0xFFFF); /* Invalid protocol */ } } @@ -181,9 +181,9 @@ int SMB_Get_Protocol(SMB_Handle_Type Con_Handle) { if (Con_Handle != NULL) { - return (Con_Handle->protocol); + return (Con_Handle->protocol); } else { - return (0xFFFF); /* Invalid protocol */ + return (0xFFFF); /* Invalid protocol */ } } @@ -199,22 +199,22 @@ SMB_Figure_Protocol(char *dialects[], int prot_index) if (dialects == SMB_Prots) { /* The jobs is easy, just index into table */ - return (SMB_Types[prot_index]); + return (SMB_Types[prot_index]); } else { /* Search through SMB_Prots looking for a match */ - for (i = 0; SMB_Prots[i] != NULL; i++) { + for (i = 0; SMB_Prots[i] != NULL; i++) { - if (strcmp(dialects[prot_index], SMB_Prots[i]) == 0) { /* A match */ + if (strcmp(dialects[prot_index], SMB_Prots[i]) == 0) { /* A match */ - return (SMB_Types[i]); + return (SMB_Types[i]); - } - } + } + } - /* If we got here, then we are in trouble, because the protocol was not */ - /* One we understand ... */ + /* If we got here, then we are in trouble, because the protocol was not */ + /* One we understand ... */ - return (SMB_P_Unknown); + return (SMB_P_Unknown); } @@ -238,7 +238,7 @@ SMB_Negotiate(SMB_Handle_Type Con_Handle, char *Prots[]) for (i = 0; Prots[i] != NULL; i++) { - prots_len = prots_len + strlen(Prots[i]) + 2; /* Account for null etc */ + prots_len = prots_len + strlen(Prots[i]) + 2; /* Account for null etc */ } @@ -252,11 +252,11 @@ SMB_Negotiate(SMB_Handle_Type Con_Handle, char *Prots[]) if (pkt_len < (SMB_hdr_wct_offset + (19 * 2) + 40)) { - alloc_len = SMB_hdr_wct_offset + (19 * 2) + 40; + alloc_len = SMB_hdr_wct_offset + (19 * 2) + 40; } else { - alloc_len = pkt_len; + alloc_len = pkt_len; } @@ -264,8 +264,8 @@ SMB_Negotiate(SMB_Handle_Type Con_Handle, char *Prots[]) if (pkt == NULL) { - SMBlib_errno = SMBlibE_NoSpace; - return (SMBlibE_BAD); + SMBlib_errno = SMBlibE_NoSpace; + return (SMBlibE_BAD); } /* Now plug in the bits we need */ @@ -287,9 +287,9 @@ SMB_Negotiate(SMB_Handle_Type Con_Handle, char *Prots[]) for (i = 0; Prots[i] != NULL; i++) { - *p = SMBdialectID; - strcpy(p + 1, Prots[i]); - p = p + strlen(Prots[i]) + 2; /* Adjust len of p for null plus dialectID */ + *p = SMBdialectID; + strcpy(p + 1, Prots[i]); + p = p + strlen(Prots[i]) + 2; /* Adjust len of p for null plus dialectID */ } @@ -299,12 +299,12 @@ SMB_Negotiate(SMB_Handle_Type Con_Handle, char *Prots[]) #ifdef DEBUG - fprintf(stderr, "Error sending negotiate protocol\n"); + fprintf(stderr, "Error sending negotiate protocol\n"); #endif - RFCNB_Free_Pkt(pkt); - SMBlib_errno = -SMBlibE_SendFailed; /* Failed, check lower layer errno */ - return (SMBlibE_BAD); + RFCNB_Free_Pkt(pkt); + SMBlib_errno = -SMBlibE_SendFailed; /* Failed, check lower layer errno */ + return (SMBlibE_BAD); } /* Now get the response ... */ @@ -312,37 +312,37 @@ SMB_Negotiate(SMB_Handle_Type Con_Handle, char *Prots[]) if (RFCNB_Recv(Con_Handle->Trans_Connect, pkt, alloc_len) < 0) { #ifdef DEBUG - fprintf(stderr, "Error receiving response to negotiate\n"); + fprintf(stderr, "Error receiving response to negotiate\n"); #endif - RFCNB_Free_Pkt(pkt); - SMBlib_errno = -SMBlibE_RecvFailed; /* Failed, check lower layer errno */ - return (SMBlibE_BAD); + RFCNB_Free_Pkt(pkt); + SMBlib_errno = -SMBlibE_RecvFailed; /* Failed, check lower layer errno */ + return (SMBlibE_BAD); } if (CVAL(SMB_Hdr(pkt), SMB_hdr_rcls_offset) != SMBC_SUCCESS) { /* Process error */ #ifdef DEBUG - fprintf(stderr, "SMB_Negotiate failed with errorclass = %i, Error Code = %i\n", - CVAL(SMB_Hdr(pkt), SMB_hdr_rcls_offset), - SVAL(SMB_Hdr(pkt), SMB_hdr_err_offset)); + fprintf(stderr, "SMB_Negotiate failed with errorclass = %i, Error Code = %i\n", + CVAL(SMB_Hdr(pkt), SMB_hdr_rcls_offset), + SVAL(SMB_Hdr(pkt), SMB_hdr_err_offset)); #endif - SMBlib_SMB_Error = IVAL(SMB_Hdr(pkt), SMB_hdr_rcls_offset); - RFCNB_Free_Pkt(pkt); - SMBlib_errno = SMBlibE_Remote; - return (SMBlibE_BAD); + SMBlib_SMB_Error = IVAL(SMB_Hdr(pkt), SMB_hdr_rcls_offset); + RFCNB_Free_Pkt(pkt); + SMBlib_errno = SMBlibE_Remote; + return (SMBlibE_BAD); } if (SVAL(SMB_Hdr(pkt), SMB_negrCP_idx_offset) == 0xFFFF) { #ifdef DEBUG - fprintf(stderr, "None of our protocols was accepted ... "); + fprintf(stderr, "None of our protocols was accepted ... "); #endif - RFCNB_Free_Pkt(pkt); - SMBlib_errno = SMBlibE_NegNoProt; - return (SMBlibE_BAD); + RFCNB_Free_Pkt(pkt); + SMBlib_errno = SMBlibE_NegNoProt; + return (SMBlibE_BAD); } /* Now, unpack the info from the response, if any and evaluate the proto */ @@ -353,71 +353,71 @@ SMB_Negotiate(SMB_Handle_Type Con_Handle, char *Prots[]) if (Con_Handle->protocol == SMB_P_Unknown) { /* No good ... */ - RFCNB_Free_Pkt(pkt); - SMBlib_errno = SMBlibE_ProtUnknown; - return (SMBlibE_BAD); + RFCNB_Free_Pkt(pkt); + SMBlib_errno = SMBlibE_ProtUnknown; + return (SMBlibE_BAD); } switch (CVAL(SMB_Hdr(pkt), SMB_hdr_wct_offset)) { case 0x01: /* No more info ... */ - break; + break; case 13: /* Up to and including LanMan 2.1 */ - Con_Handle->Security = SVAL(SMB_Hdr(pkt), SMB_negrLM_sec_offset); - Con_Handle->encrypt_passwords = ((Con_Handle->Security & SMB_sec_encrypt_mask) != 0x00); - Con_Handle->Security = Con_Handle->Security & SMB_sec_user_mask; + Con_Handle->Security = SVAL(SMB_Hdr(pkt), SMB_negrLM_sec_offset); + Con_Handle->encrypt_passwords = ((Con_Handle->Security & SMB_sec_encrypt_mask) != 0x00); + Con_Handle->Security = Con_Handle->Security & SMB_sec_user_mask; - Con_Handle->max_xmit = SVAL(SMB_Hdr(pkt), SMB_negrLM_mbs_offset); - Con_Handle->MaxMPX = SVAL(SMB_Hdr(pkt), SMB_negrLM_mmc_offset); - Con_Handle->MaxVC = SVAL(SMB_Hdr(pkt), SMB_negrLM_mnv_offset); - Con_Handle->Raw_Support = SVAL(SMB_Hdr(pkt), SMB_negrLM_rm_offset); - Con_Handle->SessionKey = IVAL(SMB_Hdr(pkt), SMB_negrLM_sk_offset); - Con_Handle->SvrTZ = SVAL(SMB_Hdr(pkt), SMB_negrLM_stz_offset); - Con_Handle->Encrypt_Key_Len = SVAL(SMB_Hdr(pkt), SMB_negrLM_ekl_offset); + Con_Handle->max_xmit = SVAL(SMB_Hdr(pkt), SMB_negrLM_mbs_offset); + Con_Handle->MaxMPX = SVAL(SMB_Hdr(pkt), SMB_negrLM_mmc_offset); + Con_Handle->MaxVC = SVAL(SMB_Hdr(pkt), SMB_negrLM_mnv_offset); + Con_Handle->Raw_Support = SVAL(SMB_Hdr(pkt), SMB_negrLM_rm_offset); + Con_Handle->SessionKey = IVAL(SMB_Hdr(pkt), SMB_negrLM_sk_offset); + Con_Handle->SvrTZ = SVAL(SMB_Hdr(pkt), SMB_negrLM_stz_offset); + Con_Handle->Encrypt_Key_Len = SVAL(SMB_Hdr(pkt), SMB_negrLM_ekl_offset); - p = (SMB_Hdr(pkt) + SMB_negrLM_buf_offset); - fprintf(stderr, "%8s", (char *) (SMB_Hdr(pkt) + SMB_negrLM_buf_offset)); - memcpy(Con_Handle->Encrypt_Key, p, 8); + p = (SMB_Hdr(pkt) + SMB_negrLM_buf_offset); + fprintf(stderr, "%8s", (char *) (SMB_Hdr(pkt) + SMB_negrLM_buf_offset)); + memcpy(Con_Handle->Encrypt_Key, p, 8); - p = (SMB_Hdr(pkt) + SMB_negrLM_buf_offset + Con_Handle->Encrypt_Key_Len); + p = (SMB_Hdr(pkt) + SMB_negrLM_buf_offset + Con_Handle->Encrypt_Key_Len); - strncpy(p, Con_Handle->Svr_PDom, sizeof(Con_Handle->Svr_PDom) - 1); + strncpy(p, Con_Handle->Svr_PDom, sizeof(Con_Handle->Svr_PDom) - 1); - break; + break; case 17: /* NT LM 0.12 and LN LM 1.0 */ - Con_Handle->Security = SVAL(SMB_Hdr(pkt), SMB_negrNTLM_sec_offset); - Con_Handle->encrypt_passwords = ((Con_Handle->Security & SMB_sec_encrypt_mask) != 0x00); - Con_Handle->Security = Con_Handle->Security & SMB_sec_user_mask; + Con_Handle->Security = SVAL(SMB_Hdr(pkt), SMB_negrNTLM_sec_offset); + Con_Handle->encrypt_passwords = ((Con_Handle->Security & SMB_sec_encrypt_mask) != 0x00); + Con_Handle->Security = Con_Handle->Security & SMB_sec_user_mask; - Con_Handle->max_xmit = IVAL(SMB_Hdr(pkt), SMB_negrNTLM_mbs_offset); - Con_Handle->MaxMPX = SVAL(SMB_Hdr(pkt), SMB_negrNTLM_mmc_offset); - Con_Handle->MaxVC = SVAL(SMB_Hdr(pkt), SMB_negrNTLM_mnv_offset); - Con_Handle->MaxRaw = IVAL(SMB_Hdr(pkt), SMB_negrNTLM_mrs_offset); - Con_Handle->SessionKey = IVAL(SMB_Hdr(pkt), SMB_negrNTLM_sk_offset); - Con_Handle->SvrTZ = SVAL(SMB_Hdr(pkt), SMB_negrNTLM_stz_offset); - Con_Handle->Encrypt_Key_Len = CVAL(SMB_Hdr(pkt), SMB_negrNTLM_ekl_offset); + Con_Handle->max_xmit = IVAL(SMB_Hdr(pkt), SMB_negrNTLM_mbs_offset); + Con_Handle->MaxMPX = SVAL(SMB_Hdr(pkt), SMB_negrNTLM_mmc_offset); + Con_Handle->MaxVC = SVAL(SMB_Hdr(pkt), SMB_negrNTLM_mnv_offset); + Con_Handle->MaxRaw = IVAL(SMB_Hdr(pkt), SMB_negrNTLM_mrs_offset); + Con_Handle->SessionKey = IVAL(SMB_Hdr(pkt), SMB_negrNTLM_sk_offset); + Con_Handle->SvrTZ = SVAL(SMB_Hdr(pkt), SMB_negrNTLM_stz_offset); + Con_Handle->Encrypt_Key_Len = CVAL(SMB_Hdr(pkt), SMB_negrNTLM_ekl_offset); - p = (SMB_Hdr(pkt) + SMB_negrNTLM_buf_offset); - memcpy(Con_Handle->Encrypt_Key, p, 8); - p = (SMB_Hdr(pkt) + SMB_negrNTLM_buf_offset + Con_Handle->Encrypt_Key_Len); + p = (SMB_Hdr(pkt) + SMB_negrNTLM_buf_offset); + memcpy(Con_Handle->Encrypt_Key, p, 8); + p = (SMB_Hdr(pkt) + SMB_negrNTLM_buf_offset + Con_Handle->Encrypt_Key_Len); - strncpy(p, Con_Handle->Svr_PDom, sizeof(Con_Handle->Svr_PDom) - 1); + strncpy(p, Con_Handle->Svr_PDom, sizeof(Con_Handle->Svr_PDom) - 1); - break; + break; default: #ifdef DEBUG - fprintf(stderr, "Unknown NegProt response format ... Ignored\n"); - fprintf(stderr, " wct = %i\n", CVAL(SMB_Hdr(pkt), SMB_hdr_wct_offset)); + fprintf(stderr, "Unknown NegProt response format ... Ignored\n"); + fprintf(stderr, " wct = %i\n", CVAL(SMB_Hdr(pkt), SMB_hdr_wct_offset)); #endif - break; + break; } #ifdef DEBUG @@ -437,13 +437,13 @@ SMB_Get_My_Name(char *name, int len) if (gethostname(name, len) < 0) { /* Error getting name */ - strncpy(name, "unknown", len); + strncpy(name, "unknown", len); - /* Should check the error */ + /* Should check the error */ #ifdef DEBUG - fprintf(stderr, "gethostname in SMB_Get_My_Name returned error:"); - perror(""); + fprintf(stderr, "gethostname in SMB_Get_My_Name returned error:"); + perror(""); #endif } @@ -456,10 +456,10 @@ SMB_Get_My_Name(char *name, int len) SMB_Tree_Handle SMB_TreeConnect(SMB_Handle_Type Con_Handle, - SMB_Tree_Handle Tree_Handle, - char *path, - char *password, - char *device) + SMB_Tree_Handle Tree_Handle, + char *path, + char *password, + char *device) { struct RFCNB_Pkt *pkt; int param_len, pkt_len; @@ -471,11 +471,11 @@ SMB_TreeConnect(SMB_Handle_Type Con_Handle, if ((path == NULL) || (password == NULL) || (device == NULL)) { #ifdef DEBUG - fprintf(stderr, "Bad parameter passed to SMB_TreeConnect\n"); + fprintf(stderr, "Bad parameter passed to SMB_TreeConnect\n"); #endif - SMBlib_errno = SMBlibE_BadParam; - return (NULL); + SMBlib_errno = SMBlibE_BadParam; + return (NULL); } /* The + 2 is because of the \0 and the marker ... */ @@ -491,26 +491,26 @@ SMB_TreeConnect(SMB_Handle_Type Con_Handle, if (pkt == NULL) { - SMBlib_errno = SMBlibE_NoSpace; - return (NULL); /* Should handle the error */ + SMBlib_errno = SMBlibE_NoSpace; + return (NULL); /* Should handle the error */ } /* Now allocate a tree for this to go into ... */ if (Tree_Handle == NULL) { - tree = (SMB_Tree_Handle) malloc(sizeof(struct SMB_Tree_Structure)); + tree = (SMB_Tree_Handle) malloc(sizeof(struct SMB_Tree_Structure)); - if (tree == NULL) { + if (tree == NULL) { - RFCNB_Free_Pkt(pkt); - SMBlib_errno = SMBlibE_NoSpace; - return (NULL); + RFCNB_Free_Pkt(pkt); + SMBlib_errno = SMBlibE_NoSpace; + return (NULL); - } + } } else { - tree = Tree_Handle; + tree = Tree_Handle; } @@ -549,14 +549,14 @@ SMB_TreeConnect(SMB_Handle_Type Con_Handle, if (RFCNB_Send(Con_Handle->Trans_Connect, pkt, pkt_len) < 0) { #ifdef DEBUG - fprintf(stderr, "Error sending TCon request\n"); + fprintf(stderr, "Error sending TCon request\n"); #endif - if (Tree_Handle == NULL) - free(tree); - RFCNB_Free_Pkt(pkt); - SMBlib_errno = -SMBlibE_SendFailed; - return (NULL); + if (Tree_Handle == NULL) + free(tree); + RFCNB_Free_Pkt(pkt); + SMBlib_errno = -SMBlibE_SendFailed; + return (NULL); } /* Now get the response ... */ @@ -564,14 +564,14 @@ SMB_TreeConnect(SMB_Handle_Type Con_Handle, if (RFCNB_Recv(Con_Handle->Trans_Connect, pkt, pkt_len) < 0) { #ifdef DEBUG - fprintf(stderr, "Error receiving response to TCon\n"); + fprintf(stderr, "Error receiving response to TCon\n"); #endif - if (Tree_Handle == NULL) - free(tree); - RFCNB_Free_Pkt(pkt); - SMBlib_errno = -SMBlibE_RecvFailed; - return (NULL); + if (Tree_Handle == NULL) + free(tree); + RFCNB_Free_Pkt(pkt); + SMBlib_errno = -SMBlibE_RecvFailed; + return (NULL); } /* Check out the response type ... */ @@ -579,17 +579,17 @@ SMB_TreeConnect(SMB_Handle_Type Con_Handle, if (CVAL(SMB_Hdr(pkt), SMB_hdr_rcls_offset) != SMBC_SUCCESS) { /* Process error */ #ifdef DEBUG - fprintf(stderr, "SMB_TCon failed with errorclass = %i, Error Code = %i\n", - CVAL(SMB_Hdr(pkt), SMB_hdr_rcls_offset), - SVAL(SMB_Hdr(pkt), SMB_hdr_err_offset)); + fprintf(stderr, "SMB_TCon failed with errorclass = %i, Error Code = %i\n", + CVAL(SMB_Hdr(pkt), SMB_hdr_rcls_offset), + SVAL(SMB_Hdr(pkt), SMB_hdr_err_offset)); #endif - if (Tree_Handle == NULL) - free(tree); - SMBlib_SMB_Error = IVAL(SMB_Hdr(pkt), SMB_hdr_rcls_offset); - RFCNB_Free_Pkt(pkt); - SMBlib_errno = SMBlibE_Remote; - return (NULL); + if (Tree_Handle == NULL) + free(tree); + SMBlib_SMB_Error = IVAL(SMB_Hdr(pkt), SMB_hdr_rcls_offset); + RFCNB_Free_Pkt(pkt); + SMBlib_errno = SMBlibE_Remote; + return (NULL); } tree->tid = SVAL(SMB_Hdr(pkt), SMB_tconr_tid_offset); @@ -597,21 +597,21 @@ SMB_TreeConnect(SMB_Handle_Type Con_Handle, #ifdef DEBUG fprintf(stderr, "TConn succeeded, with TID=%i, Max Xmit=%i\n", - tree->tid, tree->mbs); + tree->tid, tree->mbs); #endif /* Now link the Tree to the Server Structure ... */ if (Con_Handle->first_tree == NULL) { - Con_Handle->first_tree = tree; - Con_Handle->last_tree = tree; + Con_Handle->first_tree = tree; + Con_Handle->last_tree = tree; } else { - Con_Handle->last_tree->next = tree; - tree->prev = Con_Handle->last_tree; - Con_Handle->last_tree = tree; + Con_Handle->last_tree->next = tree; + tree->prev = Con_Handle->last_tree; + Con_Handle->last_tree = tree; } @@ -632,8 +632,8 @@ SMB_TreeDisconnect(SMB_Tree_Handle Tree_Handle, BOOL discard) if (pkt == NULL) { - SMBlib_errno = SMBlibE_NoSpace; - return (SMBlibE_BAD); /* Should handle the error */ + SMBlib_errno = SMBlibE_NoSpace; + return (SMBlibE_BAD); /* Should handle the error */ } /* Now plug in the values ... */ @@ -654,12 +654,12 @@ SMB_TreeDisconnect(SMB_Tree_Handle Tree_Handle, BOOL discard) if (RFCNB_Send(Tree_Handle->con->Trans_Connect, pkt, pkt_len) < 0) { #ifdef DEBUG - fprintf(stderr, "Error sending TDis request\n"); + fprintf(stderr, "Error sending TDis request\n"); #endif - RFCNB_Free_Pkt(pkt); - SMBlib_errno = -SMBlibE_SendFailed; - return (SMBlibE_BAD); + RFCNB_Free_Pkt(pkt); + SMBlib_errno = -SMBlibE_SendFailed; + return (SMBlibE_BAD); } /* Now get the response ... */ @@ -667,12 +667,12 @@ SMB_TreeDisconnect(SMB_Tree_Handle Tree_Handle, BOOL discard) if (RFCNB_Recv(Tree_Handle->con->Trans_Connect, pkt, pkt_len) < 0) { #ifdef DEBUG - fprintf(stderr, "Error receiving response to TCon\n"); + fprintf(stderr, "Error receiving response to TCon\n"); #endif - RFCNB_Free_Pkt(pkt); - SMBlib_errno = -SMBlibE_RecvFailed; - return (SMBlibE_BAD); + RFCNB_Free_Pkt(pkt); + SMBlib_errno = -SMBlibE_RecvFailed; + return (SMBlibE_BAD); } /* Check out the response type ... */ @@ -680,15 +680,15 @@ SMB_TreeDisconnect(SMB_Tree_Handle Tree_Handle, BOOL discard) if (CVAL(SMB_Hdr(pkt), SMB_hdr_rcls_offset) != SMBC_SUCCESS) { /* Process error */ #ifdef DEBUG - fprintf(stderr, "SMB_TDis failed with errorclass = %i, Error Code = %i\n", - CVAL(SMB_Hdr(pkt), SMB_hdr_rcls_offset), - SVAL(SMB_Hdr(pkt), SMB_hdr_err_offset)); + fprintf(stderr, "SMB_TDis failed with errorclass = %i, Error Code = %i\n", + CVAL(SMB_Hdr(pkt), SMB_hdr_rcls_offset), + SVAL(SMB_Hdr(pkt), SMB_hdr_err_offset)); #endif - SMBlib_SMB_Error = IVAL(SMB_Hdr(pkt), SMB_hdr_rcls_offset); - RFCNB_Free_Pkt(pkt); - SMBlib_errno = SMBlibE_Remote; - return (SMBlibE_BAD); + SMBlib_SMB_Error = IVAL(SMB_Hdr(pkt), SMB_hdr_rcls_offset); + RFCNB_Free_Pkt(pkt); + SMBlib_errno = SMBlibE_Remote; + return (SMBlibE_BAD); } Tree_Handle->tid = 0xFFFF; /* Invalid TID */ @@ -704,15 +704,15 @@ SMB_TreeDisconnect(SMB_Tree_Handle Tree_Handle, BOOL discard) if (discard == TRUE) { /* Unlink it and free it ... */ - if (Tree_Handle->next == NULL) - Tree_Handle->con->first_tree = Tree_Handle->prev; - else - Tree_Handle->next->prev = Tree_Handle->prev; + if (Tree_Handle->next == NULL) + Tree_Handle->con->first_tree = Tree_Handle->prev; + else + Tree_Handle->next->prev = Tree_Handle->prev; - if (Tree_Handle->prev == NULL) - Tree_Handle->con->last_tree = Tree_Handle->next; - else - Tree_Handle->prev->next = Tree_Handle->next; + if (Tree_Handle->prev == NULL) + Tree_Handle->con->last_tree = Tree_Handle->next; + else + Tree_Handle->prev->next = Tree_Handle->next; } RFCNB_Free_Pkt(pkt); @@ -745,8 +745,7 @@ SMB_Get_Last_SMB_Err() /* Keep this table in sync with the message codes in smblib-common.h */ -static char *SMBlib_Error_Messages[] = -{ +static char *SMBlib_Error_Messages[] = { "Request completed sucessfully.", "Server returned a non-zero SMB Error Class and Code.", @@ -761,9 +760,10 @@ static char *SMBlib_Error_Messages[] = "The logon request failed, but you were logged in as guest.", "The attempt to call the remote server failed. See protocol error info.", "The protocol dialect specified in a NegProt and accepted by the server is unknown.", - /* This next one simplifies error handling */ + /* This next one simplifies error handling */ "No such error code.", - NULL}; + NULL +}; int SMB_Get_Error_Msg(int msg, char *msgbuf, int len) @@ -771,31 +771,31 @@ SMB_Get_Error_Msg(int msg, char *msgbuf, int len) if (msg >= 0) { - strncpy(msgbuf, - SMBlib_Error_Messages[msg > SMBlibE_NoSuchMsg ? SMBlibE_NoSuchMsg : msg], - len - 1); - msgbuf[len - 1] = 0; /* Make sure it is a string */ + strncpy(msgbuf, + SMBlib_Error_Messages[msg > SMBlibE_NoSuchMsg ? SMBlibE_NoSuchMsg : msg], + len - 1); + msgbuf[len - 1] = 0; /* Make sure it is a string */ } else { /* Add the lower layer message ... */ - char prot_msg[1024]; + char prot_msg[1024]; - msg = -msg; /* Make it positive */ + msg = -msg; /* Make it positive */ - strncpy(msgbuf, - SMBlib_Error_Messages[msg > SMBlibE_NoSuchMsg ? SMBlibE_NoSuchMsg : msg], - len - 1); + strncpy(msgbuf, + SMBlib_Error_Messages[msg > SMBlibE_NoSuchMsg ? SMBlibE_NoSuchMsg : msg], + len - 1); - msgbuf[len - 1] = 0; /* make sure it is a string */ + msgbuf[len - 1] = 0; /* make sure it is a string */ - if (strlen(msgbuf) < len) { /* If there is space, put rest in */ + if (strlen(msgbuf) < len) { /* If there is space, put rest in */ - strncat(msgbuf, "\n\t", len - strlen(msgbuf)); + strncat(msgbuf, "\n\t", len - strlen(msgbuf)); - RFCNB_Get_Error(prot_msg, sizeof(prot_msg) - 1); + RFCNB_Get_Error(prot_msg, sizeof(prot_msg) - 1); - strncat(msgbuf, prot_msg, len - strlen(msgbuf)); + strncat(msgbuf, prot_msg, len - strlen(msgbuf)); - } + } } return 0; } diff --git a/helpers/ntlm_auth/SMB/smbval/smblib.c b/helpers/ntlm_auth/SMB/smbval/smblib.c index 179a6cee47..3c8073751b 100644 --- a/helpers/ntlm_auth/SMB/smbval/smblib.c +++ b/helpers/ntlm_auth/SMB/smbval/smblib.c @@ -1,11 +1,11 @@ /* UNIX SMBlib NetBIOS implementation - * + * * Version 1.0 * SMBlib Routines - * + * * Copyright (C) Richard Sharpe 1996 - * + * */ /* @@ -13,12 +13,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -54,7 +54,7 @@ SMB_Init() signal(SIGPIPE, SIG_IGN); /* Ignore these ... */ -/* If SMBLIB_Instrument is defines, turn on the instrumentation stuff */ + /* If SMBLIB_Instrument is defines, turn on the instrumentation stuff */ #ifdef SMBLIB_INSTRUMENT SMBlib_Instrument_Init(); @@ -101,7 +101,7 @@ SMBlib_Set_Sock_NoDelay(SMB_Handle_Type Con_Handle, BOOL yn) #ifdef DEBUG #endif - fprintf(stderr, "Setting no-delay on TCP socket failed ...\n"); + fprintf(stderr, "Setting no-delay on TCP socket failed ...\n"); } return (0); @@ -113,7 +113,7 @@ SMBlib_Set_Sock_NoDelay(SMB_Handle_Type Con_Handle, BOOL yn) SMB_Handle_Type SMB_Connect_Server(SMB_Handle_Type Con_Handle, - char *server, char *NTdomain) + char *server, char *NTdomain) { SMB_Handle_Type con; char called[80], calling[80], *address; @@ -125,12 +125,12 @@ SMB_Connect_Server(SMB_Handle_Type Con_Handle, if (Con_Handle == NULL) { - if ((con = (struct SMB_Connect_Def *) malloc(sizeof(struct SMB_Connect_Def))) == NULL) { + if ((con = (struct SMB_Connect_Def *) malloc(sizeof(struct SMB_Connect_Def))) == NULL) { - SMBlib_errno = SMBlibE_NoSpace; - return NULL; - } + SMBlib_errno = SMBlibE_NoSpace; + return NULL; + } } /* Init some things ... */ @@ -146,15 +146,15 @@ SMB_Connect_Server(SMB_Handle_Type Con_Handle, con->first_tree = con->last_tree = NULL; /* ugh. This is horribly broken. */ -/* SMB_Get_My_Name(con -> myname, sizeof(con -> myname)); */ + /* SMB_Get_My_Name(con -> myname, sizeof(con -> myname)); */ /* hacked by Kinkie */ i = gethostname(con->myname, sizeof(con->myname)); if (i == -1) { - strcpy(con->myname, "unknown"); + strcpy(con->myname, "unknown"); } else { - if (NULL != (address = strchr(con->myname, '.'))) { - *address = '\0'; /* truncate at first '.' */ - } + if (NULL != (address = strchr(con->myname, '.'))) { + *address = '\0'; /* truncate at first '.' */ + } } @@ -171,35 +171,35 @@ SMB_Connect_Server(SMB_Handle_Type Con_Handle, * service we are going to call, sine some servers want it in uppercase */ for (i = 0; i < strlen(server); i++) - called[i] = xtoupper(server[i]); + called[i] = xtoupper(server[i]); called[strlen(server)] = 0; /* Make it a string */ for (i = 0; i < strlen(con->myname); i++) - calling[i] = xtoupper(con->myname[i]); + calling[i] = xtoupper(con->myname[i]); calling[strlen(con->myname)] = 0; /* Make it a string */ if (strcmp(con->address, "") == 0) - address = con->desthost; + address = con->desthost; else - address = con->address; + address = con->address; con->Trans_Connect = RFCNB_Call(called, - calling, - address, /* Protocol specific */ - con->port); + calling, + address, /* Protocol specific */ + con->port); /* Did we get one? */ if (con->Trans_Connect == NULL) { - if (Con_Handle == NULL) { - Con_Handle = NULL; - free(con); - } - SMBlib_errno = -SMBlibE_CallFailed; - return NULL; + if (Con_Handle == NULL) { + Con_Handle = NULL; + free(con); + } + SMBlib_errno = -SMBlibE_CallFailed; + return NULL; } return (con); @@ -210,17 +210,17 @@ SMB_Connect_Server(SMB_Handle_Type Con_Handle, /* If Con_Handle == NULL then create a handle and connect, otherwise */ /* use the handle passed */ -char *SMB_Prots_Restrict[] = -{"PC NETWORK PROGRAM 1.0", - NULL}; +char *SMB_Prots_Restrict[] = {"PC NETWORK PROGRAM 1.0", + NULL + }; SMB_Handle_Type SMB_Connect(SMB_Handle_Type Con_Handle, - SMB_Tree_Handle * tree, - char *service, - char *username, - char *password) + SMB_Tree_Handle * tree, + char *service, + char *username, + char *password) { SMB_Handle_Type con; char *host, *address; @@ -233,11 +233,11 @@ SMB_Connect(SMB_Handle_Type Con_Handle, if (Con_Handle == NULL) { - if ((con = (struct SMB_Connect_Def *) malloc(sizeof(struct SMB_Connect_Def))) == NULL) { + if ((con = (struct SMB_Connect_Def *) malloc(sizeof(struct SMB_Connect_Def))) == NULL) { - SMBlib_errno = SMBlibE_NoSpace; - return NULL; - } + SMBlib_errno = SMBlibE_NoSpace; + return NULL; + } } /* Init some things ... */ @@ -272,52 +272,52 @@ SMB_Connect(SMB_Handle_Type Con_Handle, * service we are going to call, sine some servers want it in uppercase */ for (i = 0; i < strlen(host); i++) - called[i] = xtoupper(host[i]); + called[i] = xtoupper(host[i]); called[strlen(host)] = 0; /* Make it a string */ for (i = 0; i < strlen(con->myname); i++) - calling[i] = xtoupper(con->myname[i]); + calling[i] = xtoupper(con->myname[i]); calling[strlen(con->myname)] = 0; /* Make it a string */ if (strcmp(con->address, "") == 0) - address = con->desthost; + address = con->desthost; else - address = con->address; + address = con->address; con->Trans_Connect = RFCNB_Call(called, - calling, - address, /* Protocol specific */ - con->port); + calling, + address, /* Protocol specific */ + con->port); /* Did we get one? */ if (con->Trans_Connect == NULL) { - if (Con_Handle == NULL) { - free(con); - Con_Handle = NULL; - } - SMBlib_errno = -SMBlibE_CallFailed; - return NULL; + if (Con_Handle == NULL) { + free(con); + Con_Handle = NULL; + } + SMBlib_errno = -SMBlibE_CallFailed; + return NULL; } /* Now, negotiate the protocol */ if (SMB_Negotiate(con, SMB_Prots_Restrict) < 0) { - /* Hmmm what should we do here ... We have a connection, but could not - * negotiate ... */ + /* Hmmm what should we do here ... We have a connection, but could not + * negotiate ... */ - return NULL; + return NULL; } /* Now connect to the service ... */ if ((*tree = SMB_TreeConnect(con, NULL, service, password, "A:")) == NULL) { - return NULL; + return NULL; } return (con); @@ -329,7 +329,7 @@ SMB_Connect(SMB_Handle_Type Con_Handle, int SMB_Logon_Server(SMB_Handle_Type Con_Handle, char *UserName, - char *PassWord, char *UserDomain, int precrypted) + char *PassWord, char *UserDomain, int precrypted) { struct RFCNB_Pkt *pkt; int param_len, pkt_len, pass_len; @@ -341,153 +341,153 @@ SMB_Logon_Server(SMB_Handle_Type Con_Handle, char *UserName, if (Con_Handle->protocol < SMB_P_LanMan1) { - SMBlib_errno = SMBlibE_ProtLow; - return (SMBlibE_BAD); + SMBlib_errno = SMBlibE_ProtLow; + return (SMBlibE_BAD); } if (precrypted) { - pass_len = 24; - memcpy(pword, PassWord, 24); + pass_len = 24; + memcpy(pword, PassWord, 24); } else { - strcpy(pword, PassWord); - if (Con_Handle->encrypt_passwords) { - pass_len = 24; - SMBencrypt((uchar *) PassWord, (uchar *) Con_Handle->Encrypt_Key, (uchar *) pword); - } else - pass_len = strlen(pword); + strcpy(pword, PassWord); + if (Con_Handle->encrypt_passwords) { + pass_len = 24; + SMBencrypt((uchar *) PassWord, (uchar *) Con_Handle->Encrypt_Key, (uchar *) pword); + } else + pass_len = strlen(pword); } /* Now build the correct structure */ if (Con_Handle->protocol < SMB_P_NT1) { - param_len = strlen(UserName) + 1 + pass_len + 1 + - strlen(UserDomain) + 1 + - strlen(Con_Handle->OSName) + 1; + param_len = strlen(UserName) + 1 + pass_len + 1 + + strlen(UserDomain) + 1 + + strlen(Con_Handle->OSName) + 1; - pkt_len = SMB_ssetpLM_len + param_len; + pkt_len = SMB_ssetpLM_len + param_len; - pkt = (struct RFCNB_Pkt *) RFCNB_Alloc_Pkt(pkt_len); + pkt = (struct RFCNB_Pkt *) RFCNB_Alloc_Pkt(pkt_len); - if (pkt == NULL) { + if (pkt == NULL) { - SMBlib_errno = SMBlibE_NoSpace; - fprintf(stderr, "SMB_Logon_server: Couldn't allocate packet\n"); - return (SMBlibE_BAD); /* Should handle the error */ - } - memset(SMB_Hdr(pkt), 0, SMB_ssetpLM_len); - SIVAL(SMB_Hdr(pkt), SMB_hdr_idf_offset, SMB_DEF_IDF); /* Plunk in IDF */ - *(SMB_Hdr(pkt) + SMB_hdr_com_offset) = SMBsesssetupX; - SSVAL(SMB_Hdr(pkt), SMB_hdr_pid_offset, Con_Handle->pid); - SSVAL(SMB_Hdr(pkt), SMB_hdr_tid_offset, 0); - SSVAL(SMB_Hdr(pkt), SMB_hdr_mid_offset, Con_Handle->mid); - SSVAL(SMB_Hdr(pkt), SMB_hdr_uid_offset, Con_Handle->uid); - *(SMB_Hdr(pkt) + SMB_hdr_wct_offset) = 10; - *(SMB_Hdr(pkt) + SMB_hdr_axc_offset) = 0xFF; /* No extra command */ - SSVAL(SMB_Hdr(pkt), SMB_hdr_axo_offset, 0); + SMBlib_errno = SMBlibE_NoSpace; + fprintf(stderr, "SMB_Logon_server: Couldn't allocate packet\n"); + return (SMBlibE_BAD); /* Should handle the error */ + } + memset(SMB_Hdr(pkt), 0, SMB_ssetpLM_len); + SIVAL(SMB_Hdr(pkt), SMB_hdr_idf_offset, SMB_DEF_IDF); /* Plunk in IDF */ + *(SMB_Hdr(pkt) + SMB_hdr_com_offset) = SMBsesssetupX; + SSVAL(SMB_Hdr(pkt), SMB_hdr_pid_offset, Con_Handle->pid); + SSVAL(SMB_Hdr(pkt), SMB_hdr_tid_offset, 0); + SSVAL(SMB_Hdr(pkt), SMB_hdr_mid_offset, Con_Handle->mid); + SSVAL(SMB_Hdr(pkt), SMB_hdr_uid_offset, Con_Handle->uid); + *(SMB_Hdr(pkt) + SMB_hdr_wct_offset) = 10; + *(SMB_Hdr(pkt) + SMB_hdr_axc_offset) = 0xFF; /* No extra command */ + SSVAL(SMB_Hdr(pkt), SMB_hdr_axo_offset, 0); - SSVAL(SMB_Hdr(pkt), SMB_ssetpLM_mbs_offset, SMBLIB_MAX_XMIT); - SSVAL(SMB_Hdr(pkt), SMB_ssetpLM_mmc_offset, 2); - SSVAL(SMB_Hdr(pkt), SMB_ssetpLM_vcn_offset, Con_Handle->pid); - SIVAL(SMB_Hdr(pkt), SMB_ssetpLM_snk_offset, 0); - SSVAL(SMB_Hdr(pkt), SMB_ssetpLM_pwl_offset, pass_len + 1); - SIVAL(SMB_Hdr(pkt), SMB_ssetpLM_res_offset, 0); - SSVAL(SMB_Hdr(pkt), SMB_ssetpLM_bcc_offset, param_len); + SSVAL(SMB_Hdr(pkt), SMB_ssetpLM_mbs_offset, SMBLIB_MAX_XMIT); + SSVAL(SMB_Hdr(pkt), SMB_ssetpLM_mmc_offset, 2); + SSVAL(SMB_Hdr(pkt), SMB_ssetpLM_vcn_offset, Con_Handle->pid); + SIVAL(SMB_Hdr(pkt), SMB_ssetpLM_snk_offset, 0); + SSVAL(SMB_Hdr(pkt), SMB_ssetpLM_pwl_offset, pass_len + 1); + SIVAL(SMB_Hdr(pkt), SMB_ssetpLM_res_offset, 0); + SSVAL(SMB_Hdr(pkt), SMB_ssetpLM_bcc_offset, param_len); - /* Now copy the param strings in with the right stuff */ + /* Now copy the param strings in with the right stuff */ - p = (char *) (SMB_Hdr(pkt) + SMB_ssetpLM_buf_offset); + p = (char *) (SMB_Hdr(pkt) + SMB_ssetpLM_buf_offset); - /* Copy in password, then the rest. Password has a null at end */ + /* Copy in password, then the rest. Password has a null at end */ - memcpy(p, pword, pass_len); + memcpy(p, pword, pass_len); - p = p + pass_len + 1; + p = p + pass_len + 1; - strcpy(p, UserName); - p = p + strlen(UserName); - *p = 0; + strcpy(p, UserName); + p = p + strlen(UserName); + *p = 0; - p = p + 1; + p = p + 1; - strcpy(p, UserDomain); - p = p + strlen(UserDomain); - *p = 0; - p = p + 1; + strcpy(p, UserDomain); + p = p + strlen(UserDomain); + *p = 0; + p = p + 1; - strcpy(p, Con_Handle->OSName); - p = p + strlen(Con_Handle->OSName); - *p = 0; + strcpy(p, Con_Handle->OSName); + p = p + strlen(Con_Handle->OSName); + *p = 0; } else { - /* We don't admit to UNICODE support ... */ + /* We don't admit to UNICODE support ... */ - param_len = strlen(UserName) + 1 + pass_len + - strlen(UserDomain) + 1 + - strlen(Con_Handle->OSName) + 1 + - strlen(Con_Handle->LMType) + 1; + param_len = strlen(UserName) + 1 + pass_len + + strlen(UserDomain) + 1 + + strlen(Con_Handle->OSName) + 1 + + strlen(Con_Handle->LMType) + 1; - pkt_len = SMB_ssetpNTLM_len + param_len; + pkt_len = SMB_ssetpNTLM_len + param_len; - pkt = (struct RFCNB_Pkt *) RFCNB_Alloc_Pkt(pkt_len); + pkt = (struct RFCNB_Pkt *) RFCNB_Alloc_Pkt(pkt_len); - if (pkt == NULL) { + if (pkt == NULL) { - SMBlib_errno = SMBlibE_NoSpace; - fprintf(stderr, "SMB_Logon_server: Couldn't allocate packet\n"); - return (-1); /* Should handle the error */ - } - memset(SMB_Hdr(pkt), 0, SMB_ssetpNTLM_len); - SIVAL(SMB_Hdr(pkt), SMB_hdr_idf_offset, SMB_DEF_IDF); /* Plunk in IDF */ - *(SMB_Hdr(pkt) + SMB_hdr_com_offset) = SMBsesssetupX; - SSVAL(SMB_Hdr(pkt), SMB_hdr_pid_offset, Con_Handle->pid); - SSVAL(SMB_Hdr(pkt), SMB_hdr_tid_offset, 0); - SSVAL(SMB_Hdr(pkt), SMB_hdr_mid_offset, Con_Handle->mid); - SSVAL(SMB_Hdr(pkt), SMB_hdr_uid_offset, Con_Handle->uid); - *(SMB_Hdr(pkt) + SMB_hdr_wct_offset) = 13; - *(SMB_Hdr(pkt) + SMB_hdr_axc_offset) = 0xFF; /* No extra command */ - SSVAL(SMB_Hdr(pkt), SMB_hdr_axo_offset, 0); + SMBlib_errno = SMBlibE_NoSpace; + fprintf(stderr, "SMB_Logon_server: Couldn't allocate packet\n"); + return (-1); /* Should handle the error */ + } + memset(SMB_Hdr(pkt), 0, SMB_ssetpNTLM_len); + SIVAL(SMB_Hdr(pkt), SMB_hdr_idf_offset, SMB_DEF_IDF); /* Plunk in IDF */ + *(SMB_Hdr(pkt) + SMB_hdr_com_offset) = SMBsesssetupX; + SSVAL(SMB_Hdr(pkt), SMB_hdr_pid_offset, Con_Handle->pid); + SSVAL(SMB_Hdr(pkt), SMB_hdr_tid_offset, 0); + SSVAL(SMB_Hdr(pkt), SMB_hdr_mid_offset, Con_Handle->mid); + SSVAL(SMB_Hdr(pkt), SMB_hdr_uid_offset, Con_Handle->uid); + *(SMB_Hdr(pkt) + SMB_hdr_wct_offset) = 13; + *(SMB_Hdr(pkt) + SMB_hdr_axc_offset) = 0xFF; /* No extra command */ + SSVAL(SMB_Hdr(pkt), SMB_hdr_axo_offset, 0); - SSVAL(SMB_Hdr(pkt), SMB_ssetpNTLM_mbs_offset, SMBLIB_MAX_XMIT); - SSVAL(SMB_Hdr(pkt), SMB_ssetpNTLM_mmc_offset, 0); - SSVAL(SMB_Hdr(pkt), SMB_ssetpNTLM_vcn_offset, 1); /* Thanks Tridge! */ - SIVAL(SMB_Hdr(pkt), SMB_ssetpNTLM_snk_offset, 0); - SSVAL(SMB_Hdr(pkt), SMB_ssetpNTLM_cipl_offset, pass_len); - SSVAL(SMB_Hdr(pkt), SMB_ssetpNTLM_cspl_offset, 0); - SIVAL(SMB_Hdr(pkt), SMB_ssetpNTLM_res_offset, 0); - SIVAL(SMB_Hdr(pkt), SMB_ssetpNTLM_cap_offset, 0); - SSVAL(SMB_Hdr(pkt), SMB_ssetpNTLM_bcc_offset, param_len); + SSVAL(SMB_Hdr(pkt), SMB_ssetpNTLM_mbs_offset, SMBLIB_MAX_XMIT); + SSVAL(SMB_Hdr(pkt), SMB_ssetpNTLM_mmc_offset, 0); + SSVAL(SMB_Hdr(pkt), SMB_ssetpNTLM_vcn_offset, 1); /* Thanks Tridge! */ + SIVAL(SMB_Hdr(pkt), SMB_ssetpNTLM_snk_offset, 0); + SSVAL(SMB_Hdr(pkt), SMB_ssetpNTLM_cipl_offset, pass_len); + SSVAL(SMB_Hdr(pkt), SMB_ssetpNTLM_cspl_offset, 0); + SIVAL(SMB_Hdr(pkt), SMB_ssetpNTLM_res_offset, 0); + SIVAL(SMB_Hdr(pkt), SMB_ssetpNTLM_cap_offset, 0); + SSVAL(SMB_Hdr(pkt), SMB_ssetpNTLM_bcc_offset, param_len); - /* Now copy the param strings in with the right stuff */ + /* Now copy the param strings in with the right stuff */ - p = (char *) (SMB_Hdr(pkt) + SMB_ssetpNTLM_buf_offset); + p = (char *) (SMB_Hdr(pkt) + SMB_ssetpNTLM_buf_offset); - /* Copy in password, then the rest. Password has no null at end */ + /* Copy in password, then the rest. Password has no null at end */ - memcpy(p, pword, pass_len); + memcpy(p, pword, pass_len); - p = p + pass_len; + p = p + pass_len; - strcpy(p, UserName); - p = p + strlen(UserName); - *p = 0; + strcpy(p, UserName); + p = p + strlen(UserName); + *p = 0; - p = p + 1; + p = p + 1; - strcpy(p, UserDomain); - p = p + strlen(UserDomain); - *p = 0; - p = p + 1; + strcpy(p, UserDomain); + p = p + strlen(UserDomain); + *p = 0; + p = p + 1; - strcpy(p, Con_Handle->OSName); - p = p + strlen(Con_Handle->OSName); - *p = 0; - p = p + 1; + strcpy(p, Con_Handle->OSName); + p = p + strlen(Con_Handle->OSName); + *p = 0; + p = p + 1; - strcpy(p, Con_Handle->LMType); - p = p + strlen(Con_Handle->LMType); - *p = 0; + strcpy(p, Con_Handle->LMType); + p = p + strlen(Con_Handle->LMType); + *p = 0; } @@ -496,12 +496,12 @@ SMB_Logon_Server(SMB_Handle_Type Con_Handle, char *UserName, if (RFCNB_Send(Con_Handle->Trans_Connect, pkt, pkt_len) < 0) { #ifdef DEBUG - fprintf(stderr, "Error sending SessSetupX request\n"); + fprintf(stderr, "Error sending SessSetupX request\n"); #endif - RFCNB_Free_Pkt(pkt); - SMBlib_errno = SMBlibE_SendFailed; - return (SMBlibE_BAD); + RFCNB_Free_Pkt(pkt); + SMBlib_errno = SMBlibE_SendFailed; + return (SMBlibE_BAD); } /* Now get the response ... */ @@ -509,12 +509,12 @@ SMB_Logon_Server(SMB_Handle_Type Con_Handle, char *UserName, if (RFCNB_Recv(Con_Handle->Trans_Connect, pkt, pkt_len) < 0) { #ifdef DEBUG - fprintf(stderr, "Error receiving response to SessSetupAndX\n"); + fprintf(stderr, "Error receiving response to SessSetupAndX\n"); #endif - RFCNB_Free_Pkt(pkt); - SMBlib_errno = SMBlibE_RecvFailed; - return (SMBlibE_BAD); + RFCNB_Free_Pkt(pkt); + SMBlib_errno = SMBlibE_RecvFailed; + return (SMBlibE_BAD); } /* Check out the response type ... */ @@ -522,29 +522,29 @@ SMB_Logon_Server(SMB_Handle_Type Con_Handle, char *UserName, if (CVAL(SMB_Hdr(pkt), SMB_hdr_rcls_offset) != SMBC_SUCCESS) { /* Process error */ #ifdef DEBUG - fprintf(stderr, "SMB_SessSetupAndX failed with errorclass = %i, Error Code = %i\n", - CVAL(SMB_Hdr(pkt), SMB_hdr_rcls_offset), - SVAL(SMB_Hdr(pkt), SMB_hdr_err_offset)); + fprintf(stderr, "SMB_SessSetupAndX failed with errorclass = %i, Error Code = %i\n", + CVAL(SMB_Hdr(pkt), SMB_hdr_rcls_offset), + SVAL(SMB_Hdr(pkt), SMB_hdr_err_offset)); #endif - SMBlib_SMB_Error = IVAL(SMB_Hdr(pkt), SMB_hdr_rcls_offset); - RFCNB_Free_Pkt(pkt); - SMBlib_errno = SMBlibE_Remote; - return (SMBlibE_BAD); + SMBlib_SMB_Error = IVAL(SMB_Hdr(pkt), SMB_hdr_rcls_offset); + RFCNB_Free_Pkt(pkt); + SMBlib_errno = SMBlibE_Remote; + return (SMBlibE_BAD); } -/** @@@ mdz: check for guest login { **/ + /** @@@ mdz: check for guest login { **/ if (SVAL(SMB_Hdr(pkt), SMB_ssetpr_act_offset) & 0x1) { - /* do we allow guest login? NO! */ - return (SMBlibE_BAD); + /* do we allow guest login? NO! */ + return (SMBlibE_BAD); } -/** @@@ mdz: } **/ + /** @@@ mdz: } **/ #ifdef DEBUG fprintf(stderr, "SessSetupAndX response. Action = %i\n", - SVAL(SMB_Hdr(pkt), SMB_ssetpr_act_offset)); + SVAL(SMB_Hdr(pkt), SMB_ssetpr_act_offset)); #endif /* Now pick up the UID for future reference ... */ @@ -565,10 +565,10 @@ SMB_Discon(SMB_Handle_Type Con_Handle, BOOL KeepHandle) /* We just disconnect the connection for now ... */ if (Con_Handle != NULL) - RFCNB_Hangup(Con_Handle->Trans_Connect); + RFCNB_Hangup(Con_Handle->Trans_Connect); if (!KeepHandle) - free(Con_Handle); + free(Con_Handle); return (0); diff --git a/helpers/ntlm_auth/SMB/smbval/smblib.h b/helpers/ntlm_auth/SMB/smbval/smblib.h index 92467a60b7..e299aa466f 100644 --- a/helpers/ntlm_auth/SMB/smbval/smblib.h +++ b/helpers/ntlm_auth/SMB/smbval/smblib.h @@ -1,10 +1,10 @@ /* UNIX SMBlib NetBIOS implementation - * + * * Version 1.0 * SMBlib Defines - * + * * Copyright (C) Richard Sharpe 1996 - * + * */ /* @@ -12,12 +12,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -40,7 +40,7 @@ void *SMB_Connect_Server(void *Con, char *server, char *NTdomain); /* The handle and populate it with defaults */ void *SMB_Connect(void *Con, void **tree, - char *name, char *User, char *Password); + char *name, char *User, char *Password); /* Negotiate a protocol */ @@ -49,7 +49,7 @@ int SMB_Negotiate(void *Con_Handle, char *Prots[]); /* Connect to a tree ... */ void *SMB_TreeConnect(void *con_handle, void *tree_handle, - char *path, char *password, char *dev); + char *path, char *password, char *dev); /* Disconnect a tree ... */ @@ -58,10 +58,10 @@ int SMB_TreeDisconect(void *tree_handle); /* Open a file */ void *SMB_Open(void *tree_handle, - void *file_handle, - char *file_name, - unsigned short mode, - unsigned short search); + void *file_handle, + char *file_name, + unsigned short mode, + unsigned short search); /* Close a file */ @@ -73,9 +73,9 @@ int SMB_Close(void *file_handle); int SMB_Discon(void *Con, BOOL KeepHandle); void *SMB_Create(void *Tree_Handle, - void *File_Handle, - char *file_name, - short search); + void *File_Handle, + char *file_name, + short search); int SMB_Delete(void *tree, char *file_name, short search); @@ -92,7 +92,7 @@ int SMB_Get_Last_SMB_Err(); int SMB_Get_Error_Msg(int msg, char *msgbuf, int len); void *SMB_Logon_And_TCon(void *con, void *tree, char *user, char *pass, - char *service, char *st); + char *service, char *st); #define SMBLIB_DEFAULT_DOMAIN "anydom" diff --git a/helpers/ntlm_auth/SMB/smbval/std-defines.h b/helpers/ntlm_auth/SMB/smbval/std-defines.h index 325317dbfe..fcbffda544 100644 --- a/helpers/ntlm_auth/SMB/smbval/std-defines.h +++ b/helpers/ntlm_auth/SMB/smbval/std-defines.h @@ -3,11 +3,11 @@ /* RFCNB Standard includes ... */ /* - * + * * SMBlib Standard Includes - * + * * Copyright (C) 1996, Richard Sharpe - * + * * One day we will conditionalize these on OS types ... */ /* @@ -15,12 +15,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. diff --git a/helpers/ntlm_auth/SMB/smbval/std-includes.h b/helpers/ntlm_auth/SMB/smbval/std-includes.h index 1bd081c1eb..9155659561 100644 --- a/helpers/ntlm_auth/SMB/smbval/std-includes.h +++ b/helpers/ntlm_auth/SMB/smbval/std-includes.h @@ -1,10 +1,10 @@ /* RFCNB Standard includes ... */ /* - * + * * RFCNB Standard Includes - * + * * Copyright (C) 1996, Richard Sharpe - * + * * One day we will conditionalize these on OS types ... */ /* @@ -12,12 +12,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. diff --git a/helpers/ntlm_auth/SMB/smbval/valid.c b/helpers/ntlm_auth/SMB/smbval/valid.c index f2f6e294a1..4815049afa 100644 --- a/helpers/ntlm_auth/SMB/smbval/valid.c +++ b/helpers/ntlm_auth/SMB/smbval/valid.c @@ -12,39 +12,39 @@ int Valid_User(char *USERNAME, char *PASSWORD, char *SERVER, char *BACKUP, char *DOMAIN) { int pass_is_precrypted_p = 0; - char *SMB_Prots[] = - { -/* "PC NETWORK PROGRAM 1.0", */ -/* "MICROSOFT NETWORKS 1.03", */ -/* "MICROSOFT NETWORKS 3.0", */ - "LANMAN1.0", - "LM1.2X002", - "Samba", -/* "NT LM 0.12", */ -/* "NT LANMAN 1.0", */ - NULL}; + char *SMB_Prots[] = { + /* "PC NETWORK PROGRAM 1.0", */ + /* "MICROSOFT NETWORKS 1.03", */ + /* "MICROSOFT NETWORKS 3.0", */ + "LANMAN1.0", + "LM1.2X002", + "Samba", + /* "NT LM 0.12", */ + /* "NT LANMAN 1.0", */ + NULL + }; SMB_Handle_Type con; SMB_Init(); con = SMB_Connect_Server(NULL, SERVER, DOMAIN); if (con == NULL) { /* Error ... */ - con = SMB_Connect_Server(NULL, BACKUP, DOMAIN); - if (con == NULL) { - return (NTV_SERVER_ERROR); - } + con = SMB_Connect_Server(NULL, BACKUP, DOMAIN); + if (con == NULL) { + return (NTV_SERVER_ERROR); + } } if (SMB_Negotiate(con, SMB_Prots) < 0) { /* An error */ - SMB_Discon(con, 0); - return (NTV_PROTOCOL_ERROR); + SMB_Discon(con, 0); + return (NTV_PROTOCOL_ERROR); } /* Test for a server in share level mode do not authenticate against it */ if (con->Security == 0) { - SMB_Discon(con, 0); - return (NTV_PROTOCOL_ERROR); + SMB_Discon(con, 0); + return (NTV_PROTOCOL_ERROR); } if (SMB_Logon_Server(con, USERNAME, PASSWORD, DOMAIN, pass_is_precrypted_p) < 0) { - SMB_Discon(con, 0); - return (NTV_LOGON_ERROR); + SMB_Discon(con, 0); + return (NTV_LOGON_ERROR); } SMB_Discon(con, 0); return (NTV_NO_ERROR); @@ -53,35 +53,35 @@ Valid_User(char *USERNAME, char *PASSWORD, char *SERVER, char *BACKUP, char *DOM void * NTLM_Connect(char *SERVER, char *BACKUP, char *DOMAIN, char *nonce) { - char *SMB_Prots[] = - { -/* "PC NETWORK PROGRAM 1.0", */ -/* "MICROSOFT NETWORKS 1.03", */ -/* "MICROSOFT NETWORKS 3.0", */ - "LANMAN1.0", - "LM1.2X002", - "Samba", -/* "NT LM 0.12", */ -/* "NT LANMAN 1.0", */ - NULL}; + char *SMB_Prots[] = { + /* "PC NETWORK PROGRAM 1.0", */ + /* "MICROSOFT NETWORKS 1.03", */ + /* "MICROSOFT NETWORKS 3.0", */ + "LANMAN1.0", + "LM1.2X002", + "Samba", + /* "NT LM 0.12", */ + /* "NT LANMAN 1.0", */ + NULL + }; SMB_Handle_Type con; SMB_Init(); con = SMB_Connect_Server(NULL, SERVER, DOMAIN); if (con == NULL) { /* Error ... */ - con = SMB_Connect_Server(NULL, BACKUP, DOMAIN); - if (con == NULL) { - return (NULL); - } + con = SMB_Connect_Server(NULL, BACKUP, DOMAIN); + if (con == NULL) { + return (NULL); + } } if (SMB_Negotiate(con, SMB_Prots) < 0) { /* An error */ - SMB_Discon(con, 0); - return (NULL); + SMB_Discon(con, 0); + return (NULL); } /* Test for a server in share level mode do not authenticate against it */ if (con->Security == 0) { - SMB_Discon(con, 0); - return (NULL); + SMB_Discon(con, 0); + return (NULL); } memcpy(nonce, con->Encrypt_Key, 8); @@ -94,7 +94,7 @@ NTLM_Auth(void *handle, char *USERNAME, char *PASSWORD, int flag) SMB_Handle_Type con = handle; if (SMB_Logon_Server(con, USERNAME, PASSWORD, NULL, flag) < 0) { - return (NTV_LOGON_ERROR); + return (NTV_LOGON_ERROR); } return (NTV_NO_ERROR); } diff --git a/helpers/ntlm_auth/fakeauth/fakeauth_auth.c b/helpers/ntlm_auth/fakeauth/fakeauth_auth.c index 18c75fc3bd..10d66171a1 100644 --- a/helpers/ntlm_auth/fakeauth/fakeauth_auth.c +++ b/helpers/ntlm_auth/fakeauth/fakeauth_auth.c @@ -71,55 +71,51 @@ hex_dump(void *data, int size) */ if (!data) - return; + return; if (debug_enabled) { - unsigned char *p = data; - unsigned char c; - int n; - char bytestr[4] = - {0}; - char addrstr[10] = - {0}; - char hexstr[16 * 3 + 5] = - {0}; - char charstr[16 * 1 + 5] = - {0}; - for (n = 1; n <= size; n++) { - if (n % 16 == 1) { - /* store address for this line */ - snprintf(addrstr, sizeof(addrstr), "%.4x", - (int) (p - (unsigned char *) data)); - } - c = *p; - if (xisalnum(c) == 0) { - c = '.'; - } - /* store hex str (for left side) */ - snprintf(bytestr, sizeof(bytestr), "%02X ", *p); - strncat(hexstr, bytestr, sizeof(hexstr) - strlen(hexstr) - 1); - - /* store char str (for right side) */ - snprintf(bytestr, sizeof(bytestr), "%c", c); - strncat(charstr, bytestr, sizeof(charstr) - strlen(charstr) - 1); - - if (n % 16 == 0) { - /* line completed */ - fprintf(stderr, "[%4.4s] %-50.50s %s\n", addrstr, hexstr, charstr); - hexstr[0] = 0; - charstr[0] = 0; - } else if (n % 8 == 0) { - /* half line: add whitespaces */ - strncat(hexstr, " ", sizeof(hexstr) - strlen(hexstr) - 1); - strncat(charstr, " ", sizeof(charstr) - strlen(charstr) - 1); - } - p++; /* next byte */ - } - - if (strlen(hexstr) > 0) { - /* print rest of buffer if not empty */ - fprintf(stderr, "[%4.4s] %-50.50s %s\n", addrstr, hexstr, charstr); - } + unsigned char *p = data; + unsigned char c; + int n; + char bytestr[4] = {0}; + char addrstr[10] = {0}; + char hexstr[16 * 3 + 5] = {0}; + char charstr[16 * 1 + 5] = {0}; + for (n = 1; n <= size; n++) { + if (n % 16 == 1) { + /* store address for this line */ + snprintf(addrstr, sizeof(addrstr), "%.4x", + (int) (p - (unsigned char *) data)); + } + c = *p; + if (xisalnum(c) == 0) { + c = '.'; + } + /* store hex str (for left side) */ + snprintf(bytestr, sizeof(bytestr), "%02X ", *p); + strncat(hexstr, bytestr, sizeof(hexstr) - strlen(hexstr) - 1); + + /* store char str (for right side) */ + snprintf(bytestr, sizeof(bytestr), "%c", c); + strncat(charstr, bytestr, sizeof(charstr) - strlen(charstr) - 1); + + if (n % 16 == 0) { + /* line completed */ + fprintf(stderr, "[%4.4s] %-50.50s %s\n", addrstr, hexstr, charstr); + hexstr[0] = 0; + charstr[0] = 0; + } else if (n % 8 == 0) { + /* half line: add whitespaces */ + strncat(hexstr, " ", sizeof(hexstr) - strlen(hexstr) - 1); + strncat(charstr, " ", sizeof(charstr) - strlen(charstr) - 1); + } + p++; /* next byte */ + } + + if (strlen(hexstr) > 0) { + /* print rest of buffer if not empty */ + fprintf(stderr, "[%4.4s] %-50.50s %s\n", addrstr, hexstr, charstr); + } } } @@ -130,14 +126,14 @@ lc(char *string) { char *p = string, c; while ((c = *p)) { - *p = xtolower(c); - p++; + *p = xtolower(c); + p++; } } /* - * Generates a challenge request. The randomness of the 8 byte + * Generates a challenge request. The randomness of the 8 byte * challenge strings can be guarenteed to be poor at best. */ void @@ -153,11 +149,11 @@ ntlmMakeChallenge(struct ntlm_challenge *chal, int32_t flags) memset(chal, 0, sizeof(*chal)); memcpy(chal->hdr.signature, "NTLMSSP", 8); chal->flags = htole32(CHALLENGE_TARGET_IS_DOMAIN | - NEGOTIATE_ALWAYS_SIGN | - NEGOTIATE_USE_NTLM | - NEGOTIATE_REQUEST_TARGET | - (NEGOTIATE_UNICODE & flags ? NEGOTIATE_UNICODE : NEGOTIATE_ASCII) - ); + NEGOTIATE_ALWAYS_SIGN | + NEGOTIATE_USE_NTLM | + NEGOTIATE_REQUEST_TARGET | + (NEGOTIATE_UNICODE & flags ? NEGOTIATE_UNICODE : NEGOTIATE_ASCII) + ); chal->hdr.type = htole32(NTLM_CHALLENGE); chal->unknown[6] = htole16(0x003a); @@ -165,7 +161,7 @@ ntlmMakeChallenge(struct ntlm_challenge *chal, int32_t flags) i = 0; if (authenticate_ntlm_domain != NULL) - while (authenticate_ntlm_domain[i++]); + while (authenticate_ntlm_domain[i++]); chal->target.offset = htole32(48); @@ -176,8 +172,8 @@ ntlmMakeChallenge(struct ntlm_challenge *chal, int32_t flags) r = (hash ^ r) + r; for (i = 0; i < 8; i++) { - chal->challenge[i] = r; - r = (r >> 2) ^ r; + chal->challenge[i] = r; + r = (r >> 2) ^ r; } hash = r; @@ -189,22 +185,22 @@ ntlmMakeChallenge(struct ntlm_challenge *chal, int32_t flags) int ntlmCheckHeader(ntlmhdr * hdr, int type) { - /* + /* * Must be the correct security package and request type. The - * 8 bytes compared includes the ASCII 'NUL'. + * 8 bytes compared includes the ASCII 'NUL'. */ if (memcmp(hdr->signature, "NTLMSSP", 8) != 0) { - fprintf(stderr, "ntlmCheckHeader: bad header signature\n"); - return (-1); + fprintf(stderr, "ntlmCheckHeader: bad header signature\n"); + return (-1); } if (type == NTLM_ANY) - return 0; + return 0; if (le32toh(hdr->type) != type) { -/* don't report this error - it's ok as we do a if() around this function */ + /* don't report this error - it's ok as we do a if() around this function */ // fprintf(stderr, "ntlmCheckHeader: type is %d, wanted %d\n", - // le32toh(hdr->type), type); - return (-1); + // le32toh(hdr->type), type); + return (-1); } return (0); } @@ -225,38 +221,38 @@ ntlmGetString(ntlmhdr * hdr, strhdr * str, int flags) /* Sanity checks. XXX values arbitrarialy chosen */ if (l <= 0 || l >= 32 || o >= 256) { - fprintf(stderr, "ntlmGetString: insane: l:%d o:%d\n", l, o); - return (NULL); + fprintf(stderr, "ntlmGetString: insane: l:%d o:%d\n", l, o); + return (NULL); } if ((flags & NEGOTIATE_ASCII) == 0) { - /* UNICODE string */ - s = (u_short *) ((char *) hdr + o); - d = buf; - - for (l >>= 1; l; s++, l--) { - c = le16toh(*s); - if (c > 254 || c == '\0') { - fprintf(stderr, "ntlmGetString: bad uni: %04x\n", c); - return (NULL); - } - *d++ = c; - } - - *d = 0; + /* UNICODE string */ + s = (u_short *) ((char *) hdr + o); + d = buf; + + for (l >>= 1; l; s++, l--) { + c = le16toh(*s); + if (c > 254 || c == '\0') { + fprintf(stderr, "ntlmGetString: bad uni: %04x\n", c); + return (NULL); + } + *d++ = c; + } + + *d = 0; } else { - /* ASCII/OEM string */ - sc = (char *) hdr + o; - d = buf; - - for (; l; l--) { - if (*sc == '\0' || !xisprint(*sc)) { - fprintf(stderr, "ntlmGetString: bad ascii: %04x\n", *sc); - return (NULL); - } - *d++ = *sc++; - } - - *d = 0; + /* ASCII/OEM string */ + sc = (char *) hdr + o; + d = buf; + + for (; l; l--) { + if (*sc == '\0' || !xisprint(*sc)) { + fprintf(stderr, "ntlmGetString: bad ascii: %04x\n", *sc); + return (NULL); + } + *d++ = *sc++; + } + + *d = 0; } return (buf); @@ -273,24 +269,24 @@ ntlmDecodeAuth(struct ntlm_authenticate *auth, char *buf, size_t size) int s; if (!buf) { - return 1; + return 1; } origbuf = buf; if (ntlmCheckHeader(&auth->hdr, NTLM_AUTHENTICATE)) { - fprintf(stderr, "ntlmDecodeAuth: header check fails\n"); - return -1; + fprintf(stderr, "ntlmDecodeAuth: header check fails\n"); + return -1; } debug("ntlmDecodeAuth: size of %d\n", (int) size); debug("ntlmDecodeAuth: flg %08x\n", auth->flags); debug("ntlmDecodeAuth: usr o(%d) l(%d)\n", auth->user.offset, auth->user.len); if ((p = ntlmGetString(&auth->hdr, &auth->domain, auth->flags)) == NULL) - p = authenticate_ntlm_domain; + p = authenticate_ntlm_domain; debug("ntlmDecodeAuth: Domain '%s'.\n", p); if ((s = strlen(p) + 1) >= size) - return 1; + return 1; strcpy(buf, p); debug("ntlmDecodeAuth: Domain '%s'.\n", buf); @@ -299,14 +295,14 @@ ntlmDecodeAuth(struct ntlm_authenticate *auth, char *buf, size_t size) buf += (s - 1); *buf++ = '\\'; /* Using \ is more consistent with MS-proxy */ - if( (p = ntlmGetString(&auth->hdr, &auth->user, auth->flags)) == NULL) + if ( (p = ntlmGetString(&auth->hdr, &auth->user, auth->flags)) == NULL) return 1; if ((s = strlen(p) + 1) >= size) - return 1; + return 1; while (*p) - *buf++ = (*p++); //tolower + *buf++ = (*p++); //tolower *buf++ = '\0'; size -= s; @@ -329,12 +325,12 @@ static void usage(void) { fprintf(stderr, - "Usage: %s [-d] [-v] [-h]\n" - " -d enable debugging.\n" - " -S strip domain from username.\n" - " -v enable verbose NTLM packet debugging.\n" - " -h this message\n\n", - my_program_name); + "Usage: %s [-d] [-v] [-h]\n" + " -d enable debugging.\n" + " -S strip domain from username.\n" + " -v enable verbose NTLM packet debugging.\n" + " -h this message\n\n", + my_program_name); } @@ -345,31 +341,31 @@ process_options(int argc, char *argv[]) opterr = 0; while (-1 != (opt = getopt(argc, argv, "hdvS"))) { - switch (opt) { - case 'd': - debug_enabled = 1; - break; - case 'v': - debug_enabled = 1; - NTLM_packet_debug_enabled = 1; - break; - case 'S': - strip_domain_enabled = 1; - break; - case 'h': - usage(); - exit(0); - case '?': - opt = optopt; - /* fall thru to default */ - default: - fprintf(stderr, "unknown option: -%c. Exiting\n", opt); - usage(); - had_error = 1; - } + switch (opt) { + case 'd': + debug_enabled = 1; + break; + case 'v': + debug_enabled = 1; + NTLM_packet_debug_enabled = 1; + break; + case 'S': + strip_domain_enabled = 1; + break; + case 'h': + usage(); + exit(0); + case '?': + opt = optopt; + /* fall thru to default */ + default: + fprintf(stderr, "unknown option: -%c. Exiting\n", opt); + usage(); + had_error = 1; + } } if (had_error) - exit(1); + exit(1); } @@ -395,63 +391,62 @@ main(int argc, char *argv[]) debug("%s build " __DATE__ ", " __TIME__ " starting up...\n", my_program_name); while (fgets(buf, BUFFER_SIZE, stdin) != NULL) { - user[0] = '\0'; /*no usercode */ + user[0] = '\0'; /*no usercode */ - if ((p = strchr(buf, '\n')) != NULL) - *p = '\0'; /* strip \n */ + if ((p = strchr(buf, '\n')) != NULL) + *p = '\0'; /* strip \n */ buflen = strlen(buf); /* keep this so we only scan the buffer for \0 once per loop */ - if (buflen > 3) - decoded = base64_decode(buf + 3); - if (buflen > 3 && NTLM_packet_debug_enabled) { - strncpy(helper_command, buf, 2); - helper_command[2] = '\0'; - debug("Got '%s' from Squid with data:\n", helper_command); - hex_dump(decoded, ((strlen(buf) - 3) * 3) / 4); - } else - debug("Got '%s' from Squid\n", buf); - - if (strncasecmp(buf, "YR", 2) == 0) { - if(buflen > 3) { - nego = (struct ntlm_negotiate *) decoded; - ntlmMakeChallenge(&chal, nego->flags); - } else - ntlmMakeChallenge(&chal, NEGOTIATE_ASCII); - len = - sizeof(chal) - sizeof(chal.pad) + - le16toh(chal.target.maxlen); - data = (char *) base64_encode_bin((char *) &chal, len); - if (NTLM_packet_debug_enabled) { - printf("TT %s\n", data); - decoded = base64_decode(data); - debug("sending 'TT' to squid with data:\n"); - hex_dump(decoded, (strlen(data) * 3) / 4); - } else - SEND2("TT %s", data); - } else if (strncasecmp(buf, "KK ", 3) == 0) { - if(!decoded) { + if (buflen > 3) + decoded = base64_decode(buf + 3); + if (buflen > 3 && NTLM_packet_debug_enabled) { + strncpy(helper_command, buf, 2); + helper_command[2] = '\0'; + debug("Got '%s' from Squid with data:\n", helper_command); + hex_dump(decoded, ((strlen(buf) - 3) * 3) / 4); + } else + debug("Got '%s' from Squid\n", buf); + + if (strncasecmp(buf, "YR", 2) == 0) { + if (buflen > 3) { + nego = (struct ntlm_negotiate *) decoded; + ntlmMakeChallenge(&chal, nego->flags); + } else + ntlmMakeChallenge(&chal, NEGOTIATE_ASCII); + len = + sizeof(chal) - sizeof(chal.pad) + + le16toh(chal.target.maxlen); + data = (char *) base64_encode_bin((char *) &chal, len); + if (NTLM_packet_debug_enabled) { + printf("TT %s\n", data); + decoded = base64_decode(data); + debug("sending 'TT' to squid with data:\n"); + hex_dump(decoded, (strlen(data) * 3) / 4); + } else + SEND2("TT %s", data); + } else if (strncasecmp(buf, "KK ", 3) == 0) { + if (!decoded) { SEND2("BH received KK with no data! user=%s", user); + } else if (!ntlmCheckHeader((ntlmhdr *) decoded, NTLM_AUTHENTICATE)) { + if (!ntlmDecodeAuth((struct ntlm_authenticate *) decoded, user, 256)) { + lc(user); + if (strip_domain_enabled) { + strtok(user, "\\"); + p = strtok(NULL, "\\"); + if (!p) + p = user; + SEND2("AF %s", p); + } else { + SEND2("AF %s", user); + } + } else { + lc(user); + SEND2("NA invalid credentials, user=%s", user); + } + } else { + lc(user); + SEND2("BH wrong packet type! user=%s", user); } - else if (!ntlmCheckHeader((ntlmhdr *) decoded, NTLM_AUTHENTICATE)) { - if (!ntlmDecodeAuth((struct ntlm_authenticate *) decoded, user, 256)) { - lc(user); - if (strip_domain_enabled) { - strtok(user, "\\"); - p = strtok(NULL, "\\"); - if (!p) - p = user; - SEND2("AF %s", p); - } else { - SEND2("AF %s", user); - } - } else { - lc(user); - SEND2("NA invalid credentials, user=%s", user); - } - } else { - lc(user); - SEND2("BH wrong packet type! user=%s", user); - } - } + } } exit(0); } diff --git a/helpers/ntlm_auth/fakeauth/ntlm.h b/helpers/ntlm_auth/fakeauth/ntlm.h index fccc495603..426cb48df2 100644 --- a/helpers/ntlm_auth/fakeauth/ntlm.h +++ b/helpers/ntlm_auth/fakeauth/ntlm.h @@ -19,16 +19,16 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. - * + * */ #ifndef _NTLM_H_ @@ -131,21 +131,21 @@ debug(char *format,...) #if FAIL_DEBUG if (debug_enabled || fail_debug_enabled) { #else - if (debug_enabled) { + if (debug_enabled) { #endif - va_list args; + va_list args; - va_start(args, format); - fprintf(stderr, "ntlm-auth[%ld]: ", (long)getpid()); - vfprintf(stderr, format, args); - va_end(args); + va_start(args, format); + fprintf(stderr, "ntlm-auth[%ld]: ", (long)getpid()); + vfprintf(stderr, format, args); + va_end(args); #if FAIL_DEBUG - fail_debug_enabled = 0; + fail_debug_enabled = 0; #endif - } + } #endif /* _SQUID_MSWIN_ */ #endif /* DEBUG */ -} + } #endif /* __GNUC__ */ diff --git a/helpers/ntlm_auth/mswin_sspi/libntlmssp.c b/helpers/ntlm_auth/mswin_sspi/libntlmssp.c index 02c50bcf52..ae289797e2 100644 --- a/helpers/ntlm_auth/mswin_sspi/libntlmssp.c +++ b/helpers/ntlm_auth/mswin_sspi/libntlmssp.c @@ -8,7 +8,7 @@ * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - + * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -43,52 +43,52 @@ Valid_Group(char *UserName, char *Group) DWORD i; DWORD dwTotalCount = 0; -/* Convert ANSI User Name and Group to Unicode */ + /* Convert ANSI User Name and Group to Unicode */ MultiByteToWideChar(CP_ACP, 0, UserName, - strlen(UserName) + 1, wszUserName, - sizeof(wszUserName) / sizeof(wszUserName[0])); + strlen(UserName) + 1, wszUserName, + sizeof(wszUserName) / sizeof(wszUserName[0])); MultiByteToWideChar(CP_ACP, 0, Group, - strlen(Group) + 1, wszGroup, sizeof(wszGroup) / sizeof(wszGroup[0])); + strlen(Group) + 1, wszGroup, sizeof(wszGroup) / sizeof(wszGroup[0])); /* - * Call the NetUserGetLocalGroups function - * specifying information level 0. - * - * The LG_INCLUDE_INDIRECT flag specifies that the - * function should also return the names of the local - * groups in which the user is indirectly a member. - */ - nStatus = NetUserGetLocalGroups(NULL, - wszUserName, - dwLevel, - dwFlags, - (LPBYTE *) & pBuf, dwPrefMaxLen, &dwEntriesRead, &dwTotalEntries); - /* - * If the call succeeds, - */ + * Call the NetUserGetLocalGroups function + * specifying information level 0. + * + * The LG_INCLUDE_INDIRECT flag specifies that the + * function should also return the names of the local + * groups in which the user is indirectly a member. + */ + nStatus = NetUserGetLocalGroups(NULL, + wszUserName, + dwLevel, + dwFlags, + (LPBYTE *) & pBuf, dwPrefMaxLen, &dwEntriesRead, &dwTotalEntries); + /* + * If the call succeeds, + */ if (nStatus == NERR_Success) { - if ((pTmpBuf = pBuf) != NULL) { - for (i = 0; i < dwEntriesRead; i++) { - if (pTmpBuf == NULL) { - result = FALSE; - break; - } - if (wcscmp(pTmpBuf->lgrui0_name, wszGroup) == 0) { - result = TRUE; - break; - } - pTmpBuf++; - dwTotalCount++; - } - } + if ((pTmpBuf = pBuf) != NULL) { + for (i = 0; i < dwEntriesRead; i++) { + if (pTmpBuf == NULL) { + result = FALSE; + break; + } + if (wcscmp(pTmpBuf->lgrui0_name, wszGroup) == 0) { + result = TRUE; + break; + } + pTmpBuf++; + dwTotalCount++; + } + } } else - result = FALSE; -/* - * Free the allocated memory. - */ + result = FALSE; + /* + * Free the allocated memory. + */ if (pBuf != NULL) - NetApiBufferFree(pBuf); + NetApiBufferFree(pBuf); return result; } @@ -104,7 +104,7 @@ char * AllocStrFromLSAStr(LSA_UNICODE_STRING LsaStr) safe_free(target); target = (char *)xmalloc(len); if (target == NULL) - return NULL; + return NULL; /* copy unicode buffer */ WideCharToMultiByte(CP_ACP, 0, LsaStr.Buffer, LsaStr.Length, target, len, NULL, NULL ); @@ -126,80 +126,80 @@ char * GetDomainName(void) DWORD netret; char * DomainName = NULL; - /* + /* * Always initialize the object attributes to all zeroes. - */ + */ memset(&ObjectAttributes, '\0', sizeof(ObjectAttributes)); - /* + /* * You need the local workstation name. Use NetWkstaGetInfo at level * 100 to retrieve a WKSTA_INFO_100 structure. - * + * * The wki100_computername field contains a pointer to a UNICODE * string containing the local computer name. - */ + */ netret = NetWkstaGetInfo(NULL, 100, (LPBYTE *)&pwkiWorkstationInfo); if (netret == NERR_Success) { - /* - * We have the workstation name in: - * pwkiWorkstationInfo->wki100_computername - * - * Next, open the policy object for the local system using - * the LsaOpenPolicy function. - */ - status = LsaOpenPolicy( - NULL, - &ObjectAttributes, - GENERIC_READ | POLICY_VIEW_LOCAL_INFORMATION, - &PolicyHandle - ); - - /* - * Error checking. - */ - if (status) { - debug("OpenPolicy Error: %ld\n", status); - } else { - - /* - * You have a handle to the policy object. Now, get the - * domain information using LsaQueryInformationPolicy. - */ - status = LsaQueryInformationPolicy(PolicyHandle, - PolicyPrimaryDomainInformation, - (void **)&ppdiDomainInfo); - if (status) { - debug("LsaQueryInformationPolicy Error: %ld\n", status); - } else { - - /* Get name in useable format */ - DomainName = AllocStrFromLSAStr(ppdiDomainInfo->Name); - - /* - * Check the Sid pointer, if it is null, the - * workstation is either a stand-alone computer - * or a member of a workgroup. - */ - if (ppdiDomainInfo->Sid) { - - /* - * Member of a domain. Display it in debug mode. - */ - debug("Member of Domain %s\n",DomainName); - } else { - DomainName = NULL; + /* + * We have the workstation name in: + * pwkiWorkstationInfo->wki100_computername + * + * Next, open the policy object for the local system using + * the LsaOpenPolicy function. + */ + status = LsaOpenPolicy( + NULL, + &ObjectAttributes, + GENERIC_READ | POLICY_VIEW_LOCAL_INFORMATION, + &PolicyHandle + ); + + /* + * Error checking. + */ + if (status) { + debug("OpenPolicy Error: %ld\n", status); + } else { + + /* + * You have a handle to the policy object. Now, get the + * domain information using LsaQueryInformationPolicy. + */ + status = LsaQueryInformationPolicy(PolicyHandle, + PolicyPrimaryDomainInformation, + (void **)&ppdiDomainInfo); + if (status) { + debug("LsaQueryInformationPolicy Error: %ld\n", status); + } else { + + /* Get name in useable format */ + DomainName = AllocStrFromLSAStr(ppdiDomainInfo->Name); + + /* + * Check the Sid pointer, if it is null, the + * workstation is either a stand-alone computer + * or a member of a workgroup. + */ + if (ppdiDomainInfo->Sid) { + + /* + * Member of a domain. Display it in debug mode. + */ + debug("Member of Domain %s\n",DomainName); + } else { + DomainName = NULL; } - } - } - - /* - * Clean up all the memory buffers created by the LSA and - * Net* APIs. - */ - NetApiBufferFree(pwkiWorkstationInfo); - LsaFreeMemory((LPVOID)ppdiDomainInfo); - } else - debug("NetWkstaGetInfo Error: %ld\n", netret); + } + } + + /* + * Clean up all the memory buffers created by the LSA and + * Net* APIs. + */ + NetApiBufferFree(pwkiWorkstationInfo); + LsaFreeMemory((LPVOID)ppdiDomainInfo); + } else + debug("NetWkstaGetInfo Error: %ld\n", netret); return DomainName; } @@ -228,9 +228,9 @@ ntlm_check_auth(ntlm_authenticate * auth, int auth_length) tmp = ntlm_fetch_string((char *) auth, auth_length, &auth->domain); if (tmp.str == NULL || tmp.l == 0) { - debug("No domain supplied. Returning no-auth\n"); - ntlm_errno = NTLM_BAD_REQUEST; - return NULL; + debug("No domain supplied. Returning no-auth\n"); + ntlm_errno = NTLM_BAD_REQUEST; + return NULL; } if (Use_Unicode) { /* copy unicode buffer */ @@ -239,18 +239,18 @@ ntlm_check_auth(ntlm_authenticate * auth, int auth_length) domain[tmp.l / sizeof(WCHAR)] = '\0'; } else { if (tmp.l > DNLEN) { - debug("Domain string exceeds %d bytes, rejecting\n", DNLEN); - ntlm_errno = NTLM_BAD_REQUEST; - return NULL; + debug("Domain string exceeds %d bytes, rejecting\n", DNLEN); + ntlm_errno = NTLM_BAD_REQUEST; + return NULL; } memcpy(domain, tmp.str, tmp.l); domain[tmp.l] = '\0'; } tmp = ntlm_fetch_string((char *) auth, auth_length, &auth->user); if (tmp.str == NULL || tmp.l == 0) { - debug("No username supplied. Returning no-auth\n"); - ntlm_errno = NTLM_BAD_REQUEST; - return NULL; + debug("No username supplied. Returning no-auth\n"); + ntlm_errno = NTLM_BAD_REQUEST; + return NULL; } if (Use_Unicode) { /* copy unicode buffer */ @@ -259,9 +259,9 @@ ntlm_check_auth(ntlm_authenticate * auth, int auth_length) user[tmp.l / sizeof(WCHAR)] = '\0'; } else { if (tmp.l > UNLEN) { - debug("Username string exceeds %d bytes, rejecting\n", UNLEN); - ntlm_errno = NTLM_BAD_REQUEST; - return NULL; + debug("Username string exceeds %d bytes, rejecting\n", UNLEN); + ntlm_errno = NTLM_BAD_REQUEST; + return NULL; } memcpy(user, tmp.str, tmp.l); user[tmp.l] = '\0'; @@ -276,23 +276,23 @@ ntlm_check_auth(ntlm_authenticate * auth, int auth_length) debug("Login attempt had result %d\n", rv); if (!rv) { /* failed */ - ntlm_errno = NTLM_SSPI_ERROR; - return NULL; + ntlm_errno = NTLM_SSPI_ERROR; + return NULL; } - + if (UseAllowedGroup) { - if (!Valid_Group(credentials, NTAllowedGroup)) { - ntlm_errno = NTLM_BAD_NTGROUP; - debug("User %s not in allowed Group %s\n", credentials, NTAllowedGroup); - return NULL; - } + if (!Valid_Group(credentials, NTAllowedGroup)) { + ntlm_errno = NTLM_BAD_NTGROUP; + debug("User %s not in allowed Group %s\n", credentials, NTAllowedGroup); + return NULL; + } } if (UseDisallowedGroup) { - if (Valid_Group(credentials, NTDisAllowedGroup)) { - ntlm_errno = NTLM_BAD_NTGROUP; - debug("User %s is in denied Group %s\n", credentials, NTDisAllowedGroup); - return NULL; - } + if (Valid_Group(credentials, NTDisAllowedGroup)) { + ntlm_errno = NTLM_BAD_NTGROUP; + debug("User %s is in denied Group %s\n", credentials, NTDisAllowedGroup); + return NULL; + } } debug("credentials: %s\n", credentials); @@ -309,12 +309,12 @@ ntlm_make_negotiate(void) memcpy(ne.signature, "NTLMSSP", 8); /* set the signature */ ne.type = le32toh(NTLM_NEGOTIATE); /* this is a challenge */ ne.flags = le32toh( - NEGOTIATE_ALWAYS_SIGN | - NEGOTIATE_USE_NTLM | - NEGOTIATE_USE_LM | - NEGOTIATE_ASCII | - 0 - ); + NEGOTIATE_ALWAYS_SIGN | + NEGOTIATE_USE_NTLM | + NEGOTIATE_USE_LM | + NEGOTIATE_ASCII | + 0 + ); encoded = base64_encode_bin((char *) &ne, NEGOTIATE_LENGTH); debug("Negotiate packet not supplied - self generated\n"); return encoded; @@ -340,13 +340,13 @@ void hex_dump(void *data, int size) char addrstr[10] = {0}; char hexstr[ 16*3 + 5] = {0}; char charstr[16*1 + 5] = {0}; - for(n=1;n<=size;n++) { + for (n=1;n<=size;n++) { if (n%16 == 1) { /* store address for this line */ snprintf(addrstr, sizeof(addrstr), "%.4x", - ((unsigned int)p-(unsigned int)data) ); + ((unsigned int)p-(unsigned int)data) ); } - + c = *p; if (xisalnum(c) == 0) { c = '.'; @@ -360,12 +360,12 @@ void hex_dump(void *data, int size) snprintf(bytestr, sizeof(bytestr), "%c", c); strncat(charstr, bytestr, sizeof(charstr)-strlen(charstr)-1); - if(n%16 == 0) { + if (n%16 == 0) { /* line completed */ fprintf(stderr, "[%4.4s] %-50.50s %s\n", addrstr, hexstr, charstr); hexstr[0] = 0; charstr[0] = 0; - } else if(n%8 == 0) { + } else if (n%8 == 0) { /* half line: add whitespaces */ strncat(hexstr, " ", sizeof(hexstr)-strlen(hexstr)-1); strncat(charstr, " ", sizeof(charstr)-strlen(charstr)-1); diff --git a/helpers/ntlm_auth/mswin_sspi/ntlm.h b/helpers/ntlm_auth/mswin_sspi/ntlm.h index c632dc4d19..470d856a7d 100644 --- a/helpers/ntlm_auth/mswin_sspi/ntlm.h +++ b/helpers/ntlm_auth/mswin_sspi/ntlm.h @@ -9,7 +9,7 @@ * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - + * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -61,28 +61,28 @@ static char *__foo; #endif /* DEBUG */ #else /* __GNUC__ */ static void -debug(char *format,...) +debug(char *format,...) { #ifdef DEBUG #ifdef _SQUID_MSWIN_ #if FAIL_DEBUG if (debug_enabled || fail_debug_enabled) { #else - if (debug_enabled) { + if (debug_enabled) { #endif - va_list args; + va_list args; - va_start(args,format); - fprintf(stderr, "ntlm-auth[%d]: ",getpid()); - vfprintf(stderr, format, args); - va_end(args); + va_start(args,format); + fprintf(stderr, "ntlm-auth[%d]: ",getpid()); + vfprintf(stderr, format, args); + va_end(args); #if FAIL_DEBUG - fail_debug_enabled = 0; + fail_debug_enabled = 0; #endif - } + } #endif /* _SQUID_MSWIN_ */ #endif /* DEBUG */ -} + } #endif /* __GNUC__ */ diff --git a/helpers/ntlm_auth/mswin_sspi/ntlm_auth.c b/helpers/ntlm_auth/mswin_sspi/ntlm_auth.c index f2e8cc00db..31e76eaa0d 100644 --- a/helpers/ntlm_auth/mswin_sspi/ntlm_auth.c +++ b/helpers/ntlm_auth/mswin_sspi/ntlm_auth.c @@ -85,8 +85,8 @@ uc(char *string) { char *p = string, c; while ((c = *p)) { - *p = xtoupper(c); - p++; + *p = xtoupper(c); + p++; } } @@ -96,8 +96,8 @@ lc(char *string) { char *p = string, c; while ((c = *p)) { - *p = xtolower(c); - p++; + *p = xtolower(c); + p++; } } @@ -123,13 +123,13 @@ void usage() { fprintf(stderr, - "Usage: %s [-d] [-v] [-A|D LocalUserGroup] [-h]\n" - " -d enable debugging.\n" - " -v enable verbose NTLM packet debugging.\n" - " -A specify a Windows Local Group name allowed to authenticate\n" - " -D specify a Windows Local Group name not allowed to authenticate\n" - " -h this message\n\n", - my_program_name); + "Usage: %s [-d] [-v] [-A|D LocalUserGroup] [-h]\n" + " -d enable debugging.\n" + " -v enable verbose NTLM packet debugging.\n" + " -A specify a Windows Local Group name allowed to authenticate\n" + " -D specify a Windows Local Group name not allowed to authenticate\n" + " -h this message\n\n", + my_program_name); } @@ -140,38 +140,38 @@ process_options(int argc, char *argv[]) opterr =0; while (-1 != (opt = getopt(argc, argv, "hdvA:D:"))) { - switch (opt) { - case 'A': - safe_free(NTAllowedGroup); - NTAllowedGroup=xstrdup(optarg); - UseAllowedGroup = 1; - break; - case 'D': - safe_free(NTDisAllowedGroup); - NTDisAllowedGroup=xstrdup(optarg); - UseDisallowedGroup = 1; - break; - case 'd': - debug_enabled = 1; - break; - case 'v': - debug_enabled = 1; - NTLM_packet_debug_enabled = 1; - break; - case 'h': - usage(); - exit(0); - case '?': - opt = optopt; - /* fall thru to default */ - default: - fprintf(stderr, "unknown option: -%c. Exiting\n", opt); - usage(); - had_error = 1; - } + switch (opt) { + case 'A': + safe_free(NTAllowedGroup); + NTAllowedGroup=xstrdup(optarg); + UseAllowedGroup = 1; + break; + case 'D': + safe_free(NTDisAllowedGroup); + NTDisAllowedGroup=xstrdup(optarg); + UseDisallowedGroup = 1; + break; + case 'd': + debug_enabled = 1; + break; + case 'v': + debug_enabled = 1; + NTLM_packet_debug_enabled = 1; + break; + case 'h': + usage(); + exit(0); + case '?': + opt = optopt; + /* fall thru to default */ + default: + fprintf(stderr, "unknown option: -%c. Exiting\n", opt); + usage(); + had_error = 1; + } } if (had_error) - exit(1); + exit(1); } @@ -183,8 +183,8 @@ obtain_challenge(ntlm_negotiate * nego, int nego_length) debug("attempting SSPI challenge retrieval\n"); ch = SSP_MakeChallenge(nego, nego_length); if (ch) { - debug("Got it\n"); - return ch; /* All went OK, returning */ + debug("Got it\n"); + return ch; /* All went OK, returning */ } return NULL; } @@ -202,21 +202,21 @@ manage_request() char * ErrorMessage; try_again: - if (fgets(buf, BUFFER_SIZE, stdin) == NULL) + if (fgets(buf, BUFFER_SIZE, stdin) == NULL) return 0; c = memchr(buf, '\n', BUFFER_SIZE); /* safer against overrun than strchr */ if (c) { - if (oversized) { - helperfail("illegal request received"); - fprintf(stderr, "Illegal request received: '%s'\n", buf); - return 1; - } - *c = '\0'; + if (oversized) { + helperfail("illegal request received"); + fprintf(stderr, "Illegal request received: '%s'\n", buf); + return 1; + } + *c = '\0'; } else { - fprintf(stderr, "No newline in '%s'\n", buf); - oversized = 1; - goto try_again; + fprintf(stderr, "No newline in '%s'\n", buf); + oversized = 1; + goto try_again; } if ((strlen(buf) > 3) && NTLM_packet_debug_enabled) { decoded = base64_decode(buf + 3); @@ -226,153 +226,152 @@ try_again: } else debug("Got '%s' from Squid\n", buf); if (memcmp(buf, "YR", 2) == 0) { /* refresh-request */ - /* figure out what we got */ + /* figure out what we got */ if (strlen(buf) > 3) decoded = base64_decode(buf + 3); else decoded = base64_decode(ntlm_make_negotiate()); - /* Note: we don't need to manage memory at this point, since - * base64_decode returns a pointer to static storage. - */ - if (!decoded) { /* decoding failure, return error */ - SEND("NA Packet format error, couldn't base64-decode"); - return 1; - } - /* fast-track-decode request type. */ - fast_header = (struct _ntlmhdr *) decoded; + /* Note: we don't need to manage memory at this point, since + * base64_decode returns a pointer to static storage. + */ + if (!decoded) { /* decoding failure, return error */ + SEND("NA Packet format error, couldn't base64-decode"); + return 1; + } + /* fast-track-decode request type. */ + fast_header = (struct _ntlmhdr *) decoded; - /* sanity-check: it IS a NTLMSSP packet, isn't it? */ - if (memcmp(fast_header->signature, "NTLMSSP", 8) != 0) { - SEND("NA Broken authentication packet"); - return 1; - } - switch (fast_header->type) { - case NTLM_NEGOTIATE: - /* Obtain challenge against SSPI */ + /* sanity-check: it IS a NTLMSSP packet, isn't it? */ + if (memcmp(fast_header->signature, "NTLMSSP", 8) != 0) { + SEND("NA Broken authentication packet"); + return 1; + } + switch (fast_header->type) { + case NTLM_NEGOTIATE: + /* Obtain challenge against SSPI */ if (strlen(buf) > 3) plen = (strlen(buf) - 3) * 3 / 4; /* we only need it here. Optimization */ else plen = NEGOTIATE_LENGTH; - if ((c = (char *) obtain_challenge((ntlm_negotiate *) decoded, plen)) != NULL ) - { + if ((c = (char *) obtain_challenge((ntlm_negotiate *) decoded, plen)) != NULL ) { if (NTLM_packet_debug_enabled) { printf("TT %s\n",c); decoded = base64_decode(c); - debug("sending 'TT' to squid with data:\n"); + debug("sending 'TT' to squid with data:\n"); hex_dump(decoded, (strlen(c) * 3) / 4); if (NTLM_LocalCall) debug("NTLM Local Call detected\n"); } else { - SEND2("TT %s", c); + SEND2("TT %s", c); } have_challenge = 1; } else helperfail("can't obtain challenge"); - return 1; - /* notreached */ - case NTLM_CHALLENGE: - SEND - ("NA Got a challenge. We refuse to have our authority disputed"); - return 1; - /* notreached */ - case NTLM_AUTHENTICATE: - SEND("NA Got authentication request instead of negotiate request"); - return 1; - /* notreached */ - default: - helperfail("unknown refresh-request packet type"); - return 1; - } - return 1; + return 1; + /* notreached */ + case NTLM_CHALLENGE: + SEND + ("NA Got a challenge. We refuse to have our authority disputed"); + return 1; + /* notreached */ + case NTLM_AUTHENTICATE: + SEND("NA Got authentication request instead of negotiate request"); + return 1; + /* notreached */ + default: + helperfail("unknown refresh-request packet type"); + return 1; + } + return 1; } if (memcmp(buf, "KK ", 3) == 0) { /* authenticate-request */ if (!have_challenge) { - helperfail("invalid challenge"); - return 1; + helperfail("invalid challenge"); + return 1; } - /* figure out what we got */ - decoded = base64_decode(buf + 3); - /* Note: we don't need to manage memory at this point, since - * base64_decode returns a pointer to static storage. - */ + /* figure out what we got */ + decoded = base64_decode(buf + 3); + /* Note: we don't need to manage memory at this point, since + * base64_decode returns a pointer to static storage. + */ - if (!decoded) { /* decoding failure, return error */ - SEND("NA Packet format error, couldn't base64-decode"); - return 1; - } - /* fast-track-decode request type. */ - fast_header = (struct _ntlmhdr *) decoded; + if (!decoded) { /* decoding failure, return error */ + SEND("NA Packet format error, couldn't base64-decode"); + return 1; + } + /* fast-track-decode request type. */ + fast_header = (struct _ntlmhdr *) decoded; - /* sanity-check: it IS a NTLMSSP packet, isn't it? */ - if (memcmp(fast_header->signature, "NTLMSSP", 8) != 0) { - SEND("NA Broken authentication packet"); - return 1; - } - switch (fast_header->type) { - case NTLM_NEGOTIATE: - SEND("NA Invalid negotiation request received"); - return 1; - /* notreached */ - case NTLM_CHALLENGE: - SEND - ("NA Got a challenge. We refuse to have our authority disputed"); - return 1; - /* notreached */ - case NTLM_AUTHENTICATE: - /* check against SSPI */ - plen = (strlen(buf) - 3) * 3 / 4; /* we only need it here. Optimization */ - cred = ntlm_check_auth((ntlm_authenticate *) decoded, plen); + /* sanity-check: it IS a NTLMSSP packet, isn't it? */ + if (memcmp(fast_header->signature, "NTLMSSP", 8) != 0) { + SEND("NA Broken authentication packet"); + return 1; + } + switch (fast_header->type) { + case NTLM_NEGOTIATE: + SEND("NA Invalid negotiation request received"); + return 1; + /* notreached */ + case NTLM_CHALLENGE: + SEND + ("NA Got a challenge. We refuse to have our authority disputed"); + return 1; + /* notreached */ + case NTLM_AUTHENTICATE: + /* check against SSPI */ + plen = (strlen(buf) - 3) * 3 / 4; /* we only need it here. Optimization */ + cred = ntlm_check_auth((ntlm_authenticate *) decoded, plen); have_challenge = 0; - if (cred == NULL) { + if (cred == NULL) { #if FAIL_DEBUG fail_debug_enabled =1; #endif - switch (ntlm_errno) { - case NTLM_BAD_NTGROUP: - SEND("NA Incorrect Group Membership"); - return 1; - case NTLM_BAD_REQUEST: - SEND("NA Incorrect Request Format"); - return 1; - case NTLM_SSPI_ERROR: - FormatMessage( - FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - GetLastError(), - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language - (LPTSTR) &ErrorMessage, - 0, - NULL); + switch (ntlm_errno) { + case NTLM_BAD_NTGROUP: + SEND("NA Incorrect Group Membership"); + return 1; + case NTLM_BAD_REQUEST: + SEND("NA Incorrect Request Format"); + return 1; + case NTLM_SSPI_ERROR: + FormatMessage( + FORMAT_MESSAGE_ALLOCATE_BUFFER | + FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, + GetLastError(), + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language + (LPTSTR) &ErrorMessage, + 0, + NULL); if (ErrorMessage[strlen(ErrorMessage) - 1] == '\n') ErrorMessage[strlen(ErrorMessage) - 1] = '\0'; if (ErrorMessage[strlen(ErrorMessage) - 1] == '\r') ErrorMessage[strlen(ErrorMessage) - 1] = '\0'; - SEND2("NA %s", ErrorMessage); + SEND2("NA %s", ErrorMessage); LocalFree(ErrorMessage); - return 1; - default: - SEND("NA Unknown Error"); - return 1; - } - } - lc(cred); /* let's lowercase them for our convenience */ - SEND2("AF %s", cred); - return 1; - default: - helperfail("unknown authentication packet type"); - return 1; - } - return 1; + return 1; + default: + SEND("NA Unknown Error"); + return 1; + } + } + lc(cred); /* let's lowercase them for our convenience */ + SEND2("AF %s", cred); + return 1; + default: + helperfail("unknown authentication packet type"); + return 1; + } + return 1; } else { /* not an auth-request */ - helperfail("illegal request received"); - fprintf(stderr, "Illegal request received: '%s'\n", buf); - return 1; + helperfail("illegal request received"); + fprintf(stderr, "Illegal request received: '%s'\n", buf); + return 1; } helperfail("detected protocol error"); return 1; -/********* END ********/ + /********* END ********/ } int @@ -383,10 +382,10 @@ main(int argc, char *argv[]) process_options(argc, argv); debug("%s build " __DATE__ ", " __TIME__ " starting up...\n", my_program_name); - + if (LoadSecurityDll(SSP_NTLM, NTLM_PACKAGE_NAME) == NULL) { - fprintf(stderr, "FATAL, can't initialize SSPI, exiting.\n"); - exit(1); + fprintf(stderr, "FATAL, can't initialize SSPI, exiting.\n"); + exit(1); } debug("SSPI initialized OK\n"); @@ -397,7 +396,7 @@ main(int argc, char *argv[]) setbuf(stderr, NULL); while (manage_request()) { - /* everything is done within manage_request */ + /* everything is done within manage_request */ } exit(0); } diff --git a/lib/Array.cc b/lib/Array.cc index 24397a30c3..784b275a27 100644 --- a/lib/Array.cc +++ b/lib/Array.cc @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/lib/GNUregex.c b/lib/GNUregex.c index 34635113cd..d19f66caf0 100644 --- a/lib/GNUregex.c +++ b/lib/GNUregex.c @@ -6,19 +6,19 @@ * version 0.12. * (Implements POSIX draft P10003.2/D11.2, except for * internationalization features.) - * + * * Copyright (C) 1993 Free Software Foundation, Inc. - * + * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. */ @@ -80,18 +80,18 @@ init_syntax_once(void) static int done = 0; if (done) - return; + return; memset(re_syntax_table, 0, sizeof re_syntax_table); for (c = 'a'; c <= 'z'; c++) - re_syntax_table[c] = Sword; + re_syntax_table[c] = Sword; for (c = 'A'; c <= 'Z'; c++) - re_syntax_table[c] = Sword; + re_syntax_table[c] = Sword; for (c = '0'; c <= '9'; c++) - re_syntax_table[c] = Sword; + re_syntax_table[c] = Sword; re_syntax_table['_'] = Sword; @@ -118,24 +118,24 @@ static int re_compile_fastmap _RE_ARGS((struct re_pattern_buffer * buffer)); * match, or -2 for an internal error. Also return register * information in REGS (if REGS and BUFFER->no_sub are nonzero). */ static int re_search - _RE_ARGS((struct re_pattern_buffer * buffer, const char *string, - int length, int start, int range, struct re_registers * regs)); +_RE_ARGS((struct re_pattern_buffer * buffer, const char *string, + int length, int start, int range, struct re_registers * regs)); /* Like `re_search', but search in the concatenation of STRING1 and * STRING2. Also, stop searching at index START + STOP. */ static int re_search_2 - _RE_ARGS((struct re_pattern_buffer * buffer, const char *string1, - int length1, const char *string2, int length2, - int start, int range, struct re_registers * regs, int stop)); +_RE_ARGS((struct re_pattern_buffer * buffer, const char *string1, + int length1, const char *string2, int length2, + int start, int range, struct re_registers * regs, int stop)); /* Like `re_search_2', but return how many characters in STRING the regexp * in BUFFER matched, starting at position START. */ static int re_match_2 - _RE_ARGS((struct re_pattern_buffer * buffer, const char *string1, - int length1, const char *string2, int length2, - int start, struct re_registers * regs, int stop)); +_RE_ARGS((struct re_pattern_buffer * buffer, const char *string1, + int length1, const char *string2, int length2, + int start, struct re_registers * regs, int stop)); /* isalpha etc. are used for the character classes. */ @@ -187,8 +187,8 @@ static int re_match_2 * use `alloca' instead of `malloc'. This is because using malloc in * re_search* or re_match* could cause memory leaks when C-g is used in * Emacs; also, malloc is slower and causes storage fragmentation. On - * the other hand, malloc is more portable, and easier to debug. - * + * the other hand, malloc is more portable, and easier to debug. + * * Because we sometimes use alloca, some routines have to be macros, * not functions -- `alloca'-allocated space disappears at the end of the * function it is called in. */ @@ -257,7 +257,7 @@ typedef char boolean; * expressions. Some opcodes are followed by argument bytes. A * command code can specify any interpretation whatsoever for its * arguments. Zero bytes may appear in the compiled regular expression. - * + * * The value of `exactn' is needed in search.c (search_buffer) in Emacs. * So regex.h defines a symbol `RE_EXACTN_VALUE' to be 1; the value of * `exactn' we use here must also be 1. */ @@ -411,8 +411,8 @@ typedef enum { #ifdef DEBUG static void extract_number(dest, source) - int *dest; - unsigned char *source; +int *dest; +unsigned char *source; { int temp = SIGN_EXTEND_CHAR(*(source + 1)); *dest = *source & 0377; @@ -438,8 +438,8 @@ extract_number(dest, source) #ifdef DEBUG static void extract_number_and_incr(destination, source) - int *destination; - unsigned char **source; +int *destination; +unsigned char **source; { extract_number(destination, *source); *source += 2; @@ -486,24 +486,24 @@ extern void printchar(); void print_fastmap(fastmap) - char *fastmap; +char *fastmap; { unsigned was_a_range = 0; unsigned i = 0; while (i < (1 << BYTEWIDTH)) { - if (fastmap[i++]) { - was_a_range = 0; - printchar(i - 1); - while (i < (1 << BYTEWIDTH) && fastmap[i]) { - was_a_range = 1; - i++; - } - if (was_a_range) { - printf("-"); - printchar(i - 1); - } - } + if (fastmap[i++]) { + was_a_range = 0; + printchar(i - 1); + while (i < (1 << BYTEWIDTH) && fastmap[i]) { + was_a_range = 1; + i++; + } + if (was_a_range) { + printf("-"); + printchar(i - 1); + } + } } putchar('\n'); } @@ -514,175 +514,173 @@ print_fastmap(fastmap) void print_partial_compiled_pattern(start, end) - unsigned char *start; - unsigned char *end; +unsigned char *start; +unsigned char *end; { int mcnt, mcnt2; unsigned char *p = start; unsigned char *pend = end; if (start == NULL) { - printf("(null)\n"); - return; + printf("(null)\n"); + return; } /* Loop over pattern commands. */ while (p < pend) { - switch ((re_opcode_t) * p++) { - case no_op: - printf("/no_op"); - break; - - case exactn: - mcnt = *p++; - printf("/exactn/%d", mcnt); - do { - putchar('/'); - printchar(*p++); - } - while (--mcnt); - break; - - case start_memory: - mcnt = *p++; - printf("/start_memory/%d/%d", mcnt, *p++); - break; - - case stop_memory: - mcnt = *p++; - printf("/stop_memory/%d/%d", mcnt, *p++); - break; - - case duplicate: - printf("/duplicate/%d", *p++); - break; - - case anychar: - printf("/anychar"); - break; - - case charset: - case charset_not: - { - register int c; - - printf("/charset%s", - (re_opcode_t) * (p - 1) == charset_not ? "_not" : ""); - - assert(p + *p < pend); - - for (c = 0; c < *p; c++) { - unsigned bit; - unsigned char map_byte = p[1 + c]; - - putchar('/'); - - for (bit = 0; bit < BYTEWIDTH; bit++) - if (map_byte & (1 << bit)) - printchar(c * BYTEWIDTH + bit); - } - p += 1 + *p; - break; - } - - case begline: - printf("/begline"); - break; - - case endline: - printf("/endline"); - break; - - case on_failure_jump: - extract_number_and_incr(&mcnt, &p); - printf("/on_failure_jump/0/%d", mcnt); - break; - - case on_failure_keep_string_jump: - extract_number_and_incr(&mcnt, &p); - printf("/on_failure_keep_string_jump/0/%d", mcnt); - break; - - case dummy_failure_jump: - extract_number_and_incr(&mcnt, &p); - printf("/dummy_failure_jump/0/%d", mcnt); - break; - - case push_dummy_failure: - printf("/push_dummy_failure"); - break; - - case maybe_pop_jump: - extract_number_and_incr(&mcnt, &p); - printf("/maybe_pop_jump/0/%d", mcnt); - break; - - case pop_failure_jump: - extract_number_and_incr(&mcnt, &p); - printf("/pop_failure_jump/0/%d", mcnt); - break; - - case jump_past_alt: - extract_number_and_incr(&mcnt, &p); - printf("/jump_past_alt/0/%d", mcnt); - break; - - case jump: - extract_number_and_incr(&mcnt, &p); - printf("/jump/0/%d", mcnt); - break; - - case succeed_n: - extract_number_and_incr(&mcnt, &p); - extract_number_and_incr(&mcnt2, &p); - printf("/succeed_n/0/%d/0/%d", mcnt, mcnt2); - break; - - case jump_n: - extract_number_and_incr(&mcnt, &p); - extract_number_and_incr(&mcnt2, &p); - printf("/jump_n/0/%d/0/%d", mcnt, mcnt2); - break; - - case set_number_at: - extract_number_and_incr(&mcnt, &p); - extract_number_and_incr(&mcnt2, &p); - printf("/set_number_at/0/%d/0/%d", mcnt, mcnt2); - break; - - case wordbound: - printf("/wordbound"); - break; - - case notwordbound: - printf("/notwordbound"); - break; - - case wordbeg: - printf("/wordbeg"); - break; - - case wordend: - printf("/wordend"); - - case wordchar: - printf("/wordchar"); - break; - - case notwordchar: - printf("/notwordchar"); - break; - - case begbuf: - printf("/begbuf"); - break; - - case endbuf: - printf("/endbuf"); - break; - - default: - printf("?%d", *(p - 1)); - } + switch ((re_opcode_t) * p++) { + case no_op: + printf("/no_op"); + break; + + case exactn: + mcnt = *p++; + printf("/exactn/%d", mcnt); + do { + putchar('/'); + printchar(*p++); + } while (--mcnt); + break; + + case start_memory: + mcnt = *p++; + printf("/start_memory/%d/%d", mcnt, *p++); + break; + + case stop_memory: + mcnt = *p++; + printf("/stop_memory/%d/%d", mcnt, *p++); + break; + + case duplicate: + printf("/duplicate/%d", *p++); + break; + + case anychar: + printf("/anychar"); + break; + + case charset: + case charset_not: { + register int c; + + printf("/charset%s", + (re_opcode_t) * (p - 1) == charset_not ? "_not" : ""); + + assert(p + *p < pend); + + for (c = 0; c < *p; c++) { + unsigned bit; + unsigned char map_byte = p[1 + c]; + + putchar('/'); + + for (bit = 0; bit < BYTEWIDTH; bit++) + if (map_byte & (1 << bit)) + printchar(c * BYTEWIDTH + bit); + } + p += 1 + *p; + break; + } + + case begline: + printf("/begline"); + break; + + case endline: + printf("/endline"); + break; + + case on_failure_jump: + extract_number_and_incr(&mcnt, &p); + printf("/on_failure_jump/0/%d", mcnt); + break; + + case on_failure_keep_string_jump: + extract_number_and_incr(&mcnt, &p); + printf("/on_failure_keep_string_jump/0/%d", mcnt); + break; + + case dummy_failure_jump: + extract_number_and_incr(&mcnt, &p); + printf("/dummy_failure_jump/0/%d", mcnt); + break; + + case push_dummy_failure: + printf("/push_dummy_failure"); + break; + + case maybe_pop_jump: + extract_number_and_incr(&mcnt, &p); + printf("/maybe_pop_jump/0/%d", mcnt); + break; + + case pop_failure_jump: + extract_number_and_incr(&mcnt, &p); + printf("/pop_failure_jump/0/%d", mcnt); + break; + + case jump_past_alt: + extract_number_and_incr(&mcnt, &p); + printf("/jump_past_alt/0/%d", mcnt); + break; + + case jump: + extract_number_and_incr(&mcnt, &p); + printf("/jump/0/%d", mcnt); + break; + + case succeed_n: + extract_number_and_incr(&mcnt, &p); + extract_number_and_incr(&mcnt2, &p); + printf("/succeed_n/0/%d/0/%d", mcnt, mcnt2); + break; + + case jump_n: + extract_number_and_incr(&mcnt, &p); + extract_number_and_incr(&mcnt2, &p); + printf("/jump_n/0/%d/0/%d", mcnt, mcnt2); + break; + + case set_number_at: + extract_number_and_incr(&mcnt, &p); + extract_number_and_incr(&mcnt2, &p); + printf("/set_number_at/0/%d/0/%d", mcnt, mcnt2); + break; + + case wordbound: + printf("/wordbound"); + break; + + case notwordbound: + printf("/notwordbound"); + break; + + case wordbeg: + printf("/wordbeg"); + break; + + case wordend: + printf("/wordend"); + + case wordchar: + printf("/wordchar"); + break; + + case notwordchar: + printf("/notwordchar"); + break; + + case begbuf: + printf("/begbuf"); + break; + + case endbuf: + printf("/endbuf"); + break; + + default: + printf("?%d", *(p - 1)); + } } printf("/\n"); } @@ -690,7 +688,7 @@ print_partial_compiled_pattern(start, end) void print_compiled_pattern(bufp) - struct re_pattern_buffer *bufp; +struct re_pattern_buffer *bufp; { unsigned char *buffer = bufp->buffer; @@ -698,8 +696,8 @@ print_compiled_pattern(bufp) printf("%d bytes used/%d bytes allocated.\n", bufp->used, bufp->allocated); if (bufp->fastmap_accurate && bufp->fastmap) { - printf("fastmap: "); - print_fastmap(bufp->fastmap); + printf("fastmap: "); + print_fastmap(bufp->fastmap); } printf("re_nsub: %d\t", bufp->re_nsub); printf("regs_alloc: %d\t", bufp->regs_allocated); @@ -715,25 +713,25 @@ print_compiled_pattern(bufp) void print_double_string(where, string1, size1, string2, size2) - const char *where; - const char *string1; - const char *string2; - int size1; - int size2; +const char *where; +const char *string1; +const char *string2; +int size1; +int size2; { unsigned this_char; if (where == NULL) - printf("(null)"); + printf("(null)"); else { - if (FIRST_STRING_P(where)) { - for (this_char = where - string1; this_char < size1; this_char++) - printchar(string1[this_char]); - - where = string2; - } - for (this_char = where - string2; this_char < size2; this_char++) - printchar(string2[this_char]); + if (FIRST_STRING_P(where)) { + for (this_char = where - string1; this_char < size1; this_char++) + printchar(string1[this_char]); + + where = string2; + } + for (this_char = where - string2; this_char < size2; this_char++) + printchar(string2[this_char]); } } @@ -755,29 +753,28 @@ print_double_string(where, string1, size1, string2, size2) /* This table gives an error message for each of the error codes listed * in regex.h. Obviously the order here has to be same as there. */ -static const char *re_error_msg[] = -{NULL, /* REG_NOERROR */ - "No match", /* REG_NOMATCH */ - "Invalid regular expression", /* REG_BADPAT */ - "Invalid collation character", /* REG_ECOLLATE */ - "Invalid character class name", /* REG_ECTYPE */ - "Trailing backslash", /* REG_EESCAPE */ - "Invalid back reference", /* REG_ESUBREG */ - "Unmatched [ or [^", /* REG_EBRACK */ - "Unmatched ( or \\(", /* REG_EPAREN */ - "Unmatched \\{", /* REG_EBRACE */ - "Invalid content of \\{\\}", /* REG_BADBR */ - "Invalid range end", /* REG_ERANGE */ - "Memory exhausted", /* REG_ESPACE */ - "Invalid preceding regular expression", /* REG_BADRPT */ - "Premature end of regular expression", /* REG_EEND */ - "Regular expression too big", /* REG_ESIZE */ - "Unmatched ) or \\)", /* REG_ERPAREN */ -}; +static const char *re_error_msg[] = {NULL, /* REG_NOERROR */ + "No match", /* REG_NOMATCH */ + "Invalid regular expression", /* REG_BADPAT */ + "Invalid collation character", /* REG_ECOLLATE */ + "Invalid character class name", /* REG_ECTYPE */ + "Trailing backslash", /* REG_EESCAPE */ + "Invalid back reference", /* REG_ESUBREG */ + "Unmatched [ or [^", /* REG_EBRACK */ + "Unmatched ( or \\(", /* REG_EPAREN */ + "Unmatched \\{", /* REG_EBRACE */ + "Invalid content of \\{\\}", /* REG_BADBR */ + "Invalid range end", /* REG_ERANGE */ + "Memory exhausted", /* REG_ESPACE */ + "Invalid preceding regular expression", /* REG_BADRPT */ + "Premature end of regular expression", /* REG_EEND */ + "Regular expression too big", /* REG_ESIZE */ + "Unmatched ) or \\)", /* REG_ERPAREN */ + }; /* Subroutine declarations and macros for regex_compile. */ -/* Fetch the next character in the uncompiled pattern---translating it +/* Fetch the next character in the uncompiled pattern---translating it * if necessary. Also cast from a signed character in the constant * string passed to us by the user to an unsigned char that we can use * as an array index (in, e.g., `translate'). */ @@ -980,10 +977,10 @@ static reg_errcode_t compile_range(const char **p_ptr, const char *pend, char *t /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX. * Returns one of error codes defined in `regex.h', or zero for success. - * + * * Assumes the `allocated' (and perhaps `buffer') and `translate' * fields are set in BUFP on entry. - * + * * If it succeeds, results are put in BUFP (if it returns an error, the * contents of BUFP are undefined): * `buffer' is the compiled pattern; @@ -992,7 +989,7 @@ static reg_errcode_t compile_range(const char **p_ptr, const char *pend, char *t * `fastmap_accurate' is zero; * `re_nsub' is the number of subexpressions in PATTERN; * `not_bol' and `not_eol' are zero; - * + * * The `fastmap' and `newline_anchor' fields are neither * examined nor set. */ @@ -1051,18 +1048,18 @@ regex_compile(const char *pattern, int size, reg_syntax_t syntax, struct re_patt #ifdef DEBUG DEBUG_PRINT1("\nCompiling pattern: "); if (debug) { - unsigned debug_count; + unsigned debug_count; - for (debug_count = 0; debug_count < size; debug_count++) - printchar(pattern[debug_count]); - putchar('\n'); + for (debug_count = 0; debug_count < size; debug_count++) + printchar(pattern[debug_count]); + putchar('\n'); } #endif /* DEBUG */ /* Initialize the compile stack. */ compile_stack.stack = TALLOC(INIT_COMPILE_STACK_SIZE, compile_stack_elt_t); if (compile_stack.stack == NULL) - return REG_ESPACE; + return REG_ESPACE; compile_stack.size = INIT_COMPILE_STACK_SIZE; compile_stack.avail = 0; @@ -1086,828 +1083,824 @@ regex_compile(const char *pattern, int size, reg_syntax_t syntax, struct re_patt #endif if (bufp->allocated == 0) { - if (bufp->buffer) { /* If zero allocated, but buffer is non-null, try to realloc + if (bufp->buffer) { /* If zero allocated, but buffer is non-null, try to realloc * enough space. This loses if buffer's address is bogus, but * that is the user's responsibility. */ - RETALLOC(bufp->buffer, INIT_BUF_SIZE, unsigned char); - } else { /* Caller did not allocate a buffer. Do it for them. */ - bufp->buffer = TALLOC(INIT_BUF_SIZE, unsigned char); - } - if (!bufp->buffer) - return REG_ESPACE; - - bufp->allocated = INIT_BUF_SIZE; + RETALLOC(bufp->buffer, INIT_BUF_SIZE, unsigned char); + } else { /* Caller did not allocate a buffer. Do it for them. */ + bufp->buffer = TALLOC(INIT_BUF_SIZE, unsigned char); + } + if (!bufp->buffer) + return REG_ESPACE; + + bufp->allocated = INIT_BUF_SIZE; } begalt = b = bufp->buffer; /* Loop through the uncompiled pattern until we're at the end. */ while (p != pend) { - PATFETCH(c); - - switch (c) { - case '^': - { - if ( /* If at start of pattern, it's an operator. */ - p == pattern + 1 - /* If context independent, it's an operator. */ - || syntax & RE_CONTEXT_INDEP_ANCHORS - /* Otherwise, depends on what's come before. */ - || at_begline_loc_p(pattern, p, syntax)) - BUF_PUSH(begline); - else - goto normal_char; - } - break; - - - case '$': - { - if ( /* If at end of pattern, it's an operator. */ - p == pend - /* If context independent, it's an operator. */ - || syntax & RE_CONTEXT_INDEP_ANCHORS - /* Otherwise, depends on what's next. */ - || at_endline_loc_p(p, pend, syntax)) - BUF_PUSH(endline); - else - goto normal_char; - } - break; - - - case '+': - case '?': - if ((syntax & RE_BK_PLUS_QM) - || (syntax & RE_LIMITED_OPS)) - goto normal_char; - handle_plus: - case '*': - /* If there is no previous pattern... */ - if (!laststart) { - if (syntax & RE_CONTEXT_INVALID_OPS) - return REG_BADRPT; - else if (!(syntax & RE_CONTEXT_INDEP_OPS)) - goto normal_char; - } { - /* Are we optimizing this jump? */ - boolean keep_string_p = false; - - /* 1 means zero (many) matches is allowed. */ - char zero_times_ok = 0, many_times_ok = 0; - - /* If there is a sequence of repetition chars, collapse it - * down to just one (the right one). We can't combine - * interval operators with these because of, e.g., `a{2}*', - * which should only match an even number of `a's. */ - - for (;;) { - zero_times_ok |= c != '+'; - many_times_ok |= c != '?'; - - if (p == pend) - break; - - PATFETCH(c); - - if (c == '*' - || (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?'))); - - else if (syntax & RE_BK_PLUS_QM && c == '\\') { - if (p == pend) - return REG_EESCAPE; - - PATFETCH(c1); - if (!(c1 == '+' || c1 == '?')) { - PATUNFETCH; - PATUNFETCH; - break; - } - c = c1; - } else { - PATUNFETCH; - break; - } - - /* If we get here, we found another repeat character. */ - } - - /* Star, etc. applied to an empty pattern is equivalent - * to an empty pattern. */ - if (!laststart) - break; - - /* Now we know whether or not zero matches is allowed - * and also whether or not two or more matches is allowed. */ - if (many_times_ok) { /* More than one repetition is allowed, so put in at the + PATFETCH(c); + + switch (c) { + case '^': { + if ( /* If at start of pattern, it's an operator. */ + p == pattern + 1 + /* If context independent, it's an operator. */ + || syntax & RE_CONTEXT_INDEP_ANCHORS + /* Otherwise, depends on what's come before. */ + || at_begline_loc_p(pattern, p, syntax)) + BUF_PUSH(begline); + else + goto normal_char; + } + break; + + + case '$': { + if ( /* If at end of pattern, it's an operator. */ + p == pend + /* If context independent, it's an operator. */ + || syntax & RE_CONTEXT_INDEP_ANCHORS + /* Otherwise, depends on what's next. */ + || at_endline_loc_p(p, pend, syntax)) + BUF_PUSH(endline); + else + goto normal_char; + } + break; + + + case '+': + case '?': + if ((syntax & RE_BK_PLUS_QM) + || (syntax & RE_LIMITED_OPS)) + goto normal_char; +handle_plus: + case '*': + /* If there is no previous pattern... */ + if (!laststart) { + if (syntax & RE_CONTEXT_INVALID_OPS) + return REG_BADRPT; + else if (!(syntax & RE_CONTEXT_INDEP_OPS)) + goto normal_char; + } { + /* Are we optimizing this jump? */ + boolean keep_string_p = false; + + /* 1 means zero (many) matches is allowed. */ + char zero_times_ok = 0, many_times_ok = 0; + + /* If there is a sequence of repetition chars, collapse it + * down to just one (the right one). We can't combine + * interval operators with these because of, e.g., `a{2}*', + * which should only match an even number of `a's. */ + + for (;;) { + zero_times_ok |= c != '+'; + many_times_ok |= c != '?'; + + if (p == pend) + break; + + PATFETCH(c); + + if (c == '*' + || (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?'))); + + else if (syntax & RE_BK_PLUS_QM && c == '\\') { + if (p == pend) + return REG_EESCAPE; + + PATFETCH(c1); + if (!(c1 == '+' || c1 == '?')) { + PATUNFETCH; + PATUNFETCH; + break; + } + c = c1; + } else { + PATUNFETCH; + break; + } + + /* If we get here, we found another repeat character. */ + } + + /* Star, etc. applied to an empty pattern is equivalent + * to an empty pattern. */ + if (!laststart) + break; + + /* Now we know whether or not zero matches is allowed + * and also whether or not two or more matches is allowed. */ + if (many_times_ok) { /* More than one repetition is allowed, so put in at the * end a backward relative jump from `b' to before the next * jump we're going to put in below (which jumps from - * laststart to after this jump). - * + * laststart to after this jump). + * * But if we are at the `*' in the exact sequence `.*\n', * insert an unconditional jump backwards to the ., * instead of the beginning of the loop. This way we only * push a failure point once, instead of every time * through the loop. */ - assert(p - 1 > pattern); - - /* Allocate the space for the jump. */ - GET_BUFFER_SPACE(3); - - /* We know we are not at the first character of the pattern, - * because laststart was nonzero. And we've already - * incremented `p', by the way, to be the character after - * the `*'. Do we have to do something analogous here - * for null bytes, because of RE_DOT_NOT_NULL? */ - if (TRANSLATE(*(p - 2)) == TRANSLATE('.') - && zero_times_ok - && p < pend && TRANSLATE(*p) == TRANSLATE('\n') - && !(syntax & RE_DOT_NEWLINE)) { /* We have .*\n. */ - STORE_JUMP(jump, b, laststart); - keep_string_p = true; - } else - /* Anything else. */ - STORE_JUMP(maybe_pop_jump, b, laststart - 3); - - /* We've added more stuff to the buffer. */ - b += 3; - } - /* On failure, jump from laststart to b + 3, which will be the - * end of the buffer after this jump is inserted. */ - GET_BUFFER_SPACE(3); - INSERT_JUMP(keep_string_p ? on_failure_keep_string_jump - : on_failure_jump, - laststart, b + 3); - pending_exact = 0; - b += 3; - - if (!zero_times_ok) { - /* At least one repetition is required, so insert a - * `dummy_failure_jump' before the initial - * `on_failure_jump' instruction of the loop. This - * effects a skip over that instruction the first time - * we hit that loop. */ - GET_BUFFER_SPACE(3); - INSERT_JUMP(dummy_failure_jump, laststart, laststart + 6); - b += 3; - } - } - break; - - - case '.': - laststart = b; - BUF_PUSH(anychar); - break; - - - case '[': - { - boolean had_char_class = false; - - if (p == pend) - return REG_EBRACK; - - /* Ensure that we have enough space to push a charset: the - * opcode, the length count, and the bitset; 34 bytes in all. */ - GET_BUFFER_SPACE(34); - - laststart = b; - - /* We test `*p == '^' twice, instead of using an if - * statement, so we only need one BUF_PUSH. */ - BUF_PUSH(*p == '^' ? charset_not : charset); - if (*p == '^') - p++; - - /* Remember the first position in the bracket expression. */ - p1 = p; - - /* Push the number of bytes in the bitmap. */ - BUF_PUSH((1 << BYTEWIDTH) / BYTEWIDTH); - - /* Clear the whole map. */ - memset(b, 0, (1 << BYTEWIDTH) / BYTEWIDTH); - - /* charset_not matches newline according to a syntax bit. */ - if ((re_opcode_t) b[-2] == charset_not - && (syntax & RE_HAT_LISTS_NOT_NEWLINE)) - SET_LIST_BIT('\n'); - - /* Read in characters and ranges, setting map bits. */ - for (;;) { - if (p == pend) - return REG_EBRACK; - - PATFETCH(c); - - /* \ might escape characters inside [...] and [^...]. */ - if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\') { - if (p == pend) - return REG_EESCAPE; - - PATFETCH(c1); - SET_LIST_BIT(c1); - continue; - } - /* Could be the end of the bracket expression. If it's - * not (i.e., when the bracket expression is `[]' so - * far), the ']' character bit gets set way below. */ - if (c == ']' && p != p1 + 1) - break; - - /* Look ahead to see if it's a range when the last thing - * was a character class. */ - if (had_char_class && c == '-' && *p != ']') - return REG_ERANGE; - - /* Look ahead to see if it's a range when the last thing - * was a character: if this is a hyphen not at the - * beginning or the end of a list, then it's the range - * operator. */ - if (c == '-' - && !(p - 2 >= pattern && p[-2] == '[') - && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^') - && *p != ']') { - reg_errcode_t ret - = compile_range(&p, pend, translate, syntax, b); - if (ret != REG_NOERROR) - return ret; - } else if (p[0] == '-' && p[1] != ']') { /* This handles ranges made up of characters only. */ - reg_errcode_t ret; - - /* Move past the `-'. */ - PATFETCH(c1); - - ret = compile_range(&p, pend, translate, syntax, b); - if (ret != REG_NOERROR) - return ret; - } - /* See if we're at the beginning of a possible character - * class. */ - - else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':') { /* Leave room for the null. */ - char str[CHAR_CLASS_MAX_LENGTH + 1]; - - PATFETCH(c); - c1 = 0; - - /* If pattern is `[[:'. */ - if (p == pend) - return REG_EBRACK; - - for (;;) { - PATFETCH(c); - if (c == ':' || c == ']' || p == pend - || c1 == CHAR_CLASS_MAX_LENGTH) - break; - str[c1++] = c; - } - str[c1] = '\0'; - - /* If isn't a word bracketed by `[:' and:`]': - * undo the ending character, the letters, and leave - * the leading `:' and `[' (but set bits for them). */ - if (c == ':' && *p == ']') { - int ch; - boolean is_alnum = STREQ(str, "alnum"); - boolean is_alpha = STREQ(str, "alpha"); - boolean is_blank = STREQ(str, "blank"); - boolean is_cntrl = STREQ(str, "cntrl"); - boolean is_digit = STREQ(str, "digit"); - boolean is_graph = STREQ(str, "graph"); - boolean is_lower = STREQ(str, "lower"); - boolean is_print = STREQ(str, "print"); - boolean is_punct = STREQ(str, "punct"); - boolean is_space = STREQ(str, "space"); - boolean is_upper = STREQ(str, "upper"); - boolean is_xdigit = STREQ(str, "xdigit"); - - if (!IS_CHAR_CLASS(str)) - return REG_ECTYPE; - - /* Throw away the ] at the end of the character - * class. */ - PATFETCH(c); - - if (p == pend) - return REG_EBRACK; - - for (ch = 0; ch < 1 << BYTEWIDTH; ch++) { - if ((is_alnum && ISALNUM(ch)) - || (is_alpha && ISALPHA(ch)) - || (is_blank && ISBLANK(ch)) - || (is_cntrl && ISCNTRL(ch)) - || (is_digit && ISDIGIT(ch)) - || (is_graph && ISGRAPH(ch)) - || (is_lower && ISLOWER(ch)) - || (is_print && ISPRINT(ch)) - || (is_punct && ISPUNCT(ch)) - || (is_space && ISSPACE(ch)) - || (is_upper && ISUPPER(ch)) - || (is_xdigit && ISXDIGIT(ch))) - SET_LIST_BIT(ch); - } - had_char_class = true; - } else { - c1++; - while (c1--) - PATUNFETCH; - SET_LIST_BIT('['); - SET_LIST_BIT(':'); - had_char_class = false; - } - } else { - had_char_class = false; - SET_LIST_BIT(c); - } - } - - /* Discard any (non)matching list bytes that are all 0 at the - * end of the map. Decrease the map-length byte too. */ - while ((int) b[-1] > 0 && b[b[-1] - 1] == 0) - b[-1]--; - b += b[-1]; - } - break; - - - case '(': - if (syntax & RE_NO_BK_PARENS) - goto handle_open; - else - goto normal_char; - - - case ')': - if (syntax & RE_NO_BK_PARENS) - goto handle_close; - else - goto normal_char; - - - case '\n': - if (syntax & RE_NEWLINE_ALT) - goto handle_alt; - else - goto normal_char; - - - case '|': - if (syntax & RE_NO_BK_VBAR) - goto handle_alt; - else - goto normal_char; - - - case '{': - if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES) - goto handle_interval; - else - goto normal_char; - - - case '\\': - if (p == pend) - return REG_EESCAPE; - - /* Do not translate the character after the \, so that we can - * distinguish, e.g., \B from \b, even if we normally would - * translate, e.g., B to b. */ - PATFETCH_RAW(c); - - switch (c) { - case '(': - if (syntax & RE_NO_BK_PARENS) - goto normal_backslash; - - handle_open: - bufp->re_nsub++; - regnum++; - - if (COMPILE_STACK_FULL) { - RETALLOC(compile_stack.stack, compile_stack.size << 1, - compile_stack_elt_t); - if (compile_stack.stack == NULL) - return REG_ESPACE; - - compile_stack.size <<= 1; - } - /* These are the values to restore when we hit end of this - * group. They are all relative offsets, so that if the - * whole pattern moves because of realloc, they will still - * be valid. */ - COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer; - COMPILE_STACK_TOP.fixup_alt_jump - = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0; - COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer; - COMPILE_STACK_TOP.regnum = regnum; - - /* We will eventually replace the 0 with the number of - * groups inner to this one. But do not push a - * start_memory for groups beyond the last one we can - * represent in the compiled pattern. */ - if (regnum <= MAX_REGNUM) { - COMPILE_STACK_TOP.inner_group_offset = b - bufp->buffer + 2; - BUF_PUSH_3(start_memory, regnum, 0); - } - compile_stack.avail++; - - fixup_alt_jump = 0; - laststart = 0; - begalt = b; - /* If we've reached MAX_REGNUM groups, then this open - * won't actually generate any code, so we'll have to - * clear pending_exact explicitly. */ - pending_exact = 0; - break; - - - case ')': - if (syntax & RE_NO_BK_PARENS) - goto normal_backslash; - - if (COMPILE_STACK_EMPTY) { - if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD) - goto normal_backslash; - else - return REG_ERPAREN; - } - handle_close: - if (fixup_alt_jump) { /* Push a dummy failure point at the end of the + assert(p - 1 > pattern); + + /* Allocate the space for the jump. */ + GET_BUFFER_SPACE(3); + + /* We know we are not at the first character of the pattern, + * because laststart was nonzero. And we've already + * incremented `p', by the way, to be the character after + * the `*'. Do we have to do something analogous here + * for null bytes, because of RE_DOT_NOT_NULL? */ + if (TRANSLATE(*(p - 2)) == TRANSLATE('.') + && zero_times_ok + && p < pend && TRANSLATE(*p) == TRANSLATE('\n') + && !(syntax & RE_DOT_NEWLINE)) { /* We have .*\n. */ + STORE_JUMP(jump, b, laststart); + keep_string_p = true; + } else + /* Anything else. */ + STORE_JUMP(maybe_pop_jump, b, laststart - 3); + + /* We've added more stuff to the buffer. */ + b += 3; + } + /* On failure, jump from laststart to b + 3, which will be the + * end of the buffer after this jump is inserted. */ + GET_BUFFER_SPACE(3); + INSERT_JUMP(keep_string_p ? on_failure_keep_string_jump + : on_failure_jump, + laststart, b + 3); + pending_exact = 0; + b += 3; + + if (!zero_times_ok) { + /* At least one repetition is required, so insert a + * `dummy_failure_jump' before the initial + * `on_failure_jump' instruction of the loop. This + * effects a skip over that instruction the first time + * we hit that loop. */ + GET_BUFFER_SPACE(3); + INSERT_JUMP(dummy_failure_jump, laststart, laststart + 6); + b += 3; + } + } + break; + + + case '.': + laststart = b; + BUF_PUSH(anychar); + break; + + + case '[': { + boolean had_char_class = false; + + if (p == pend) + return REG_EBRACK; + + /* Ensure that we have enough space to push a charset: the + * opcode, the length count, and the bitset; 34 bytes in all. */ + GET_BUFFER_SPACE(34); + + laststart = b; + + /* We test `*p == '^' twice, instead of using an if + * statement, so we only need one BUF_PUSH. */ + BUF_PUSH(*p == '^' ? charset_not : charset); + if (*p == '^') + p++; + + /* Remember the first position in the bracket expression. */ + p1 = p; + + /* Push the number of bytes in the bitmap. */ + BUF_PUSH((1 << BYTEWIDTH) / BYTEWIDTH); + + /* Clear the whole map. */ + memset(b, 0, (1 << BYTEWIDTH) / BYTEWIDTH); + + /* charset_not matches newline according to a syntax bit. */ + if ((re_opcode_t) b[-2] == charset_not + && (syntax & RE_HAT_LISTS_NOT_NEWLINE)) + SET_LIST_BIT('\n'); + + /* Read in characters and ranges, setting map bits. */ + for (;;) { + if (p == pend) + return REG_EBRACK; + + PATFETCH(c); + + /* \ might escape characters inside [...] and [^...]. */ + if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\') { + if (p == pend) + return REG_EESCAPE; + + PATFETCH(c1); + SET_LIST_BIT(c1); + continue; + } + /* Could be the end of the bracket expression. If it's + * not (i.e., when the bracket expression is `[]' so + * far), the ']' character bit gets set way below. */ + if (c == ']' && p != p1 + 1) + break; + + /* Look ahead to see if it's a range when the last thing + * was a character class. */ + if (had_char_class && c == '-' && *p != ']') + return REG_ERANGE; + + /* Look ahead to see if it's a range when the last thing + * was a character: if this is a hyphen not at the + * beginning or the end of a list, then it's the range + * operator. */ + if (c == '-' + && !(p - 2 >= pattern && p[-2] == '[') + && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^') + && *p != ']') { + reg_errcode_t ret + = compile_range(&p, pend, translate, syntax, b); + if (ret != REG_NOERROR) + return ret; + } else if (p[0] == '-' && p[1] != ']') { /* This handles ranges made up of characters only. */ + reg_errcode_t ret; + + /* Move past the `-'. */ + PATFETCH(c1); + + ret = compile_range(&p, pend, translate, syntax, b); + if (ret != REG_NOERROR) + return ret; + } + /* See if we're at the beginning of a possible character + * class. */ + + else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':') { /* Leave room for the null. */ + char str[CHAR_CLASS_MAX_LENGTH + 1]; + + PATFETCH(c); + c1 = 0; + + /* If pattern is `[[:'. */ + if (p == pend) + return REG_EBRACK; + + for (;;) { + PATFETCH(c); + if (c == ':' || c == ']' || p == pend + || c1 == CHAR_CLASS_MAX_LENGTH) + break; + str[c1++] = c; + } + str[c1] = '\0'; + + /* If isn't a word bracketed by `[:' and:`]': + * undo the ending character, the letters, and leave + * the leading `:' and `[' (but set bits for them). */ + if (c == ':' && *p == ']') { + int ch; + boolean is_alnum = STREQ(str, "alnum"); + boolean is_alpha = STREQ(str, "alpha"); + boolean is_blank = STREQ(str, "blank"); + boolean is_cntrl = STREQ(str, "cntrl"); + boolean is_digit = STREQ(str, "digit"); + boolean is_graph = STREQ(str, "graph"); + boolean is_lower = STREQ(str, "lower"); + boolean is_print = STREQ(str, "print"); + boolean is_punct = STREQ(str, "punct"); + boolean is_space = STREQ(str, "space"); + boolean is_upper = STREQ(str, "upper"); + boolean is_xdigit = STREQ(str, "xdigit"); + + if (!IS_CHAR_CLASS(str)) + return REG_ECTYPE; + + /* Throw away the ] at the end of the character + * class. */ + PATFETCH(c); + + if (p == pend) + return REG_EBRACK; + + for (ch = 0; ch < 1 << BYTEWIDTH; ch++) { + if ((is_alnum && ISALNUM(ch)) + || (is_alpha && ISALPHA(ch)) + || (is_blank && ISBLANK(ch)) + || (is_cntrl && ISCNTRL(ch)) + || (is_digit && ISDIGIT(ch)) + || (is_graph && ISGRAPH(ch)) + || (is_lower && ISLOWER(ch)) + || (is_print && ISPRINT(ch)) + || (is_punct && ISPUNCT(ch)) + || (is_space && ISSPACE(ch)) + || (is_upper && ISUPPER(ch)) + || (is_xdigit && ISXDIGIT(ch))) + SET_LIST_BIT(ch); + } + had_char_class = true; + } else { + c1++; + while (c1--) + PATUNFETCH; + SET_LIST_BIT('['); + SET_LIST_BIT(':'); + had_char_class = false; + } + } else { + had_char_class = false; + SET_LIST_BIT(c); + } + } + + /* Discard any (non)matching list bytes that are all 0 at the + * end of the map. Decrease the map-length byte too. */ + while ((int) b[-1] > 0 && b[b[-1] - 1] == 0) + b[-1]--; + b += b[-1]; + } + break; + + + case '(': + if (syntax & RE_NO_BK_PARENS) + goto handle_open; + else + goto normal_char; + + + case ')': + if (syntax & RE_NO_BK_PARENS) + goto handle_close; + else + goto normal_char; + + + case '\n': + if (syntax & RE_NEWLINE_ALT) + goto handle_alt; + else + goto normal_char; + + + case '|': + if (syntax & RE_NO_BK_VBAR) + goto handle_alt; + else + goto normal_char; + + + case '{': + if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES) + goto handle_interval; + else + goto normal_char; + + + case '\\': + if (p == pend) + return REG_EESCAPE; + + /* Do not translate the character after the \, so that we can + * distinguish, e.g., \B from \b, even if we normally would + * translate, e.g., B to b. */ + PATFETCH_RAW(c); + + switch (c) { + case '(': + if (syntax & RE_NO_BK_PARENS) + goto normal_backslash; + +handle_open: + bufp->re_nsub++; + regnum++; + + if (COMPILE_STACK_FULL) { + RETALLOC(compile_stack.stack, compile_stack.size << 1, + compile_stack_elt_t); + if (compile_stack.stack == NULL) + return REG_ESPACE; + + compile_stack.size <<= 1; + } + /* These are the values to restore when we hit end of this + * group. They are all relative offsets, so that if the + * whole pattern moves because of realloc, they will still + * be valid. */ + COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer; + COMPILE_STACK_TOP.fixup_alt_jump + = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0; + COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer; + COMPILE_STACK_TOP.regnum = regnum; + + /* We will eventually replace the 0 with the number of + * groups inner to this one. But do not push a + * start_memory for groups beyond the last one we can + * represent in the compiled pattern. */ + if (regnum <= MAX_REGNUM) { + COMPILE_STACK_TOP.inner_group_offset = b - bufp->buffer + 2; + BUF_PUSH_3(start_memory, regnum, 0); + } + compile_stack.avail++; + + fixup_alt_jump = 0; + laststart = 0; + begalt = b; + /* If we've reached MAX_REGNUM groups, then this open + * won't actually generate any code, so we'll have to + * clear pending_exact explicitly. */ + pending_exact = 0; + break; + + + case ')': + if (syntax & RE_NO_BK_PARENS) + goto normal_backslash; + + if (COMPILE_STACK_EMPTY) { + if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD) + goto normal_backslash; + else + return REG_ERPAREN; + } +handle_close: + if (fixup_alt_jump) { /* Push a dummy failure point at the end of the * alternative for a possible future * `pop_failure_jump' to pop. See comments at * `push_dummy_failure' in `re_match_2'. */ - BUF_PUSH(push_dummy_failure); - - /* We allocated space for this jump when we assigned - * to `fixup_alt_jump', in the `handle_alt' case below. */ - STORE_JUMP(jump_past_alt, fixup_alt_jump, b - 1); - } - /* See similar code for backslashed left paren above. */ - if (COMPILE_STACK_EMPTY) { - if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD) - goto normal_char; - else - return REG_ERPAREN; - } - /* Since we just checked for an empty stack above, this - * ``can't happen''. */ - assert(compile_stack.avail != 0); - { - /* We don't just want to restore into `regnum', because - * later groups should continue to be numbered higher, - * as in `(ab)c(de)' -- the second group is #2. */ - regnum_t this_group_regnum; - - compile_stack.avail--; - begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset; - fixup_alt_jump - = COMPILE_STACK_TOP.fixup_alt_jump - ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1 - : 0; - laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset; - this_group_regnum = COMPILE_STACK_TOP.regnum; - /* If we've reached MAX_REGNUM groups, then this open - * won't actually generate any code, so we'll have to - * clear pending_exact explicitly. */ - pending_exact = 0; - - /* We're at the end of the group, so now we know how many - * groups were inside this one. */ - if (this_group_regnum <= MAX_REGNUM) { - unsigned char *inner_group_loc - = bufp->buffer + COMPILE_STACK_TOP.inner_group_offset; - - *inner_group_loc = regnum - this_group_regnum; - BUF_PUSH_3(stop_memory, this_group_regnum, - regnum - this_group_regnum); - } - } - break; - - - case '|': /* `\|'. */ - if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR) - goto normal_backslash; - handle_alt: - if (syntax & RE_LIMITED_OPS) - goto normal_char; - - /* Insert before the previous alternative a jump which - * jumps to this alternative if the former fails. */ - GET_BUFFER_SPACE(3); - INSERT_JUMP(on_failure_jump, begalt, b + 6); - pending_exact = 0; - b += 3; - - /* The alternative before this one has a jump after it - * which gets executed if it gets matched. Adjust that - * jump so it will jump to this alternative's analogous - * jump (put in below, which in turn will jump to the next - * (if any) alternative's such jump, etc.). The last such - * jump jumps to the correct final destination. A picture: - * _____ _____ - * | | | | - * | v | v - * a | b | c - * - * If we are at `b', then fixup_alt_jump right now points to a - * three-byte space after `a'. We'll put in the jump, set - * fixup_alt_jump to right after `b', and leave behind three - * bytes which we'll fill in when we get to after `c'. */ - - if (fixup_alt_jump) - STORE_JUMP(jump_past_alt, fixup_alt_jump, b); - - /* Mark and leave space for a jump after this alternative, - * to be filled in later either by next alternative or - * when know we're at the end of a series of alternatives. */ - fixup_alt_jump = b; - GET_BUFFER_SPACE(3); - b += 3; - - laststart = 0; - begalt = b; - break; - - - case '{': - /* If \{ is a literal. */ - if (!(syntax & RE_INTERVALS) - /* If we're at `\{' and it's not the open-interval - * operator. */ - || ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES)) - || (p - 2 == pattern && p == pend)) - goto normal_backslash; - - handle_interval: - { - /* If got here, then the syntax allows intervals. */ - - /* At least (most) this many matches must be made. */ - int lower_bound = -1, upper_bound = -1; - - beg_interval = p - 1; - - if (p == pend) { - if (syntax & RE_NO_BK_BRACES) - goto unfetch_interval; - else - return REG_EBRACE; - } - GET_UNSIGNED_NUMBER(lower_bound); - - if (c == ',') { - GET_UNSIGNED_NUMBER(upper_bound); - if (upper_bound < 0) - upper_bound = RE_DUP_MAX; - } else - /* Interval such as `{1}' => match exactly once. */ - upper_bound = lower_bound; - - if (lower_bound < 0 || upper_bound > RE_DUP_MAX - || lower_bound > upper_bound) { - if (syntax & RE_NO_BK_BRACES) - goto unfetch_interval; - else - return REG_BADBR; - } - if (!(syntax & RE_NO_BK_BRACES)) { - if (c != '\\') - return REG_EBRACE; - - PATFETCH(c); - } - if (c != '}') { - if (syntax & RE_NO_BK_BRACES) - goto unfetch_interval; - else - return REG_BADBR; - } - /* We just parsed a valid interval. */ - - /* If it's invalid to have no preceding re. */ - if (!laststart) { - if (syntax & RE_CONTEXT_INVALID_OPS) - return REG_BADRPT; - else if (syntax & RE_CONTEXT_INDEP_OPS) - laststart = b; - else - goto unfetch_interval; - } - /* If the upper bound is zero, don't want to succeed at - * all; jump from `laststart' to `b + 3', which will be - * the end of the buffer after we insert the jump. */ - if (upper_bound == 0) { - GET_BUFFER_SPACE(3); - INSERT_JUMP(jump, laststart, b + 3); - b += 3; - } - /* Otherwise, we have a nontrivial interval. When - * we're all done, the pattern will look like: - * set_number_at - * set_number_at - * succeed_n - * - * jump_n - * (The upper bound and `jump_n' are omitted if - * `upper_bound' is 1, though.) */ - else { /* If the upper bound is > 1, we need to insert + BUF_PUSH(push_dummy_failure); + + /* We allocated space for this jump when we assigned + * to `fixup_alt_jump', in the `handle_alt' case below. */ + STORE_JUMP(jump_past_alt, fixup_alt_jump, b - 1); + } + /* See similar code for backslashed left paren above. */ + if (COMPILE_STACK_EMPTY) { + if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD) + goto normal_char; + else + return REG_ERPAREN; + } + /* Since we just checked for an empty stack above, this + * ``can't happen''. */ + assert(compile_stack.avail != 0); + { + /* We don't just want to restore into `regnum', because + * later groups should continue to be numbered higher, + * as in `(ab)c(de)' -- the second group is #2. */ + regnum_t this_group_regnum; + + compile_stack.avail--; + begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset; + fixup_alt_jump + = COMPILE_STACK_TOP.fixup_alt_jump + ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1 + : 0; + laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset; + this_group_regnum = COMPILE_STACK_TOP.regnum; + /* If we've reached MAX_REGNUM groups, then this open + * won't actually generate any code, so we'll have to + * clear pending_exact explicitly. */ + pending_exact = 0; + + /* We're at the end of the group, so now we know how many + * groups were inside this one. */ + if (this_group_regnum <= MAX_REGNUM) { + unsigned char *inner_group_loc + = bufp->buffer + COMPILE_STACK_TOP.inner_group_offset; + + *inner_group_loc = regnum - this_group_regnum; + BUF_PUSH_3(stop_memory, this_group_regnum, + regnum - this_group_regnum); + } + } + break; + + + case '|': /* `\|'. */ + if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR) + goto normal_backslash; +handle_alt: + if (syntax & RE_LIMITED_OPS) + goto normal_char; + + /* Insert before the previous alternative a jump which + * jumps to this alternative if the former fails. */ + GET_BUFFER_SPACE(3); + INSERT_JUMP(on_failure_jump, begalt, b + 6); + pending_exact = 0; + b += 3; + + /* The alternative before this one has a jump after it + * which gets executed if it gets matched. Adjust that + * jump so it will jump to this alternative's analogous + * jump (put in below, which in turn will jump to the next + * (if any) alternative's such jump, etc.). The last such + * jump jumps to the correct final destination. A picture: + * _____ _____ + * | | | | + * | v | v + * a | b | c + * + * If we are at `b', then fixup_alt_jump right now points to a + * three-byte space after `a'. We'll put in the jump, set + * fixup_alt_jump to right after `b', and leave behind three + * bytes which we'll fill in when we get to after `c'. */ + + if (fixup_alt_jump) + STORE_JUMP(jump_past_alt, fixup_alt_jump, b); + + /* Mark and leave space for a jump after this alternative, + * to be filled in later either by next alternative or + * when know we're at the end of a series of alternatives. */ + fixup_alt_jump = b; + GET_BUFFER_SPACE(3); + b += 3; + + laststart = 0; + begalt = b; + break; + + + case '{': + /* If \{ is a literal. */ + if (!(syntax & RE_INTERVALS) + /* If we're at `\{' and it's not the open-interval + * operator. */ + || ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES)) + || (p - 2 == pattern && p == pend)) + goto normal_backslash; + +handle_interval: { + /* If got here, then the syntax allows intervals. */ + + /* At least (most) this many matches must be made. */ + int lower_bound = -1, upper_bound = -1; + + beg_interval = p - 1; + + if (p == pend) { + if (syntax & RE_NO_BK_BRACES) + goto unfetch_interval; + else + return REG_EBRACE; + } + GET_UNSIGNED_NUMBER(lower_bound); + + if (c == ',') { + GET_UNSIGNED_NUMBER(upper_bound); + if (upper_bound < 0) + upper_bound = RE_DUP_MAX; + } else + /* Interval such as `{1}' => match exactly once. */ + upper_bound = lower_bound; + + if (lower_bound < 0 || upper_bound > RE_DUP_MAX + || lower_bound > upper_bound) { + if (syntax & RE_NO_BK_BRACES) + goto unfetch_interval; + else + return REG_BADBR; + } + if (!(syntax & RE_NO_BK_BRACES)) { + if (c != '\\') + return REG_EBRACE; + + PATFETCH(c); + } + if (c != '}') { + if (syntax & RE_NO_BK_BRACES) + goto unfetch_interval; + else + return REG_BADBR; + } + /* We just parsed a valid interval. */ + + /* If it's invalid to have no preceding re. */ + if (!laststart) { + if (syntax & RE_CONTEXT_INVALID_OPS) + return REG_BADRPT; + else if (syntax & RE_CONTEXT_INDEP_OPS) + laststart = b; + else + goto unfetch_interval; + } + /* If the upper bound is zero, don't want to succeed at + * all; jump from `laststart' to `b + 3', which will be + * the end of the buffer after we insert the jump. */ + if (upper_bound == 0) { + GET_BUFFER_SPACE(3); + INSERT_JUMP(jump, laststart, b + 3); + b += 3; + } + /* Otherwise, we have a nontrivial interval. When + * we're all done, the pattern will look like: + * set_number_at + * set_number_at + * succeed_n + * + * jump_n + * (The upper bound and `jump_n' are omitted if + * `upper_bound' is 1, though.) */ + else { /* If the upper bound is > 1, we need to insert * more at the end of the loop. */ - unsigned nbytes = 10 + (upper_bound > 1) * 10; - - GET_BUFFER_SPACE(nbytes); - - /* Initialize lower bound of the `succeed_n', even - * though it will be set during matching by its - * attendant `set_number_at' (inserted next), - * because `re_compile_fastmap' needs to know. - * Jump to the `jump_n' we might insert below. */ - INSERT_JUMP2(succeed_n, laststart, - b + 5 + (upper_bound > 1) * 5, - lower_bound); - b += 5; - - /* Code to initialize the lower bound. Insert - * before the `succeed_n'. The `5' is the last two - * bytes of this `set_number_at', plus 3 bytes of - * the following `succeed_n'. */ - insert_op2(set_number_at, laststart, 5, lower_bound, b); - b += 5; - - if (upper_bound > 1) { /* More than one repetition is allowed, so + unsigned nbytes = 10 + (upper_bound > 1) * 10; + + GET_BUFFER_SPACE(nbytes); + + /* Initialize lower bound of the `succeed_n', even + * though it will be set during matching by its + * attendant `set_number_at' (inserted next), + * because `re_compile_fastmap' needs to know. + * Jump to the `jump_n' we might insert below. */ + INSERT_JUMP2(succeed_n, laststart, + b + 5 + (upper_bound > 1) * 5, + lower_bound); + b += 5; + + /* Code to initialize the lower bound. Insert + * before the `succeed_n'. The `5' is the last two + * bytes of this `set_number_at', plus 3 bytes of + * the following `succeed_n'. */ + insert_op2(set_number_at, laststart, 5, lower_bound, b); + b += 5; + + if (upper_bound > 1) { /* More than one repetition is allowed, so * append a backward jump to the `succeed_n' * that starts this interval. - * + * * When we've reached this during matching, * we'll have matched the interval once, so * jump back only `upper_bound - 1' times. */ - STORE_JUMP2(jump_n, b, laststart + 5, - upper_bound - 1); - b += 5; - - /* The location we want to set is the second - * parameter of the `jump_n'; that is `b-2' as - * an absolute address. `laststart' will be - * the `set_number_at' we're about to insert; - * `laststart+3' the number to set, the source - * for the relative address. But we are - * inserting into the middle of the pattern -- - * so everything is getting moved up by 5. - * Conclusion: (b - 2) - (laststart + 3) + 5, - * i.e., b - laststart. - * - * We insert this at the beginning of the loop - * so that if we fail during matching, we'll - * reinitialize the bounds. */ - insert_op2(set_number_at, laststart, b - laststart, - upper_bound - 1, b); - b += 5; - } - } - pending_exact = 0; - beg_interval = NULL; - } - break; - - unfetch_interval: - /* If an invalid interval, match the characters as literals. */ - assert(beg_interval); - p = beg_interval; - beg_interval = NULL; - - /* normal_char and normal_backslash need `c'. */ - PATFETCH(c); - - if (!(syntax & RE_NO_BK_BRACES)) { - if (p > pattern && p[-1] == '\\') - goto normal_backslash; - } - goto normal_char; - - - case 'w': - laststart = b; - BUF_PUSH(wordchar); - break; - - - case 'W': - laststart = b; - BUF_PUSH(notwordchar); - break; - - - case '<': - BUF_PUSH(wordbeg); - break; - - case '>': - BUF_PUSH(wordend); - break; - - case 'b': - BUF_PUSH(wordbound); - break; - - case 'B': - BUF_PUSH(notwordbound); - break; - - case '`': - BUF_PUSH(begbuf); - break; - - case '\'': - BUF_PUSH(endbuf); - break; - - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - if (syntax & RE_NO_BK_REFS) - goto normal_char; - - c1 = c - '0'; - - if (c1 > regnum) - return REG_ESUBREG; - - /* Can't back reference to a subexpression if inside of it. */ - if (group_in_compile_stack(compile_stack, c1)) - goto normal_char; - - laststart = b; - BUF_PUSH_2(duplicate, c1); - break; - - - case '+': - case '?': - if (syntax & RE_BK_PLUS_QM) - goto handle_plus; - else - goto normal_backslash; - - default: - normal_backslash: - /* You might think it would be useful for \ to mean - * not to translate; but if we don't translate it - * it will never match anything. */ - c = TRANSLATE(c); - goto normal_char; - } - break; - - - default: - /* Expects the character in `c'. */ - normal_char: - /* If no exactn currently being built. */ - if (!pending_exact - - /* If last exactn not at current position. */ - || pending_exact + *pending_exact + 1 != b - - /* We have only one byte following the exactn for the count. */ - || *pending_exact == (1 << BYTEWIDTH) - 1 - - /* If followed by a repetition operator. */ - || *p == '*' || *p == '^' - || ((syntax & RE_BK_PLUS_QM) - ? *p == '\\' && (p[1] == '+' || p[1] == '?') - : (*p == '+' || *p == '?')) - || ((syntax & RE_INTERVALS) - && ((syntax & RE_NO_BK_BRACES) - ? *p == '{' - : (p[0] == '\\' && p[1] == '{')))) { - /* Start building a new exactn. */ - - laststart = b; - - BUF_PUSH_2(exactn, 0); - pending_exact = b - 1; - } - BUF_PUSH(c); - (*pending_exact)++; - break; - } /* switch (c) */ + STORE_JUMP2(jump_n, b, laststart + 5, + upper_bound - 1); + b += 5; + + /* The location we want to set is the second + * parameter of the `jump_n'; that is `b-2' as + * an absolute address. `laststart' will be + * the `set_number_at' we're about to insert; + * `laststart+3' the number to set, the source + * for the relative address. But we are + * inserting into the middle of the pattern -- + * so everything is getting moved up by 5. + * Conclusion: (b - 2) - (laststart + 3) + 5, + * i.e., b - laststart. + * + * We insert this at the beginning of the loop + * so that if we fail during matching, we'll + * reinitialize the bounds. */ + insert_op2(set_number_at, laststart, b - laststart, + upper_bound - 1, b); + b += 5; + } + } + pending_exact = 0; + beg_interval = NULL; + } + break; + +unfetch_interval: + /* If an invalid interval, match the characters as literals. */ + assert(beg_interval); + p = beg_interval; + beg_interval = NULL; + + /* normal_char and normal_backslash need `c'. */ + PATFETCH(c); + + if (!(syntax & RE_NO_BK_BRACES)) { + if (p > pattern && p[-1] == '\\') + goto normal_backslash; + } + goto normal_char; + + + case 'w': + laststart = b; + BUF_PUSH(wordchar); + break; + + + case 'W': + laststart = b; + BUF_PUSH(notwordchar); + break; + + + case '<': + BUF_PUSH(wordbeg); + break; + + case '>': + BUF_PUSH(wordend); + break; + + case 'b': + BUF_PUSH(wordbound); + break; + + case 'B': + BUF_PUSH(notwordbound); + break; + + case '`': + BUF_PUSH(begbuf); + break; + + case '\'': + BUF_PUSH(endbuf); + break; + + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + if (syntax & RE_NO_BK_REFS) + goto normal_char; + + c1 = c - '0'; + + if (c1 > regnum) + return REG_ESUBREG; + + /* Can't back reference to a subexpression if inside of it. */ + if (group_in_compile_stack(compile_stack, c1)) + goto normal_char; + + laststart = b; + BUF_PUSH_2(duplicate, c1); + break; + + + case '+': + case '?': + if (syntax & RE_BK_PLUS_QM) + goto handle_plus; + else + goto normal_backslash; + + default: +normal_backslash: + /* You might think it would be useful for \ to mean + * not to translate; but if we don't translate it + * it will never match anything. */ + c = TRANSLATE(c); + goto normal_char; + } + break; + + + default: + /* Expects the character in `c'. */ +normal_char: + /* If no exactn currently being built. */ + if (!pending_exact + + /* If last exactn not at current position. */ + || pending_exact + *pending_exact + 1 != b + + /* We have only one byte following the exactn for the count. */ + || *pending_exact == (1 << BYTEWIDTH) - 1 + + /* If followed by a repetition operator. */ + || *p == '*' || *p == '^' + || ((syntax & RE_BK_PLUS_QM) + ? *p == '\\' && (p[1] == '+' || p[1] == '?') + : (*p == '+' || *p == '?')) + || ((syntax & RE_INTERVALS) + && ((syntax & RE_NO_BK_BRACES) + ? *p == '{' + : (p[0] == '\\' && p[1] == '{')))) { + /* Start building a new exactn. */ + + laststart = b; + + BUF_PUSH_2(exactn, 0); + pending_exact = b - 1; + } + BUF_PUSH(c); + (*pending_exact)++; + break; + } /* switch (c) */ } /* while p != pend */ /* Through the pattern now. */ if (fixup_alt_jump) - STORE_JUMP(jump_past_alt, fixup_alt_jump, b); + STORE_JUMP(jump_past_alt, fixup_alt_jump, b); if (!COMPILE_STACK_EMPTY) - return REG_EPAREN; + return REG_EPAREN; free(compile_stack.stack); @@ -1916,8 +1909,8 @@ regex_compile(const char *pattern, int size, reg_syntax_t syntax, struct re_patt #ifdef DEBUG if (debug) { - DEBUG_PRINT1("\nCompiled pattern: "); - print_compiled_pattern(bufp); + DEBUG_PRINT1("\nCompiled pattern: "); + print_compiled_pattern(bufp); } #endif /* DEBUG */ @@ -1956,7 +1949,7 @@ insert_op1(re_opcode_t op, unsigned char *loc, int arg, unsigned char *end) register unsigned char *pto = end + 3; while (pfrom != loc) - *--pto = *--pfrom; + *--pto = *--pfrom; store_op1(op, loc, arg); } @@ -1971,7 +1964,7 @@ insert_op2(re_opcode_t op, unsigned char *loc, int arg1, int arg2, unsigned char register unsigned char *pto = end + 5; while (pfrom != loc) - *--pto = *--pfrom; + *--pto = *--pfrom; store_op2(op, loc, arg1, arg2); } @@ -1988,10 +1981,10 @@ at_begline_loc_p(const char * pattern, const char *p, reg_syntax_t syntax) boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\'; return - /* After a subexpression? */ - (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash)) - /* After an alternative? */ - || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash)); + /* After a subexpression? */ + (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash)) + /* After an alternative? */ + || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash)); } @@ -2006,16 +1999,16 @@ at_endline_loc_p(const char *p, const char *pend, int syntax) const char *next_next = p + 1 < pend ? p + 1 : NULL; return - /* Before a subexpression? */ - (syntax & RE_NO_BK_PARENS ? *next == ')' - : next_backslash && next_next && *next_next == ')') - /* Before an alternative? */ - || (syntax & RE_NO_BK_VBAR ? *next == '|' - : next_backslash && next_next && *next_next == '|'); + /* Before a subexpression? */ + (syntax & RE_NO_BK_PARENS ? *next == ')' + : next_backslash && next_next && *next_next == ')') + /* Before an alternative? */ + || (syntax & RE_NO_BK_VBAR ? *next == '|' + : next_backslash && next_next && *next_next == '|'); } -/* Returns true if REGNUM is in one of COMPILE_STACK's elements and +/* Returns true if REGNUM is in one of COMPILE_STACK's elements and * false if it's not. */ boolean @@ -2024,10 +2017,10 @@ group_in_compile_stack(compile_stack_type compile_stack, regnum_t regnum) int this_element; for (this_element = compile_stack.avail - 1; - this_element >= 0; - this_element--) - if (compile_stack.stack[this_element].regnum == regnum) - return true; + this_element >= 0; + this_element--) + if (compile_stack.stack[this_element].regnum == regnum) + return true; return false; } @@ -2038,9 +2031,9 @@ group_in_compile_stack(compile_stack_type compile_stack, regnum_t regnum) * starting character is in `P[-2]'. (`P[-1]' is the character `-'.) * Then we set the translation of all bits between the starting and * ending characters (inclusive) in the compiled pattern B. - * + * * Return an error code. - * + * * We use these short variable names so we can use the same macros as * `regex_compile' itself. */ @@ -2053,14 +2046,14 @@ compile_range(const char **p_ptr, const char *pend, char *translate, reg_syntax_ int range_start, range_end; if (p == pend) - return REG_ERANGE; + return REG_ERANGE; /* Even though the pattern is a signed `char *', we need to fetch * with unsigned char *'s; if the high bit of the pattern character * is set, the range endpoints will be negative if we fetch using a * signed char *. - * - * We also want to fetch the endpoints without translating them; the + * + * We also want to fetch the endpoints without translating them; the * appropriate translation is done in the bit-setting loop below. */ range_start = ((unsigned char *) p)[-2]; range_end = ((unsigned char *) p)[0]; @@ -2071,14 +2064,14 @@ compile_range(const char **p_ptr, const char *pend, char *translate, reg_syntax_ /* If the start is after the end, the range is empty. */ if (range_start > range_end) - return syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR; + return syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR; /* Here we see why `this_char' has to be larger than an `unsigned * char' -- the range is inclusive, so if `range_end' == 0xff * (assuming 8-bit characters), we would otherwise go into an infinite * loop, since all characters <= 0xff. */ for (this_char = range_start; this_char <= range_end; this_char++) { - SET_LIST_BIT(TRANSLATE(this_char)); + SET_LIST_BIT(TRANSLATE(this_char)); } return REG_NOERROR; @@ -2132,10 +2125,10 @@ typedef struct { /* Double the size of FAIL_STACK, up to approximately `re_max_failures' items. - * + * * Return 1 if succeeds, and 0 if either ran out of memory - * allocating space for it or it was already too large. - * + * allocating space for it or it was already too large. + * * REGEX_REALLOCATE requires `destination' be declared. */ #define DOUBLE_FAIL_STACK(fail_stack) \ @@ -2152,8 +2145,8 @@ typedef struct { 1))) -/* Push PATTERN_OP on FAIL_STACK. - * +/* Push PATTERN_OP on FAIL_STACK. + * * Return 1 if was able to do so and 0 if ran out of memory allocating * space to do so. */ #define PUSH_PATTERN_OP(pattern_op, fail_stack) \ @@ -2183,12 +2176,12 @@ typedef struct { /* Push the information about the state we will need - * if we ever fail back to it. - * + * if we ever fail back to it. + * * Requires variables fail_stack, regstart, regend, reg_info, and * num_regs be declared. DOUBLE_FAIL_STACK requires `destination' be * declared. - * + * * Does `return FAILURE_CODE' if runs out of memory. */ #define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code) \ @@ -2289,14 +2282,14 @@ typedef struct { /* Pops what PUSH_FAIL_STACK pushes. - * + * * We restore into the parameters, all of which should be lvalues: * STR -- the saved data position. * PAT -- the saved pattern position. * LOW_REG, HIGH_REG -- the highest and lowest active registers. * REGSTART, REGEND -- arrays of string positions. * REG_INFO -- array of information about each subexpression. - * + * * Also assumes the variables `fail_stack' and (if debugging), `bufp', * `pend', `string1', `size1', `string2', and `size2'. */ @@ -2361,18 +2354,18 @@ typedef struct { * BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible * characters can start a string that matches the pattern. This fastmap * is used by re_search to skip quickly over impossible starting points. - * + * * The caller must supply the address of a (1 << BYTEWIDTH)-byte data * area as BUFP->fastmap. - * + * * We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in * the pattern buffer. - * + * * Returns 0 if we succeed, -2 if an internal error. */ int re_compile_fastmap(bufp) - struct re_pattern_buffer *bufp; +struct re_pattern_buffer *bufp; { int j, k; fail_stack_type fail_stack; @@ -2405,199 +2398,199 @@ re_compile_fastmap(bufp) bufp->can_be_null = 0; while (p != pend || !FAIL_STACK_EMPTY()) { - if (p == pend) { - bufp->can_be_null |= path_can_be_null; + if (p == pend) { + bufp->can_be_null |= path_can_be_null; - /* Reset for next path. */ - path_can_be_null = true; + /* Reset for next path. */ + path_can_be_null = true; - p = fail_stack.stack[--fail_stack.avail]; - } - /* We should never be about to go beyond the end of the pattern. */ - assert(p < pend); + p = fail_stack.stack[--fail_stack.avail]; + } + /* We should never be about to go beyond the end of the pattern. */ + assert(p < pend); #ifdef SWITCH_ENUM_BUG - switch ((int) ((re_opcode_t) * p++)) + switch ((int) ((re_opcode_t) * p++)) #else - switch ((re_opcode_t) * p++) + switch ((re_opcode_t) * p++) #endif - { - - /* I guess the idea here is to simply not bother with a fastmap - * if a backreference is used, since it's too hard to figure out - * the fastmap for the corresponding group. Setting - * `can_be_null' stops `re_search_2' from using the fastmap, so - * that is all we do. */ - case duplicate: - bufp->can_be_null = 1; - return 0; - - - /* Following are the cases which match a character. These end - * with `break'. */ + { + + /* I guess the idea here is to simply not bother with a fastmap + * if a backreference is used, since it's too hard to figure out + * the fastmap for the corresponding group. Setting + * `can_be_null' stops `re_search_2' from using the fastmap, so + * that is all we do. */ + case duplicate: + bufp->can_be_null = 1; + return 0; + + + /* Following are the cases which match a character. These end + * with `break'. */ - case exactn: - fastmap[p[1]] = 1; - break; - - - case charset: - for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--) - if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))) - fastmap[j] = 1; - break; - - - case charset_not: - /* Chars beyond end of map must be allowed. */ - for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++) - fastmap[j] = 1; - - for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--) - if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))) - fastmap[j] = 1; - break; - - - case wordchar: - for (j = 0; j < (1 << BYTEWIDTH); j++) - if (SYNTAX(j) == Sword) - fastmap[j] = 1; - break; - - - case notwordchar: - for (j = 0; j < (1 << BYTEWIDTH); j++) - if (SYNTAX(j) != Sword) - fastmap[j] = 1; - break; - - - case anychar: - /* `.' matches anything ... */ - for (j = 0; j < (1 << BYTEWIDTH); j++) - fastmap[j] = 1; - - /* ... except perhaps newline. */ - if (!(bufp->syntax & RE_DOT_NEWLINE)) - fastmap['\n'] = 0; - - /* Return if we have already set `can_be_null'; if we have, - * then the fastmap is irrelevant. Something's wrong here. */ - else if (bufp->can_be_null) - return 0; - - /* Otherwise, have to check alternative paths. */ - break; - - - case no_op: - case begline: - case endline: - case begbuf: - case endbuf: - case wordbound: - case notwordbound: - case wordbeg: - case wordend: - case push_dummy_failure: - continue; - - - case jump_n: - case pop_failure_jump: - case maybe_pop_jump: - case jump: - case jump_past_alt: - case dummy_failure_jump: - EXTRACT_NUMBER_AND_INCR(j, p); - p += j; - if (j > 0) - continue; - - /* Jump backward implies we just went through the body of a - * loop and matched nothing. Opcode jumped to should be - * `on_failure_jump' or `succeed_n'. Just treat it like an - * ordinary jump. For a * loop, it has pushed its failure - * point already; if so, discard that as redundant. */ - if ((re_opcode_t) * p != on_failure_jump - && (re_opcode_t) * p != succeed_n) - continue; - - p++; - EXTRACT_NUMBER_AND_INCR(j, p); - p += j; - - /* If what's on the stack is where we are now, pop it. */ - if (!FAIL_STACK_EMPTY() - && fail_stack.stack[fail_stack.avail - 1] == p) - fail_stack.avail--; - - continue; - - - case on_failure_jump: - case on_failure_keep_string_jump: - handle_on_failure_jump: - EXTRACT_NUMBER_AND_INCR(j, p); - - /* For some patterns, e.g., `(a?)?', `p+j' here points to the - * end of the pattern. We don't want to push such a point, - * since when we restore it above, entering the switch will - * increment `p' past the end of the pattern. We don't need - * to push such a point since we obviously won't find any more - * fastmap entries beyond `pend'. Such a pattern can match - * the null string, though. */ - if (p + j < pend) { - if (!PUSH_PATTERN_OP(p + j, fail_stack)) - return -2; - } else - bufp->can_be_null = 1; - - if (succeed_n_p) { - EXTRACT_NUMBER_AND_INCR(k, p); /* Skip the n. */ - succeed_n_p = false; - } - continue; - - - case succeed_n: - /* Get to the number of times to succeed. */ - p += 2; - - /* Increment p past the n for when k != 0. */ - EXTRACT_NUMBER_AND_INCR(k, p); - if (k == 0) { - p -= 4; - succeed_n_p = true; /* Spaghetti code alert. */ - goto handle_on_failure_jump; - } - continue; - - - case set_number_at: - p += 4; - continue; - - - case start_memory: - case stop_memory: - p += 2; - continue; - - - default: - abort(); /* We have listed all the cases. */ - } /* switch *p++ */ - - /* Getting here means we have found the possible starting - * characters for one path of the pattern -- and that the empty - * string does not match. We need not follow this path further. - * Instead, look at the next alternative (remembered on the - * stack), or quit if no more. The test at the top of the loop - * does these things. */ - path_can_be_null = false; - p = pend; + case exactn: + fastmap[p[1]] = 1; + break; + + + case charset: + for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--) + if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))) + fastmap[j] = 1; + break; + + + case charset_not: + /* Chars beyond end of map must be allowed. */ + for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++) + fastmap[j] = 1; + + for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--) + if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))) + fastmap[j] = 1; + break; + + + case wordchar: + for (j = 0; j < (1 << BYTEWIDTH); j++) + if (SYNTAX(j) == Sword) + fastmap[j] = 1; + break; + + + case notwordchar: + for (j = 0; j < (1 << BYTEWIDTH); j++) + if (SYNTAX(j) != Sword) + fastmap[j] = 1; + break; + + + case anychar: + /* `.' matches anything ... */ + for (j = 0; j < (1 << BYTEWIDTH); j++) + fastmap[j] = 1; + + /* ... except perhaps newline. */ + if (!(bufp->syntax & RE_DOT_NEWLINE)) + fastmap['\n'] = 0; + + /* Return if we have already set `can_be_null'; if we have, + * then the fastmap is irrelevant. Something's wrong here. */ + else if (bufp->can_be_null) + return 0; + + /* Otherwise, have to check alternative paths. */ + break; + + + case no_op: + case begline: + case endline: + case begbuf: + case endbuf: + case wordbound: + case notwordbound: + case wordbeg: + case wordend: + case push_dummy_failure: + continue; + + + case jump_n: + case pop_failure_jump: + case maybe_pop_jump: + case jump: + case jump_past_alt: + case dummy_failure_jump: + EXTRACT_NUMBER_AND_INCR(j, p); + p += j; + if (j > 0) + continue; + + /* Jump backward implies we just went through the body of a + * loop and matched nothing. Opcode jumped to should be + * `on_failure_jump' or `succeed_n'. Just treat it like an + * ordinary jump. For a * loop, it has pushed its failure + * point already; if so, discard that as redundant. */ + if ((re_opcode_t) * p != on_failure_jump + && (re_opcode_t) * p != succeed_n) + continue; + + p++; + EXTRACT_NUMBER_AND_INCR(j, p); + p += j; + + /* If what's on the stack is where we are now, pop it. */ + if (!FAIL_STACK_EMPTY() + && fail_stack.stack[fail_stack.avail - 1] == p) + fail_stack.avail--; + + continue; + + + case on_failure_jump: + case on_failure_keep_string_jump: +handle_on_failure_jump: + EXTRACT_NUMBER_AND_INCR(j, p); + + /* For some patterns, e.g., `(a?)?', `p+j' here points to the + * end of the pattern. We don't want to push such a point, + * since when we restore it above, entering the switch will + * increment `p' past the end of the pattern. We don't need + * to push such a point since we obviously won't find any more + * fastmap entries beyond `pend'. Such a pattern can match + * the null string, though. */ + if (p + j < pend) { + if (!PUSH_PATTERN_OP(p + j, fail_stack)) + return -2; + } else + bufp->can_be_null = 1; + + if (succeed_n_p) { + EXTRACT_NUMBER_AND_INCR(k, p); /* Skip the n. */ + succeed_n_p = false; + } + continue; + + + case succeed_n: + /* Get to the number of times to succeed. */ + p += 2; + + /* Increment p past the n for when k != 0. */ + EXTRACT_NUMBER_AND_INCR(k, p); + if (k == 0) { + p -= 4; + succeed_n_p = true; /* Spaghetti code alert. */ + goto handle_on_failure_jump; + } + continue; + + + case set_number_at: + p += 4; + continue; + + + case start_memory: + case stop_memory: + p += 2; + continue; + + + default: + abort(); /* We have listed all the cases. */ + } /* switch *p++ */ + + /* Getting here means we have found the possible starting + * characters for one path of the pattern -- and that the empty + * string does not match. We need not follow this path further. + * Instead, look at the next alternative (remembered on the + * stack), or quit if no more. The test at the top of the loop + * does these things. */ + path_can_be_null = false; + p = pend; } /* while p */ /* Set `can_be_null' for the last path (also the first path, if the @@ -2613,46 +2606,46 @@ re_compile_fastmap(bufp) static int re_search(bufp, string, size, startpos, range, regs) - struct re_pattern_buffer *bufp; - const char *string; - int size, startpos, range; - struct re_registers *regs; +struct re_pattern_buffer *bufp; +const char *string; +int size, startpos, range; +struct re_registers *regs; { return re_search_2(bufp, NULL, 0, string, size, startpos, range, - regs, size); + regs, size); } /* Using the compiled pattern in BUFP->buffer, first tries to match the * virtual concatenation of STRING1 and STRING2, starting first at index * STARTPOS, then at STARTPOS + 1, and so on. - * + * * STRING1 and STRING2 have length SIZE1 and SIZE2, respectively. - * + * * RANGE is how far to scan while trying to match. RANGE = 0 means try * only at STARTPOS; in general, the last start tried is STARTPOS + * RANGE. - * + * * In REGS, return the indices of the virtual concatenation of STRING1 * and STRING2 that matched the entire BUFP->buffer and its contained * subexpressions. - * + * * Do not consider matching one past the index STOP in the virtual * concatenation of STRING1 and STRING2. - * + * * We return either the position in the strings at which the match was * found, -1 if no match, or -2 if error (such as failure * stack overflow). */ static int re_search_2(bufp, string1, size1, string2, size2, startpos, range, regs, stop) - struct re_pattern_buffer *bufp; - const char *string1, *string2; - int size1, size2; - int startpos; - int range; - struct re_registers *regs; - int stop; +struct re_pattern_buffer *bufp; +const char *string1, *string2; +int size1, size2; +int startpos; +int range; +struct re_registers *regs; +int stop; { int val; register char *fastmap = bufp->fastmap; @@ -2662,89 +2655,89 @@ re_search_2(bufp, string1, size1, string2, size2, startpos, range, regs, stop) /* Check for out-of-range STARTPOS. */ if (startpos < 0 || startpos > total_size) - return -1; + return -1; /* Fix up RANGE if it might eventually take us outside * the virtual concatenation of STRING1 and STRING2. */ if (endpos < -1) - range = -1 - startpos; + range = -1 - startpos; else if (endpos > total_size) - range = total_size - startpos; + range = total_size - startpos; /* If the search isn't to be a backwards one, don't waste time in a * search for a pattern that must be anchored. */ if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0) { - if (startpos > 0) - return -1; - else - range = 1; + if (startpos > 0) + return -1; + else + range = 1; } /* Update the fastmap now if not correct already. */ if (fastmap && !bufp->fastmap_accurate) - if (re_compile_fastmap(bufp) == -2) - return -2; + if (re_compile_fastmap(bufp) == -2) + return -2; /* Loop through the string, looking for a place to start matching. */ for (;;) { - /* If a fastmap is supplied, skip quickly over characters that - * cannot be the start of a match. If the pattern can match the - * null string, however, we don't need to skip characters; we want - * the first null string. */ - if (fastmap && startpos < total_size && !bufp->can_be_null) { - if (range > 0) { /* Searching forwards. */ - register const char *d; - register int lim = 0; - int irange = range; - - if (startpos < size1 && startpos + range >= size1) - lim = range - (size1 - startpos); - - d = (startpos >= size1 ? string2 - size1 : string1) + startpos; - - /* Written out as an if-else to avoid testing `translate' - * inside the loop. */ - if (translate) - while (range > lim - && !fastmap[(unsigned char) - translate[(unsigned char) *d++]]) - range--; - else - while (range > lim && !fastmap[(unsigned char) *d++]) - range--; - - startpos += irange - range; - } else { /* Searching backwards. */ - register char c = (size1 == 0 || startpos >= size1 - ? string2[startpos - size1] - : string1[startpos]); - - if (!fastmap[(unsigned char) TRANSLATE(c)]) - goto advance; - } - } - /* If can't match the null string, and that's all we have left, fail. */ - if (range >= 0 && startpos == total_size && fastmap - && !bufp->can_be_null) - return -1; - - val = re_match_2(bufp, string1, size1, string2, size2, - startpos, regs, stop); - if (val >= 0) - return startpos; - - if (val == -2) - return -2; - - advance: - if (!range) - break; - else if (range > 0) { - range--; - startpos++; - } else { - range++; - startpos--; - } + /* If a fastmap is supplied, skip quickly over characters that + * cannot be the start of a match. If the pattern can match the + * null string, however, we don't need to skip characters; we want + * the first null string. */ + if (fastmap && startpos < total_size && !bufp->can_be_null) { + if (range > 0) { /* Searching forwards. */ + register const char *d; + register int lim = 0; + int irange = range; + + if (startpos < size1 && startpos + range >= size1) + lim = range - (size1 - startpos); + + d = (startpos >= size1 ? string2 - size1 : string1) + startpos; + + /* Written out as an if-else to avoid testing `translate' + * inside the loop. */ + if (translate) + while (range > lim + && !fastmap[(unsigned char) + translate[(unsigned char) *d++]]) + range--; + else + while (range > lim && !fastmap[(unsigned char) *d++]) + range--; + + startpos += irange - range; + } else { /* Searching backwards. */ + register char c = (size1 == 0 || startpos >= size1 + ? string2[startpos - size1] + : string1[startpos]); + + if (!fastmap[(unsigned char) TRANSLATE(c)]) + goto advance; + } + } + /* If can't match the null string, and that's all we have left, fail. */ + if (range >= 0 && startpos == total_size && fastmap + && !bufp->can_be_null) + return -1; + + val = re_match_2(bufp, string1, size1, string2, size2, + startpos, regs, stop); + if (val >= 0) + return startpos; + + if (val == -2) + return -2; + +advance: + if (!range) + break; + else if (range > 0) { + range--; + startpos++; + } else { + range++; + startpos--; + } } return -1; } /* re_search_2 */ @@ -2756,8 +2749,8 @@ re_search_2(bufp, string1, size1, string2, size2, startpos, range, regs, stop) * onto the failure stack. Other register information, such as the * starting and ending positions (which are addresses), and the list of * inner groups (which is a bits list) are maintained in separate - * variables. - * + * variables. + * * We are making a (strictly speaking) nonportable assumption here: that * the compiler will pack our bit fields into something that fits into * the type of `word', i.e., is something that fits into one item on the @@ -2765,13 +2758,13 @@ re_search_2(bufp, string1, size1, string2, size2, startpos, range, regs, stop) typedef union { fail_stack_elt_t word; struct { - /* This field is one if this group can match the empty string, - * zero if not. If not yet determined, `MATCH_NULL_UNSET_VALUE'. */ + /* This field is one if this group can match the empty string, + * zero if not. If not yet determined, `MATCH_NULL_UNSET_VALUE'. */ #define MATCH_NULL_UNSET_VALUE 3 - unsigned match_null_string_p:2; - unsigned is_active:1; - unsigned matched_something:1; - unsigned ever_matched_something:1; + unsigned match_null_string_p:2; + unsigned is_active:1; + unsigned matched_something:1; + unsigned ever_matched_something:1; } bits; } register_info_type; static boolean alt_match_null_string_p(unsigned char *p, unsigned char *end, register_info_type *reg_info); @@ -2890,23 +2883,23 @@ static boolean group_match_null_string_p(unsigned char **p, unsigned char *end, * the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1 * and SIZE2, respectively). We start matching at POS, and stop * matching at STOP. - * + * * If REGS is non-null and the `no_sub' field of BUFP is nonzero, we * store offsets for the substring each group matched in REGS. See the * documentation for exactly how many groups we fill. - * + * * We return -1 if no match, -2 if an internal error (such as the * failure stack overflowing). Otherwise, we return the length of the * matched substring. */ int re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) - struct re_pattern_buffer *bufp; - const char *string1, *string2; - int size1, size2; - int pos; - struct re_registers *regs; - int stop; +struct re_pattern_buffer *bufp; +const char *string1, *string2; +int size1, size2; +int pos; +struct re_registers *regs; +int stop; { /* General temporaries. */ int mcnt; @@ -2978,7 +2971,7 @@ re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) register_info_type *reg_info = NULL; /* The following record the register info as found in the above - * variables when we find a match better than any we've seen before. + * variables when we find a match better than any we've seen before. * This happens as we backtrack through the failure points, which in * turn happens only if we have not yet matched the entire string. */ unsigned best_regs_set = false; @@ -3013,82 +3006,82 @@ re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) * pattern), even though we never use it, since it simplifies the * array indexing. We should fix this. */ if (bufp->re_nsub) { - regstart = REGEX_TALLOC(num_regs, const char *); - regend = REGEX_TALLOC(num_regs, const char *); - old_regstart = REGEX_TALLOC(num_regs, const char *); - old_regend = REGEX_TALLOC(num_regs, const char *); - best_regstart = REGEX_TALLOC(num_regs, const char *); - best_regend = REGEX_TALLOC(num_regs, const char *); - reg_info = REGEX_TALLOC(num_regs, register_info_type); - reg_dummy = REGEX_TALLOC(num_regs, const char *); - reg_info_dummy = REGEX_TALLOC(num_regs, register_info_type); - - if (!(regstart && regend && old_regstart && old_regend && reg_info - && best_regstart && best_regend && reg_dummy && reg_info_dummy)) { - FREE_VARIABLES(); - return -2; - } + regstart = REGEX_TALLOC(num_regs, const char *); + regend = REGEX_TALLOC(num_regs, const char *); + old_regstart = REGEX_TALLOC(num_regs, const char *); + old_regend = REGEX_TALLOC(num_regs, const char *); + best_regstart = REGEX_TALLOC(num_regs, const char *); + best_regend = REGEX_TALLOC(num_regs, const char *); + reg_info = REGEX_TALLOC(num_regs, register_info_type); + reg_dummy = REGEX_TALLOC(num_regs, const char *); + reg_info_dummy = REGEX_TALLOC(num_regs, register_info_type); + + if (!(regstart && regend && old_regstart && old_regend && reg_info + && best_regstart && best_regend && reg_dummy && reg_info_dummy)) { + FREE_VARIABLES(); + return -2; + } } #ifdef REGEX_MALLOC else { - /* We must initialize all our variables to NULL, so that - * `FREE_VARIABLES' doesn't try to free them. */ - regstart = regend = old_regstart = old_regend = best_regstart - = best_regend = reg_dummy = NULL; - reg_info = reg_info_dummy = (register_info_type *) NULL; + /* We must initialize all our variables to NULL, so that + * `FREE_VARIABLES' doesn't try to free them. */ + regstart = regend = old_regstart = old_regend = best_regstart + = best_regend = reg_dummy = NULL; + reg_info = reg_info_dummy = (register_info_type *) NULL; } #endif /* REGEX_MALLOC */ /* The starting position is bogus. */ if (pos < 0 || pos > size1 + size2) { - FREE_VARIABLES(); - return -1; + FREE_VARIABLES(); + return -1; } /* Initialize subexpression text positions to -1 to mark ones that no * start_memory/stop_memory has been seen for. Also initialize the * register information struct. */ for (mcnt = 1; mcnt < num_regs; mcnt++) { - regstart[mcnt] = regend[mcnt] - = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE; + regstart[mcnt] = regend[mcnt] + = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE; - REG_MATCH_NULL_STRING_P(reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE; - IS_ACTIVE(reg_info[mcnt]) = 0; - MATCHED_SOMETHING(reg_info[mcnt]) = 0; - EVER_MATCHED_SOMETHING(reg_info[mcnt]) = 0; + REG_MATCH_NULL_STRING_P(reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE; + IS_ACTIVE(reg_info[mcnt]) = 0; + MATCHED_SOMETHING(reg_info[mcnt]) = 0; + EVER_MATCHED_SOMETHING(reg_info[mcnt]) = 0; } /* We move `string1' into `string2' if the latter's empty -- but not if * `string1' is null. */ if (size2 == 0 && string1 != NULL) { - string2 = string1; - size2 = size1; - string1 = 0; - size1 = 0; + string2 = string1; + size2 = size1; + string1 = 0; + size1 = 0; } end1 = string1 + size1; end2 = string2 + size2; /* Compute where to stop matching, within the two strings. */ if (stop <= size1) { - end_match_1 = string1 + stop; - end_match_2 = string2; + end_match_1 = string1 + stop; + end_match_2 = string2; } else { - end_match_1 = end1; - end_match_2 = string2 + stop - size1; + end_match_1 = end1; + end_match_2 = string2 + stop - size1; } - /* `p' scans through the pattern as `d' scans through the data. + /* `p' scans through the pattern as `d' scans through the data. * `dend' is the end of the input string that `d' points within. `d' * is advanced into the following input string whenever necessary, but * this happens before fetching; therefore, at the beginning of the * loop, `d' can be pointing at the end of a string, but it cannot * equal `string2'. */ if (size1 > 0 && pos <= size1) { - d = string1 + pos; - dend = end_match_1; + d = string1 + pos; + dend = end_match_1; } else { - d = string2 + pos - size1; - dend = end_match_2; + d = string2 + pos - size1; + dend = end_match_2; } DEBUG_PRINT1("The compiled pattern is: "); @@ -3101,849 +3094,845 @@ re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) * function if the match is complete, or it drops through if the match * fails at this starting point in the input data. */ for (;;) { - DEBUG_PRINT2("\n0x%x: ", p); - - if (p == pend) { /* End of pattern means we might have succeeded. */ - DEBUG_PRINT1("end of pattern ... "); - - /* If we haven't matched the entire string, and we want the - * longest match, try backtracking. */ - if (d != end_match_2) { - DEBUG_PRINT1("backtracking.\n"); - - if (!FAIL_STACK_EMPTY()) { /* More failure points to try. */ - boolean same_str_p = (FIRST_STRING_P(match_end) - == MATCHING_IN_FIRST_STRING); - - /* If exceeds best match so far, save it. */ - if (!best_regs_set - || (same_str_p && d > match_end) - || (!same_str_p && !MATCHING_IN_FIRST_STRING)) { - best_regs_set = true; - match_end = d; - - DEBUG_PRINT1("\nSAVING match as best so far.\n"); - - for (mcnt = 1; mcnt < num_regs; mcnt++) { - best_regstart[mcnt] = regstart[mcnt]; - best_regend[mcnt] = regend[mcnt]; - } - } - goto fail; - } - /* If no failure points, don't restore garbage. */ - else if (best_regs_set) { - restore_best_regs: - /* Restore best match. It may happen that `dend == - * end_match_1' while the restored d is in string2. - * For example, the pattern `x.*y.*z' against the - * strings `x-' and `y-z-', if the two strings are - * not consecutive in memory. */ - DEBUG_PRINT1("Restoring best registers.\n"); - - d = match_end; - dend = ((d >= string1 && d <= end1) - ? end_match_1 : end_match_2); - - for (mcnt = 1; mcnt < num_regs; mcnt++) { - regstart[mcnt] = best_regstart[mcnt]; - regend[mcnt] = best_regend[mcnt]; - } - } - } /* d != end_match_2 */ - DEBUG_PRINT1("Accepting match.\n"); - - /* If caller wants register contents data back, do it. */ - if (regs && !bufp->no_sub) { - /* Have the register data arrays been allocated? */ - if (bufp->regs_allocated == REGS_UNALLOCATED) { /* No. So allocate them with malloc. We need one + DEBUG_PRINT2("\n0x%x: ", p); + + if (p == pend) { /* End of pattern means we might have succeeded. */ + DEBUG_PRINT1("end of pattern ... "); + + /* If we haven't matched the entire string, and we want the + * longest match, try backtracking. */ + if (d != end_match_2) { + DEBUG_PRINT1("backtracking.\n"); + + if (!FAIL_STACK_EMPTY()) { /* More failure points to try. */ + boolean same_str_p = (FIRST_STRING_P(match_end) + == MATCHING_IN_FIRST_STRING); + + /* If exceeds best match so far, save it. */ + if (!best_regs_set + || (same_str_p && d > match_end) + || (!same_str_p && !MATCHING_IN_FIRST_STRING)) { + best_regs_set = true; + match_end = d; + + DEBUG_PRINT1("\nSAVING match as best so far.\n"); + + for (mcnt = 1; mcnt < num_regs; mcnt++) { + best_regstart[mcnt] = regstart[mcnt]; + best_regend[mcnt] = regend[mcnt]; + } + } + goto fail; + } + /* If no failure points, don't restore garbage. */ + else if (best_regs_set) { +restore_best_regs: + /* Restore best match. It may happen that `dend == + * end_match_1' while the restored d is in string2. + * For example, the pattern `x.*y.*z' against the + * strings `x-' and `y-z-', if the two strings are + * not consecutive in memory. */ + DEBUG_PRINT1("Restoring best registers.\n"); + + d = match_end; + dend = ((d >= string1 && d <= end1) + ? end_match_1 : end_match_2); + + for (mcnt = 1; mcnt < num_regs; mcnt++) { + regstart[mcnt] = best_regstart[mcnt]; + regend[mcnt] = best_regend[mcnt]; + } + } + } /* d != end_match_2 */ + DEBUG_PRINT1("Accepting match.\n"); + + /* If caller wants register contents data back, do it. */ + if (regs && !bufp->no_sub) { + /* Have the register data arrays been allocated? */ + if (bufp->regs_allocated == REGS_UNALLOCATED) { /* No. So allocate them with malloc. We need one * extra element beyond `num_regs' for the `-1' marker * GNU code uses. */ - regs->num_regs = MAX(RE_NREGS, num_regs + 1); - regs->start = TALLOC(regs->num_regs, regoff_t); - regs->end = TALLOC(regs->num_regs, regoff_t); - if (regs->start == NULL || regs->end == NULL) - return -2; - bufp->regs_allocated = REGS_REALLOCATE; - } else if (bufp->regs_allocated == REGS_REALLOCATE) { /* Yes. If we need more elements than were already + regs->num_regs = MAX(RE_NREGS, num_regs + 1); + regs->start = TALLOC(regs->num_regs, regoff_t); + regs->end = TALLOC(regs->num_regs, regoff_t); + if (regs->start == NULL || regs->end == NULL) + return -2; + bufp->regs_allocated = REGS_REALLOCATE; + } else if (bufp->regs_allocated == REGS_REALLOCATE) { /* Yes. If we need more elements than were already * allocated, reallocate them. If we need fewer, just * leave it alone. */ - if (regs->num_regs < num_regs + 1) { - regs->num_regs = num_regs + 1; - RETALLOC(regs->start, regs->num_regs, regoff_t); - RETALLOC(regs->end, regs->num_regs, regoff_t); - if (regs->start == NULL || regs->end == NULL) - return -2; - } - } else - assert(bufp->regs_allocated == REGS_FIXED); - - /* Convert the pointer data in `regstart' and `regend' to - * indices. Register zero has to be set differently, - * since we haven't kept track of any info for it. */ - if (regs->num_regs > 0) { - regs->start[0] = pos; - regs->end[0] = (MATCHING_IN_FIRST_STRING ? d - string1 - : d - string2 + size1); - } - /* Go through the first `min (num_regs, regs->num_regs)' - * registers, since that is all we initialized. */ - for (mcnt = 1; mcnt < MIN(num_regs, regs->num_regs); mcnt++) { - if (REG_UNSET(regstart[mcnt]) || REG_UNSET(regend[mcnt])) - regs->start[mcnt] = regs->end[mcnt] = -1; - else { - regs->start[mcnt] = POINTER_TO_OFFSET(regstart[mcnt]); - regs->end[mcnt] = POINTER_TO_OFFSET(regend[mcnt]); - } - } - - /* If the regs structure we return has more elements than - * were in the pattern, set the extra elements to -1. If - * we (re)allocated the registers, this is the case, - * because we always allocate enough to have at least one - * -1 at the end. */ - for (mcnt = num_regs; mcnt < regs->num_regs; mcnt++) - regs->start[mcnt] = regs->end[mcnt] = -1; - } /* regs && !bufp->no_sub */ - FREE_VARIABLES(); - DEBUG_PRINT4("%u failure points pushed, %u popped (%u remain).\n", - nfailure_points_pushed, nfailure_points_popped, - nfailure_points_pushed - nfailure_points_popped); - DEBUG_PRINT2("%u registers pushed.\n", num_regs_pushed); - - mcnt = d - pos - (MATCHING_IN_FIRST_STRING - ? string1 - : string2 - size1); - - DEBUG_PRINT2("Returning %d from re_match_2.\n", mcnt); - - return mcnt; - } - /* Otherwise match next pattern command. */ + if (regs->num_regs < num_regs + 1) { + regs->num_regs = num_regs + 1; + RETALLOC(regs->start, regs->num_regs, regoff_t); + RETALLOC(regs->end, regs->num_regs, regoff_t); + if (regs->start == NULL || regs->end == NULL) + return -2; + } + } else + assert(bufp->regs_allocated == REGS_FIXED); + + /* Convert the pointer data in `regstart' and `regend' to + * indices. Register zero has to be set differently, + * since we haven't kept track of any info for it. */ + if (regs->num_regs > 0) { + regs->start[0] = pos; + regs->end[0] = (MATCHING_IN_FIRST_STRING ? d - string1 + : d - string2 + size1); + } + /* Go through the first `min (num_regs, regs->num_regs)' + * registers, since that is all we initialized. */ + for (mcnt = 1; mcnt < MIN(num_regs, regs->num_regs); mcnt++) { + if (REG_UNSET(regstart[mcnt]) || REG_UNSET(regend[mcnt])) + regs->start[mcnt] = regs->end[mcnt] = -1; + else { + regs->start[mcnt] = POINTER_TO_OFFSET(regstart[mcnt]); + regs->end[mcnt] = POINTER_TO_OFFSET(regend[mcnt]); + } + } + + /* If the regs structure we return has more elements than + * were in the pattern, set the extra elements to -1. If + * we (re)allocated the registers, this is the case, + * because we always allocate enough to have at least one + * -1 at the end. */ + for (mcnt = num_regs; mcnt < regs->num_regs; mcnt++) + regs->start[mcnt] = regs->end[mcnt] = -1; + } /* regs && !bufp->no_sub */ + FREE_VARIABLES(); + DEBUG_PRINT4("%u failure points pushed, %u popped (%u remain).\n", + nfailure_points_pushed, nfailure_points_popped, + nfailure_points_pushed - nfailure_points_popped); + DEBUG_PRINT2("%u registers pushed.\n", num_regs_pushed); + + mcnt = d - pos - (MATCHING_IN_FIRST_STRING + ? string1 + : string2 - size1); + + DEBUG_PRINT2("Returning %d from re_match_2.\n", mcnt); + + return mcnt; + } + /* Otherwise match next pattern command. */ #ifdef SWITCH_ENUM_BUG - switch ((int) ((re_opcode_t) * p++)) + switch ((int) ((re_opcode_t) * p++)) #else - switch ((re_opcode_t) * p++) + switch ((re_opcode_t) * p++) #endif - { - /* Ignore these. Used to ignore the n of succeed_n's which - * currently have n == 0. */ - case no_op: - DEBUG_PRINT1("EXECUTING no_op.\n"); - break; - - - /* Match the next n pattern characters exactly. The following - * byte in the pattern defines n, and the n bytes after that - * are the characters to match. */ - case exactn: - mcnt = *p++; - DEBUG_PRINT2("EXECUTING exactn %d.\n", mcnt); - - /* This is written out as an if-else so we don't waste time - * testing `translate' inside the loop. */ - if (translate) { - do { - PREFETCH(); - if (translate[(unsigned char) *d++] != (char) *p++) - goto fail; - } - while (--mcnt); - } else { - do { - PREFETCH(); - if (*d++ != (char) *p++) - goto fail; - } - while (--mcnt); - } - SET_REGS_MATCHED(); - break; - - - /* Match any character except possibly a newline or a null. */ - case anychar: - DEBUG_PRINT1("EXECUTING anychar.\n"); - - PREFETCH(); - - if ((!(bufp->syntax & RE_DOT_NEWLINE) && TRANSLATE(*d) == '\n') - || (bufp->syntax & RE_DOT_NOT_NULL && TRANSLATE(*d) == '\000')) - goto fail; - - SET_REGS_MATCHED(); - DEBUG_PRINT2(" Matched `%d'.\n", *d); - d++; - break; - - - case charset: - case charset_not: - { - register unsigned char c; - boolean not = (re_opcode_t) * (p - 1) == charset_not; - - DEBUG_PRINT2("EXECUTING charset%s.\n", not ? "_not" : ""); - - PREFETCH(); - c = TRANSLATE(*d); /* The character to match. */ - - /* Cast to `unsigned' instead of `unsigned char' in case the - * bit list is a full 32 bytes long. */ - if (c < (unsigned) (*p * BYTEWIDTH) - && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH))) - not = !not; - - p += 1 + *p; - - if (!not) - goto fail; - - SET_REGS_MATCHED(); - d++; - break; - } - - - /* The beginning of a group is represented by start_memory. - * The arguments are the register number in the next byte, and the - * number of groups inner to this one in the next. The text - * matched within the group is recorded (in the internal - * registers data structure) under the register number. */ - case start_memory: - DEBUG_PRINT3("EXECUTING start_memory %d (%d):\n", *p, p[1]); - - /* Find out if this group can match the empty string. */ - p1 = p; /* To send to group_match_null_string_p. */ - - if (REG_MATCH_NULL_STRING_P(reg_info[*p]) == MATCH_NULL_UNSET_VALUE) - REG_MATCH_NULL_STRING_P(reg_info[*p]) - = group_match_null_string_p(&p1, pend, reg_info); - - /* Save the position in the string where we were the last time - * we were at this open-group operator in case the group is - * operated upon by a repetition operator, e.g., with `(a*)*b' - * against `ab'; then we want to ignore where we are now in - * the string in case this attempt to match fails. */ - old_regstart[*p] = REG_MATCH_NULL_STRING_P(reg_info[*p]) - ? REG_UNSET(regstart[*p]) ? d : regstart[*p] - : regstart[*p]; - DEBUG_PRINT2(" old_regstart: %d\n", - POINTER_TO_OFFSET(old_regstart[*p])); - - regstart[*p] = d; - DEBUG_PRINT2(" regstart: %d\n", POINTER_TO_OFFSET(regstart[*p])); - - IS_ACTIVE(reg_info[*p]) = 1; - MATCHED_SOMETHING(reg_info[*p]) = 0; - - /* This is the new highest active register. */ - highest_active_reg = *p; - - /* If nothing was active before, this is the new lowest active - * register. */ - if (lowest_active_reg == NO_LOWEST_ACTIVE_REG) - lowest_active_reg = *p; - - /* Move past the register number and inner group count. */ - p += 2; - break; - - - /* The stop_memory opcode represents the end of a group. Its - * arguments are the same as start_memory's: the register - * number, and the number of inner groups. */ - case stop_memory: - DEBUG_PRINT3("EXECUTING stop_memory %d (%d):\n", *p, p[1]); - - /* We need to save the string position the last time we were at - * this close-group operator in case the group is operated - * upon by a repetition operator, e.g., with `((a*)*(b*)*)*' - * against `aba'; then we want to ignore where we are now in - * the string in case this attempt to match fails. */ - old_regend[*p] = REG_MATCH_NULL_STRING_P(reg_info[*p]) - ? REG_UNSET(regend[*p]) ? d : regend[*p] - : regend[*p]; - DEBUG_PRINT2(" old_regend: %d\n", - POINTER_TO_OFFSET(old_regend[*p])); - - regend[*p] = d; - DEBUG_PRINT2(" regend: %d\n", POINTER_TO_OFFSET(regend[*p])); - - /* This register isn't active anymore. */ - IS_ACTIVE(reg_info[*p]) = 0; - - /* If this was the only register active, nothing is active - * anymore. */ - if (lowest_active_reg == highest_active_reg) { - lowest_active_reg = NO_LOWEST_ACTIVE_REG; - highest_active_reg = NO_HIGHEST_ACTIVE_REG; - } else { /* We must scan for the new highest active register, since + { + /* Ignore these. Used to ignore the n of succeed_n's which + * currently have n == 0. */ + case no_op: + DEBUG_PRINT1("EXECUTING no_op.\n"); + break; + + + /* Match the next n pattern characters exactly. The following + * byte in the pattern defines n, and the n bytes after that + * are the characters to match. */ + case exactn: + mcnt = *p++; + DEBUG_PRINT2("EXECUTING exactn %d.\n", mcnt); + + /* This is written out as an if-else so we don't waste time + * testing `translate' inside the loop. */ + if (translate) { + do { + PREFETCH(); + if (translate[(unsigned char) *d++] != (char) *p++) + goto fail; + } while (--mcnt); + } else { + do { + PREFETCH(); + if (*d++ != (char) *p++) + goto fail; + } while (--mcnt); + } + SET_REGS_MATCHED(); + break; + + + /* Match any character except possibly a newline or a null. */ + case anychar: + DEBUG_PRINT1("EXECUTING anychar.\n"); + + PREFETCH(); + + if ((!(bufp->syntax & RE_DOT_NEWLINE) && TRANSLATE(*d) == '\n') + || (bufp->syntax & RE_DOT_NOT_NULL && TRANSLATE(*d) == '\000')) + goto fail; + + SET_REGS_MATCHED(); + DEBUG_PRINT2(" Matched `%d'.\n", *d); + d++; + break; + + + case charset: + case charset_not: { + register unsigned char c; + boolean not = (re_opcode_t) * (p - 1) == charset_not; + + DEBUG_PRINT2("EXECUTING charset%s.\n", not ? "_not" : ""); + + PREFETCH(); + c = TRANSLATE(*d); /* The character to match. */ + + /* Cast to `unsigned' instead of `unsigned char' in case the + * bit list is a full 32 bytes long. */ + if (c < (unsigned) (*p * BYTEWIDTH) + && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH))) + not = !not; + + p += 1 + *p; + + if (!not) + goto fail; + + SET_REGS_MATCHED(); + d++; + break; + } + + + /* The beginning of a group is represented by start_memory. + * The arguments are the register number in the next byte, and the + * number of groups inner to this one in the next. The text + * matched within the group is recorded (in the internal + * registers data structure) under the register number. */ + case start_memory: + DEBUG_PRINT3("EXECUTING start_memory %d (%d):\n", *p, p[1]); + + /* Find out if this group can match the empty string. */ + p1 = p; /* To send to group_match_null_string_p. */ + + if (REG_MATCH_NULL_STRING_P(reg_info[*p]) == MATCH_NULL_UNSET_VALUE) + REG_MATCH_NULL_STRING_P(reg_info[*p]) + = group_match_null_string_p(&p1, pend, reg_info); + + /* Save the position in the string where we were the last time + * we were at this open-group operator in case the group is + * operated upon by a repetition operator, e.g., with `(a*)*b' + * against `ab'; then we want to ignore where we are now in + * the string in case this attempt to match fails. */ + old_regstart[*p] = REG_MATCH_NULL_STRING_P(reg_info[*p]) + ? REG_UNSET(regstart[*p]) ? d : regstart[*p] + : regstart[*p]; + DEBUG_PRINT2(" old_regstart: %d\n", + POINTER_TO_OFFSET(old_regstart[*p])); + + regstart[*p] = d; + DEBUG_PRINT2(" regstart: %d\n", POINTER_TO_OFFSET(regstart[*p])); + + IS_ACTIVE(reg_info[*p]) = 1; + MATCHED_SOMETHING(reg_info[*p]) = 0; + + /* This is the new highest active register. */ + highest_active_reg = *p; + + /* If nothing was active before, this is the new lowest active + * register. */ + if (lowest_active_reg == NO_LOWEST_ACTIVE_REG) + lowest_active_reg = *p; + + /* Move past the register number and inner group count. */ + p += 2; + break; + + + /* The stop_memory opcode represents the end of a group. Its + * arguments are the same as start_memory's: the register + * number, and the number of inner groups. */ + case stop_memory: + DEBUG_PRINT3("EXECUTING stop_memory %d (%d):\n", *p, p[1]); + + /* We need to save the string position the last time we were at + * this close-group operator in case the group is operated + * upon by a repetition operator, e.g., with `((a*)*(b*)*)*' + * against `aba'; then we want to ignore where we are now in + * the string in case this attempt to match fails. */ + old_regend[*p] = REG_MATCH_NULL_STRING_P(reg_info[*p]) + ? REG_UNSET(regend[*p]) ? d : regend[*p] + : regend[*p]; + DEBUG_PRINT2(" old_regend: %d\n", + POINTER_TO_OFFSET(old_regend[*p])); + + regend[*p] = d; + DEBUG_PRINT2(" regend: %d\n", POINTER_TO_OFFSET(regend[*p])); + + /* This register isn't active anymore. */ + IS_ACTIVE(reg_info[*p]) = 0; + + /* If this was the only register active, nothing is active + * anymore. */ + if (lowest_active_reg == highest_active_reg) { + lowest_active_reg = NO_LOWEST_ACTIVE_REG; + highest_active_reg = NO_HIGHEST_ACTIVE_REG; + } else { /* We must scan for the new highest active register, since * it isn't necessarily one less than now: consider * (a(b)c(d(e)f)g). When group 3 ends, after the f), the * new highest active register is 1. */ - unsigned char r = *p - 1; - while (r > 0 && !IS_ACTIVE(reg_info[r])) - r--; - - /* If we end up at register zero, that means that we saved - * the registers as the result of an `on_failure_jump', not - * a `start_memory', and we jumped to past the innermost - * `stop_memory'. For example, in ((.)*) we save - * registers 1 and 2 as a result of the *, but when we pop - * back to the second ), we are at the stop_memory 1. - * Thus, nothing is active. */ - if (r == 0) { - lowest_active_reg = NO_LOWEST_ACTIVE_REG; - highest_active_reg = NO_HIGHEST_ACTIVE_REG; - } else - highest_active_reg = r; - } - - /* If just failed to match something this time around with a - * group that's operated on by a repetition operator, try to - * force exit from the ``loop'', and restore the register - * information for this group that we had before trying this - * last match. */ - if ((!MATCHED_SOMETHING(reg_info[*p]) - || (re_opcode_t) p[-3] == start_memory) - && (p + 2) < pend) { - boolean is_a_jump_n = false; - - p1 = p + 2; - mcnt = 0; - switch ((re_opcode_t) * p1++) { - case jump_n: - is_a_jump_n = true; - case pop_failure_jump: - case maybe_pop_jump: - case jump: - case dummy_failure_jump: - EXTRACT_NUMBER_AND_INCR(mcnt, p1); - if (is_a_jump_n) - p1 += 2; - break; - - default: - /* do nothing */ ; - } - p1 += mcnt; - - /* If the next operation is a jump backwards in the pattern - * to an on_failure_jump right before the start_memory - * corresponding to this stop_memory, exit from the loop - * by forcing a failure after pushing on the stack the - * on_failure_jump's jump in the pattern, and d. */ - if (mcnt < 0 && (re_opcode_t) * p1 == on_failure_jump - && (re_opcode_t) p1[3] == start_memory && p1[4] == *p) { - /* If this group ever matched anything, then restore - * what its registers were before trying this last - * failed match, e.g., with `(a*)*b' against `ab' for - * regstart[1], and, e.g., with `((a*)*(b*)*)*' - * against `aba' for regend[3]. - * - * Also restore the registers for inner groups for, - * e.g., `((a*)(b*))*' against `aba' (register 3 would - * otherwise get trashed). */ - - if (EVER_MATCHED_SOMETHING(reg_info[*p])) { - unsigned r; - - EVER_MATCHED_SOMETHING(reg_info[*p]) = 0; - - /* Restore this and inner groups' (if any) registers. */ - for (r = *p; r < *p + *(p + 1); r++) { - regstart[r] = old_regstart[r]; - - /* xx why this test? */ - if ((long) old_regend[r] >= (long) regstart[r]) - regend[r] = old_regend[r]; - } - } - p1++; - EXTRACT_NUMBER_AND_INCR(mcnt, p1); - PUSH_FAILURE_POINT(p1 + mcnt, d, -2); - - goto fail; - } - } - /* Move past the register number and the inner group count. */ - p += 2; - break; - - - /* \ has been turned into a `duplicate' command which is - * followed by the numeric value of as the register number. */ - case duplicate: - { - register const char *d2, *dend2; - int regno = *p++; /* Get which register to match against. */ - DEBUG_PRINT2("EXECUTING duplicate %d.\n", regno); - - /* Can't back reference a group which we've never matched. */ - if (REG_UNSET(regstart[regno]) || REG_UNSET(regend[regno])) - goto fail; - - /* Where in input to try to start matching. */ - d2 = regstart[regno]; - - /* Where to stop matching; if both the place to start and - * the place to stop matching are in the same string, then - * set to the place to stop, otherwise, for now have to use - * the end of the first string. */ - - dend2 = ((FIRST_STRING_P(regstart[regno]) - == FIRST_STRING_P(regend[regno])) - ? regend[regno] : end_match_1); - for (;;) { - /* If necessary, advance to next segment in register - * contents. */ - while (d2 == dend2) { - if (dend2 == end_match_2) - break; - if (dend2 == regend[regno]) - break; - - /* End of string1 => advance to string2. */ - d2 = string2; - dend2 = regend[regno]; - } - /* At end of register contents => success */ - if (d2 == dend2) - break; - - /* If necessary, advance to next segment in data. */ - PREFETCH(); - - /* How many characters left in this segment to match. */ - mcnt = dend - d; - - /* Want how many consecutive characters we can match in - * one shot, so, if necessary, adjust the count. */ - if (mcnt > dend2 - d2) - mcnt = dend2 - d2; - - /* Compare that many; failure if mismatch, else move - * past them. */ - if (translate - ? bcmp_translate((unsigned char *)d, (unsigned char *)d2, mcnt, translate) - : memcmp(d, d2, mcnt)) - goto fail; - d += mcnt, d2 += mcnt; - } - } - break; - - - /* begline matches the empty string at the beginning of the string - * (unless `not_bol' is set in `bufp'), and, if - * `newline_anchor' is set, after newlines. */ - case begline: - DEBUG_PRINT1("EXECUTING begline.\n"); - - if (AT_STRINGS_BEG(d)) { - if (!bufp->not_bol) - break; - } else if (d[-1] == '\n' && bufp->newline_anchor) { - break; - } - /* In all other cases, we fail. */ - goto fail; - - - /* endline is the dual of begline. */ - case endline: - DEBUG_PRINT1("EXECUTING endline.\n"); - - if (AT_STRINGS_END(d)) { - if (!bufp->not_eol) - break; - } - /* We have to ``prefetch'' the next character. */ - else if ((d == end1 ? *string2 : *d) == '\n' - && bufp->newline_anchor) { - break; - } - goto fail; - - - /* Match at the very beginning of the data. */ - case begbuf: - DEBUG_PRINT1("EXECUTING begbuf.\n"); - if (AT_STRINGS_BEG(d)) - break; - goto fail; - - - /* Match at the very end of the data. */ - case endbuf: - DEBUG_PRINT1("EXECUTING endbuf.\n"); - if (AT_STRINGS_END(d)) - break; - goto fail; - - - /* on_failure_keep_string_jump is used to optimize `.*\n'. It - * pushes NULL as the value for the string on the stack. Then - * `pop_failure_point' will keep the current value for the - * string, instead of restoring it. To see why, consider - * matching `foo\nbar' against `.*\n'. The .* matches the foo; - * then the . fails against the \n. But the next thing we want - * to do is match the \n against the \n; if we restored the - * string value, we would be back at the foo. - * - * Because this is used only in specific cases, we don't need to - * check all the things that `on_failure_jump' does, to make - * sure the right things get saved on the stack. Hence we don't - * share its code. The only reason to push anything on the - * stack at all is that otherwise we would have to change - * `anychar's code to do something besides goto fail in this - * case; that seems worse than this. */ - case on_failure_keep_string_jump: - DEBUG_PRINT1("EXECUTING on_failure_keep_string_jump"); - - EXTRACT_NUMBER_AND_INCR(mcnt, p); - DEBUG_PRINT3(" %d (to 0x%x):\n", mcnt, p + mcnt); - - PUSH_FAILURE_POINT(p + mcnt, NULL, -2); - break; - - - /* Uses of on_failure_jump: - * - * Each alternative starts with an on_failure_jump that points - * to the beginning of the next alternative. Each alternative - * except the last ends with a jump that in effect jumps past - * the rest of the alternatives. (They really jump to the - * ending jump of the following alternative, because tensioning - * these jumps is a hassle.) - * - * Repeats start with an on_failure_jump that points past both - * the repetition text and either the following jump or - * pop_failure_jump back to this on_failure_jump. */ - case on_failure_jump: - on_failure: - DEBUG_PRINT1("EXECUTING on_failure_jump"); - - EXTRACT_NUMBER_AND_INCR(mcnt, p); - DEBUG_PRINT3(" %d (to 0x%x)", mcnt, p + mcnt); - - /* If this on_failure_jump comes right before a group (i.e., - * the original * applied to a group), save the information - * for that group and all inner ones, so that if we fail back - * to this point, the group's information will be correct. - * For example, in \(a*\)*\1, we need the preceding group, - * and in \(\(a*\)b*\)\2, we need the inner group. */ - - /* We can't use `p' to check ahead because we push - * a failure point to `p + mcnt' after we do this. */ - p1 = p; - - /* We need to skip no_op's before we look for the - * start_memory in case this on_failure_jump is happening as - * the result of a completed succeed_n, as in \(a\)\{1,3\}b\1 - * against aba. */ - while (p1 < pend && (re_opcode_t) * p1 == no_op) - p1++; - - if (p1 < pend && (re_opcode_t) * p1 == start_memory) { - /* We have a new highest active register now. This will - * get reset at the start_memory we are about to get to, - * but we will have saved all the registers relevant to - * this repetition op, as described above. */ - highest_active_reg = *(p1 + 1) + *(p1 + 2); - if (lowest_active_reg == NO_LOWEST_ACTIVE_REG) - lowest_active_reg = *(p1 + 1); - } - DEBUG_PRINT1(":\n"); - PUSH_FAILURE_POINT(p + mcnt, d, -2); - break; - - - /* A smart repeat ends with `maybe_pop_jump'. - * We change it to either `pop_failure_jump' or `jump'. */ - case maybe_pop_jump: - EXTRACT_NUMBER_AND_INCR(mcnt, p); - DEBUG_PRINT2("EXECUTING maybe_pop_jump %d.\n", mcnt); - { - register unsigned char *p2 = p; - - /* Compare the beginning of the repeat with what in the - * pattern follows its end. If we can establish that there - * is nothing that they would both match, i.e., that we - * would have to backtrack because of (as in, e.g., `a*a') - * then we can change to pop_failure_jump, because we'll - * never have to backtrack. - * - * This is not true in the case of alternatives: in - * `(a|ab)*' we do need to backtrack to the `ab' alternative - * (e.g., if the string was `ab'). But instead of trying to - * detect that here, the alternative has put on a dummy - * failure point which is what we will end up popping. */ - - /* Skip over open/close-group commands. */ - while (p2 + 2 < pend - && ((re_opcode_t) * p2 == stop_memory - || (re_opcode_t) * p2 == start_memory)) - p2 += 3; /* Skip over args, too. */ - - /* If we're at the end of the pattern, we can change. */ - if (p2 == pend) { - /* Consider what happens when matching ":\(.*\)" - * against ":/". I don't really understand this code - * yet. */ - p[-3] = (unsigned char) pop_failure_jump; - DEBUG_PRINT1 - (" End of pattern: change to `pop_failure_jump'.\n"); - } else if ((re_opcode_t) * p2 == exactn - || (bufp->newline_anchor && (re_opcode_t) * p2 == endline)) { - register unsigned char c - = *p2 == (unsigned char) endline ? '\n' : p2[2]; - p1 = p + mcnt; - - /* p1[0] ... p1[2] are the `on_failure_jump' corresponding - * to the `maybe_finalize_jump' of this case. Examine what - * follows. */ - if ((re_opcode_t) p1[3] == exactn && p1[5] != c) { - p[-3] = (unsigned char) pop_failure_jump; - DEBUG_PRINT3(" %c != %c => pop_failure_jump.\n", - c, p1[5]); - } else if ((re_opcode_t) p1[3] == charset - || (re_opcode_t) p1[3] == charset_not) { - int not = (re_opcode_t) p1[3] == charset_not; - - if (c < (unsigned char) (p1[4] * BYTEWIDTH) - && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH))) - not = !not; - - /* `not' is equal to 1 if c would match, which means - * that we can't change to pop_failure_jump. */ - if (!not) { - p[-3] = (unsigned char) pop_failure_jump; - DEBUG_PRINT1(" No match => pop_failure_jump.\n"); - } - } - } - } - p -= 2; /* Point at relative address again. */ - if ((re_opcode_t) p[-1] != pop_failure_jump) { - p[-1] = (unsigned char) jump; - DEBUG_PRINT1(" Match => jump.\n"); - goto unconditional_jump; - } - /* Note fall through. */ - - - /* The end of a simple repeat has a pop_failure_jump back to - * its matching on_failure_jump, where the latter will push a - * failure point. The pop_failure_jump takes off failure - * points put on by this pop_failure_jump's matching - * on_failure_jump; we got through the pattern to here from the - * matching on_failure_jump, so didn't fail. */ - case pop_failure_jump: - { - /* We need to pass separate storage for the lowest and - * highest registers, even though we don't care about the - * actual values. Otherwise, we will restore only one - * register from the stack, since lowest will == highest in - * `pop_failure_point'. */ - unsigned long dummy_low_reg, dummy_high_reg; - unsigned char *pdummy; - const char *sdummy; - - DEBUG_PRINT1("EXECUTING pop_failure_jump.\n"); - POP_FAILURE_POINT(sdummy, pdummy, - dummy_low_reg, dummy_high_reg, - reg_dummy, reg_dummy, reg_info_dummy); - } - /* Note fall through. */ - - - /* Unconditionally jump (without popping any failure points). */ - case jump: - unconditional_jump: - EXTRACT_NUMBER_AND_INCR(mcnt, p); /* Get the amount to jump. */ - DEBUG_PRINT2("EXECUTING jump %d ", mcnt); - p += mcnt; /* Do the jump. */ - DEBUG_PRINT2("(to 0x%x).\n", p); - break; - - - /* We need this opcode so we can detect where alternatives end - * in `group_match_null_string_p' et al. */ - case jump_past_alt: - DEBUG_PRINT1("EXECUTING jump_past_alt.\n"); - goto unconditional_jump; - - - /* Normally, the on_failure_jump pushes a failure point, which - * then gets popped at pop_failure_jump. We will end up at - * pop_failure_jump, also, and with a pattern of, say, `a+', we - * are skipping over the on_failure_jump, so we have to push - * something meaningless for pop_failure_jump to pop. */ - case dummy_failure_jump: - DEBUG_PRINT1("EXECUTING dummy_failure_jump.\n"); - /* It doesn't matter what we push for the string here. What - * the code at `fail' tests is the value for the pattern. */ - PUSH_FAILURE_POINT(0, 0, -2); - goto unconditional_jump; - - - /* At the end of an alternative, we need to push a dummy failure - * point in case we are followed by a `pop_failure_jump', because - * we don't want the failure point for the alternative to be - * popped. For example, matching `(a|ab)*' against `aab' - * requires that we match the `ab' alternative. */ - case push_dummy_failure: - DEBUG_PRINT1("EXECUTING push_dummy_failure.\n"); - /* See comments just above at `dummy_failure_jump' about the - * two zeroes. */ - PUSH_FAILURE_POINT(0, 0, -2); - break; - - /* Have to succeed matching what follows at least n times. - * After that, handle like `on_failure_jump'. */ - case succeed_n: - EXTRACT_NUMBER(mcnt, p + 2); - DEBUG_PRINT2("EXECUTING succeed_n %d.\n", mcnt); - - assert(mcnt >= 0); - /* Originally, this is how many times we HAVE to succeed. */ - if (mcnt > 0) { - mcnt--; - p += 2; - STORE_NUMBER_AND_INCR(p, mcnt); - DEBUG_PRINT3(" Setting 0x%x to %d.\n", p, mcnt); - } else if (mcnt == 0) { - DEBUG_PRINT2(" Setting two bytes from 0x%x to no_op.\n", p + 2); - p[2] = (unsigned char) no_op; - p[3] = (unsigned char) no_op; - goto on_failure; - } - break; - - case jump_n: - EXTRACT_NUMBER(mcnt, p + 2); - DEBUG_PRINT2("EXECUTING jump_n %d.\n", mcnt); - - /* Originally, this is how many times we CAN jump. */ - if (mcnt) { - mcnt--; - STORE_NUMBER(p + 2, mcnt); - goto unconditional_jump; - } - /* If don't have to jump any more, skip over the rest of command. */ - else - p += 4; - break; - - case set_number_at: - { - DEBUG_PRINT1("EXECUTING set_number_at.\n"); - - EXTRACT_NUMBER_AND_INCR(mcnt, p); - p1 = p + mcnt; - EXTRACT_NUMBER_AND_INCR(mcnt, p); - DEBUG_PRINT3(" Setting 0x%x to %d.\n", p1, mcnt); - STORE_NUMBER(p1, mcnt); - break; - } - - case wordbound: - DEBUG_PRINT1("EXECUTING wordbound.\n"); - if (AT_WORD_BOUNDARY(d)) - break; - goto fail; - - case notwordbound: - DEBUG_PRINT1("EXECUTING notwordbound.\n"); - if (AT_WORD_BOUNDARY(d)) - goto fail; - break; - - case wordbeg: - DEBUG_PRINT1("EXECUTING wordbeg.\n"); - if (WORDCHAR_P(d) && (AT_STRINGS_BEG(d) || !WORDCHAR_P(d - 1))) - break; - goto fail; - - case wordend: - DEBUG_PRINT1("EXECUTING wordend.\n"); - if (!AT_STRINGS_BEG(d) && WORDCHAR_P(d - 1) - && (!WORDCHAR_P(d) || AT_STRINGS_END(d))) - break; - goto fail; - - case wordchar: - DEBUG_PRINT1("EXECUTING non-Emacs wordchar.\n"); - PREFETCH(); - if (!WORDCHAR_P(d)) - goto fail; - SET_REGS_MATCHED(); - d++; - break; - - case notwordchar: - DEBUG_PRINT1("EXECUTING non-Emacs notwordchar.\n"); - PREFETCH(); - if (WORDCHAR_P(d)) - goto fail; - SET_REGS_MATCHED(); - d++; - break; - - default: - abort(); - } - continue; /* Successfully executed one pattern command; keep going. */ - - - /* We goto here if a matching operation fails. */ - fail: - if (!FAIL_STACK_EMPTY()) { /* A restart point is known. Restore to that state. */ - DEBUG_PRINT1("\nFAIL:\n"); - POP_FAILURE_POINT(d, p, - lowest_active_reg, highest_active_reg, - regstart, regend, reg_info); - - /* If this failure point is a dummy, try the next one. */ - if (!p) - goto fail; - - /* If we failed to the end of the pattern, don't examine *p. */ - assert(p <= pend); - if (p < pend) { - boolean is_a_jump_n = false; - - /* If failed to a backwards jump that's part of a repetition - * loop, need to pop this failure point and use the next one. */ - switch ((re_opcode_t) * p) { - case jump_n: - is_a_jump_n = true; - case maybe_pop_jump: - case pop_failure_jump: - case jump: - p1 = p + 1; - EXTRACT_NUMBER_AND_INCR(mcnt, p1); - p1 += mcnt; - - if ((is_a_jump_n && (re_opcode_t) * p1 == succeed_n) - || (!is_a_jump_n - && (re_opcode_t) * p1 == on_failure_jump)) - goto fail; - break; - default: - /* do nothing */ ; - } - } - if (d >= string1 && d <= end1) - dend = end_match_1; - } else - break; /* Matching at this starting point really fails. */ + unsigned char r = *p - 1; + while (r > 0 && !IS_ACTIVE(reg_info[r])) + r--; + + /* If we end up at register zero, that means that we saved + * the registers as the result of an `on_failure_jump', not + * a `start_memory', and we jumped to past the innermost + * `stop_memory'. For example, in ((.)*) we save + * registers 1 and 2 as a result of the *, but when we pop + * back to the second ), we are at the stop_memory 1. + * Thus, nothing is active. */ + if (r == 0) { + lowest_active_reg = NO_LOWEST_ACTIVE_REG; + highest_active_reg = NO_HIGHEST_ACTIVE_REG; + } else + highest_active_reg = r; + } + + /* If just failed to match something this time around with a + * group that's operated on by a repetition operator, try to + * force exit from the ``loop'', and restore the register + * information for this group that we had before trying this + * last match. */ + if ((!MATCHED_SOMETHING(reg_info[*p]) + || (re_opcode_t) p[-3] == start_memory) + && (p + 2) < pend) { + boolean is_a_jump_n = false; + + p1 = p + 2; + mcnt = 0; + switch ((re_opcode_t) * p1++) { + case jump_n: + is_a_jump_n = true; + case pop_failure_jump: + case maybe_pop_jump: + case jump: + case dummy_failure_jump: + EXTRACT_NUMBER_AND_INCR(mcnt, p1); + if (is_a_jump_n) + p1 += 2; + break; + + default: + /* do nothing */ + ; + } + p1 += mcnt; + + /* If the next operation is a jump backwards in the pattern + * to an on_failure_jump right before the start_memory + * corresponding to this stop_memory, exit from the loop + * by forcing a failure after pushing on the stack the + * on_failure_jump's jump in the pattern, and d. */ + if (mcnt < 0 && (re_opcode_t) * p1 == on_failure_jump + && (re_opcode_t) p1[3] == start_memory && p1[4] == *p) { + /* If this group ever matched anything, then restore + * what its registers were before trying this last + * failed match, e.g., with `(a*)*b' against `ab' for + * regstart[1], and, e.g., with `((a*)*(b*)*)*' + * against `aba' for regend[3]. + * + * Also restore the registers for inner groups for, + * e.g., `((a*)(b*))*' against `aba' (register 3 would + * otherwise get trashed). */ + + if (EVER_MATCHED_SOMETHING(reg_info[*p])) { + unsigned r; + + EVER_MATCHED_SOMETHING(reg_info[*p]) = 0; + + /* Restore this and inner groups' (if any) registers. */ + for (r = *p; r < *p + *(p + 1); r++) { + regstart[r] = old_regstart[r]; + + /* xx why this test? */ + if ((long) old_regend[r] >= (long) regstart[r]) + regend[r] = old_regend[r]; + } + } + p1++; + EXTRACT_NUMBER_AND_INCR(mcnt, p1); + PUSH_FAILURE_POINT(p1 + mcnt, d, -2); + + goto fail; + } + } + /* Move past the register number and the inner group count. */ + p += 2; + break; + + + /* \ has been turned into a `duplicate' command which is + * followed by the numeric value of as the register number. */ + case duplicate: { + register const char *d2, *dend2; + int regno = *p++; /* Get which register to match against. */ + DEBUG_PRINT2("EXECUTING duplicate %d.\n", regno); + + /* Can't back reference a group which we've never matched. */ + if (REG_UNSET(regstart[regno]) || REG_UNSET(regend[regno])) + goto fail; + + /* Where in input to try to start matching. */ + d2 = regstart[regno]; + + /* Where to stop matching; if both the place to start and + * the place to stop matching are in the same string, then + * set to the place to stop, otherwise, for now have to use + * the end of the first string. */ + + dend2 = ((FIRST_STRING_P(regstart[regno]) + == FIRST_STRING_P(regend[regno])) + ? regend[regno] : end_match_1); + for (;;) { + /* If necessary, advance to next segment in register + * contents. */ + while (d2 == dend2) { + if (dend2 == end_match_2) + break; + if (dend2 == regend[regno]) + break; + + /* End of string1 => advance to string2. */ + d2 = string2; + dend2 = regend[regno]; + } + /* At end of register contents => success */ + if (d2 == dend2) + break; + + /* If necessary, advance to next segment in data. */ + PREFETCH(); + + /* How many characters left in this segment to match. */ + mcnt = dend - d; + + /* Want how many consecutive characters we can match in + * one shot, so, if necessary, adjust the count. */ + if (mcnt > dend2 - d2) + mcnt = dend2 - d2; + + /* Compare that many; failure if mismatch, else move + * past them. */ + if (translate + ? bcmp_translate((unsigned char *)d, (unsigned char *)d2, mcnt, translate) + : memcmp(d, d2, mcnt)) + goto fail; + d += mcnt, d2 += mcnt; + } + } + break; + + + /* begline matches the empty string at the beginning of the string + * (unless `not_bol' is set in `bufp'), and, if + * `newline_anchor' is set, after newlines. */ + case begline: + DEBUG_PRINT1("EXECUTING begline.\n"); + + if (AT_STRINGS_BEG(d)) { + if (!bufp->not_bol) + break; + } else if (d[-1] == '\n' && bufp->newline_anchor) { + break; + } + /* In all other cases, we fail. */ + goto fail; + + + /* endline is the dual of begline. */ + case endline: + DEBUG_PRINT1("EXECUTING endline.\n"); + + if (AT_STRINGS_END(d)) { + if (!bufp->not_eol) + break; + } + /* We have to ``prefetch'' the next character. */ + else if ((d == end1 ? *string2 : *d) == '\n' + && bufp->newline_anchor) { + break; + } + goto fail; + + + /* Match at the very beginning of the data. */ + case begbuf: + DEBUG_PRINT1("EXECUTING begbuf.\n"); + if (AT_STRINGS_BEG(d)) + break; + goto fail; + + + /* Match at the very end of the data. */ + case endbuf: + DEBUG_PRINT1("EXECUTING endbuf.\n"); + if (AT_STRINGS_END(d)) + break; + goto fail; + + + /* on_failure_keep_string_jump is used to optimize `.*\n'. It + * pushes NULL as the value for the string on the stack. Then + * `pop_failure_point' will keep the current value for the + * string, instead of restoring it. To see why, consider + * matching `foo\nbar' against `.*\n'. The .* matches the foo; + * then the . fails against the \n. But the next thing we want + * to do is match the \n against the \n; if we restored the + * string value, we would be back at the foo. + * + * Because this is used only in specific cases, we don't need to + * check all the things that `on_failure_jump' does, to make + * sure the right things get saved on the stack. Hence we don't + * share its code. The only reason to push anything on the + * stack at all is that otherwise we would have to change + * `anychar's code to do something besides goto fail in this + * case; that seems worse than this. */ + case on_failure_keep_string_jump: + DEBUG_PRINT1("EXECUTING on_failure_keep_string_jump"); + + EXTRACT_NUMBER_AND_INCR(mcnt, p); + DEBUG_PRINT3(" %d (to 0x%x):\n", mcnt, p + mcnt); + + PUSH_FAILURE_POINT(p + mcnt, NULL, -2); + break; + + + /* Uses of on_failure_jump: + * + * Each alternative starts with an on_failure_jump that points + * to the beginning of the next alternative. Each alternative + * except the last ends with a jump that in effect jumps past + * the rest of the alternatives. (They really jump to the + * ending jump of the following alternative, because tensioning + * these jumps is a hassle.) + * + * Repeats start with an on_failure_jump that points past both + * the repetition text and either the following jump or + * pop_failure_jump back to this on_failure_jump. */ + case on_failure_jump: +on_failure: + DEBUG_PRINT1("EXECUTING on_failure_jump"); + + EXTRACT_NUMBER_AND_INCR(mcnt, p); + DEBUG_PRINT3(" %d (to 0x%x)", mcnt, p + mcnt); + + /* If this on_failure_jump comes right before a group (i.e., + * the original * applied to a group), save the information + * for that group and all inner ones, so that if we fail back + * to this point, the group's information will be correct. + * For example, in \(a*\)*\1, we need the preceding group, + * and in \(\(a*\)b*\)\2, we need the inner group. */ + + /* We can't use `p' to check ahead because we push + * a failure point to `p + mcnt' after we do this. */ + p1 = p; + + /* We need to skip no_op's before we look for the + * start_memory in case this on_failure_jump is happening as + * the result of a completed succeed_n, as in \(a\)\{1,3\}b\1 + * against aba. */ + while (p1 < pend && (re_opcode_t) * p1 == no_op) + p1++; + + if (p1 < pend && (re_opcode_t) * p1 == start_memory) { + /* We have a new highest active register now. This will + * get reset at the start_memory we are about to get to, + * but we will have saved all the registers relevant to + * this repetition op, as described above. */ + highest_active_reg = *(p1 + 1) + *(p1 + 2); + if (lowest_active_reg == NO_LOWEST_ACTIVE_REG) + lowest_active_reg = *(p1 + 1); + } + DEBUG_PRINT1(":\n"); + PUSH_FAILURE_POINT(p + mcnt, d, -2); + break; + + + /* A smart repeat ends with `maybe_pop_jump'. + * We change it to either `pop_failure_jump' or `jump'. */ + case maybe_pop_jump: + EXTRACT_NUMBER_AND_INCR(mcnt, p); + DEBUG_PRINT2("EXECUTING maybe_pop_jump %d.\n", mcnt); + { + register unsigned char *p2 = p; + + /* Compare the beginning of the repeat with what in the + * pattern follows its end. If we can establish that there + * is nothing that they would both match, i.e., that we + * would have to backtrack because of (as in, e.g., `a*a') + * then we can change to pop_failure_jump, because we'll + * never have to backtrack. + * + * This is not true in the case of alternatives: in + * `(a|ab)*' we do need to backtrack to the `ab' alternative + * (e.g., if the string was `ab'). But instead of trying to + * detect that here, the alternative has put on a dummy + * failure point which is what we will end up popping. */ + + /* Skip over open/close-group commands. */ + while (p2 + 2 < pend + && ((re_opcode_t) * p2 == stop_memory + || (re_opcode_t) * p2 == start_memory)) + p2 += 3; /* Skip over args, too. */ + + /* If we're at the end of the pattern, we can change. */ + if (p2 == pend) { + /* Consider what happens when matching ":\(.*\)" + * against ":/". I don't really understand this code + * yet. */ + p[-3] = (unsigned char) pop_failure_jump; + DEBUG_PRINT1 + (" End of pattern: change to `pop_failure_jump'.\n"); + } else if ((re_opcode_t) * p2 == exactn + || (bufp->newline_anchor && (re_opcode_t) * p2 == endline)) { + register unsigned char c + = *p2 == (unsigned char) endline ? '\n' : p2[2]; + p1 = p + mcnt; + + /* p1[0] ... p1[2] are the `on_failure_jump' corresponding + * to the `maybe_finalize_jump' of this case. Examine what + * follows. */ + if ((re_opcode_t) p1[3] == exactn && p1[5] != c) { + p[-3] = (unsigned char) pop_failure_jump; + DEBUG_PRINT3(" %c != %c => pop_failure_jump.\n", + c, p1[5]); + } else if ((re_opcode_t) p1[3] == charset + || (re_opcode_t) p1[3] == charset_not) { + int not = (re_opcode_t) p1[3] == charset_not; + + if (c < (unsigned char) (p1[4] * BYTEWIDTH) + && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH))) + not = !not; + + /* `not' is equal to 1 if c would match, which means + * that we can't change to pop_failure_jump. */ + if (!not) { + p[-3] = (unsigned char) pop_failure_jump; + DEBUG_PRINT1(" No match => pop_failure_jump.\n"); + } + } + } + } + p -= 2; /* Point at relative address again. */ + if ((re_opcode_t) p[-1] != pop_failure_jump) { + p[-1] = (unsigned char) jump; + DEBUG_PRINT1(" Match => jump.\n"); + goto unconditional_jump; + } + /* Note fall through. */ + + + /* The end of a simple repeat has a pop_failure_jump back to + * its matching on_failure_jump, where the latter will push a + * failure point. The pop_failure_jump takes off failure + * points put on by this pop_failure_jump's matching + * on_failure_jump; we got through the pattern to here from the + * matching on_failure_jump, so didn't fail. */ + case pop_failure_jump: { + /* We need to pass separate storage for the lowest and + * highest registers, even though we don't care about the + * actual values. Otherwise, we will restore only one + * register from the stack, since lowest will == highest in + * `pop_failure_point'. */ + unsigned long dummy_low_reg, dummy_high_reg; + unsigned char *pdummy; + const char *sdummy; + + DEBUG_PRINT1("EXECUTING pop_failure_jump.\n"); + POP_FAILURE_POINT(sdummy, pdummy, + dummy_low_reg, dummy_high_reg, + reg_dummy, reg_dummy, reg_info_dummy); + } + /* Note fall through. */ + + + /* Unconditionally jump (without popping any failure points). */ + case jump: +unconditional_jump: + EXTRACT_NUMBER_AND_INCR(mcnt, p); /* Get the amount to jump. */ + DEBUG_PRINT2("EXECUTING jump %d ", mcnt); + p += mcnt; /* Do the jump. */ + DEBUG_PRINT2("(to 0x%x).\n", p); + break; + + + /* We need this opcode so we can detect where alternatives end + * in `group_match_null_string_p' et al. */ + case jump_past_alt: + DEBUG_PRINT1("EXECUTING jump_past_alt.\n"); + goto unconditional_jump; + + + /* Normally, the on_failure_jump pushes a failure point, which + * then gets popped at pop_failure_jump. We will end up at + * pop_failure_jump, also, and with a pattern of, say, `a+', we + * are skipping over the on_failure_jump, so we have to push + * something meaningless for pop_failure_jump to pop. */ + case dummy_failure_jump: + DEBUG_PRINT1("EXECUTING dummy_failure_jump.\n"); + /* It doesn't matter what we push for the string here. What + * the code at `fail' tests is the value for the pattern. */ + PUSH_FAILURE_POINT(0, 0, -2); + goto unconditional_jump; + + + /* At the end of an alternative, we need to push a dummy failure + * point in case we are followed by a `pop_failure_jump', because + * we don't want the failure point for the alternative to be + * popped. For example, matching `(a|ab)*' against `aab' + * requires that we match the `ab' alternative. */ + case push_dummy_failure: + DEBUG_PRINT1("EXECUTING push_dummy_failure.\n"); + /* See comments just above at `dummy_failure_jump' about the + * two zeroes. */ + PUSH_FAILURE_POINT(0, 0, -2); + break; + + /* Have to succeed matching what follows at least n times. + * After that, handle like `on_failure_jump'. */ + case succeed_n: + EXTRACT_NUMBER(mcnt, p + 2); + DEBUG_PRINT2("EXECUTING succeed_n %d.\n", mcnt); + + assert(mcnt >= 0); + /* Originally, this is how many times we HAVE to succeed. */ + if (mcnt > 0) { + mcnt--; + p += 2; + STORE_NUMBER_AND_INCR(p, mcnt); + DEBUG_PRINT3(" Setting 0x%x to %d.\n", p, mcnt); + } else if (mcnt == 0) { + DEBUG_PRINT2(" Setting two bytes from 0x%x to no_op.\n", p + 2); + p[2] = (unsigned char) no_op; + p[3] = (unsigned char) no_op; + goto on_failure; + } + break; + + case jump_n: + EXTRACT_NUMBER(mcnt, p + 2); + DEBUG_PRINT2("EXECUTING jump_n %d.\n", mcnt); + + /* Originally, this is how many times we CAN jump. */ + if (mcnt) { + mcnt--; + STORE_NUMBER(p + 2, mcnt); + goto unconditional_jump; + } + /* If don't have to jump any more, skip over the rest of command. */ + else + p += 4; + break; + + case set_number_at: { + DEBUG_PRINT1("EXECUTING set_number_at.\n"); + + EXTRACT_NUMBER_AND_INCR(mcnt, p); + p1 = p + mcnt; + EXTRACT_NUMBER_AND_INCR(mcnt, p); + DEBUG_PRINT3(" Setting 0x%x to %d.\n", p1, mcnt); + STORE_NUMBER(p1, mcnt); + break; + } + + case wordbound: + DEBUG_PRINT1("EXECUTING wordbound.\n"); + if (AT_WORD_BOUNDARY(d)) + break; + goto fail; + + case notwordbound: + DEBUG_PRINT1("EXECUTING notwordbound.\n"); + if (AT_WORD_BOUNDARY(d)) + goto fail; + break; + + case wordbeg: + DEBUG_PRINT1("EXECUTING wordbeg.\n"); + if (WORDCHAR_P(d) && (AT_STRINGS_BEG(d) || !WORDCHAR_P(d - 1))) + break; + goto fail; + + case wordend: + DEBUG_PRINT1("EXECUTING wordend.\n"); + if (!AT_STRINGS_BEG(d) && WORDCHAR_P(d - 1) + && (!WORDCHAR_P(d) || AT_STRINGS_END(d))) + break; + goto fail; + + case wordchar: + DEBUG_PRINT1("EXECUTING non-Emacs wordchar.\n"); + PREFETCH(); + if (!WORDCHAR_P(d)) + goto fail; + SET_REGS_MATCHED(); + d++; + break; + + case notwordchar: + DEBUG_PRINT1("EXECUTING non-Emacs notwordchar.\n"); + PREFETCH(); + if (WORDCHAR_P(d)) + goto fail; + SET_REGS_MATCHED(); + d++; + break; + + default: + abort(); + } + continue; /* Successfully executed one pattern command; keep going. */ + + + /* We goto here if a matching operation fails. */ +fail: + if (!FAIL_STACK_EMPTY()) { /* A restart point is known. Restore to that state. */ + DEBUG_PRINT1("\nFAIL:\n"); + POP_FAILURE_POINT(d, p, + lowest_active_reg, highest_active_reg, + regstart, regend, reg_info); + + /* If this failure point is a dummy, try the next one. */ + if (!p) + goto fail; + + /* If we failed to the end of the pattern, don't examine *p. */ + assert(p <= pend); + if (p < pend) { + boolean is_a_jump_n = false; + + /* If failed to a backwards jump that's part of a repetition + * loop, need to pop this failure point and use the next one. */ + switch ((re_opcode_t) * p) { + case jump_n: + is_a_jump_n = true; + case maybe_pop_jump: + case pop_failure_jump: + case jump: + p1 = p + 1; + EXTRACT_NUMBER_AND_INCR(mcnt, p1); + p1 += mcnt; + + if ((is_a_jump_n && (re_opcode_t) * p1 == succeed_n) + || (!is_a_jump_n + && (re_opcode_t) * p1 == on_failure_jump)) + goto fail; + break; + default: + /* do nothing */ + ; + } + } + if (d >= string1 && d <= end1) + dend = end_match_1; + } else + break; /* Matching at this starting point really fails. */ } /* for (;;) */ if (best_regs_set) - goto restore_best_regs; + goto restore_best_regs; FREE_VARIABLES(); @@ -3953,13 +3942,13 @@ re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) /* Subroutine definitions for re_match_2. */ /* We are passed P pointing to a register number after a start_memory. - * + * * Return true if the pattern up to the corresponding stop_memory can * match the empty string, and false otherwise. - * + * * If we find the matching stop_memory, sets P to point to one past its number. * Otherwise, sets P to an undefined byte less than or equal to END. - * + * * We don't handle duplicates properly (yet). */ boolean @@ -3970,90 +3959,90 @@ group_match_null_string_p(unsigned char **p, unsigned char *end, register_info_t unsigned char *p1 = *p + 2; while (p1 < end) { - /* Skip over opcodes that can match nothing, and return true or - * false, as appropriate, when we get to one that can't, or to the - * matching stop_memory. */ - - switch ((re_opcode_t) * p1) { - /* Could be either a loop or a series of alternatives. */ - case on_failure_jump: - p1++; - EXTRACT_NUMBER_AND_INCR(mcnt, p1); - - /* If the next operation is not a jump backwards in the - * pattern. */ - - if (mcnt >= 0) { - /* Go through the on_failure_jumps of the alternatives, - * seeing if any of the alternatives cannot match nothing. - * The last alternative starts with only a jump, - * whereas the rest start with on_failure_jump and end - * with a jump, e.g., here is the pattern for `a|b|c': - * - * /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6 - * /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3 - * /exactn/1/c - * - * So, we have to first go through the first (n-1) - * alternatives and then deal with the last one separately. */ - - - /* Deal with the first (n-1) alternatives, which start - * with an on_failure_jump (see above) that jumps to right - * past a jump_past_alt. */ - - while ((re_opcode_t) p1[mcnt - 3] == jump_past_alt) { - /* `mcnt' holds how many bytes long the alternative - * is, including the ending `jump_past_alt' and - * its number. */ - - if (!alt_match_null_string_p(p1, p1 + mcnt - 3, - reg_info)) - return false; - - /* Move to right after this alternative, including the - * jump_past_alt. */ - p1 += mcnt; - - /* Break if it's the beginning of an n-th alternative - * that doesn't begin with an on_failure_jump. */ - if ((re_opcode_t) * p1 != on_failure_jump) - break; - - /* Still have to check that it's not an n-th - * alternative that starts with an on_failure_jump. */ - p1++; - EXTRACT_NUMBER_AND_INCR(mcnt, p1); - if ((re_opcode_t) p1[mcnt - 3] != jump_past_alt) { - /* Get to the beginning of the n-th alternative. */ - p1 -= 3; - break; - } - } - - /* Deal with the last alternative: go back and get number - * of the `jump_past_alt' just before it. `mcnt' contains - * the length of the alternative. */ - EXTRACT_NUMBER(mcnt, p1 - 2); - - if (!alt_match_null_string_p(p1, p1 + mcnt, reg_info)) - return false; - - p1 += mcnt; /* Get past the n-th alternative. */ - } /* if mcnt > 0 */ - break; - - - case stop_memory: - assert(p1[1] == **p); - *p = p1 + 2; - return true; - - - default: - if (!common_op_match_null_string_p(&p1, end, reg_info)) - return false; - } + /* Skip over opcodes that can match nothing, and return true or + * false, as appropriate, when we get to one that can't, or to the + * matching stop_memory. */ + + switch ((re_opcode_t) * p1) { + /* Could be either a loop or a series of alternatives. */ + case on_failure_jump: + p1++; + EXTRACT_NUMBER_AND_INCR(mcnt, p1); + + /* If the next operation is not a jump backwards in the + * pattern. */ + + if (mcnt >= 0) { + /* Go through the on_failure_jumps of the alternatives, + * seeing if any of the alternatives cannot match nothing. + * The last alternative starts with only a jump, + * whereas the rest start with on_failure_jump and end + * with a jump, e.g., here is the pattern for `a|b|c': + * + * /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6 + * /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3 + * /exactn/1/c + * + * So, we have to first go through the first (n-1) + * alternatives and then deal with the last one separately. */ + + + /* Deal with the first (n-1) alternatives, which start + * with an on_failure_jump (see above) that jumps to right + * past a jump_past_alt. */ + + while ((re_opcode_t) p1[mcnt - 3] == jump_past_alt) { + /* `mcnt' holds how many bytes long the alternative + * is, including the ending `jump_past_alt' and + * its number. */ + + if (!alt_match_null_string_p(p1, p1 + mcnt - 3, + reg_info)) + return false; + + /* Move to right after this alternative, including the + * jump_past_alt. */ + p1 += mcnt; + + /* Break if it's the beginning of an n-th alternative + * that doesn't begin with an on_failure_jump. */ + if ((re_opcode_t) * p1 != on_failure_jump) + break; + + /* Still have to check that it's not an n-th + * alternative that starts with an on_failure_jump. */ + p1++; + EXTRACT_NUMBER_AND_INCR(mcnt, p1); + if ((re_opcode_t) p1[mcnt - 3] != jump_past_alt) { + /* Get to the beginning of the n-th alternative. */ + p1 -= 3; + break; + } + } + + /* Deal with the last alternative: go back and get number + * of the `jump_past_alt' just before it. `mcnt' contains + * the length of the alternative. */ + EXTRACT_NUMBER(mcnt, p1 - 2); + + if (!alt_match_null_string_p(p1, p1 + mcnt, reg_info)) + return false; + + p1 += mcnt; /* Get past the n-th alternative. */ + } /* if mcnt > 0 */ + break; + + + case stop_memory: + assert(p1[1] == **p); + *p = p1 + 2; + return true; + + + default: + if (!common_op_match_null_string_p(&p1, end, reg_info)) + return false; + } } /* while p1 < end */ return false; @@ -4071,21 +4060,21 @@ alt_match_null_string_p(unsigned char *p, unsigned char *end, register_info_type unsigned char *p1 = p; while (p1 < end) { - /* Skip over opcodes that can match nothing, and break when we get - * to one that can't. */ - - switch ((re_opcode_t) * p1) { - /* It's a loop. */ - case on_failure_jump: - p1++; - EXTRACT_NUMBER_AND_INCR(mcnt, p1); - p1 += mcnt; - break; - - default: - if (!common_op_match_null_string_p(&p1, end, reg_info)) - return false; - } + /* Skip over opcodes that can match nothing, and break when we get + * to one that can't. */ + + switch ((re_opcode_t) * p1) { + /* It's a loop. */ + case on_failure_jump: + p1++; + EXTRACT_NUMBER_AND_INCR(mcnt, p1); + p1 += mcnt; + break; + + default: + if (!common_op_match_null_string_p(&p1, end, reg_info)) + return false; + } } /* while p1 < end */ return true; @@ -4093,8 +4082,8 @@ alt_match_null_string_p(unsigned char *p, unsigned char *end, register_info_type /* Deals with the ops common to group_match_null_string_p and - * alt_match_null_string_p. - * + * alt_match_null_string_p. + * * Sets P to one after the op and its arguments, if any. */ boolean @@ -4115,56 +4104,56 @@ common_op_match_null_string_p( unsigned char **p, unsigned char *end, register_i case wordend: case wordbound: case notwordbound: - break; + break; case start_memory: - reg_no = *p1; - assert(reg_no > 0 && reg_no <= MAX_REGNUM); - ret = group_match_null_string_p(&p1, end, reg_info); + reg_no = *p1; + assert(reg_no > 0 && reg_no <= MAX_REGNUM); + ret = group_match_null_string_p(&p1, end, reg_info); - /* Have to set this here in case we're checking a group which - * contains a group and a back reference to it. */ + /* Have to set this here in case we're checking a group which + * contains a group and a back reference to it. */ - if (REG_MATCH_NULL_STRING_P(reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE) - REG_MATCH_NULL_STRING_P(reg_info[reg_no]) = ret; + if (REG_MATCH_NULL_STRING_P(reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE) + REG_MATCH_NULL_STRING_P(reg_info[reg_no]) = ret; - if (!ret) - return false; - break; + if (!ret) + return false; + break; - /* If this is an optimized succeed_n for zero times, make the jump. */ + /* If this is an optimized succeed_n for zero times, make the jump. */ case jump: - EXTRACT_NUMBER_AND_INCR(mcnt, p1); - if (mcnt >= 0) - p1 += mcnt; - else - return false; - break; + EXTRACT_NUMBER_AND_INCR(mcnt, p1); + if (mcnt >= 0) + p1 += mcnt; + else + return false; + break; case succeed_n: - /* Get to the number of times to succeed. */ - p1 += 2; - EXTRACT_NUMBER_AND_INCR(mcnt, p1); - - if (mcnt == 0) { - p1 -= 4; - EXTRACT_NUMBER_AND_INCR(mcnt, p1); - p1 += mcnt; - } else - return false; - break; + /* Get to the number of times to succeed. */ + p1 += 2; + EXTRACT_NUMBER_AND_INCR(mcnt, p1); + + if (mcnt == 0) { + p1 -= 4; + EXTRACT_NUMBER_AND_INCR(mcnt, p1); + p1 += mcnt; + } else + return false; + break; case duplicate: - if (!REG_MATCH_NULL_STRING_P(reg_info[*p1])) - return false; - break; + if (!REG_MATCH_NULL_STRING_P(reg_info[*p1])) + return false; + break; case set_number_at: - p1 += 4; + p1 += 4; default: - /* All other opcodes mean we cannot match the empty string. */ - return false; + /* All other opcodes mean we cannot match the empty string. */ + return false; } *p = p1; @@ -4180,9 +4169,9 @@ bcmp_translate(unsigned char const *s1, unsigned char const*s2, register int len { register unsigned char const *p1 = s1, *p2 = s2; while (len) { - if (translate[*p1++] != translate[*p2++]) - return 1; - len--; + if (translate[*p1++] != translate[*p2++]) + return 1; + len--; } return 0; } @@ -4193,10 +4182,10 @@ bcmp_translate(unsigned char const *s1, unsigned char const*s2, register int len /* POSIX.2 functions */ /* regcomp takes a regular expression as a string and compiles it. - * + * * PREG is a regex_t *. We do not expect any fields to be initialized, * since POSIX says we shouldn't. Thus, we set - * + * * `buffer' to the compiled pattern; * `used' to the length of the compiled pattern; * `syntax' to RE_SYNTAX_POSIX_EXTENDED if the @@ -4205,37 +4194,37 @@ bcmp_translate(unsigned char const *s1, unsigned char const*s2, register int len * `newline_anchor' to REG_NEWLINE being set in CFLAGS; * `fastmap' and `fastmap_accurate' to zero; * `re_nsub' to the number of subexpressions in PATTERN. - * + * * PATTERN is the address of the pattern string. - * + * * CFLAGS is a series of bits which affect compilation. - * + * * If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we * use POSIX basic syntax. - * + * * If REG_NEWLINE is set, then . and [^...] don't match newline. * Also, regexec will try a match beginning after every newline. - * + * * If REG_ICASE is set, then we considers upper- and lowercase * versions of letters to be equivalent when matching. - * + * * If REG_NOSUB is set, then when PREG is passed to regexec, that * routine will report only success or failure, and nothing about the * registers. - * + * * It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for * the return codes and their meanings.) */ int regcomp(preg, pattern, cflags) - regex_t *preg; - const char *pattern; - int cflags; +regex_t *preg; +const char *pattern; +int cflags; { reg_errcode_t ret; unsigned syntax = (cflags & REG_EXTENDED) ? - RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC; + RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC; /* regex_compile will allocate the space for the compiled pattern. */ preg->buffer = 0; @@ -4248,37 +4237,37 @@ regcomp(preg, pattern, cflags) preg->fastmap = 0; if (cflags & REG_ICASE) { - unsigned i; + unsigned i; - preg->translate = (char *) malloc(CHAR_SET_SIZE); - if (preg->translate == NULL) - return (int) REG_ESPACE; + preg->translate = (char *) malloc(CHAR_SET_SIZE); + if (preg->translate == NULL) + return (int) REG_ESPACE; - /* Map uppercase characters to corresponding lowercase ones. */ - for (i = 0; i < CHAR_SET_SIZE; i++) - preg->translate[i] = ISUPPER(i) ? tolower(i) : i; + /* Map uppercase characters to corresponding lowercase ones. */ + for (i = 0; i < CHAR_SET_SIZE; i++) + preg->translate[i] = ISUPPER(i) ? tolower(i) : i; } else - preg->translate = NULL; + preg->translate = NULL; /* If REG_NEWLINE is set, newlines are treated differently. */ if (cflags & REG_NEWLINE) { /* REG_NEWLINE implies neither . nor [^...] match newline. */ - syntax &= ~RE_DOT_NEWLINE; - syntax |= RE_HAT_LISTS_NOT_NEWLINE; - /* It also changes the matching behavior. */ - preg->newline_anchor = 1; + syntax &= ~RE_DOT_NEWLINE; + syntax |= RE_HAT_LISTS_NOT_NEWLINE; + /* It also changes the matching behavior. */ + preg->newline_anchor = 1; } else - preg->newline_anchor = 0; + preg->newline_anchor = 0; preg->no_sub = !!(cflags & REG_NOSUB); - /* POSIX says a null character in the pattern terminates it, so we + /* POSIX says a null character in the pattern terminates it, so we * can use strlen here in compiling the pattern. */ ret = regex_compile(pattern, strlen(pattern), syntax, preg); /* POSIX doesn't distinguish between an unmatched open-group and an * unmatched close-group: both are REG_EPAREN. */ if (ret == REG_ERPAREN) - ret = REG_EPAREN; + ret = REG_EPAREN; return (int) ret; } @@ -4286,25 +4275,25 @@ regcomp(preg, pattern, cflags) /* regexec searches for a given pattern, specified by PREG, in the * string STRING. - * + * * If NMATCH is zero or REG_NOSUB was set in the cflags argument to * `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at * least NMATCH elements, and we set them to the offsets of the * corresponding matched substrings. - * + * * EFLAGS specifies `execution flags' which affect matching: if * REG_NOTBOL is set, then ^ does not match at the beginning of the * string; if REG_NOTEOL is set, then $ does not match at the end. - * + * * We return 0 if we find a match and REG_NOMATCH if not. */ int regexec(preg, string, nmatch, pmatch, eflags) - const regex_t *preg; - const char *string; - size_t nmatch; - regmatch_t pmatch[]; - int eflags; +const regex_t *preg; +const char *string; +size_t nmatch; +regmatch_t pmatch[]; +int eflags; { int ret; struct re_registers regs; @@ -4323,30 +4312,30 @@ regexec(preg, string, nmatch, pmatch, eflags) private_preg.regs_allocated = REGS_FIXED; if (want_reg_info) { - regs.num_regs = nmatch; - regs.start = TALLOC(nmatch, regoff_t); - regs.end = TALLOC(nmatch, regoff_t); - if (regs.start == NULL || regs.end == NULL) - return (int) REG_NOMATCH; + regs.num_regs = nmatch; + regs.start = TALLOC(nmatch, regoff_t); + regs.end = TALLOC(nmatch, regoff_t); + if (regs.start == NULL || regs.end == NULL) + return (int) REG_NOMATCH; } /* Perform the searching operation. */ ret = re_search(&private_preg, string, len, - /* start: */ 0, /* range: */ len, - want_reg_info ? ®s : (struct re_registers *) 0); + /* start: */ 0, /* range: */ len, + want_reg_info ? ®s : (struct re_registers *) 0); /* Copy the register information to the POSIX structure. */ if (want_reg_info) { - if (ret >= 0) { - unsigned r; - - for (r = 0; r < nmatch; r++) { - pmatch[r].rm_so = regs.start[r]; - pmatch[r].rm_eo = regs.end[r]; - } - } - /* If we needed the temporary register info, free the space now. */ - free(regs.start); - free(regs.end); + if (ret >= 0) { + unsigned r; + + for (r = 0; r < nmatch; r++) { + pmatch[r].rm_so = regs.start[r]; + pmatch[r].rm_eo = regs.end[r]; + } + } + /* If we needed the temporary register info, free the space now. */ + free(regs.start); + free(regs.end); } /* We want zero return to mean success, unlike `re_search'. */ return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH; @@ -4363,28 +4352,28 @@ regerror(int errcode, const regex_t *preg, char *errbuf, size_t errbuf_size) size_t msg_size; if (errcode < 0 - || errcode >= (sizeof(re_error_msg) / sizeof(re_error_msg[0]))) - /* Only error codes returned by the rest of the code should be passed - * to this routine. If we are given anything else, or if other regex - * code generates an invalid error code, then the program has a bug. - * Dump core so we can fix it. */ - abort(); + || errcode >= (sizeof(re_error_msg) / sizeof(re_error_msg[0]))) + /* Only error codes returned by the rest of the code should be passed + * to this routine. If we are given anything else, or if other regex + * code generates an invalid error code, then the program has a bug. + * Dump core so we can fix it. */ + abort(); msg = re_error_msg[errcode]; /* POSIX doesn't require that we do anything in this case, but why * not be nice. */ if (!msg) - msg = "Success"; + msg = "Success"; msg_size = strlen(msg) + 1; /* Includes the null. */ if (errbuf_size != 0) { - if (msg_size > errbuf_size) { - strncpy(errbuf, msg, errbuf_size - 1); - errbuf[errbuf_size - 1] = 0; - } else - strcpy(errbuf, msg); + if (msg_size > errbuf_size) { + strncpy(errbuf, msg, errbuf_size - 1); + errbuf[errbuf_size - 1] = 0; + } else + strcpy(errbuf, msg); } return msg_size; } @@ -4394,22 +4383,22 @@ regerror(int errcode, const regex_t *preg, char *errbuf, size_t errbuf_size) void regfree(preg) - regex_t *preg; +regex_t *preg; { if (preg->buffer != NULL) - free(preg->buffer); + free(preg->buffer); preg->buffer = NULL; preg->allocated = 0; preg->used = 0; if (preg->fastmap != NULL) - free(preg->fastmap); + free(preg->fastmap); preg->fastmap = NULL; preg->fastmap_accurate = 0; if (preg->translate != NULL) - free(preg->translate); + free(preg->translate); preg->translate = NULL; } diff --git a/lib/IPAddress.cc b/lib/IPAddress.cc index 08b94eb080..b16d59d019 100644 --- a/lib/IPAddress.cc +++ b/lib/IPAddress.cc @@ -24,12 +24,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -137,7 +137,7 @@ IPAddress::GetCIDR() const /* return IPv4 CIDR for any Mapped address */ /* Thus only check the mapped bit */ - if( !IsIPv6() ) { + if ( !IsIPv6() ) { shift = 12; } @@ -175,7 +175,7 @@ const int IPAddress::ApplyMask(IPAddress const &mask_addr) unsigned int changes = 0; for (unsigned int i = 0; i < blen; i++) { - if((p1[i] & p2[i]) != p1[i]) + if ((p1[i] & p2[i]) != p1[i]) changes++; p1[i] &= p2[i]; @@ -195,11 +195,11 @@ bool IPAddress::ApplyMask(const unsigned int cidr, int mtype) #if !USE_IPV6 IASSERT("mtype != AF_INET6", mtype != AF_INET6); /* using IPv6 in IPv4 is invalid. */ - if(mtype == AF_UNSPEC) + if (mtype == AF_UNSPEC) mtype = AF_INET; #else - if(mtype == AF_UNSPEC) + if (mtype == AF_UNSPEC) mtype = AF_INET6; #endif @@ -214,7 +214,7 @@ bool IPAddress::ApplyMask(const unsigned int cidr, int mtype) clearbits = (uint8_t)( (mtype==AF_INET6?128:32) -cidr); // short-cut - if(clearbits == 0) + if (clearbits == 0) return true; #if USE_IPV6 @@ -228,7 +228,7 @@ bool IPAddress::ApplyMask(const unsigned int cidr, int mtype) #endif for (; clearbits>0 && p >= (uint8_t*)&m_SocketAddr.sin6_addr ; p-- ) { - if(clearbits < 8) { + if (clearbits < 8) { *p &= ((0xFF << clearbits) & 0xFF); clearbits = 0; } else { @@ -274,7 +274,7 @@ bool IPAddress::IsIPv6() const !( m_SocketAddr.sin6_addr.s6_addr32[0] == htonl(0x00000000) && m_SocketAddr.sin6_addr.s6_addr32[1] == htonl(0x00000000) && m_SocketAddr.sin6_addr.s6_addr32[2] == htonl(0x0000FFFF) - ); + ); #else return false; // enforce IPv4 in IPv4-only mode. #endif @@ -315,19 +315,19 @@ bool IPAddress::SetIPv4() #if USE_IPV6 #if !IPV6_SPECIAL_LOCALHOST - if( IsLocalhost() ) { + if ( IsLocalhost() ) { m_SocketAddr.sin6_addr.s6_addr32[2] = htonl(0xffff); m_SocketAddr.sin6_addr.s6_addr32[3] = htonl(0x7F000001); return true; } #endif - if( IsAnyAddr() ) { + if ( IsAnyAddr() ) { m_SocketAddr.sin6_addr.s6_addr32[2] = htonl(0xffff); return true; } - if( IsIPv4()) + if ( IsIPv4()) return true; // anything non-IPv4 and non-convertable is BAD. @@ -341,19 +341,19 @@ bool IPAddress::IsLocalhost() const { #if USE_IPV6 return ( m_SocketAddr.sin6_addr.s6_addr32[0] == 0 - && m_SocketAddr.sin6_addr.s6_addr32[1] == 0 - && m_SocketAddr.sin6_addr.s6_addr32[2] == 0 - && m_SocketAddr.sin6_addr.s6_addr32[3] == htonl(0x1) + && m_SocketAddr.sin6_addr.s6_addr32[1] == 0 + && m_SocketAddr.sin6_addr.s6_addr32[2] == 0 + && m_SocketAddr.sin6_addr.s6_addr32[3] == htonl(0x1) ) #if !IPV6_SPECIAL_LOCALHOST - || + || ( m_SocketAddr.sin6_addr.s6_addr32[0] == 0 - && m_SocketAddr.sin6_addr.s6_addr32[1] == 0 - && m_SocketAddr.sin6_addr.s6_addr32[2] == htonl(0xffff) - && m_SocketAddr.sin6_addr.s6_addr32[3] == htonl(0x7F000001) + && m_SocketAddr.sin6_addr.s6_addr32[1] == 0 + && m_SocketAddr.sin6_addr.s6_addr32[2] == htonl(0xffff) + && m_SocketAddr.sin6_addr.s6_addr32[3] == htonl(0x7F000001) ) #endif - ; + ; #else return (htonl(0x7F000001) == m_SocketAddr.sin_addr.s_addr); @@ -416,8 +416,7 @@ bool IPAddress::GetReverseString6(char buf[MAX_IPSTRLEN], const struct in6_addr /* Compile Err: 'Too many arguments for format. */ - for(int i = 15; i >= 0; i--, p+=4) - { + for (int i = 15; i >= 0; i--, p+=4) { snprintf(p, 5, "%x.%x.", ((r[i])&0xf), (((r[i])>>4)&0xf) ); } @@ -444,7 +443,7 @@ bool IPAddress::GetReverseString4(char buf[MAX_IPSTRLEN], const struct in_addr & bool IPAddress::GetReverseString(char buf[MAX_IPSTRLEN], int show_type) const { - if(show_type == AF_UNSPEC) { + if (show_type == AF_UNSPEC) { #if USE_IPV6 show_type = IsIPv6() ? AF_INET6 : AF_INET ; #else @@ -503,7 +502,7 @@ bool IPAddress::LookupHostIP(const char *s, bool nodns) struct addrinfo want; memset(&want, 0, sizeof(struct addrinfo)); - if(nodns) { + if (nodns) { want.ai_flags = AI_NUMERICHOST; // prevent actual DNS lookups! } #if !USE_IPV6 @@ -513,7 +512,7 @@ bool IPAddress::LookupHostIP(const char *s, bool nodns) if ( (err = xgetaddrinfo(s, NULL, &want, &res)) != 0) { debugs(14,1, HERE << "Given Bad IP '" << s << "': " << xgai_strerror(err) ); /* free the memory xgetaddrinfo() dynamically allocated. */ - if(res) { + if (res) { xfreeaddrinfo(res); res = NULL; } @@ -563,10 +562,9 @@ IPAddress& IPAddress::operator =(const struct sockaddr_storage &s) { #if USE_IPV6 /* some AF_* magic to tell socket types apart and what we need to do */ - if(s.ss_family == AF_INET6) { + if (s.ss_family == AF_INET6) { memcpy(&m_SocketAddr, &s, sizeof(struct sockaddr_in)); - } - else { // convert it to our storage mapping. + } else { // convert it to our storage mapping. struct sockaddr_in *sin = (struct sockaddr_in*)&s; m_SocketAddr.sin6_port = sin->sin_port; Map4to6( sin->sin_addr, m_SocketAddr.sin6_addr); @@ -579,7 +577,7 @@ IPAddress& IPAddress::operator =(const struct sockaddr_storage &s) void IPAddress::check4Mapped() { - // obsolete. + // obsolete. // TODO use this NOW to set the sin6_family properly on exporting. not on import. } @@ -662,9 +660,9 @@ IPAddress::IPAddress(IPAddress *s) IPAddress& IPAddress::operator =(IPAddress *s) { IPAddress *tmp = NULL; - if(!s) return *this; + if (!s) return *this; tmp = dynamic_cast(s); - if(!tmp) return *this; + if (!tmp) return *this; return operator=(*tmp); } @@ -689,8 +687,7 @@ bool IPAddress::operator =(const struct hostent &s) // char **h_addr_list; /* list of addresses */ //} - switch(s.h_addrtype) - { + switch (s.h_addrtype) { case AF_INET: ipv4 = (in_addr*)(s.h_addr_list[0]); @@ -714,8 +711,8 @@ bool IPAddress::operator =(const struct hostent &s) break; default: - IASSERT("false",false); - return false; + IASSERT("false",false); + return false; } return true; @@ -745,8 +742,7 @@ bool IPAddress::operator =(const struct addrinfo &s) // struct addrinfo *ai_next; /* pointer to next in list */ //} - switch(s.ai_family) - { + switch (s.ai_family) { case AF_INET: ipv4 = (sockaddr_in*)(s.ai_addr); @@ -779,18 +775,17 @@ bool IPAddress::operator =(const struct addrinfo &s) default: // attempt to handle partially initialised addrinfo. // such as those where data only comes from getsockopt() - if(s.ai_addr != NULL) { + if (s.ai_addr != NULL) { #if USE_IPV6 - if(s.ai_addrlen == sizeof(struct sockaddr_in6)) { + if (s.ai_addrlen == sizeof(struct sockaddr_in6)) { operator=(*((struct sockaddr_in6*)s.ai_addr)); return true; - } - else + } else #endif - if(s.ai_addrlen == sizeof(struct sockaddr_in)) { - operator=(*((struct sockaddr_in*)s.ai_addr)); - return true; - } + if (s.ai_addrlen == sizeof(struct sockaddr_in)) { + operator=(*((struct sockaddr_in*)s.ai_addr)); + return true; + } } return false; } @@ -800,8 +795,7 @@ bool IPAddress::operator =(const struct addrinfo &s) void IPAddress::GetAddrInfo(struct addrinfo *&dst, int force) const { - if(dst == NULL) - { + if (dst == NULL) { dst = new addrinfo; } @@ -810,20 +804,19 @@ void IPAddress::GetAddrInfo(struct addrinfo *&dst, int force) const // set defaults dst->ai_flags = AI_NUMERICHOST; - if(dst->ai_socktype == 0) + if (dst->ai_socktype == 0) dst->ai_socktype = SOCK_STREAM; - if(dst->ai_socktype == SOCK_STREAM // implies TCP + if (dst->ai_socktype == SOCK_STREAM // implies TCP && dst->ai_protocol == 0) dst->ai_protocol = IPPROTO_TCP; - if(dst->ai_socktype == SOCK_DGRAM // implies UDP + if (dst->ai_socktype == SOCK_DGRAM // implies UDP && dst->ai_protocol == 0) dst->ai_protocol = IPPROTO_UDP; #if USE_IPV6 - if( force == AF_INET6 || (force == AF_UNSPEC && IsIPv6()) ) - { + if ( force == AF_INET6 || (force == AF_UNSPEC && IsIPv6()) ) { dst->ai_addr = (struct sockaddr*)new sockaddr_in6; memset(dst->ai_addr,0,sizeof(struct sockaddr_in6)); @@ -850,8 +843,7 @@ void IPAddress::GetAddrInfo(struct addrinfo *&dst, int force) const } else #endif - if( force == AF_INET || (force == AF_UNSPEC && IsIPv4()) ) - { + if ( force == AF_INET || (force == AF_UNSPEC && IsIPv4()) ) { dst->ai_addr = (struct sockaddr*)new sockaddr_in; @@ -862,21 +854,20 @@ void IPAddress::GetAddrInfo(struct addrinfo *&dst, int force) const dst->ai_addrlen = sizeof(struct sockaddr_in); dst->ai_family = ((struct sockaddr_in*)dst->ai_addr)->sin_family; - } else - { + } else { IASSERT("false",false); } } void IPAddress::InitAddrInfo(struct addrinfo *&ai) const { - if(ai == NULL) { + if (ai == NULL) { ai = new addrinfo; memset(ai,0,sizeof(struct addrinfo)); } // remove any existing data. - if(ai->ai_addr) delete ai->ai_addr; + if (ai->ai_addr) delete ai->ai_addr; ai->ai_addr = (struct sockaddr*)new sockaddr_in6; memset(ai->ai_addr, 0, sizeof(struct sockaddr_in6)); @@ -887,9 +878,9 @@ void IPAddress::InitAddrInfo(struct addrinfo *&ai) const void IPAddress::FreeAddrInfo(struct addrinfo *&ai) const { - if(ai == NULL) return; + if (ai == NULL) return; - if(ai->ai_addr) delete ai->ai_addr; + if (ai->ai_addr) delete ai->ai_addr; ai->ai_addr = NULL; @@ -914,12 +905,12 @@ int IPAddress::matchIPAddr(const IPAddress &rhs) const // loop a byte-wise compare // NP: match MUST be R-to-L : L-to-R produces inconsistent gt/lt results at varying CIDR // expected difference on CIDR is gt/eq or lt/eq ONLY. - for(unsigned int i = 0 ; i < sizeof(m_SocketAddr.sin6_addr) ; i++) { + for (unsigned int i = 0 ; i < sizeof(m_SocketAddr.sin6_addr) ; i++) { - if(l[i] < r[i]) + if (l[i] < r[i]) return -1; - if(l[i] > r[i]) + if (l[i] > r[i]) return 1; } @@ -938,7 +929,7 @@ bool IPAddress::operator !=(const IPAddress &s) const bool IPAddress::operator <=(const IPAddress &rhs) const { - if(IsAnyAddr() && !rhs.IsAnyAddr()) + if (IsAnyAddr() && !rhs.IsAnyAddr()) return true; return (matchIPAddr(rhs) <= 0); @@ -946,7 +937,7 @@ bool IPAddress::operator <=(const IPAddress &rhs) const bool IPAddress::operator >=(const IPAddress &rhs) const { - if(IsNoAddr() && !rhs.IsNoAddr()) + if (IsNoAddr() && !rhs.IsNoAddr()) return true; return ( matchIPAddr(rhs) >= 0); @@ -954,7 +945,7 @@ bool IPAddress::operator >=(const IPAddress &rhs) const bool IPAddress::operator >(const IPAddress &rhs) const { - if(IsNoAddr() && !rhs.IsNoAddr()) + if (IsNoAddr() && !rhs.IsNoAddr()) return true; return ( matchIPAddr(rhs) > 0); @@ -962,7 +953,7 @@ bool IPAddress::operator >(const IPAddress &rhs) const bool IPAddress::operator <(const IPAddress &rhs) const { - if(IsNoAddr() && !rhs.IsNoAddr()) + if (IsNoAddr() && !rhs.IsNoAddr()) return true; return ( matchIPAddr(rhs) < 0); @@ -993,13 +984,13 @@ u_short IPAddress::SetPort(u_short prt) char* IPAddress::NtoA(char* buf, const unsigned int blen, int force) const { // Ensure we have a buffer. - if(buf == NULL) { + if (buf == NULL) { return NULL; } /* some external code may have blindly memset a parent. */ /* thats okay, our default is known */ - if( IsAnyAddr() ) { + if ( IsAnyAddr() ) { #if USE_IPV6 memcpy(buf,"::\0", xmin(3,blen)); #else @@ -1012,15 +1003,15 @@ char* IPAddress::NtoA(char* buf, const unsigned int blen, int force) const /* Pure-IPv6 CANNOT be displayed in IPv4 format. */ /* However IPv4 CAN. */ - if( force == AF_INET && !IsIPv4() ) { - if( IsIPv6() ) { + if ( force == AF_INET && !IsIPv4() ) { + if ( IsIPv6() ) { memcpy(buf, "{!IPv4}\0", xmin(8,blen)); } return buf; } #if USE_IPV6 - if( force == AF_INET6 || (force == AF_UNSPEC && IsIPv6()) ) { + if ( force == AF_INET6 || (force == AF_UNSPEC && IsIPv6()) ) { xinet_ntop(AF_INET6, &m_SocketAddr.sin6_addr, buf, blen); @@ -1030,12 +1021,12 @@ char* IPAddress::NtoA(char* buf, const unsigned int blen, int force) const GetInAddr(tmp); xinet_ntop(AF_INET, &tmp, buf, blen); #else - if ( force == AF_UNSPEC || (force == AF_INET && IsIPv4()) ) { + if ( force == AF_UNSPEC || (force == AF_INET && IsIPv4()) ) { xinet_ntop(AF_INET, &m_SocketAddr.sin_addr, buf, blen); #endif } else { debugs(14,0,"WARNING: Corrupt IP Address details OR required to display in unknown format (" << - force << "). accepted={" << AF_UNSPEC << "," << AF_INET << "," << AF_INET6 << "}"); + force << "). accepted={" << AF_UNSPEC << "," << AF_INET << "," << AF_INET6 << "}"); fprintf(stderr,"WARNING: Corrupt IP Address details OR required to display in unknown format (%d). accepted={%d,%d,%d} ", force, AF_UNSPEC, AF_INET, AF_INET6); memcpy(buf,"dead:beef::\0", xmin(13,blen)); @@ -1045,26 +1036,25 @@ char* IPAddress::NtoA(char* buf, const unsigned int blen, int force) const return buf; } -unsigned int IPAddress::ToHostname(char *buf, const unsigned int blen) const -{ +unsigned int IPAddress::ToHostname(char *buf, const unsigned int blen) const { char *p = buf; - if(IsIPv6() && blen > 0) { + if (IsIPv6() && blen > 0) { *p = '['; p++; } /* 7 being space for [,], and port */ - if( IsIPv6() ) + if ( IsIPv6() ) NtoA(p, blen-7, AF_INET6); else NtoA(p, blen-7, AF_INET); // find the end of the new string - while(*p != '\0' && p < buf+blen) + while (*p != '\0' && p < buf+blen) p++; - if(IsIPv6() && p < (buf+blen-1) ) { + if (IsIPv6() && p < (buf+blen-1) ) { *p = ']'; p++; } @@ -1076,19 +1066,18 @@ unsigned int IPAddress::ToHostname(char *buf, const unsigned int blen) const return (p - buf); } -char* IPAddress::ToURL(char* buf, unsigned int blen) const -{ +char* IPAddress::ToURL(char* buf, unsigned int blen) const { char *p = buf; // Ensure we have a buffer. - if(buf == NULL) { + if (buf == NULL) { return NULL; } p += ToHostname(p, blen); - if(m_SocketAddr.sin6_port > 0 && p < (buf+blen-6) ) { + if (m_SocketAddr.sin6_port > 0 && p < (buf+blen-6) ) { /* 6 is max length of expected ':port' (short int) */ snprintf(p, 6,":%d", GetPort() ); } @@ -1099,21 +1088,19 @@ char* IPAddress::ToURL(char* buf, unsigned int blen) const return buf; } -void IPAddress::GetSockAddr(struct sockaddr_storage &addr, const int family) const -{ +void IPAddress::GetSockAddr(struct sockaddr_storage &addr, const int family) const { struct sockaddr_in *sin = NULL; - if( family == AF_INET && !IsIPv4()) { + if ( family == AF_INET && !IsIPv4()) { // FIXME INET6: caller using the wrong socket type! debugs(14, DBG_CRITICAL, HERE << "IPAddress::GetSockAddr : Cannot convert non-IPv4 to IPv4. from " << *this); assert(false); } #if USE_IPV6 - if( family == AF_INET6 || (family == AF_UNSPEC && IsIPv6()) ) - { + if ( family == AF_INET6 || (family == AF_UNSPEC && IsIPv6()) ) { memcpy(&addr, &m_SocketAddr, sizeof(struct sockaddr_in6)); - if(addr.ss_family == 0) { + if (addr.ss_family == 0) { addr.ss_family = AF_INET6; } #if HAVE_SS_LEN_IN_SS @@ -1122,7 +1109,7 @@ void IPAddress::GetSockAddr(struct sockaddr_storage &addr, const int family) con #elif HAVE_SIN6_LEN_IN_SAI sin->sin6_len = htons(sizeof(struct sockaddr_in6)); #endif - } else if( family == AF_INET || (family == AF_UNSPEC && IsIPv4()) ) { + } else if ( family == AF_INET || (family == AF_UNSPEC && IsIPv4()) ) { sin = (struct sockaddr_in*)&addr; addr.ss_family = AF_INET; sin->sin_port = m_SocketAddr.sin6_port; @@ -1146,23 +1133,20 @@ void IPAddress::GetSockAddr(struct sockaddr_storage &addr, const int family) con /* not all OS have this field, BUT when they do it can be a problem if set wrong */ addr.ss_len = htons(sizeof(struct sockaddr_in)); #elif HAVE_SIN_LEN_IN_SAI - sin->sin_len = htons(sizeof(struct sockaddr_in)); + sin->sin_len = htons(sizeof(struct sockaddr_in)); #endif #endif /* USE_IPV6 */ } -void IPAddress::GetSockAddr(struct sockaddr_in &buf) const -{ +void IPAddress::GetSockAddr(struct sockaddr_in &buf) const { #if USE_IPV6 - if( IsIPv4() ) - { + if ( IsIPv4() ) { buf.sin_family = AF_INET; buf.sin_port = m_SocketAddr.sin6_port; Map6to4( m_SocketAddr.sin6_addr, buf.sin_addr); - } else - { + } else { debugs(14, DBG_CRITICAL, HERE << "IPAddress::GetSockAddr : Cannot convert non-IPv4 to IPv4. from " << *this ); memset(&buf,0xFFFFFFFF,sizeof(struct sockaddr_in)); @@ -1173,8 +1157,7 @@ void IPAddress::GetSockAddr(struct sockaddr_in &buf) const memcpy(&buf, &m_SocketAddr, sizeof(struct sockaddr_in)); - if(buf.sin_family == 0) - { + if (buf.sin_family == 0) { buf.sin_family = AF_INET; } @@ -1183,8 +1166,7 @@ void IPAddress::GetSockAddr(struct sockaddr_in &buf) const #if USE_IPV6 -void IPAddress::GetSockAddr(struct sockaddr_in6 &buf) const -{ +void IPAddress::GetSockAddr(struct sockaddr_in6 &buf) const { memcpy(&buf, &m_SocketAddr, sizeof(struct sockaddr_in6)); /* maintain address family. It may have changed inside us. */ buf.sin6_family = AF_INET6; @@ -1194,17 +1176,14 @@ void IPAddress::GetSockAddr(struct sockaddr_in6 &buf) const #if USE_IPV6 -void IPAddress::Map4to6(const struct in_addr &in, struct in6_addr &out) const -{ +void IPAddress::Map4to6(const struct in_addr &in, struct in6_addr &out) const { /* check for special cases */ - if( in.s_addr == 0x00000000) - { + if ( in.s_addr == 0x00000000) { /* ANYADDR */ memset(&out, 0, sizeof(struct in6_addr)); - } else if( in.s_addr == 0xFFFFFFFF) - { + } else if ( in.s_addr == 0xFFFFFFFF) { /* NOADDR */ out.s6_addr32[0] = 0xFFFFFFFF; @@ -1213,16 +1192,14 @@ void IPAddress::Map4to6(const struct in_addr &in, struct in6_addr &out) const out.s6_addr32[3] = 0xFFFFFFFF; #if IPV6_SPECIAL_LOCALHOST - } else if( in.s_addr == htonl(0x7F000001)) - { + } else if ( in.s_addr == htonl(0x7F000001)) { /* LOCALHOST */ memset(&out, 0, sizeof(struct in6_addr)); out.s6_addr32[3] = htonl(0x1); #endif - } else - { + } else { /* general */ memset(&out, 0, sizeof(struct in6_addr)); @@ -1231,8 +1208,7 @@ void IPAddress::Map4to6(const struct in_addr &in, struct in6_addr &out) const } } -void IPAddress::Map6to4(const struct in6_addr &in, struct in_addr &out) const -{ +void IPAddress::Map6to4(const struct in6_addr &in, struct in_addr &out) const { /* ANYADDR */ /* NOADDR */ /* general */ @@ -1243,8 +1219,7 @@ void IPAddress::Map6to4(const struct in6_addr &in, struct in_addr &out) const #if IPV6_SPECIAL_LOCALHOST /* LOCALHOST */ - if( IsLocalhost() ) - { + if ( IsLocalhost() ) { out.s_addr = htonl(0x7F000001); } #endif @@ -1254,24 +1229,22 @@ void IPAddress::Map6to4(const struct in6_addr &in, struct in_addr &out) const #endif #if USE_IPV6 -void IPAddress::GetInAddr(in6_addr &buf) const -{ +void IPAddress::GetInAddr(in6_addr &buf) const { memcpy(&buf, &m_SocketAddr.sin6_addr, sizeof(struct in6_addr)); } #endif -bool IPAddress::GetInAddr(struct in_addr &buf) const -{ +bool IPAddress::GetInAddr(struct in_addr &buf) const { #if USE_IPV6 - if( IsIPv4() ) { + if ( IsIPv4() ) { Map6to4((const in6_addr)m_SocketAddr.sin6_addr, buf); return true; } #else - if( IsIPv4() ) { + if ( IsIPv4() ) { memcpy(&buf, &m_SocketAddr.sin_addr, sizeof(struct in_addr)); return true; } diff --git a/lib/MemPool.cc b/lib/MemPool.cc index a833d0230a..4ef5b3f4e9 100644 --- a/lib/MemPool.cc +++ b/lib/MemPool.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -39,7 +39,7 @@ * each item is individually malloc()ed from system, imposing libmalloc * overhead, and additionally we add our overhead of pointer size per item * as we keep a list of pointer to free items. - * + * * Chunking: * xmalloc Chunk that fits at least MEM_MIN_FREE (32) items in an array, but * limit Chunk size to MEM_CHUNK_MAX_SIZE (256K). Chunk size is rounded up to @@ -47,26 +47,26 @@ * Minimum Chunk size is MEM_CHUNK_SIZE (16K). * A number of items fits into a single chunk, depending on item size. * Maximum number of items per chunk is limited to MEM_MAX_FREE (65535). - * + * * We populate Chunk with a linkedlist, each node at first word of item, * and pointing at next free item. Chunk->FreeList is pointing at first * free node. Thus we stuff free housekeeping into the Chunk itself, and * omit pointer overhead per item. - * + * * Chunks are created on demand, and new chunks are inserted into linklist * of chunks so that Chunks with smaller pointer value are placed closer * to the linklist head. Head is a hotspot, servicing most of requests, so * slow sorting occurs and Chunks in highest memory tend to become idle * and freeable. - * + * * event is registered that runs every 15 secs and checks reference time * of each idle chunk. If a chunk is not referenced for 15 secs, it is * released. - * + * * [If mem_idle_limit is exceeded with pools, every chunk that becomes * idle is immediately considered for release, unless this is the only * chunk with free items in it.] (not implemented) - * + * * In cachemgr output, there are new columns for chunking. Special item, * Frag, is shown to estimate approximately fragmentation of chunked * pools. Fragmentation is calculated by taking amount of items in use, @@ -76,7 +76,7 @@ * twice the needed amount of chunks are in use. * "part" item shows number of chunks partially filled. This shows how * badly fragmentation is spread across all chunks. - * + * * Andres Kroonmaa. * Copyright (c) 2003, Robert Collins */ @@ -118,7 +118,7 @@ MemPools::GetInstance() * if we are called during static initialisations. */ if (!Instance) - Instance = new MemPools; + Instance = new MemPools; return *Instance; } @@ -147,7 +147,7 @@ memPoolIterateNext(MemPoolIterator * iter) pool = iter->pool; if (!pool) - return NULL; + return NULL; iter->pool = pool->next; return pool; @@ -170,30 +170,30 @@ static int memCompChunks(MemChunk * const &chunkA, MemChunk * const &chunkB) { if (chunkA->objCache > chunkB->objCache) - return 1; + return 1; else if (chunkA->objCache < chunkB->objCache) - return -1; + return -1; else - return 0; + return 0; } /* Compare object to chunk */ -static int +static int memCompObjChunks(void *const &obj, MemChunk * const &chunk) { /* object is lower in memory than the chunks arena */ if (obj < chunk->objCache) - return -1; + return -1; /* object is within the pool */ if (obj < (void *) ((char *) chunk->objCache + chunk->pool->chunk_size)) - return 0; + return 0; /* object is above the pool */ return 1; } -MemChunk::MemChunk(MemPool *aPool) +MemChunk::MemChunk(MemPool *aPool) { - /* should have a pool for this too - + /* should have a pool for this too - * note that this requres: * allocate one chunk for the pool of chunks's first chunk * allocate a chunk from that pool @@ -209,14 +209,14 @@ MemChunk::MemChunk(MemPool *aPool) void **Free = (void **)freeList; for (int i = 1; i < pool->chunk_capacity; i++) { - *Free = (void *) ((char *) Free + pool->obj_size); - void **nextFree = (void **)*Free; - (void) VALGRIND_MAKE_MEM_NOACCESS(Free, pool->obj_size); - Free = nextFree; + *Free = (void *) ((char *) Free + pool->obj_size); + void **nextFree = (void **)*Free; + (void) VALGRIND_MAKE_MEM_NOACCESS(Free, pool->obj_size); + Free = nextFree; } nextFreeChunk = pool->nextFreeChunk; pool->nextFreeChunk = this; - + memMeterAdd(pool->getMeter().alloc, pool->chunk_capacity); memMeterAdd(pool->getMeter().idle, pool->chunk_capacity); pool->idle += pool->chunk_capacity; @@ -245,11 +245,11 @@ MemPool::MemPool(const char *aLabel, size_t aSize) : MemImplementingAllocator(aL /* Append as Last */ for (last_pool = MemPools::GetInstance().pools; last_pool && last_pool->next;) - last_pool = last_pool->next; + last_pool = last_pool->next; if (last_pool) - last_pool->next = this; + last_pool->next = this; else - MemPools::GetInstance().pools = this; + MemPools::GetInstance().pools = this; memPID = ++Pool_id_counter; } @@ -294,16 +294,16 @@ MemPool::get() /* first, try cache */ if (freeCache) { - Free = (void **)freeCache; - (void) VALGRIND_MAKE_MEM_DEFINED(Free, obj_size); - freeCache = *Free; - *Free = NULL; - return Free; + Free = (void **)freeCache; + (void) VALGRIND_MAKE_MEM_DEFINED(Free, obj_size); + freeCache = *Free; + *Free = NULL; + return Free; } /* then try perchunk freelist chain */ if (nextFreeChunk == NULL) { - /* no chunk with frees, so create new one */ - createChunk(); + /* no chunk with frees, so create new one */ + createChunk(); } /* now we have some in perchunk freelist chain */ MemChunk *chunk = nextFreeChunk; @@ -315,8 +315,8 @@ MemPool::get() chunk->lastref = squid_curtime; if (chunk->freeList == NULL) { - /* last free in this chunk, so remove us from perchunk freelist chain */ - nextFreeChunk = chunk->nextFreeChunk; + /* last free in this chunk, so remove us from perchunk freelist chain */ + nextFreeChunk = chunk->nextFreeChunk; } (void) VALGRIND_MAKE_MEM_DEFINED(Free, obj_size); return Free; @@ -332,23 +332,23 @@ MemPool::createChunk() chunk = Chunks; if (chunk == NULL) { /* first chunk in pool */ - Chunks = newChunk; - return; + Chunks = newChunk; + return; } if (newChunk->objCache < chunk->objCache) { - /* we are lowest ram chunk, insert as first chunk */ - newChunk->next = chunk; - Chunks = newChunk; - return; + /* we are lowest ram chunk, insert as first chunk */ + newChunk->next = chunk; + Chunks = newChunk; + return; } while (chunk->next) { - if (newChunk->objCache < chunk->next->objCache) { - /* new chunk is in lower ram, insert here */ - newChunk->next = chunk->next; - chunk->next = newChunk; - return; - } - chunk = chunk->next; + if (newChunk->objCache < chunk->next->objCache) { + /* new chunk is in lower ram, insert here */ + newChunk->next = chunk->next; + chunk->next = newChunk; + return; + } + chunk = chunk->next; } /* we are the worst chunk in chain, add as last */ chunk->next = newChunk; @@ -359,11 +359,11 @@ MemPool::createChunk() * MemPools::GetInstance().setDefaultPoolChunking() can be called. */ MemPools::MemPools() : pools(NULL), mem_idle_limit(2 * MB), - poolCount (0), defaultIsChunked (!DISABLE_POOLS && !RUNNING_ON_VALGRIND) + poolCount (0), defaultIsChunked (!DISABLE_POOLS && !RUNNING_ON_VALGRIND) { char *cfg = getenv("MEMPOOLS"); if (cfg) - defaultIsChunked = atoi(cfg); + defaultIsChunked = atoi(cfg); #if HAVE_MALLOPT && M_MMAP_MAX mallopt(M_MMAP_MAX, MEM_MAX_MMAP_CHUNKS); #endif @@ -376,19 +376,19 @@ MemPool::setChunkSize(size_t chunksize) size_t csize = chunksize; if (Chunks) /* unsafe to tamper */ - return; + return; csize = ((csize + MEM_PAGE_SIZE - 1) / MEM_PAGE_SIZE) * MEM_PAGE_SIZE; /* round up to page size */ cap = csize / obj_size; if (cap < MEM_MIN_FREE) - cap = MEM_MIN_FREE; + cap = MEM_MIN_FREE; if (cap * obj_size > MEM_CHUNK_MAX_SIZE) - cap = MEM_CHUNK_MAX_SIZE / obj_size; + cap = MEM_CHUNK_MAX_SIZE / obj_size; if (cap > MEM_MAX_FREE) - cap = MEM_MAX_FREE; + cap = MEM_MAX_FREE; if (cap < 1) - cap = 1; + cap = 1; csize = cap * obj_size; csize = ((csize + MEM_PAGE_SIZE - 1) / MEM_PAGE_SIZE) * MEM_PAGE_SIZE; /* round up to page size */ @@ -409,9 +409,9 @@ MemPools::create(const char *label, size_t obj_size, bool const chunked) { ++poolCount; if (chunked) - return new MemPool (label, obj_size); + return new MemPool (label, obj_size); else - return new MemMalloc (label, obj_size); + return new MemMalloc (label, obj_size); } void @@ -434,9 +434,9 @@ MemPool::~MemPool() assert(inuse == 0 && "While trying to destroy pool"); chunk = Chunks; - while( (fchunk = chunk) != NULL) { + while ( (fchunk = chunk) != NULL) { chunk = chunk->next; - delete fchunk; + delete fchunk; } /* TODO we should be doing something about the original Chunks pointer here. */ @@ -444,13 +444,13 @@ MemPool::~MemPool() /* Pool clean, remove it from List and free */ for (find_pool = MemPools::GetInstance().pools, prev_pool = NULL; (find_pool && this != find_pool); find_pool = find_pool->next) - prev_pool = find_pool; + prev_pool = find_pool; assert(find_pool != NULL && "pool to destroy not found"); if (prev_pool) - prev_pool->next = next; + prev_pool->next = next; else - MemPools::GetInstance().pools = next; + MemPools::GetInstance().pools = next; --MemPools::GetInstance().poolCount; } @@ -473,17 +473,17 @@ MemImplementingAllocator::flushMeters() calls = free_calls; if (calls) { - getMeter().gb_freed.count += calls; - memMeterDel(getMeter().inuse, calls); - memMeterAdd(getMeter().idle, calls); - free_calls = 0; + getMeter().gb_freed.count += calls; + memMeterDel(getMeter().inuse, calls); + memMeterAdd(getMeter().idle, calls); + free_calls = 0; } calls = alloc_calls; if (calls) { - meter.gb_saved.count += calls; - memMeterAdd(meter.inuse, calls); - memMeterDel(meter.idle, calls); - alloc_calls = 0; + meter.gb_saved.count += calls; + memMeterAdd(meter.inuse, calls); + memMeterDel(meter.idle, calls); + alloc_calls = 0; } } @@ -496,7 +496,7 @@ MemImplementingAllocator::flushMetersFull() } void -MemPoolMeter::flush() +MemPoolMeter::flush() { alloc.level = 0; inuse.level = 0; @@ -519,14 +519,14 @@ MemPools::flushMeters() iter = memPoolIterate(); while ((pool = memPoolIterateNext(iter))) { - pool->flushMetersFull(); - memMeterAdd(TheMeter.alloc, pool->getMeter().alloc.level * pool->obj_size); - memMeterAdd(TheMeter.inuse, pool->getMeter().inuse.level * pool->obj_size); - memMeterAdd(TheMeter.idle, pool->getMeter().idle.level * pool->obj_size); - TheMeter.gb_saved.count += pool->getMeter().gb_saved.count; - TheMeter.gb_freed.count += pool->getMeter().gb_freed.count; - TheMeter.gb_saved.bytes += pool->getMeter().gb_saved.bytes; - TheMeter.gb_freed.bytes += pool->getMeter().gb_freed.bytes; + pool->flushMetersFull(); + memMeterAdd(TheMeter.alloc, pool->getMeter().alloc.level * pool->obj_size); + memMeterAdd(TheMeter.inuse, pool->getMeter().inuse.level * pool->obj_size); + memMeterAdd(TheMeter.idle, pool->getMeter().idle.level * pool->obj_size); + TheMeter.gb_saved.count += pool->getMeter().gb_saved.count; + TheMeter.gb_freed.count += pool->getMeter().gb_freed.count; + TheMeter.gb_saved.bytes += pool->getMeter().gb_saved.bytes; + TheMeter.gb_freed.bytes += pool->getMeter().gb_freed.bytes; } memPoolIterateDone(&iter); } @@ -549,7 +549,7 @@ void * MemImplementingAllocator::alloc() { if (++alloc_calls == FLUSH_LIMIT) - flushMeters(); + flushMeters(); return allocate(); } @@ -594,21 +594,21 @@ MemPool::convertFreeCacheToChunkFreeCache() void *Free; /* * OK, so we have to go through all the global freeCache and find the Chunk - * any given Free belongs to, and stuff it into that Chunk's freelist + * any given Free belongs to, and stuff it into that Chunk's freelist */ while ((Free = freeCache) != NULL) { - MemChunk *chunk = NULL; - chunk = const_cast(*allChunks.find(Free, memCompObjChunks)); - assert(splayLastResult == 0); - assert(chunk->inuse_count > 0); - chunk->inuse_count--; - (void) VALGRIND_MAKE_MEM_DEFINED(Free, sizeof(void *)); - freeCache = *(void **)Free; /* remove from global cache */ - *(void **)Free = chunk->freeList; /* stuff into chunks freelist */ - (void) VALGRIND_MAKE_MEM_NOACCESS(Free, sizeof(void *)); - chunk->freeList = Free; - chunk->lastref = squid_curtime; + MemChunk *chunk = NULL; + chunk = const_cast(*allChunks.find(Free, memCompObjChunks)); + assert(splayLastResult == 0); + assert(chunk->inuse_count > 0); + chunk->inuse_count--; + (void) VALGRIND_MAKE_MEM_DEFINED(Free, sizeof(void *)); + freeCache = *(void **)Free; /* remove from global cache */ + *(void **)Free = chunk->freeList; /* stuff into chunks freelist */ + (void) VALGRIND_MAKE_MEM_NOACCESS(Free, sizeof(void *)); + chunk->freeList = Free; + chunk->lastref = squid_curtime; } } @@ -621,9 +621,9 @@ MemPool::clean(time_t maxage) time_t age; if (!this) - return; + return; if (!Chunks) - return; + return; flushMetersFull(); convertFreeCacheToChunkFreeCache(); @@ -634,17 +634,17 @@ MemPool::clean(time_t maxage) chunk = Chunks; while ((freechunk = chunk->next) != NULL) { - age = squid_curtime - freechunk->lastref; - freechunk->nextFreeChunk = NULL; - if (freechunk->inuse_count == 0) - if (age >= maxage) { - chunk->next = freechunk->next; - delete freechunk; - freechunk = NULL; - } - if (chunk->next == NULL) - break; - chunk = chunk->next; + age = squid_curtime - freechunk->lastref; + freechunk->nextFreeChunk = NULL; + if (freechunk->inuse_count == 0) + if (age >= maxage) { + chunk->next = freechunk->next; + delete freechunk; + freechunk = NULL; + } + if (chunk->next == NULL) + break; + chunk = chunk->next; } /* Recreate nextFreeChunk list from scratch */ @@ -657,30 +657,30 @@ MemPool::clean(time_t maxage) chunk->nextFreeChunk = NULL; while (chunk->next) { - chunk->next->nextFreeChunk = NULL; - if (chunk->next->inuse_count < chunk_capacity) { - listTail = nextFreeChunk; - while (listTail->nextFreeChunk) { - if (chunk->next->inuse_count > listTail->nextFreeChunk->inuse_count) - break; - if ((chunk->next->inuse_count == listTail->nextFreeChunk->inuse_count) && - (chunk->next->objCache < listTail->nextFreeChunk->objCache)) - break; - listTail = listTail->nextFreeChunk; - } - chunk->next->nextFreeChunk = listTail->nextFreeChunk; - listTail->nextFreeChunk = chunk->next; - } - chunk = chunk->next; + chunk->next->nextFreeChunk = NULL; + if (chunk->next->inuse_count < chunk_capacity) { + listTail = nextFreeChunk; + while (listTail->nextFreeChunk) { + if (chunk->next->inuse_count > listTail->nextFreeChunk->inuse_count) + break; + if ((chunk->next->inuse_count == listTail->nextFreeChunk->inuse_count) && + (chunk->next->objCache < listTail->nextFreeChunk->objCache)) + break; + listTail = listTail->nextFreeChunk; + } + chunk->next->nextFreeChunk = listTail->nextFreeChunk; + listTail->nextFreeChunk = chunk->next; + } + chunk = chunk->next; } /* We started from 2nd chunk. If first chunk is full, remove it */ if (nextFreeChunk->inuse_count == chunk_capacity) - nextFreeChunk = nextFreeChunk->nextFreeChunk; + nextFreeChunk = nextFreeChunk->nextFreeChunk; return; } -/* +/* * Returns all cached frees to their home chunks * If chunks unreferenced age is over, destroys Idle chunk * Flushes meters for a pool @@ -698,12 +698,12 @@ MemPools::clean(time_t maxage) int shift = 1; flushMeters(); if (TheMeter.idle.level > mem_idle_limit) - maxage = shift = 0; + maxage = shift = 0; iter = memPoolIterate(); while ((pool = memPoolIterateNext(iter))) - if (pool->idleTrigger(shift)) - pool->clean(maxage); + if (pool->idleTrigger(shift)) + pool->clean(maxage); memPoolIterateDone(&iter); } @@ -727,8 +727,8 @@ MemPool::getStats(MemPoolStats * stats) int chunks_partial = 0; if (stats != &pp_stats) /* need skip memset for GlobalStats accumulation */ - /* XXX Fixme */ - memset(stats, 0, sizeof(MemPoolStats)); + /* XXX Fixme */ + memset(stats, 0, sizeof(MemPoolStats)); clean((time_t) 555555); /* don't want to get chunks released before reporting */ @@ -741,11 +741,11 @@ MemPool::getStats(MemPoolStats * stats) /* gather stats for each Chunk */ chunk = Chunks; while (chunk) { - if (chunk->inuse_count == 0) - chunks_free++; - else if (chunk->inuse_count < chunk_capacity) - chunks_partial++; - chunk = chunk->next; + if (chunk->inuse_count == 0) + chunks_free++; + else if (chunk->inuse_count < chunk_capacity) + chunks_partial++; + chunk = chunk->next; } stats->chunks_alloc += chunkCount; @@ -767,8 +767,8 @@ int MemMalloc::getStats(MemPoolStats * stats) { if (stats != &pp_stats) /* need skip memset for GlobalStats accumulation */ - /* XXX Fixme */ - memset(stats, 0, sizeof(MemPoolStats)); + /* XXX Fixme */ + memset(stats, 0, sizeof(MemPoolStats)); stats->pool = this; stats->label = objectType(); @@ -793,7 +793,7 @@ MemMalloc::getStats(MemPoolStats * stats) int MemMalloc::getInUseCount() { - return inuse; + return inuse; } /* @@ -814,8 +814,8 @@ memPoolGetGlobalStats(MemPoolGlobalStats * stats) /* gather all stats for Totals */ iter = memPoolIterate(); while ((pool = memPoolIterateNext(iter))) { - if (pool->getStats(&pp_stats) > 0) - pools_inuse++; + if (pool->getStats(&pp_stats) > 0) + pools_inuse++; } memPoolIterateDone(&iter); @@ -894,7 +894,7 @@ MemAllocator * MemAllocatorProxy::getAllocator() const { if (!theAllocator) - theAllocator = MemPools::GetInstance().create(objectType(), size); + theAllocator = MemPools::GetInstance().create(objectType(), size); return theAllocator; } @@ -902,9 +902,9 @@ int MemAllocatorProxy::inUseCount() const { if (!theAllocator) - return 0; + return 0; else - return memPoolInUseCount(theAllocator); + return memPoolInUseCount(theAllocator); } size_t @@ -932,17 +932,17 @@ MemAllocatorProxy::getStats(MemPoolStats * stats) } MemImplementingAllocator::MemImplementingAllocator(char const *aLabel, size_t aSize) : MemAllocator(aLabel), - next(NULL), - alloc_calls(0), - free_calls(0), - obj_size(RoundedSize(aSize)) + next(NULL), + alloc_calls(0), + free_calls(0), + obj_size(RoundedSize(aSize)) { } void MemAllocator::zeroOnPush(bool doIt) { - doZeroOnPush = doIt; + doZeroOnPush = doIt; } MemPoolMeter const & diff --git a/lib/Profiler.c b/lib/Profiler.c index 0f0cb4a9f9..d56a46c36a 100644 --- a/lib/Profiler.c +++ b/lib/Profiler.c @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -35,37 +35,37 @@ /* * CPU Profiling implementation. - * + * * This library implements the Probes needed to gather stats. * See src/ProfStats.c which implements historical recording and * presentation in CacheMgr.cgi. - * + * * For timing we prefer on-CPU ops that retrieve cpu ticks counter. * For Intel, this is "rdtsc", which is 64-bit counter that virtually * never wraps. For alpha, this is "rpcc" which is 32-bit counter and * wraps every few seconds. Currently, no handling of wrapping counters * is implemented. Other CPU's are also not covered. Potentially all * modern CPU's has similar counters. - * + * * Usage. * Insert macro PROF_state(probename) in strategic places in code. * PROF_start(probename); * ... section of code measured ... * PROF_stop(probename); - * + * * probename must be added to profiling.h into xprof_type enum list * with prepended "XPROF_" string. * * Description. * PROF gathers stats per probename into structures. It indexes these * structures by enum type index in an array. - * + * * PROF records best, best, average and worst values for delta time, * also, if UNACCED is defined, it measures "empty" time during which * no probes are in measuring state. This allows to see time "unaccounted" * for. If OVERHEAD is defined, additional calculations are made at every * probe to measure approximate overhead of the probe code itself. - * + * * Probe data is stored in linked-list, so the more probes you define, * the more overhead is added to find the deepest nested probe. To reduce * average overhead, linked list is manipulated each time PR_start is @@ -76,17 +76,17 @@ * ticks, which on the scale of submicroseconds. Yet, to optimise really * fast and frequent sections of code, we want to reduce this overhead * to absolute minimum possible. - * + * * For actual measurements, probe overhead cancels out mostly. Still, * do not take the measured times as facts, they should be viewed in * relative comparison to overall CPU time and on the same platform. - * + * * Every 1 second, Event within squid is called that parses gathered * statistics of every probe, and accumulates that into historical * structures for last 1,5,30 secs, 1,5,30 mins, and 1,5 and 24 hours. * Each second active probe stats are reset, and only historical data * is presented in cachemgr output. - * + * * Reading stats. * "Worst case" may be misleading. Anything can happen at any section * of code that could delay reaching to probe stop. For eg. system may @@ -98,11 +98,11 @@ * time in given timeframe, which really show percentage of time spent * in given section of code, and its average completion time. This data * could be used to detect bottlenecks withing squid and optimise them. - * + * * TOTALS are quite off reality. Its there just to summarise cumulative * times and percent column. Percent values over 100% shows that there * have been some probes nested into each other. - * + * */ #include "profiling.h" @@ -131,9 +131,9 @@ TimersArray *xprof_Timers = NULL; #define MAXSTACKDEPTH 512 struct _callstack_entry { - int timer; /* index into timers array */ - const char *name; - hrtime_t start, stop, accum; + int timer; /* index into timers array */ + const char *name; + hrtime_t start, stop, accum; }; struct _callstack_entry cstack[MAXSTACKDEPTH]; @@ -147,9 +147,9 @@ static inline void xprof_update(xprof_stats_data * head) { if (head->delta < head->best) - head->best = head->delta; + head->best = head->delta; if (head->worst < head->delta) - head->worst = head->delta; + head->worst = head->delta; head->summ += head->delta; head->count++; } @@ -161,7 +161,7 @@ static void xprof_InitLib(void) { if (xprof_inited) - return; + return; xprof_Timers = calloc(XPROF_LAST + 2, sizeof(xprof_stats_node)); @@ -177,20 +177,20 @@ xprof_start(xprof_type type, const char *timer) { hrtime_t tt = get_tick(); if (!xprof_inited) - xprof_InitLib(); + xprof_InitLib(); /* If nested, stop current stack frame */ if (cstack_head > 0) { - cstack[cstack_head - 1].accum += get_tick() - cstack[cstack_head - 1].start; - cstack[cstack_head - 1].start = -1; + cstack[cstack_head - 1].accum += get_tick() - cstack[cstack_head - 1].start; + cstack[cstack_head - 1].start = -1; } /* Are we at the first level? If so; stop the unaccounted timer */ if (cstack_head == 0) { - assert(xp_UNACCOUNTED->start != -1); - xp_UNACCOUNTED->delta = tt - xp_UNACCOUNTED->start; - xp_UNACCOUNTED->start = -1; - xprof_update(xp_UNACCOUNTED); + assert(xp_UNACCOUNTED->start != -1); + xp_UNACCOUNTED->delta = tt - xp_UNACCOUNTED->start; + xp_UNACCOUNTED->start = -1; + xprof_update(xp_UNACCOUNTED); } /* Allocate new stack frame */ @@ -222,9 +222,9 @@ xprof_stop(xprof_type type, const char *timer) /* Restart previous timer if we're not at the top level */ if (cstack_head > 0) { - cstack[cstack_head - 1].start = tt; - cstack[cstack_head - 1].stop = 0; - return; + cstack[cstack_head - 1].start = tt; + cstack[cstack_head - 1].stop = 0; + return; } /* Get here? We're at the top level; unaccounted */ xp_UNACCOUNTED->start = tt; diff --git a/lib/assert.c b/lib/assert.c index 067898f80f..87c43dceaa 100644 --- a/lib/assert.c +++ b/lib/assert.c @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -39,7 +39,8 @@ #include "assert.h" -void xassert(const char *expr, const char *file, int line) { +void xassert(const char *expr, const char *file, int line) +{ fprintf(stderr, "assertion failed: %s:%d: \"%s\"\n", file, line, expr); abort(); } diff --git a/lib/base64.c b/lib/base64.c index f829c6d65a..94521f80ae 100644 --- a/lib/base64.c +++ b/lib/base64.c @@ -28,10 +28,10 @@ base64_init(void) int i; for (i = 0; i < BASE64_VALUE_SZ; i++) - base64_value[i] = -1; + base64_value[i] = -1; for (i = 0; i < 64; i++) - base64_value[(int) base64_code[i]] = i; + base64_value[(int) base64_code[i]] = i; base64_value['='] = 0; base64_initialized = 1; @@ -45,23 +45,23 @@ base64_decode(const char *p) int c; long val; if (!p) - return NULL; + return NULL; if (!base64_initialized) - base64_init(); + base64_init(); val = c = 0; for (j = 0; *p && j + 4 < BASE64_RESULT_SZ; p++) { - unsigned int k = ((unsigned char) *p) % BASE64_VALUE_SZ; - if (base64_value[k] < 0) - continue; - val <<= 6; - val += base64_value[k]; - if (++c < 4) - continue; - /* One quantum of four encoding characters/24 bit */ - result[j++] = (val >> 16) & 0xff; /* High 8 bits */ - result[j++] = (val >> 8) & 0xff; /* Mid 8 bits */ - result[j++] = val & 0xff; /* Low 8 bits */ - val = c = 0; + unsigned int k = ((unsigned char) *p) % BASE64_VALUE_SZ; + if (base64_value[k] < 0) + continue; + val <<= 6; + val += base64_value[k]; + if (++c < 4) + continue; + /* One quantum of four encoding characters/24 bit */ + result[j++] = (val >> 16) & 0xff; /* High 8 bits */ + result[j++] = (val >> 8) & 0xff; /* Mid 8 bits */ + result[j++] = val & 0xff; /* Low 8 bits */ + val = c = 0; } result[j] = 0; return result; @@ -78,36 +78,36 @@ base64_encode(const char *decoded_str) int c; if (!decoded_str) - return decoded_str; + return decoded_str; if (!base64_initialized) - base64_init(); + base64_init(); while ((c = (unsigned char) *decoded_str++) && out_cnt < sizeof(result) - 5) { - bits += c; - char_count++; - if (char_count == 3) { - result[out_cnt++] = base64_code[bits >> 18]; - result[out_cnt++] = base64_code[(bits >> 12) & 0x3f]; - result[out_cnt++] = base64_code[(bits >> 6) & 0x3f]; - result[out_cnt++] = base64_code[bits & 0x3f]; - bits = 0; - char_count = 0; - } else { - bits <<= 8; - } + bits += c; + char_count++; + if (char_count == 3) { + result[out_cnt++] = base64_code[bits >> 18]; + result[out_cnt++] = base64_code[(bits >> 12) & 0x3f]; + result[out_cnt++] = base64_code[(bits >> 6) & 0x3f]; + result[out_cnt++] = base64_code[bits & 0x3f]; + bits = 0; + char_count = 0; + } else { + bits <<= 8; + } } if (char_count != 0) { - bits <<= 16 - (8 * char_count); - result[out_cnt++] = base64_code[bits >> 18]; - result[out_cnt++] = base64_code[(bits >> 12) & 0x3f]; - if (char_count == 1) { - result[out_cnt++] = '='; - result[out_cnt++] = '='; - } else { - result[out_cnt++] = base64_code[(bits >> 6) & 0x3f]; - result[out_cnt++] = '='; - } + bits <<= 16 - (8 * char_count); + result[out_cnt++] = base64_code[bits >> 18]; + result[out_cnt++] = base64_code[(bits >> 12) & 0x3f]; + if (char_count == 1) { + result[out_cnt++] = '='; + result[out_cnt++] = '='; + } else { + result[out_cnt++] = base64_code[(bits >> 6) & 0x3f]; + result[out_cnt++] = '='; + } } result[out_cnt] = '\0'; /* terminate */ return result; @@ -123,37 +123,37 @@ base64_encode_bin(const char *data, int len) int out_cnt = 0; if (!data) - return data; + return data; if (!base64_initialized) - base64_init(); + base64_init(); while (len-- && out_cnt < sizeof(result) - 5) { - int c = (unsigned char) *data++; - bits += c; - char_count++; - if (char_count == 3) { - result[out_cnt++] = base64_code[bits >> 18]; - result[out_cnt++] = base64_code[(bits >> 12) & 0x3f]; - result[out_cnt++] = base64_code[(bits >> 6) & 0x3f]; - result[out_cnt++] = base64_code[bits & 0x3f]; - bits = 0; - char_count = 0; - } else { - bits <<= 8; - } + int c = (unsigned char) *data++; + bits += c; + char_count++; + if (char_count == 3) { + result[out_cnt++] = base64_code[bits >> 18]; + result[out_cnt++] = base64_code[(bits >> 12) & 0x3f]; + result[out_cnt++] = base64_code[(bits >> 6) & 0x3f]; + result[out_cnt++] = base64_code[bits & 0x3f]; + bits = 0; + char_count = 0; + } else { + bits <<= 8; + } } if (char_count != 0) { - bits <<= 16 - (8 * char_count); - result[out_cnt++] = base64_code[bits >> 18]; - result[out_cnt++] = base64_code[(bits >> 12) & 0x3f]; - if (char_count == 1) { - result[out_cnt++] = '='; - result[out_cnt++] = '='; - } else { - result[out_cnt++] = base64_code[(bits >> 6) & 0x3f]; - result[out_cnt++] = '='; - } + bits <<= 16 - (8 * char_count); + result[out_cnt++] = base64_code[bits >> 18]; + result[out_cnt++] = base64_code[(bits >> 12) & 0x3f]; + if (char_count == 1) { + result[out_cnt++] = '='; + result[out_cnt++] = '='; + } else { + result[out_cnt++] = base64_code[(bits >> 6) & 0x3f]; + result[out_cnt++] = '='; + } } result[out_cnt] = '\0'; /* terminate */ return result; diff --git a/lib/charset.c b/lib/charset.c index bc0223a460..cb0b606869 100644 --- a/lib/charset.c +++ b/lib/charset.c @@ -1,9 +1,9 @@ /* * $Id: charset.c,v 1.1 2008/07/07 11:04:47 hno Exp $ * - * DEBUG: + * DEBUG: * AUTHOR: Henrik Nordstrom - * + * * Copyright (C) 2008 Henrik Nordstrom * * SQUID Web Proxy Cache http://www.squid-cache.org/ @@ -13,12 +13,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -35,20 +35,20 @@ latin1_to_utf8(char *out, size_t size, const char *in) { unsigned char *p; for (p = (unsigned char *)out; *in && size > 2; in++) { - unsigned char ch = (unsigned char)*in; - if (ch < 0x80) { - *p++ = ch; - size--; - } else { - *p++ = (ch >> 6) | 0xc0; - size--; - *p++ = (ch & 0x3f) | 0x80; - size--; - } + unsigned char ch = (unsigned char)*in; + if (ch < 0x80) { + *p++ = ch; + size--; + } else { + *p++ = (ch >> 6) | 0xc0; + size--; + *p++ = (ch & 0x3f) | 0x80; + size--; + } } *p++ = '\0'; if (*in) - return NULL; + return NULL; return out; } diff --git a/lib/dirent.c b/lib/dirent.c index 73ddc05235..1f575facf5 100644 --- a/lib/dirent.c +++ b/lib/dirent.c @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -38,14 +38,14 @@ * This file is a part of the mingw-runtime package. * No warranty is given; refer to the file DISCLAIMER within the package. * - * Derived from DIRLIB.C by Matt J. Weinstein + * Derived from DIRLIB.C by Matt J. Weinstein * This note appears in the DIRLIB.H * DIRLIB.H by M. J. Weinstein Released to public domain 1-Jan-89 * * Updated by Jeremy Bettis * Significantly revised and rewinddir, seekdir and telldir added by Colin * Peters - * + * */ #include "util.h" @@ -81,24 +81,24 @@ opendir(const CHAR * szPath) errno = 0; if (!szPath) { - errno = EFAULT; - return (DIR *) 0; + errno = EFAULT; + return (DIR *) 0; } if (szPath[0] == '\0') { - errno = ENOTDIR; - return (DIR *) 0; + errno = ENOTDIR; + return (DIR *) 0; } /* Attempt to determine if the given path really is a directory. */ rc = GetFileAttributes(szPath); if (rc == (unsigned int) -1) { - /* call GetLastError for more error info */ - errno = ENOENT; - return (DIR *) 0; + /* call GetLastError for more error info */ + errno = ENOENT; + return (DIR *) 0; } if (!(rc & FILE_ATTRIBUTE_DIRECTORY)) { - /* Error, entry exists but not a directory. */ - errno = ENOTDIR; - return (DIR *) 0; + /* Error, entry exists but not a directory. */ + errno = ENOTDIR; + return (DIR *) 0; } /* Make an absolute pathname. */ _fullpath(szFullPath, szPath, MAX_PATH); @@ -106,25 +106,25 @@ opendir(const CHAR * szPath) /* Allocate enough space to store DIR structure and the complete * directory path given. */ nd = (DIR *) malloc(sizeof(DIR) + (strlen(szFullPath) - + strlen(SLASH) - + strlen(SUFFIX) + 1) - * sizeof(CHAR)); + + strlen(SLASH) + + strlen(SUFFIX) + 1) + * sizeof(CHAR)); if (!nd) { - /* Error, out of memory. */ - errno = ENOMEM; - return (DIR *) 0; + /* Error, out of memory. */ + errno = ENOMEM; + return (DIR *) 0; } /* Create the search expression. */ strcpy(nd->dd_name, szFullPath); /* Add on a slash if the path does not end with one. */ if (nd->dd_name[0] != '\0' - && strchr(nd->dd_name, '/') != nd->dd_name - + strlen(nd->dd_name) - 1 - && strchr(nd->dd_name, '\\') != nd->dd_name - + strlen(nd->dd_name) - 1) { - strcat(nd->dd_name, SLASH); + && strchr(nd->dd_name, '/') != nd->dd_name + + strlen(nd->dd_name) - 1 + && strchr(nd->dd_name, '\\') != nd->dd_name + + strlen(nd->dd_name) - 1) { + strcat(nd->dd_name, SLASH); } /* Add on the search pattern */ strcat(nd->dd_name, SUFFIX); @@ -155,57 +155,56 @@ opendir(const CHAR * szPath) * next entry in the directory. */ struct dirent * -readdir(DIR * dirp) -{ + readdir(DIR * dirp) { errno = 0; /* Check for valid DIR struct. */ if (!dirp) { - errno = EFAULT; - return (struct dirent *) 0; + errno = EFAULT; + return (struct dirent *) 0; } if (dirp->dd_stat < 0) { - /* We have already returned all files in the directory - * (or the structure has an invalid dd_stat). */ - return (struct dirent *) 0; + /* We have already returned all files in the directory + * (or the structure has an invalid dd_stat). */ + return (struct dirent *) 0; } else if (dirp->dd_stat == 0) { - /* We haven't started the search yet. */ - /* Start the search */ - dirp->dd_handle = _findfirst(dirp->dd_name, &(dirp->dd_dta)); - - if (dirp->dd_handle == -1) { - /* Whoops! Seems there are no files in that - * directory. */ - dirp->dd_stat = -1; - } else { - dirp->dd_stat = 1; - } + /* We haven't started the search yet. */ + /* Start the search */ + dirp->dd_handle = _findfirst(dirp->dd_name, &(dirp->dd_dta)); + + if (dirp->dd_handle == -1) { + /* Whoops! Seems there are no files in that + * directory. */ + dirp->dd_stat = -1; + } else { + dirp->dd_stat = 1; + } } else { - /* Get the next search entry. */ - if (_findnext(dirp->dd_handle, &(dirp->dd_dta))) { - /* We are off the end or otherwise error. - * _findnext sets errno to ENOENT if no more file - * Undo this. */ - DWORD winerr = GetLastError(); - if (winerr == ERROR_NO_MORE_FILES) - errno = 0; - _findclose(dirp->dd_handle); - dirp->dd_handle = -1; - dirp->dd_stat = -1; - } else { - /* Update the status to indicate the correct - * number. */ - dirp->dd_stat++; - } + /* Get the next search entry. */ + if (_findnext(dirp->dd_handle, &(dirp->dd_dta))) { + /* We are off the end or otherwise error. + * _findnext sets errno to ENOENT if no more file + * Undo this. */ + DWORD winerr = GetLastError(); + if (winerr == ERROR_NO_MORE_FILES) + errno = 0; + _findclose(dirp->dd_handle); + dirp->dd_handle = -1; + dirp->dd_stat = -1; + } else { + /* Update the status to indicate the correct + * number. */ + dirp->dd_stat++; + } } if (dirp->dd_stat > 0) { - /* Successfully got an entry. Everything about the file is - * already appropriately filled in except the length of the - * file name. */ - dirp->dd_dir.d_namlen = strlen(dirp->dd_dta.name); - strcpy(dirp->dd_dir.d_name, dirp->dd_dta.name); - return &dirp->dd_dir; + /* Successfully got an entry. Everything about the file is + * already appropriately filled in except the length of the + * file name. */ + dirp->dd_dir.d_namlen = strlen(dirp->dd_dta.name); + strcpy(dirp->dd_dir.d_name, dirp->dd_dta.name); + return &dirp->dd_dir; } return (struct dirent *) 0; } @@ -225,11 +224,11 @@ closedir(DIR * dirp) rc = 0; if (!dirp) { - errno = EFAULT; - return -1; + errno = EFAULT; + return -1; } if (dirp->dd_handle != -1) { - rc = _findclose(dirp->dd_handle); + rc = _findclose(dirp->dd_handle); } /* Delete the dir structure. */ free(dirp); @@ -249,11 +248,11 @@ rewinddir(DIR * dirp) errno = 0; if (!dirp) { - errno = EFAULT; - return; + errno = EFAULT; + return; } if (dirp->dd_handle != -1) { - _findclose(dirp->dd_handle); + _findclose(dirp->dd_handle); } dirp->dd_handle = -1; dirp->dd_stat = 0; @@ -271,8 +270,8 @@ telldir(DIR * dirp) errno = 0; if (!dirp) { - errno = EFAULT; - return -1; + errno = EFAULT; + return -1; } return dirp->dd_stat; } @@ -292,25 +291,25 @@ seekdir(DIR * dirp, long lPos) errno = 0; if (!dirp) { - errno = EFAULT; - return; + errno = EFAULT; + return; } if (lPos < -1) { - /* Seeking to an invalid position. */ - errno = EINVAL; - return; + /* Seeking to an invalid position. */ + errno = EINVAL; + return; } else if (lPos == -1) { - /* Seek past end. */ - if (dirp->dd_handle != -1) { - _findclose(dirp->dd_handle); - } - dirp->dd_handle = -1; - dirp->dd_stat = -1; + /* Seek past end. */ + if (dirp->dd_handle != -1) { + _findclose(dirp->dd_handle); + } + dirp->dd_handle = -1; + dirp->dd_stat = -1; } else { - /* Rewind and read forward to the appropriate index. */ - rewinddir(dirp); + /* Rewind and read forward to the appropriate index. */ + rewinddir(dirp); - while ((dirp->dd_stat < lPos) && readdir(dirp)); + while ((dirp->dd_stat < lPos) && readdir(dirp)); } } #endif /* _SQUID_MSWIN_ */ diff --git a/lib/drand48.c b/lib/drand48.c index 0c40f09b15..0a9927eec7 100644 --- a/lib/drand48.c +++ b/lib/drand48.c @@ -23,9 +23,7 @@ #define C 0xB static void next(void); -static unsigned x[3] = -{X0, X1, X2}, a[3] = -{A0, A1, A2}, c = C; +static unsigned x[3] = {X0, X1, X2}, a[3] = {A0, A1, A2}, c = C; double drand48(void); @@ -49,7 +47,7 @@ next(void) ADDEQU(p[1], q[0], carry0); MUL(a[1], x[0], r); x[2] = LOW(carry0 + carry1 + CARRY(p[1], r[0]) + q[1] + r[1] + - a[0] * x[2] + a[1] * x[1] + a[2] * x[0]); + a[0] * x[2] + a[1] * x[1] + a[2] * x[0]); x[1] = LOW(p[1] + r[0]); x[0] = LOW(p[0]); } diff --git a/lib/encrypt.c b/lib/encrypt.c index f5ee0942e0..f90c4e5b12 100644 --- a/lib/encrypt.c +++ b/lib/encrypt.c @@ -1,16 +1,16 @@ /* encrypt.c - providing 56 bit DES encryption * Copyright (C) 1991 Jochen Obalek - * + * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ @@ -29,8 +29,7 @@ static char schluessel[16][KS]; -static char PC1[] = -{ +static char PC1[] = { 56, 48, 40, 32, 24, 16, 8, 0, 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, @@ -42,8 +41,7 @@ static char PC1[] = }; -static char PC2[] = -{ +static char PC2[] = { 13, 16, 10, 23, 0, 4, 2, 27, 14, 5, 20, 9, 22, 18, 11, 3, 25, 7, 15, 6, 26, 19, 12, 1, @@ -53,8 +51,7 @@ static char PC2[] = }; -static char IP[] = -{ +static char IP[] = { 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, @@ -66,8 +63,7 @@ static char IP[] = }; -static char EP[] = -{ +static char EP[] = { 7, 39, 15, 47, 23, 55, 31, 63, 6, 38, 14, 46, 22, 54, 30, 62, 5, 37, 13, 45, 21, 53, 29, 61, @@ -79,8 +75,7 @@ static char EP[] = }; -static char E0[] = -{ +static char E0[] = { 31, 0, 1, 2, 3, 4, 3, 4, 5, 6, 7, 8, 7, 8, 9, 10, 11, 12, 11, 12, 13, 14, 15, 16, @@ -93,8 +88,7 @@ static char E0[] = static char E[KS]; -static char PERM[] = -{ +static char PERM[] = { 15, 6, 19, 20, 28, 11, 27, 16, 0, 14, 22, 25, 4, 17, 30, 9, 1, 7, 23, 13, 31, 26, 2, 8, @@ -102,72 +96,71 @@ static char PERM[] = }; -static char S_BOX[][64] = -{ +static char S_BOX[][64] = { { - 14, 0, 4, 15, 13, 7, 1, 4, 2, 14, 15, 2, 11, 13, 8, 1, - 3, 10, 10, 6, 6, 12, 12, 11, 5, 9, 9, 5, 0, 3, 7, 8, - 4, 15, 1, 12, 14, 8, 8, 2, 13, 4, 6, 9, 2, 1, 11, 7, - 15, 5, 12, 11, 9, 3, 7, 14, 3, 10, 10, 0, 5, 6, 0, 13 + 14, 0, 4, 15, 13, 7, 1, 4, 2, 14, 15, 2, 11, 13, 8, 1, + 3, 10, 10, 6, 6, 12, 12, 11, 5, 9, 9, 5, 0, 3, 7, 8, + 4, 15, 1, 12, 14, 8, 8, 2, 13, 4, 6, 9, 2, 1, 11, 7, + 15, 5, 12, 11, 9, 3, 7, 14, 3, 10, 10, 0, 5, 6, 0, 13 }, { - 15, 3, 1, 13, 8, 4, 14, 7, 6, 15, 11, 2, 3, 8, 4, 14, - 9, 12, 7, 0, 2, 1, 13, 10, 12, 6, 0, 9, 5, 11, 10, 5, - 0, 13, 14, 8, 7, 10, 11, 1, 10, 3, 4, 15, 13, 4, 1, 2, - 5, 11, 8, 6, 12, 7, 6, 12, 9, 0, 3, 5, 2, 14, 15, 9 + 15, 3, 1, 13, 8, 4, 14, 7, 6, 15, 11, 2, 3, 8, 4, 14, + 9, 12, 7, 0, 2, 1, 13, 10, 12, 6, 0, 9, 5, 11, 10, 5, + 0, 13, 14, 8, 7, 10, 11, 1, 10, 3, 4, 15, 13, 4, 1, 2, + 5, 11, 8, 6, 12, 7, 6, 12, 9, 0, 3, 5, 2, 14, 15, 9 }, { - 10, 13, 0, 7, 9, 0, 14, 9, 6, 3, 3, 4, 15, 6, 5, 10, - 1, 2, 13, 8, 12, 5, 7, 14, 11, 12, 4, 11, 2, 15, 8, 1, - 13, 1, 6, 10, 4, 13, 9, 0, 8, 6, 15, 9, 3, 8, 0, 7, - 11, 4, 1, 15, 2, 14, 12, 3, 5, 11, 10, 5, 14, 2, 7, 12 + 10, 13, 0, 7, 9, 0, 14, 9, 6, 3, 3, 4, 15, 6, 5, 10, + 1, 2, 13, 8, 12, 5, 7, 14, 11, 12, 4, 11, 2, 15, 8, 1, + 13, 1, 6, 10, 4, 13, 9, 0, 8, 6, 15, 9, 3, 8, 0, 7, + 11, 4, 1, 15, 2, 14, 12, 3, 5, 11, 10, 5, 14, 2, 7, 12 }, { - 7, 13, 13, 8, 14, 11, 3, 5, 0, 6, 6, 15, 9, 0, 10, 3, - 1, 4, 2, 7, 8, 2, 5, 12, 11, 1, 12, 10, 4, 14, 15, 9, - 10, 3, 6, 15, 9, 0, 0, 6, 12, 10, 11, 1, 7, 13, 13, 8, - 15, 9, 1, 4, 3, 5, 14, 11, 5, 12, 2, 7, 8, 2, 4, 14 + 7, 13, 13, 8, 14, 11, 3, 5, 0, 6, 6, 15, 9, 0, 10, 3, + 1, 4, 2, 7, 8, 2, 5, 12, 11, 1, 12, 10, 4, 14, 15, 9, + 10, 3, 6, 15, 9, 0, 0, 6, 12, 10, 11, 1, 7, 13, 13, 8, + 15, 9, 1, 4, 3, 5, 14, 11, 5, 12, 2, 7, 8, 2, 4, 14 }, { - 2, 14, 12, 11, 4, 2, 1, 12, 7, 4, 10, 7, 11, 13, 6, 1, - 8, 5, 5, 0, 3, 15, 15, 10, 13, 3, 0, 9, 14, 8, 9, 6, - 4, 11, 2, 8, 1, 12, 11, 7, 10, 1, 13, 14, 7, 2, 8, 13, - 15, 6, 9, 15, 12, 0, 5, 9, 6, 10, 3, 4, 0, 5, 14, 3 + 2, 14, 12, 11, 4, 2, 1, 12, 7, 4, 10, 7, 11, 13, 6, 1, + 8, 5, 5, 0, 3, 15, 15, 10, 13, 3, 0, 9, 14, 8, 9, 6, + 4, 11, 2, 8, 1, 12, 11, 7, 10, 1, 13, 14, 7, 2, 8, 13, + 15, 6, 9, 15, 12, 0, 5, 9, 6, 10, 3, 4, 0, 5, 14, 3 }, { - 12, 10, 1, 15, 10, 4, 15, 2, 9, 7, 2, 12, 6, 9, 8, 5, - 0, 6, 13, 1, 3, 13, 4, 14, 14, 0, 7, 11, 5, 3, 11, 8, - 9, 4, 14, 3, 15, 2, 5, 12, 2, 9, 8, 5, 12, 15, 3, 10, - 7, 11, 0, 14, 4, 1, 10, 7, 1, 6, 13, 0, 11, 8, 6, 13 + 12, 10, 1, 15, 10, 4, 15, 2, 9, 7, 2, 12, 6, 9, 8, 5, + 0, 6, 13, 1, 3, 13, 4, 14, 14, 0, 7, 11, 5, 3, 11, 8, + 9, 4, 14, 3, 15, 2, 5, 12, 2, 9, 8, 5, 12, 15, 3, 10, + 7, 11, 0, 14, 4, 1, 10, 7, 1, 6, 13, 0, 11, 8, 6, 13 }, { - 4, 13, 11, 0, 2, 11, 14, 7, 15, 4, 0, 9, 8, 1, 13, 10, - 3, 14, 12, 3, 9, 5, 7, 12, 5, 2, 10, 15, 6, 8, 1, 6, - 1, 6, 4, 11, 11, 13, 13, 8, 12, 1, 3, 4, 7, 10, 14, 7, - 10, 9, 15, 5, 6, 0, 8, 15, 0, 14, 5, 2, 9, 3, 2, 12 + 4, 13, 11, 0, 2, 11, 14, 7, 15, 4, 0, 9, 8, 1, 13, 10, + 3, 14, 12, 3, 9, 5, 7, 12, 5, 2, 10, 15, 6, 8, 1, 6, + 1, 6, 4, 11, 11, 13, 13, 8, 12, 1, 3, 4, 7, 10, 14, 7, + 10, 9, 15, 5, 6, 0, 8, 15, 0, 14, 5, 2, 9, 3, 2, 12 }, { - 13, 1, 2, 15, 8, 13, 4, 8, 6, 10, 15, 3, 11, 7, 1, 4, - 10, 12, 9, 5, 3, 6, 14, 11, 5, 0, 0, 14, 12, 9, 7, 2, - 7, 2, 11, 1, 4, 14, 1, 7, 9, 4, 12, 10, 14, 8, 2, 13, - 0, 15, 6, 12, 10, 9, 13, 0, 15, 3, 3, 5, 5, 6, 8, 11 + 13, 1, 2, 15, 8, 13, 4, 8, 6, 10, 15, 3, 11, 7, 1, 4, + 10, 12, 9, 5, 3, 6, 14, 11, 5, 0, 0, 14, 12, 9, 7, 2, + 7, 2, 11, 1, 4, 14, 1, 7, 9, 4, 12, 10, 14, 8, 2, 13, + 0, 15, 6, 12, 10, 9, 13, 0, 15, 3, 3, 5, 5, 6, 8, 11 } }; static void perm(a, e, pc, n) - register char *a, *e; - register char *pc; - int n; +register char *a, *e; +register char *pc; +int n; { for (; n--; pc++, a++) - *a = e[*pc]; + *a = e[*pc]; } static void crypt_main(nachr_l, nachr_r, schl) - register char *nachr_l, *nachr_r; - register char *schl; +register char *nachr_l, *nachr_r; +register char *schl; { char tmp[KS]; register int sbval; @@ -176,17 +169,17 @@ crypt_main(nachr_l, nachr_r, schl) register int i, j; for (i = 0; i < 8; i++) { - for (j = 0, sbval = 0; j < 6; j++) - sbval = (sbval << 1) | (nachr_r[*e++] ^ *schl++); - sbval = S_BOX[i][sbval]; - for (tp += 4, j = 4; j--; sbval >>= 1) - *--tp = sbval & 1; - tp += 4; + for (j = 0, sbval = 0; j < 6; j++) + sbval = (sbval << 1) | (nachr_r[*e++] ^ *schl++); + sbval = S_BOX[i][sbval]; + for (tp += 4, j = 4; j--; sbval >>= 1) + *--tp = sbval & 1; + tp += 4; } e = PERM; for (i = 0; i < BS2; i++) - *nachr_l++ ^= tmp[*e++]; + *nachr_l++ ^= tmp[*e++]; } void @@ -199,16 +192,16 @@ encrypt(char *nachr, int decr) perm(tmp, nachr, IP, BS); for (i = 8; i--;) { - crypt_main(tmp, tmp + BS2, *schl); - if (decr) - schl--; - else - schl++; - crypt_main(tmp + BS2, tmp, *schl); - if (decr) - schl--; - else - schl++; + crypt_main(tmp, tmp + BS2, *schl); + if (decr) + schl--; + else + schl++; + crypt_main(tmp + BS2, tmp, *schl); + if (decr) + schl--; + else + schl++; } perm(nachr, tmp, EP, BS); @@ -227,17 +220,17 @@ setkey(char *schl) perm(tmp1, schl, PC1, IS); for (i = 0; i < 16; i++) { - shval += 1 + (ls & 1); - akt_schl = schluessel[i]; - for (j = 0; j < KS; j++) { - if ((k = PC2[j]) >= IS2) { - if ((k += shval) >= IS) - k = (k - IS2) % IS2 + IS2; - } else if ((k += shval) >= IS2) - k %= IS2; - *akt_schl++ = tmp1[k]; - } - ls >>= 1; + shval += 1 + (ls & 1); + akt_schl = schluessel[i]; + for (j = 0; j < KS; j++) { + if ((k = PC2[j]) >= IS2) { + if ((k += shval) >= IS) + k = (k - IS2) % IS2 + IS2; + } else if ((k += shval) >= IS2) + k %= IS2; + *akt_schl++ = tmp1[k]; + } + ls >>= 1; } } @@ -253,57 +246,57 @@ crypt(const char *wort, const char *salt) memset(key, 0, BS + 2); for (k = key, i = 0; i < BS; i++) { - if (!(keybyte = *wort++)) - break; - k += 7; - for (j = 0; j < 7; j++, i++) { - *--k = keybyte & 1; - keybyte >>= 1; - } - k += 8; + if (!(keybyte = *wort++)) + break; + k += 7; + for (j = 0; j < 7; j++, i++) { + *--k = keybyte & 1; + keybyte >>= 1; + } + k += 8; } setkey(key); memset(key, 0, BS + 2); for (k = E, i = 0; i < 2; i++) { - retkey[i] = keybyte = *salt++; - if (keybyte > 'Z') - keybyte -= 'a' - 'Z' - 1; - if (keybyte > '9') - keybyte -= 'A' - '9' - 1; - keybyte -= '.'; - - for (j = 0; j < 6; j++, keybyte >>= 1, k++) { - if (!(keybyte & 1)) - continue; - tmp = *k; - *k = k[24]; - k[24] = tmp; - } + retkey[i] = keybyte = *salt++; + if (keybyte > 'Z') + keybyte -= 'a' - 'Z' - 1; + if (keybyte > '9') + keybyte -= 'A' - '9' - 1; + keybyte -= '.'; + + for (j = 0; j < 6; j++, keybyte >>= 1, k++) { + if (!(keybyte & 1)) + continue; + tmp = *k; + *k = k[24]; + k[24] = tmp; + } } for (i = 0; i < 25; i++) - encrypt(key, 0); + encrypt(key, 0); for (k = key, i = 0; i < 11; i++) { - for (j = keybyte = 0; j < 6; j++) { - keybyte <<= 1; - keybyte |= *k++; - } - - keybyte += '.'; - if (keybyte > '9') - keybyte += 'A' - '9' - 1; - if (keybyte > 'Z') - keybyte += 'a' - 'Z' - 1; - retkey[i + 2] = keybyte; + for (j = keybyte = 0; j < 6; j++) { + keybyte <<= 1; + keybyte |= *k++; + } + + keybyte += '.'; + if (keybyte > '9') + keybyte += 'A' - '9' - 1; + if (keybyte > 'Z') + keybyte += 'a' - 'Z' - 1; + retkey[i + 2] = keybyte; } retkey[i + 2] = 0; if (!retkey[1]) - retkey[1] = *retkey; + retkey[1] = *retkey; return retkey; } diff --git a/lib/getaddrinfo.c b/lib/getaddrinfo.c index 3cecfb1e83..5e32cd8dba 100644 --- a/lib/getaddrinfo.c +++ b/lib/getaddrinfo.c @@ -83,267 +83,257 @@ #include "inet_pton.h" static struct addrinfo * -dup_addrinfo (struct addrinfo *info, void *addr, size_t addrlen) -{ - struct addrinfo *ret; - - ret = malloc (sizeof (struct addrinfo)); - if (ret == NULL) - return NULL; - memcpy (ret, info, sizeof (struct addrinfo)); - ret->ai_addr = malloc (addrlen); - if (ret->ai_addr == NULL) - { - free (ret); - return NULL; + dup_addrinfo (struct addrinfo *info, void *addr, size_t addrlen) { + struct addrinfo *ret; + + ret = malloc (sizeof (struct addrinfo)); + if (ret == NULL) + return NULL; + memcpy (ret, info, sizeof (struct addrinfo)); + ret->ai_addr = malloc (addrlen); + if (ret->ai_addr == NULL) { + free (ret); + return NULL; } - memcpy (ret->ai_addr, addr, addrlen); - ret->ai_addrlen = addrlen; - return ret; + memcpy (ret->ai_addr, addr, addrlen); + ret->ai_addrlen = addrlen; + return ret; } int xgetaddrinfo (const char *nodename, const char *servname, - const struct addrinfo *hints, struct addrinfo **res) + const struct addrinfo *hints, struct addrinfo **res) { - struct hostent *hp; - struct servent *servent; - const char *socktype; - int port; - struct addrinfo hint, result; - struct addrinfo *ai, *sai, *eai; - char **addrs; - - if (servname == NULL && nodename == NULL) - return EAI_NONAME; - - memset (&result, 0, sizeof result); - - /* default for hints */ - if (hints == NULL) - { - memset (&hint, 0, sizeof hint); - hint.ai_family = PF_UNSPEC; - hints = &hint; + struct hostent *hp; + struct servent *servent; + const char *socktype; + int port; + struct addrinfo hint, result; + struct addrinfo *ai, *sai, *eai; + char **addrs; + + if (servname == NULL && nodename == NULL) + return EAI_NONAME; + + memset (&result, 0, sizeof result); + + /* default for hints */ + if (hints == NULL) { + memset (&hint, 0, sizeof hint); + hint.ai_family = PF_UNSPEC; + hints = &hint; } - if (servname == NULL) - port = 0; - else { - /* check for tcp or udp sockets only */ - if (hints->ai_socktype == SOCK_STREAM) - socktype = "tcp"; - else if (hints->ai_socktype == SOCK_DGRAM) - socktype = "udp"; - else - return EAI_SERVICE; - result.ai_socktype = hints->ai_socktype; - - /* Note: maintain port in host byte order to make debugging easier */ - if (isdigit (*servname)) - port = strtol (servname, NULL, 10); - else if ((servent = getservbyname (servname, socktype)) != NULL) - port = ntohs (servent->s_port); - else - return EAI_NONAME; - } - - /* if nodename == NULL refer to the local host for a client or any - for a server */ - if (nodename == NULL) - { - struct sockaddr_in sin; - - /* check protocol family is PF_UNSPEC or PF_INET - could try harder - for IPv6 but that's more code than I'm prepared to write */ - if (hints->ai_family == PF_UNSPEC || hints->ai_family == PF_INET) - result.ai_family = AF_INET; - else - return EAI_FAMILY; - - sin.sin_family = result.ai_family; - sin.sin_port = htons (port); - if (hints->ai_flags & AI_PASSIVE) - sin.sin_addr.s_addr = htonl (INADDR_ANY); - else - sin.sin_addr.s_addr = htonl (INADDR_LOOPBACK); - /* Duplicate result and addr and return */ - *res = dup_addrinfo (&result, &sin, sizeof sin); - return (*res == NULL) ? EAI_MEMORY : 0; + if (servname == NULL) + port = 0; + else { + /* check for tcp or udp sockets only */ + if (hints->ai_socktype == SOCK_STREAM) + socktype = "tcp"; + else if (hints->ai_socktype == SOCK_DGRAM) + socktype = "udp"; + else + return EAI_SERVICE; + result.ai_socktype = hints->ai_socktype; + + /* Note: maintain port in host byte order to make debugging easier */ + if (isdigit (*servname)) + port = strtol (servname, NULL, 10); + else if ((servent = getservbyname (servname, socktype)) != NULL) + port = ntohs (servent->s_port); + else + return EAI_NONAME; } - /* If AI_NUMERIC is specified, use xinet_pton to translate numbers and - dots notation. */ - if (hints->ai_flags & AI_NUMERICHOST) - { - struct sockaddr_in sin; - - /* check protocol family is PF_UNSPEC or PF_INET */ - if (hints->ai_family == PF_UNSPEC || hints->ai_family == PF_INET) - result.ai_family = AF_INET; - else - return EAI_FAMILY; - - sin.sin_family = result.ai_family; - sin.sin_port = htons (port); - if (xinet_pton(result.ai_family, nodename, &sin.sin_addr)) - return EAI_NONAME; - sin.sin_addr.s_addr = inet_addr (nodename); - /* Duplicate result and addr and return */ - *res = dup_addrinfo (&result, &sin, sizeof sin); - return (*res == NULL) ? EAI_MEMORY : 0; + /* if nodename == NULL refer to the local host for a client or any + for a server */ + if (nodename == NULL) { + struct sockaddr_in sin; + + /* check protocol family is PF_UNSPEC or PF_INET - could try harder + for IPv6 but that's more code than I'm prepared to write */ + if (hints->ai_family == PF_UNSPEC || hints->ai_family == PF_INET) + result.ai_family = AF_INET; + else + return EAI_FAMILY; + + sin.sin_family = result.ai_family; + sin.sin_port = htons (port); + if (hints->ai_flags & AI_PASSIVE) + sin.sin_addr.s_addr = htonl (INADDR_ANY); + else + sin.sin_addr.s_addr = htonl (INADDR_LOOPBACK); + /* Duplicate result and addr and return */ + *res = dup_addrinfo (&result, &sin, sizeof sin); + return (*res == NULL) ? EAI_MEMORY : 0; + } + + /* If AI_NUMERIC is specified, use xinet_pton to translate numbers and + dots notation. */ + if (hints->ai_flags & AI_NUMERICHOST) { + struct sockaddr_in sin; + + /* check protocol family is PF_UNSPEC or PF_INET */ + if (hints->ai_family == PF_UNSPEC || hints->ai_family == PF_INET) + result.ai_family = AF_INET; + else + return EAI_FAMILY; + + sin.sin_family = result.ai_family; + sin.sin_port = htons (port); + if (xinet_pton(result.ai_family, nodename, &sin.sin_addr)) + return EAI_NONAME; + sin.sin_addr.s_addr = inet_addr (nodename); + /* Duplicate result and addr and return */ + *res = dup_addrinfo (&result, &sin, sizeof sin); + return (*res == NULL) ? EAI_MEMORY : 0; } - h_errno = 0; - errno = 0; - hp = gethostbyname(nodename); - if (hp == NULL) - { + h_errno = 0; + errno = 0; + hp = gethostbyname(nodename); + if (hp == NULL) { #ifdef EAI_SYSTEM - if (errno != 0) { - return EAI_SYSTEM; - } + if (errno != 0) { + return EAI_SYSTEM; + } #endif - switch (h_errno) - { - case HOST_NOT_FOUND: return EAI_NODATA; - case NO_DATA: return EAI_NODATA; + switch (h_errno) { + case HOST_NOT_FOUND: + return EAI_NODATA; + case NO_DATA: + return EAI_NODATA; #if defined(NO_ADDRESS) && NO_ADDRESS != NO_DATA - case NO_ADDRESS: return EAI_NODATA; + case NO_ADDRESS: + return EAI_NODATA; #endif - case NO_RECOVERY: return EAI_FAIL; - case TRY_AGAIN: return EAI_AGAIN; - default: return EAI_FAIL; + case NO_RECOVERY: + return EAI_FAIL; + case TRY_AGAIN: + return EAI_AGAIN; + default: + return EAI_FAIL; } - return EAI_FAIL; + return EAI_FAIL; } - /* Check that the address family is acceptable. - */ - switch (hp->h_addrtype) - { + /* Check that the address family is acceptable. + */ + switch (hp->h_addrtype) { case AF_INET: - if (!(hints->ai_family == PF_UNSPEC || hints->ai_family == PF_INET)) - return EAI_FAMILY; - break; + if (!(hints->ai_family == PF_UNSPEC || hints->ai_family == PF_INET)) + return EAI_FAMILY; + break; #if USE_IPV6 case AF_INET6: - if (!(hints->ai_family == PF_UNSPEC || hints->ai_family == PF_INET6)) - return EAI_FAMILY; - break; + if (!(hints->ai_family == PF_UNSPEC || hints->ai_family == PF_INET6)) + return EAI_FAMILY; + break; #endif default: - return EAI_FAMILY; + return EAI_FAMILY; } - /* For each element pointed to by hp, create an element in the - result linked list. */ - sai = eai = NULL; - for (addrs = hp->h_addr_list; *addrs != NULL; addrs++) - { - struct sockaddr sa; - size_t addrlen; - - if (hp->h_length < 1) - continue; - sa.sa_family = hp->h_addrtype; - switch (hp->h_addrtype) - { + /* For each element pointed to by hp, create an element in the + result linked list. */ + sai = eai = NULL; + for (addrs = hp->h_addr_list; *addrs != NULL; addrs++) { + struct sockaddr sa; + size_t addrlen; + + if (hp->h_length < 1) + continue; + sa.sa_family = hp->h_addrtype; + switch (hp->h_addrtype) { case AF_INET: - ((struct sockaddr_in *) &sa)->sin_port = htons (port); - memcpy (&((struct sockaddr_in *) &sa)->sin_addr, - *addrs, hp->h_length); - addrlen = sizeof (struct sockaddr_in); - break; + ((struct sockaddr_in *) &sa)->sin_port = htons (port); + memcpy (&((struct sockaddr_in *) &sa)->sin_addr, + *addrs, hp->h_length); + addrlen = sizeof (struct sockaddr_in); + break; #if USE_IPV6 case AF_INET6: #if SIN6_LEN - ((struct sockaddr_in6 *) &sa)->sin6_len = hp->h_length; + ((struct sockaddr_in6 *) &sa)->sin6_len = hp->h_length; #endif - ((struct sockaddr_in6 *) &sa)->sin6_port = htons (port); - memcpy (&((struct sockaddr_in6 *) &sa)->sin6_addr, - *addrs, hp->h_length); - addrlen = sizeof (struct sockaddr_in6); - break; + ((struct sockaddr_in6 *) &sa)->sin6_port = htons (port); + memcpy (&((struct sockaddr_in6 *) &sa)->sin6_addr, + *addrs, hp->h_length); + addrlen = sizeof (struct sockaddr_in6); + break; #endif default: - continue; + continue; } - result.ai_family = hp->h_addrtype; - ai = dup_addrinfo (&result, &sa, addrlen); - if (ai == NULL) - { - xfreeaddrinfo (sai); - return EAI_MEMORY; + result.ai_family = hp->h_addrtype; + ai = dup_addrinfo (&result, &sa, addrlen); + if (ai == NULL) { + xfreeaddrinfo (sai); + return EAI_MEMORY; } - if (sai == NULL) - sai = ai; - else - eai->ai_next = ai; - eai = ai; + if (sai == NULL) + sai = ai; + else + eai->ai_next = ai; + eai = ai; } - if (sai == NULL) - { - return EAI_NODATA; + if (sai == NULL) { + return EAI_NODATA; } - - if (hints->ai_flags & AI_CANONNAME) - { - sai->ai_canonname = malloc (strlen (hp->h_name) + 1); - if (sai->ai_canonname == NULL) - { - xfreeaddrinfo (sai); - return EAI_MEMORY; + + if (hints->ai_flags & AI_CANONNAME) { + sai->ai_canonname = malloc (strlen (hp->h_name) + 1); + if (sai->ai_canonname == NULL) { + xfreeaddrinfo (sai); + return EAI_MEMORY; } - strcpy (sai->ai_canonname, hp->h_name); + strcpy (sai->ai_canonname, hp->h_name); } - *res = sai; - return 0; + *res = sai; + return 0; } void xfreeaddrinfo (struct addrinfo *ai) { - struct addrinfo *next; - - while (ai != NULL) - { - next = ai->ai_next; - if (ai->ai_canonname != NULL) - free (ai->ai_canonname); - if (ai->ai_addr != NULL) - free (ai->ai_addr); - free (ai); - ai = next; + struct addrinfo *next; + + while (ai != NULL) { + next = ai->ai_next; + if (ai->ai_canonname != NULL) + free (ai->ai_canonname); + if (ai->ai_addr != NULL) + free (ai->ai_addr); + free (ai); + ai = next; } } const char * xgai_strerror (int ecode) { - static const char *eai_descr[] = - { - "no error", - "address family for nodename not supported", /* EAI_ADDRFAMILY */ - "temporary failure in name resolution", /* EAI_AGAIN */ - "invalid value for ai_flags", /* EAI_BADFLAGS */ - "non-recoverable failure in name resolution", /* EAI_FAIL */ - "ai_family not supported", /* EAI_FAMILY */ - "memory allocation failure", /* EAI_MEMORY */ - "no address associated with nodename", /* EAI_NODATA */ - "nodename nor servname provided, or not known", /* EAI_NONAME */ - "servname not supported for ai_socktype", /* EAI_SERVICE */ - "ai_socktype not supported", /* EAI_SOCKTYPE */ - "system error returned in errno", /* EAI_SYSTEM */ - "argument buffer overflow", /* EAI_OVERFLOW */ + static const char *eai_descr[] = { + "no error", + "address family for nodename not supported", /* EAI_ADDRFAMILY */ + "temporary failure in name resolution", /* EAI_AGAIN */ + "invalid value for ai_flags", /* EAI_BADFLAGS */ + "non-recoverable failure in name resolution", /* EAI_FAIL */ + "ai_family not supported", /* EAI_FAMILY */ + "memory allocation failure", /* EAI_MEMORY */ + "no address associated with nodename", /* EAI_NODATA */ + "nodename nor servname provided, or not known", /* EAI_NONAME */ + "servname not supported for ai_socktype", /* EAI_SERVICE */ + "ai_socktype not supported", /* EAI_SOCKTYPE */ + "system error returned in errno", /* EAI_SYSTEM */ + "argument buffer overflow", /* EAI_OVERFLOW */ }; - if (ecode < 0 || ecode > (int) (sizeof eai_descr/ sizeof eai_descr[0])) - return "unknown error"; - return eai_descr[ecode]; + if (ecode < 0 || ecode > (int) (sizeof eai_descr/ sizeof eai_descr[0])) + return "unknown error"; + return eai_descr[ecode]; } #endif /* HAVE_GETADDRINFO */ diff --git a/lib/getfullhostname.c b/lib/getfullhostname.c index d3e1a45b6e..212037ccbb 100644 --- a/lib/getfullhostname.c +++ b/lib/getfullhostname.c @@ -1,7 +1,7 @@ /* * $Id: getfullhostname.c,v 1.20 2003/01/23 00:37:01 robertc Exp $ * - * DEBUG: + * DEBUG: * AUTHOR: Harvest Derived * * SQUID Web Proxy Cache http://www.squid-cache.org/ @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -95,9 +95,9 @@ getfullhostname(void) static char buf[RFC2181_MAXHOSTNAMELEN + 1]; if (gethostname(buf, RFC2181_MAXHOSTNAMELEN) < 0) - return NULL; + return NULL; /** \todo convert this to a xgetaddrinfo() call */ if ((hp = gethostbyname(buf)) != NULL) - xstrncpy(buf, hp->h_name, RFC2181_MAXHOSTNAMELEN); + xstrncpy(buf, hp->h_name, RFC2181_MAXHOSTNAMELEN); return buf; } diff --git a/lib/getnameinfo.c b/lib/getnameinfo.c index d17c053c0d..82b3da8af8 100644 --- a/lib/getnameinfo.c +++ b/lib/getnameinfo.c @@ -129,300 +129,298 @@ #endif static const struct afd { - int a_af; - int a_addrlen; - int a_socklen; - int a_off; - int a_portoff; + int a_af; + int a_addrlen; + int a_socklen; + int a_off; + int a_portoff; } afdl [] = { #ifdef INET6 - {PF_INET6, sizeof(struct in6_addr), sizeof(struct sockaddr_in6), - offsetof(struct sockaddr_in6, sin6_addr), - offsetof(struct sockaddr_in6, sin6_port)}, + {PF_INET6, sizeof(struct in6_addr), sizeof(struct sockaddr_in6), + offsetof(struct sockaddr_in6, sin6_addr), + offsetof(struct sockaddr_in6, sin6_port)}, #endif - {PF_INET, sizeof(struct in_addr), sizeof(struct sockaddr_in), - offsetof(struct sockaddr_in, sin_addr), - offsetof(struct sockaddr_in, sin_port)}, - {0, 0, 0, 0, 0}, + {PF_INET, sizeof(struct in_addr), sizeof(struct sockaddr_in), + offsetof(struct sockaddr_in, sin_addr), + offsetof(struct sockaddr_in, sin_port)}, + {0, 0, 0, 0, 0}, }; #ifdef INET6 static int ip6_parsenumeric __P((const struct sockaddr *, const char *, char *, - size_t, int)); + size_t, int)); static int ip6_sa2str __P((const struct sockaddr_in6 *, char *, size_t, int)); #endif int xgetnameinfo(sa, salen, host, hostlen, serv, servlen, flags) - const struct sockaddr *sa; - socklen_t salen; - char *host; - size_t hostlen; - char *serv; - size_t servlen; - int flags; +const struct sockaddr *sa; +socklen_t salen; +char *host; +size_t hostlen; +char *serv; +size_t servlen; +int flags; { - const struct afd *afd; - struct servent *sp; - struct hostent *hp; - u_short port; - int family, i; - const char *addr; - u_int32_t v4a; - int h_error; - char numserv[512]; - - if (sa == NULL) - return EAI_FAIL; + const struct afd *afd; + struct servent *sp; + struct hostent *hp; + u_short port; + int family, i; + const char *addr; + u_int32_t v4a; + int h_error; + char numserv[512]; + + if (sa == NULL) + return EAI_FAIL; #ifdef HAVE_SA_LEN /*XXX*/ - if (sa->sa_len != salen) - return EAI_FAIL; + if (sa->sa_len != salen) + return EAI_FAIL; #endif - family = sa->sa_family; - for (i = 0; afdl[i].a_af; i++) - if (afdl[i].a_af == family) { - afd = &afdl[i]; - goto found; - } - return EAI_FAMILY; - - found: - if (salen != afd->a_socklen) - return EAI_FAIL; - - /* network byte order */ - memcpy(&port, (const char *)sa + afd->a_portoff, sizeof(port)); - addr = (const char *)sa + afd->a_off; - - if (serv == NULL || servlen == 0) { - /* - * do nothing in this case. - * in case you are wondering if "&&" is more correct than - * "||" here: RFC3493 says that serv == NULL OR servlen == 0 - * means that the caller does not want the result. - */ - } else { - if (flags & NI_NUMERICSERV) - sp = NULL; - else { - sp = getservbyport(port, - (flags & NI_DGRAM) ? "udp" : "tcp"); - } - if (sp) { - if (strlen(sp->s_name) + 1 > servlen) - return EAI_OVERFLOW; - strncpy(serv, sp->s_name, servlen); - } else { - snprintf(numserv, sizeof(numserv), "%u", ntohs(port)); - if (strlen(numserv) + 1 > servlen) - return EAI_OVERFLOW; - strncpy(serv, numserv, servlen); - } - } - - switch (sa->sa_family) { - case AF_INET: - v4a = (u_int32_t) - ntohl(((const struct sockaddr_in *)sa)->sin_addr.s_addr); - if (IN_MULTICAST(v4a) || IN_EXPERIMENTAL(v4a)) - flags |= NI_NUMERICHOST; - v4a >>= IN_CLASSA_NSHIFT; - if (v4a == 0) - flags |= NI_NUMERICHOST; - break; + family = sa->sa_family; + for (i = 0; afdl[i].a_af; i++) + if (afdl[i].a_af == family) { + afd = &afdl[i]; + goto found; + } + return EAI_FAMILY; + +found: + if (salen != afd->a_socklen) + return EAI_FAIL; + + /* network byte order */ + memcpy(&port, (const char *)sa + afd->a_portoff, sizeof(port)); + addr = (const char *)sa + afd->a_off; + + if (serv == NULL || servlen == 0) { + /* + * do nothing in this case. + * in case you are wondering if "&&" is more correct than + * "||" here: RFC3493 says that serv == NULL OR servlen == 0 + * means that the caller does not want the result. + */ + } else { + if (flags & NI_NUMERICSERV) + sp = NULL; + else { + sp = getservbyport(port, + (flags & NI_DGRAM) ? "udp" : "tcp"); + } + if (sp) { + if (strlen(sp->s_name) + 1 > servlen) + return EAI_OVERFLOW; + strncpy(serv, sp->s_name, servlen); + } else { + snprintf(numserv, sizeof(numserv), "%u", ntohs(port)); + if (strlen(numserv) + 1 > servlen) + return EAI_OVERFLOW; + strncpy(serv, numserv, servlen); + } + } + + switch (sa->sa_family) { + case AF_INET: + v4a = (u_int32_t) + ntohl(((const struct sockaddr_in *)sa)->sin_addr.s_addr); + if (IN_MULTICAST(v4a) || IN_EXPERIMENTAL(v4a)) + flags |= NI_NUMERICHOST; + v4a >>= IN_CLASSA_NSHIFT; + if (v4a == 0) + flags |= NI_NUMERICHOST; + break; #ifdef INET6 - case AF_INET6: - { - const struct sockaddr_in6 *sin6; - sin6 = (const struct sockaddr_in6 *)sa; - switch (sin6->sin6_addr.s6_addr[0]) { - case 0x00: - if (IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) - ; - else if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr)) - ; - else - flags |= NI_NUMERICHOST; - break; - default: - if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) - flags |= NI_NUMERICHOST; - else if (IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr)) - flags |= NI_NUMERICHOST; - break; - } - } - break; + case AF_INET6: { + const struct sockaddr_in6 *sin6; + sin6 = (const struct sockaddr_in6 *)sa; + switch (sin6->sin6_addr.s6_addr[0]) { + case 0x00: + if (IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) + ; + else if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr)) + ; + else + flags |= NI_NUMERICHOST; + break; + default: + if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) + flags |= NI_NUMERICHOST; + else if (IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr)) + flags |= NI_NUMERICHOST; + break; + } + } + break; #endif - } - if (host == NULL || hostlen == 0) { - /* - * do nothing in this case. - * in case you are wondering if "&&" is more correct than - * "||" here: RFC3493 says that host == NULL or hostlen == 0 - * means that the caller does not want the result. - */ - } else if (flags & NI_NUMERICHOST) { - /* NUMERICHOST and NAMEREQD conflicts with each other */ - if (flags & NI_NAMEREQD) - return EAI_NONAME; - - goto numeric; - } else { + } + if (host == NULL || hostlen == 0) { + /* + * do nothing in this case. + * in case you are wondering if "&&" is more correct than + * "||" here: RFC3493 says that host == NULL or hostlen == 0 + * means that the caller does not want the result. + */ + } else if (flags & NI_NUMERICHOST) { + /* NUMERICHOST and NAMEREQD conflicts with each other */ + if (flags & NI_NAMEREQD) + return EAI_NONAME; + + goto numeric; + } else { #ifdef USE_GETIPNODEBY - hp = getipnodebyaddr(addr, afd->a_addrlen, afd->a_af, &h_error); + hp = getipnodebyaddr(addr, afd->a_addrlen, afd->a_af, &h_error); #else - hp = gethostbyaddr(addr, afd->a_addrlen, afd->a_af); + hp = gethostbyaddr(addr, afd->a_addrlen, afd->a_af); #ifdef HAVE_H_ERRNO - h_error = h_errno; + h_error = h_errno; #else - h_error = EINVAL; + h_error = EINVAL; #endif #endif - if (hp) { + if (hp) { #if 0 - if (flags & NI_NOFQDN) { - /* - * According to RFC3493 section 6.2, NI_NOFQDN - * means "node name portion of the FQDN shall - * be returned for local hosts." The following - * code tries to implement it by returning the - * first label (the part before the first - * period) of the FQDN. However, it is not - * clear if this always makes sense, since the - * given address may be outside of "local - * hosts." Due to the unclear description, we - * disable the code in this implementation. - */ - char *p; - p = strchr(hp->h_name, '.'); - if (p) - *p = '\0'; - } + if (flags & NI_NOFQDN) { + /* + * According to RFC3493 section 6.2, NI_NOFQDN + * means "node name portion of the FQDN shall + * be returned for local hosts." The following + * code tries to implement it by returning the + * first label (the part before the first + * period) of the FQDN. However, it is not + * clear if this always makes sense, since the + * given address may be outside of "local + * hosts." Due to the unclear description, we + * disable the code in this implementation. + */ + char *p; + p = strchr(hp->h_name, '.'); + if (p) + *p = '\0'; + } #endif - if (strlen(hp->h_name) + 1 > hostlen) { + if (strlen(hp->h_name) + 1 > hostlen) { #ifdef USE_GETIPNODEBY - freehostent(hp); + freehostent(hp); #endif - return EAI_OVERFLOW; - } - strncpy(host, hp->h_name, hostlen); + return EAI_OVERFLOW; + } + strncpy(host, hp->h_name, hostlen); #ifdef USE_GETIPNODEBY - freehostent(hp); + freehostent(hp); #endif - } else { - if (flags & NI_NAMEREQD) - return EAI_NONAME; + } else { + if (flags & NI_NAMEREQD) + return EAI_NONAME; - numeric: - switch(afd->a_af) { +numeric: + switch (afd->a_af) { #ifdef INET6 - case AF_INET6: - { - int error; - - if ((error = ip6_parsenumeric(sa, addr, host, - hostlen, - flags)) != 0) - return(error); - break; - } + case AF_INET6: { + int error; + + if ((error = ip6_parsenumeric(sa, addr, host, + hostlen, + flags)) != 0) + return(error); + break; + } #endif - default: - if (xinet_ntop(afd->a_af, addr, host, - hostlen) == NULL) - return EAI_SYSTEM; - break; - } - } - } - return(0); + default: + if (xinet_ntop(afd->a_af, addr, host, + hostlen) == NULL) + return EAI_SYSTEM; + break; + } + } + } + return(0); } #ifdef INET6 static int ip6_parsenumeric(sa, addr, host, hostlen, flags) - const struct sockaddr *sa; - const char *addr; - char *host; - size_t hostlen; - int flags; +const struct sockaddr *sa; +const char *addr; +char *host; +size_t hostlen; +int flags; { - int numaddrlen; - char numaddr[512]; - - if (xinet_ntop(AF_INET6, addr, numaddr, sizeof(numaddr)) == NULL) - return EAI_SYSTEM; - - numaddrlen = strlen(numaddr); - if (numaddrlen + 1 > hostlen) /* don't forget terminator */ - return EAI_OVERFLOW; - strncpy(host, numaddr, hostlen); - - if (((const struct sockaddr_in6 *)sa)->sin6_scope_id) { - char zonebuf[SQUIDHOSTNAMELEN]; - int zonelen; - - zonelen = ip6_sa2str( - (const struct sockaddr_in6 *)(const void *)sa, - zonebuf, sizeof(zonebuf), flags); - if (zonelen < 0) - return EAI_OVERFLOW; - if (zonelen + 1 + numaddrlen + 1 > hostlen) - return EAI_OVERFLOW; - - /* construct */ - memcpy(host + numaddrlen + 1, zonebuf, - (size_t)zonelen); - host[numaddrlen] = SCOPE_DELIMITER; - host[numaddrlen + 1 + zonelen] = '\0'; - } - - return 0; + int numaddrlen; + char numaddr[512]; + + if (xinet_ntop(AF_INET6, addr, numaddr, sizeof(numaddr)) == NULL) + return EAI_SYSTEM; + + numaddrlen = strlen(numaddr); + if (numaddrlen + 1 > hostlen) /* don't forget terminator */ + return EAI_OVERFLOW; + strncpy(host, numaddr, hostlen); + + if (((const struct sockaddr_in6 *)sa)->sin6_scope_id) { + char zonebuf[SQUIDHOSTNAMELEN]; + int zonelen; + + zonelen = ip6_sa2str( + (const struct sockaddr_in6 *)(const void *)sa, + zonebuf, sizeof(zonebuf), flags); + if (zonelen < 0) + return EAI_OVERFLOW; + if (zonelen + 1 + numaddrlen + 1 > hostlen) + return EAI_OVERFLOW; + + /* construct */ + memcpy(host + numaddrlen + 1, zonebuf, + (size_t)zonelen); + host[numaddrlen] = SCOPE_DELIMITER; + host[numaddrlen + 1 + zonelen] = '\0'; + } + + return 0; } /* ARGSUSED */ static int ip6_sa2str(sa6, buf, bufsiz, flags) - const struct sockaddr_in6 *sa6; - char *buf; - size_t bufsiz; - int flags; +const struct sockaddr_in6 *sa6; +char *buf; +size_t bufsiz; +int flags; { - unsigned int ifindex; - const struct in6_addr *a6; - int n; + unsigned int ifindex; + const struct in6_addr *a6; + int n; - ifindex = (unsigned int)sa6->sin6_scope_id; - a6 = &sa6->sin6_addr; + ifindex = (unsigned int)sa6->sin6_scope_id; + a6 = &sa6->sin6_addr; #ifdef NI_NUMERICSCOPE - if ((flags & NI_NUMERICSCOPE) != 0) { - n = snprintf(buf, bufsiz, "%u", sa6->sin6_scope_id); - if (n < 0 || n >= bufsiz) - return -1; - else - return n; - } + if ((flags & NI_NUMERICSCOPE) != 0) { + n = snprintf(buf, bufsiz, "%u", sa6->sin6_scope_id); + if (n < 0 || n >= bufsiz) + return -1; + else + return n; + } #endif - /* if_indextoname() does not take buffer size. not a good api... */ - if ((IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6) || - IN6_IS_ADDR_MC_NODELOCAL(a6)) && bufsiz >= IF_NAMESIZE) { - char *p = if_indextoname(ifindex, buf); - if (p) - return (strlen(p)); - } - - /* last resort */ - n = snprintf(buf, bufsiz, "%u", sa6->sin6_scope_id); - if (n < 0 || n >= bufsiz) - return -1; - else - return n; + /* if_indextoname() does not take buffer size. not a good api... */ + if ((IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6) || + IN6_IS_ADDR_MC_NODELOCAL(a6)) && bufsiz >= IF_NAMESIZE) { + char *p = if_indextoname(ifindex, buf); + if (p) + return (strlen(p)); + } + + /* last resort */ + n = snprintf(buf, bufsiz, "%u", sa6->sin6_scope_id); + if (n < 0 || n >= bufsiz) + return -1; + else + return n; } #endif /* INET6 */ #endif diff --git a/lib/getopt.c b/lib/getopt.c index f5d4a51f27..1574e4d79f 100644 --- a/lib/getopt.c +++ b/lib/getopt.c @@ -36,9 +36,9 @@ static char sccsid[] = "@(#)getopt.c 8.3 (Berkeley) 4/27/95"; #include int opterr = 1, /* if error message should be printed */ - optind = 1, /* index into parent argv vector */ - optopt, /* character checked for validity */ - optreset; /* reset getopt */ + optind = 1, /* index into parent argv vector */ + optopt, /* character checked for validity */ + optreset; /* reset getopt */ char *optarg; /* argument associated with option */ #define BADCH (int)'?' @@ -51,60 +51,60 @@ char *optarg; /* argument associated with option */ */ int getopt(nargc, nargv, ostr) - int nargc; - char *const *nargv; - const char *ostr; +int nargc; +char *const *nargv; +const char *ostr; { static char *place = EMSG; /* option letter processing */ char *oli; /* option letter list index */ if (optreset || !*place) { /* update scanning pointer */ - optreset = 0; - if (optind >= nargc || *(place = nargv[optind]) != '-') { - place = EMSG; - return (-1); - } - if (place[1] && *++place == '-') { /* found "--" */ - ++optind; - place = EMSG; - return (-1); - } + optreset = 0; + if (optind >= nargc || *(place = nargv[optind]) != '-') { + place = EMSG; + return (-1); + } + if (place[1] && *++place == '-') { /* found "--" */ + ++optind; + place = EMSG; + return (-1); + } } /* option letter okay? */ if ((optopt = (int) *place++) == (int) ':' || - !(oli = strchr(ostr, optopt))) { - /* - * if the user didn't specify '-' as an option, - * assume it means -1. - */ - if (optopt == (int) '-') - return (-1); - if (!*place) - ++optind; - if (opterr && *ostr != ':') - (void) fprintf(stderr, - "%s: illegal option -- %c\n", __FILE__, optopt); - return (BADCH); + !(oli = strchr(ostr, optopt))) { + /* + * if the user didn't specify '-' as an option, + * assume it means -1. + */ + if (optopt == (int) '-') + return (-1); + if (!*place) + ++optind; + if (opterr && *ostr != ':') + (void) fprintf(stderr, + "%s: illegal option -- %c\n", __FILE__, optopt); + return (BADCH); } if (*++oli != ':') { /* don't need argument */ - optarg = NULL; - if (!*place) - ++optind; + optarg = NULL; + if (!*place) + ++optind; } else { /* need an argument */ - if (*place) /* no white space */ - optarg = place; - else if (nargc <= ++optind) { /* no arg */ - place = EMSG; - if (*ostr == ':') - return (BADARG); - if (opterr) - (void) fprintf(stderr, - "%s: option requires an argument -- %c\n", - __FILE__, optopt); - return (BADCH); - } else /* white space */ - optarg = nargv[optind]; - place = EMSG; - ++optind; + if (*place) /* no white space */ + optarg = place; + else if (nargc <= ++optind) { /* no arg */ + place = EMSG; + if (*ostr == ':') + return (BADARG); + if (opterr) + (void) fprintf(stderr, + "%s: option requires an argument -- %c\n", + __FILE__, optopt); + return (BADCH); + } else /* white space */ + optarg = nargv[optind]; + place = EMSG; + ++optind; } return (optopt); /* dump back option letter */ } diff --git a/lib/hash.c b/lib/hash.c index 0ff9c86a9b..5501233007 100644 --- a/lib/hash.c +++ b/lib/hash.c @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -73,8 +73,8 @@ hash_string(const void *data, unsigned int size) unsigned int j = 0; unsigned int i = 0; while (*s) { - j++; - n ^= 271 * (unsigned) *s++; + j++; + n ^= 271 * (unsigned) *s++; } i = n ^ (j * 271); return i % size; @@ -101,37 +101,37 @@ hash4(const void *data, unsigned int size) loop = len >> 3; switch (len & (8 - 1)) { case 0: - break; + break; case 7: - HASH4; - /* FALLTHROUGH */ + HASH4; + /* FALLTHROUGH */ case 6: - HASH4; - /* FALLTHROUGH */ + HASH4; + /* FALLTHROUGH */ case 5: - HASH4; - /* FALLTHROUGH */ + HASH4; + /* FALLTHROUGH */ case 4: - HASH4; - /* FALLTHROUGH */ + HASH4; + /* FALLTHROUGH */ case 3: - HASH4; - /* FALLTHROUGH */ + HASH4; + /* FALLTHROUGH */ case 2: - HASH4; - /* FALLTHROUGH */ + HASH4; + /* FALLTHROUGH */ case 1: - HASH4; + HASH4; } while (loop--) { - HASH4; - HASH4; - HASH4; - HASH4; - HASH4; - HASH4; - HASH4; - HASH4; + HASH4; + HASH4; + HASH4; + HASH4; + HASH4; + HASH4; + HASH4; + HASH4; } return h % size; } @@ -146,9 +146,9 @@ hash_create(HASHCMP * cmp_func, int hash_sz, HASHHASH * hash_func) { hash_table *hid = xcalloc(1, sizeof(hash_table)); if (!hash_sz) - hid->size = (unsigned int) DEFAULT_HASH_SIZE; + hid->size = (unsigned int) DEFAULT_HASH_SIZE; else - hid->size = (unsigned int) hash_sz; + hid->size = (unsigned int) hash_sz; /* allocate and null the buckets */ hid->buckets = xcalloc(hid->size, sizeof(hash_link *)); hid->cmp = cmp_func; @@ -160,7 +160,7 @@ hash_create(HASHCMP * cmp_func, int hash_sz, HASHHASH * hash_func) /* * hash_join - joins a hash_link under its key lnk->key - * into the hash table 'hid'. + * into the hash table 'hid'. * * It does not copy any data into the hash table, only links pointers. */ @@ -188,11 +188,11 @@ hash_lookup(hash_table * hid, const void *k) assert(k != NULL); b = hid->hash(k, hid->size); for (walker = hid->buckets[b]; walker != NULL; walker = walker->next) { - if ((hid->cmp) (k, walker->key) == 0) { - PROF_stop(hash_lookup); - return (walker); - } - assert(walker != walker->next); + if ((hid->cmp) (k, walker->key) == 0) { + PROF_stop(hash_lookup); + return (walker); + } + assert(walker != walker->next); } PROF_stop(hash_lookup); return NULL; @@ -202,7 +202,7 @@ static void hash_next_bucket(hash_table * hid) { while (hid->next == NULL && ++hid->current_slot < hid->size) - hid->next = hid->buckets[hid->current_slot]; + hid->next = hid->buckets[hid->current_slot]; } /* @@ -216,12 +216,12 @@ hash_first(hash_table * hid) hid->current_slot = 0; hid->next = hid->buckets[hid->current_slot]; if (NULL == hid->next) - hash_next_bucket(hid); + hash_next_bucket(hid); } /* * hash_next - returns the next item in the hash table 'hid'. - * Otherwise, returns NULL on error or end of list. + * Otherwise, returns NULL on error or end of list. * * MUST call hash_first() before hash_next(). */ @@ -230,10 +230,10 @@ hash_next(hash_table * hid) { hash_link *this = hid->next; if (NULL == this) - return NULL; + return NULL; hid->next = this->next; if (NULL == hid->next) - hash_next_bucket(hid); + hash_next_bucket(hid); return this; } @@ -250,7 +250,7 @@ hash_last(hash_table * hid) } /* - * hash_remove_link - deletes the given hash_link node from the + * hash_remove_link - deletes the given hash_link node from the * hash table 'hid'. Does not free the item, only removes it * from the list. * @@ -265,29 +265,29 @@ hash_remove_link(hash_table * hid, hash_link * hl) assert(hl != NULL); i = hid->hash(hl->key, hid->size); for (P = &hid->buckets[i]; *P; P = &(*P)->next) { - if (*P != hl) - continue; - *P = hl->next; - if (hid->next == hl) { - hid->next = hl->next; - if (NULL == hid->next) - hash_next_bucket(hid); - } - hid->count--; - return; + if (*P != hl) + continue; + *P = hl->next; + if (hid->next == hl) { + hid->next = hl->next; + if (NULL == hid->next) + hash_next_bucket(hid); + } + hid->count--; + return; } assert(0); } /* - * hash_get_bucket - returns the head item of the bucket + * hash_get_bucket - returns the head item of the bucket * in the hash table 'hid'. Otherwise, returns NULL on error. */ hash_link * hash_get_bucket(hash_table * hid, unsigned int bucket) { if (bucket >= hid->size) - return NULL; + return NULL; return (hid->buckets[bucket]); } @@ -301,11 +301,11 @@ hashFreeItems(hash_table * hid, HASHFREE * free_func) list = xcalloc(hid->count, sizeof(hash_link *)); hash_first(hid); while ((l = hash_next(hid)) && i < hid->count) { - *(list + i) = l; - i++; + *(list + i) = l; + i++; } for (j = 0; j < i; j++) - free_func(*(list + j)); + free_func(*(list + j)); xfree(list); } @@ -314,12 +314,11 @@ hashFreeMemory(hash_table * hid) { assert(hid != NULL); if (hid->buckets) - xfree(hid->buckets); + xfree(hid->buckets); xfree(hid); } -static int hash_primes[] = -{ +static int hash_primes[] = { 103, 229, 467, @@ -343,11 +342,11 @@ hashPrime(int n) double min = fabs(log((double) n) - log((double) hash_primes[0])); double d; for (i = 0; i < I; i++) { - d = fabs(log((double) n) - log((double) hash_primes[i])); - if (d > min) - continue; - min = d; - best_prime = hash_primes[i]; + d = fabs(log((double) n) - log((double) hash_primes[i])); + if (d > min) + continue; + min = d; + best_prime = hash_primes[i]; } return best_prime; } @@ -382,36 +381,36 @@ main(void) printf("creating hash table\n"); if ((hid = hash_create((HASHCMP *) strcmp, 229, hash4)) < 0) { - printf("hash_create error.\n"); - exit(1); + printf("hash_create error.\n"); + exit(1); } printf("done creating hash table: %d\n", hid); while (fgets(buf, BUFSIZ, stdin)) { - buf[strlen(buf) - 1] = '\0'; - printf("Inserting '%s' for item %p to hash table: %d\n", - buf, buf, hid); - hash_insert(hid, xstrdup(buf), (void *) 0x12345678); - if (random() % 17 == 0) - strcpy(todelete, buf); + buf[strlen(buf) - 1] = '\0'; + printf("Inserting '%s' for item %p to hash table: %d\n", + buf, buf, hid); + hash_insert(hid, xstrdup(buf), (void *) 0x12345678); + if (random() % 17 == 0) + strcpy(todelete, buf); } printf("walking hash table...\n"); for (i = 0, walker = hash_first(hid); walker; walker = hash_next(hid)) { - printf("item %5d: key: '%s' item: %p\n", i++, walker->key, - walker->item); + printf("item %5d: key: '%s' item: %p\n", i++, walker->key, + walker->item); } printf("done walking hash table...\n"); if (todelete[0]) { - printf("deleting %s from %d\n", todelete, hid); - if (hash_delete(hid, todelete)) - printf("hash_delete error\n"); + printf("deleting %s from %d\n", todelete, hid); + if (hash_delete(hid, todelete)) + printf("hash_delete error\n"); } printf("walking hash table...\n"); for (i = 0, walker = hash_first(hid); walker; walker = hash_next(hid)) { - printf("item %5d: key: '%s' item: %p\n", i++, walker->key, - walker->item); + printf("item %5d: key: '%s' item: %p\n", i++, walker->key, + walker->item); } printf("done walking hash table...\n"); diff --git a/lib/heap.c b/lib/heap.c index 9daefcf213..e55ee4485f 100644 --- a/lib/heap.c +++ b/lib/heap.c @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -64,7 +64,7 @@ #define mutex_trylock(m) (void)0 #define mutex_init(m) ((m)=123456) -/* +/* * Private function prototypes. */ static void _heap_ify_up(heap * hp, heap_node * elm); @@ -101,7 +101,7 @@ new_heap(int initSize, heap_key_func gen_key) assert(hp != NULL); if (initSize <= 0) - initSize = MinSize; + initSize = MinSize; hp->nodes = xcalloc(initSize, sizeof(heap_node *)); assert(hp->nodes != NULL); @@ -124,7 +124,7 @@ delete_heap(heap * hp) int i; assert(hp != NULL); for (i = 0; i < hp->last; i++) { - xfree(hp->nodes[i]); + xfree(hp->nodes[i]); } xfree(hp->nodes); xfree(hp); @@ -149,7 +149,7 @@ heap_insert(heap * hp, void *dat) elm->data = dat; if (_heap_should_grow(hp)) - _heap_grow(hp); + _heap_grow(hp); hp->nodes[hp->last] = elm; elm->id = hp->last; @@ -179,20 +179,20 @@ heap_delete(heap * hp, heap_node * elm) heap_extractlast(hp); if (elm == lastNode) { - /* - * lastNode just got freed, so don't access it in the next - * block. - */ - (void) 0; + /* + * lastNode just got freed, so don't access it in the next + * block. + */ + (void) 0; } else if (hp->last > 0) { - if (lastNode->key < hp->nodes[Parent(lastNode->id)]->key) - _heap_ify_up(hp, lastNode); /* COOL! */ - _heap_ify_down(hp, lastNode); + if (lastNode->key < hp->nodes[Parent(lastNode->id)]->key) + _heap_ify_up(hp, lastNode); /* COOL! */ + _heap_ify_down(hp, lastNode); } return data; } -/* +/* * Delete the last element (leaf) out of the heap. Does not require a * heapify operation. */ @@ -209,7 +209,7 @@ heap_gen_key(heap * hp, heap_t dat) #endif /* heap_gen_key */ -/* +/* * Returns the data of the node with the largest KEY value and removes that * node from the heap. Returns NULL if the heap was empty. */ @@ -219,7 +219,7 @@ heap_extractmin(heap * hp) heap_t data; if (hp->last <= 0) - return NULL; + return NULL; mutex_lock(hp->lock); @@ -232,7 +232,7 @@ heap_extractmin(heap * hp) } -/* +/* * Remove the last node in HP. Frees the heap internal structure and * returns the data pointes to by the last node. */ @@ -248,7 +248,7 @@ heap_extractlast(heap * hp) } -/* +/* * The semantics of this routine is the same as the followings: * heap_delete(hp, elm); * heap_insert(hp, dat); @@ -265,14 +265,14 @@ heap_update(heap * hp, heap_node * elm, void *dat) elm->data = dat; if (elm->key < hp->nodes[Parent(elm->id)]->key) - _heap_ify_up(hp, elm); + _heap_ify_up(hp, elm); _heap_ify_down(hp, elm); return old; } -/* +/* * A pointer to the root node's DATA. */ void * @@ -283,7 +283,7 @@ heap_peepmin(heap * hp) } -/* +/* * The KEY of the root node. */ heap_key @@ -294,7 +294,7 @@ heap_peepminkey(heap * hp) } -/* +/* * Same as heap_peep except that this return the KEY of the node. * Only meant for iteration. */ @@ -306,7 +306,7 @@ heap_peepkey(heap * hp, int n) } -/* +/* * A pointer to Nth node's DATA. The caller can iterate through HP by * calling this routine. eg. Caller can execute the following code: * for(i = 0; i < heap_nodes(hp); i++) @@ -323,7 +323,7 @@ heap_peep(heap * hp, int n) #ifndef heap_nodes -/* +/* * Current number of nodes in HP. */ int @@ -335,7 +335,7 @@ heap_nodes(heap * hp) #ifndef heap_empty -/* +/* * Determine if the heap is empty. Returns 1 if HP has no elements and 0 * otherwise. */ @@ -348,7 +348,7 @@ heap_empty(heap * hp) /****************** Private Functions *******************/ -/* +/* * Maintain the heap order property (parent is smaller than children) which * may only be violated at ELM downwards. Assumes caller has locked the heap. */ @@ -359,31 +359,31 @@ _heap_ify_down(heap * hp, heap_node * elm) int left = 0, right = 0; int true = 1; while (true) { - left = Left(elm->id); - right = Right(elm->id); - if (!_heap_node_exist(hp, left)) { - /* At the bottom of the heap (no child). */ - - assert(!_heap_node_exist(hp, right)); - break; - } else if (!_heap_node_exist(hp, right)) - /* Only left child exists. */ - - kid = hp->nodes[left]; - else { - if (hp->nodes[right]->key < hp->nodes[left]->key) - kid = hp->nodes[right]; - else - kid = hp->nodes[left]; - } - if (elm->key <= kid->key) - break; - _heap_swap_element(hp, kid, elm); + left = Left(elm->id); + right = Right(elm->id); + if (!_heap_node_exist(hp, left)) { + /* At the bottom of the heap (no child). */ + + assert(!_heap_node_exist(hp, right)); + break; + } else if (!_heap_node_exist(hp, right)) + /* Only left child exists. */ + + kid = hp->nodes[left]; + else { + if (hp->nodes[right]->key < hp->nodes[left]->key) + kid = hp->nodes[right]; + else + kid = hp->nodes[left]; + } + if (elm->key <= kid->key) + break; + _heap_swap_element(hp, kid, elm); } } -/* +/* * Maintain the heap property above ELM. Caller has locked the heap. */ static void @@ -391,17 +391,17 @@ _heap_ify_up(heap * hp, heap_node * elm) { heap_node *parentNode; while (elm->id > 0) { - parentNode = hp->nodes[Parent(elm->id)]; - if (parentNode->key <= elm->key) - break; - _heap_swap_element(hp, parentNode, elm); /* Demote the parent. */ + parentNode = hp->nodes[Parent(elm->id)]; + if (parentNode->key <= elm->key) + break; + _heap_swap_element(hp, parentNode, elm); /* Demote the parent. */ } } -/* +/* * Swap the position of ELM1 and ELM2 in heap structure. Their IDs are also - * swapped. + * swapped. */ static void _heap_swap_element(heap * hp, heap_node * elm1, heap_node * elm2) @@ -416,7 +416,7 @@ _heap_swap_element(heap * hp, heap_node * elm1, heap_node * elm2) #ifdef NOTDEF -/* +/* * Copy KEY and DATA fields of SRC to DEST. ID field is NOT copied. */ static void @@ -429,19 +429,19 @@ _heap_copy_element(heap_node * src, heap_node * dest) #endif /* NOTDEF */ -/* +/* * True if HP needs to be grown in size. */ static int _heap_should_grow(heap * hp) { if (hp->size <= hp->last) - return 1; + return 1; return 0; } -/* +/* * Grow HP. */ static void @@ -450,14 +450,14 @@ _heap_grow(heap * hp) int newSize; if (hp->size > Threshold) - newSize = hp->size * SlowRate; + newSize = hp->size * SlowRate; else - newSize = hp->size * NormalRate; + newSize = hp->size * NormalRate; hp->nodes = xrealloc(hp->nodes, newSize * sizeof(heap_node *)); #if COMMENTED_OUT for (i = 0; i < hp->size; i++) - newNodes[i] = hp->nodes[i]; + newNodes[i] = hp->nodes[i]; xfree(hp->nodes); hp->nodes = newNodes; #endif @@ -465,14 +465,14 @@ _heap_grow(heap * hp) } -/* +/* * True if a node with ID exists in HP. */ static int _heap_node_exist(heap * hp, int id) { if ((id >= hp->last) || (id < 0) || (hp->nodes[id] == NULL)) - return 0; + return 0; return 1; } @@ -480,15 +480,15 @@ _heap_node_exist(heap * hp, int id) * Printing and debug functions ****************************************************************************/ -/* - * Print the heap in element order, id..last. +/* + * Print the heap in element order, id..last. */ static void heap_print_inorder(heap * hp, int id) { while (id < hp->last) { - printf("%d\tKey = %.04f\n", id, hp->nodes[id]->key); - id++; + printf("%d\tKey = %.04f\n", id, hp->nodes[id]->key); + id++; } } @@ -501,18 +501,18 @@ verify_heap_property(heap * hp) int i = 0; int correct = 1; for (i = 0; i < hp->last / 2; i++) { - correct = 1; - if (_heap_node_exist(hp, Left(i))) - if (hp->nodes[i]->key > hp->nodes[Left(i)]->key) - correct = 0; - if (_heap_node_exist(hp, Right(i))) - if (hp->nodes[i]->key > hp->nodes[Right(i)]->key) - correct = 0; - if (!correct) { - printf("verifyHeap: violated at %d", i); - heap_print_inorder(hp, 0); - break; - } + correct = 1; + if (_heap_node_exist(hp, Left(i))) + if (hp->nodes[i]->key > hp->nodes[Left(i)]->key) + correct = 0; + if (_heap_node_exist(hp, Right(i))) + if (hp->nodes[i]->key > hp->nodes[Right(i)]->key) + correct = 0; + if (!correct) { + printf("verifyHeap: violated at %d", i); + heap_print_inorder(hp, 0); + break; + } } return correct; } @@ -530,9 +530,9 @@ compare_heap_keys(const void *a, const void *b) heap_node **bn = (heap_node **) b; float cmp = (*an)->key - (*bn)->key; if (cmp < 0) - return -1; + return -1; else - return 1; + return 1; } /* @@ -556,7 +556,7 @@ calc_heap_skew(heap * heap, int replace) float norm = 0; unsigned long max; - /* + /* * Lock the heap to copy it. If replacing it need to keep the heap locked * until we are all done. */ @@ -564,52 +564,52 @@ calc_heap_skew(heap * heap, int replace) max = heap_nodes(heap); - /* + /* * Copy the heap nodes to a new storage area for offline sorting. */ nodes = xmalloc(max * sizeof(heap_node *)); memcpy(nodes, heap->nodes, max * sizeof(heap_node *)); if (replace == 0) { - /* - * Unlock the heap to allow updates from other threads before the sort. - * This allows other heap operations to proceed concurrently with the - * heap skew computation on the heap at the time of the call ... - */ - mutex_unlock(hp->lock); + /* + * Unlock the heap to allow updates from other threads before the sort. + * This allows other heap operations to proceed concurrently with the + * heap skew computation on the heap at the time of the call ... + */ + mutex_unlock(hp->lock); } qsort(nodes, max, sizeof(heap_node *), compare_heap_keys); for (id = 0; id < max; id++) { - diff = id - nodes[id]->id; - skew += abs(diff); + diff = id - nodes[id]->id; + skew += abs(diff); #ifdef HEAP_DEBUG_SKEW - skewsq += diff * diff; + skewsq += diff * diff; #ifdef HEAP_DEBUG_ALL - printf("%d\tKey = %f, diff = %d\n", id, nodes[id]->key, diff); + printf("%d\tKey = %f, diff = %d\n", id, nodes[id]->key, diff); #endif /* HEAP_DEBUG */ #endif /* HEAP_DEBUG_SKEW */ } if (replace != 0) { - /* - * Replace the original heap with the newly sorted heap and let it - * continue. Then compute the skew using the copy of the previous heap - * which we maintain as private data. - */ - memcpy(heap->nodes, nodes, max * sizeof(heap_node *)); - - for (id = 0; id < max; id++) { - /* - * Fix up all the ID values in the copied nodes. - */ - heap->nodes[id]->id = id; - } - - mutex_unlock(hp->lock); + /* + * Replace the original heap with the newly sorted heap and let it + * continue. Then compute the skew using the copy of the previous heap + * which we maintain as private data. + */ + memcpy(heap->nodes, nodes, max * sizeof(heap_node *)); + + for (id = 0; id < max; id++) { + /* + * Fix up all the ID values in the copied nodes. + */ + heap->nodes[id]->id = id; + } + + mutex_unlock(hp->lock); } - /* + /* * The skew value is normalized to a range of [0..1]; the distribution * appears to be a skewed Gaussian distribution. For random insertions * into a heap the normalized skew will be slightly less than 0.5. The @@ -618,7 +618,7 @@ calc_heap_skew(heap * heap, int replace) */ norm = skew * 2.56 / (max * max); - /* + /* * Free the nodes array; note this is just an array of pointers, not data! */ xfree(nodes); diff --git a/lib/html_quote.c b/lib/html_quote.c index f708b4c6a2..dabcbde018 100644 --- a/lib/html_quote.c +++ b/lib/html_quote.c @@ -1,6 +1,6 @@ /* * $Id: html_quote.c,v 1.6 2007/12/06 02:37:15 amosjeffries Exp $ - * + * * DEBUG: * AUTHOR: Robert Collins * @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -43,7 +43,7 @@ #include "util.h" -/* +/* * HTML defines these characters as special entities that should be quoted. */ static struct { @@ -56,27 +56,27 @@ static struct { * see close to the MemPool commend below */ { - '<', "<" + '<', "<" }, { - '>', ">" + '>', ">" }, { - '"', """ + '"', """ }, { - '&', "&" + '&', "&" }, { - '\'', "'" + '\'', "'" }, { - 0, NULL + 0, NULL } }; /* - * html_do_quote - Returns a static buffer containing the quoted + * html_do_quote - Returns a static buffer containing the quoted * string. */ char * @@ -92,40 +92,40 @@ html_quote(const char *string) * MemPools are not yet available in lib... */ if (buf == NULL || strlen(string) * 6 > bufsize) { - xfree(buf); - bufsize = strlen(string) * 6 + 1; - buf = xcalloc(bufsize, 1); + xfree(buf); + bufsize = strlen(string) * 6 + 1; + buf = xcalloc(bufsize, 1); } for (src = string, dst = buf; *src; src++) { - const char *escape = NULL; - const unsigned char ch = *src; + const char *escape = NULL; + const unsigned char ch = *src; - /* Walk thru the list of HTML Entities that must be quoted to - * display safely - */ - for (i = 0; htmlstandardentities[i].code; i++) { - if (ch == htmlstandardentities[i].code) { - escape = htmlstandardentities[i].quote; - break; - } - } - /* Encode control chars just to be on the safe side, and make - * sure all 8-bit characters are encoded to protect from buggy - * clients - */ - if (!escape && (ch <= 0x1F || ch >= 0x7f) && ch != '\n' && ch != '\r' && ch != '\t') { - static char dec_encoded[7]; - snprintf(dec_encoded, sizeof dec_encoded, "&#%3d;", (int) ch); - escape = dec_encoded; - } - if (escape) { - /* Ok, An escaped form was found above. Use it */ - strncpy(dst, escape, 6); - dst += strlen(escape); - } else { - /* Apparently there is no need to escape this character */ - *dst++ = ch; - } + /* Walk thru the list of HTML Entities that must be quoted to + * display safely + */ + for (i = 0; htmlstandardentities[i].code; i++) { + if (ch == htmlstandardentities[i].code) { + escape = htmlstandardentities[i].quote; + break; + } + } + /* Encode control chars just to be on the safe side, and make + * sure all 8-bit characters are encoded to protect from buggy + * clients + */ + if (!escape && (ch <= 0x1F || ch >= 0x7f) && ch != '\n' && ch != '\r' && ch != '\t') { + static char dec_encoded[7]; + snprintf(dec_encoded, sizeof dec_encoded, "&#%3d;", (int) ch); + escape = dec_encoded; + } + if (escape) { + /* Ok, An escaped form was found above. Use it */ + strncpy(dst, escape, 6); + dst += strlen(escape); + } else { + /* Apparently there is no need to escape this character */ + *dst++ = ch; + } } /* Nullterminate and return the result */ *dst = '\0'; diff --git a/lib/inet_ntoa.c b/lib/inet_ntoa.c index 2abf830ef4..62131ac53f 100644 --- a/lib/inet_ntoa.c +++ b/lib/inet_ntoa.c @@ -49,6 +49,6 @@ inet_ntoa(struct in_addr in) p = (char *) ∈ #define UC(b) (((int)b)&0xff) (void) snprintf(b, sizeof(b), - "%d.%d.%d.%d", UC(p[0]), UC(p[1]), UC(p[2]), UC(p[3])); + "%d.%d.%d.%d", UC(p[0]), UC(p[1]), UC(p[2]), UC(p[3])); return (b); } diff --git a/lib/inet_ntop.c b/lib/inet_ntop.c index e780286d0d..3b9c68fd91 100644 --- a/lib/inet_ntop.c +++ b/lib/inet_ntop.c @@ -108,21 +108,21 @@ static const char *inet_ntop6 (const u_char *src, char *dst, size_t size); */ const char * xinet_ntop(af, src, dst, size) - int af; - const void *src; - char *dst; - size_t size; +int af; +const void *src; +char *dst; +size_t size; { - switch (af) { - case AF_INET: - return (inet_ntop4(src, dst, size)); - case AF_INET6: - return (inet_ntop6(src, dst, size)); - default: - errno = EAFNOSUPPORT; - return (NULL); - } - /* NOTREACHED */ + switch (af) { + case AF_INET: + return (inet_ntop4(src, dst, size)); + case AF_INET6: + return (inet_ntop6(src, dst, size)); + default: + errno = EAFNOSUPPORT; + return (NULL); + } + /* NOTREACHED */ } /* const char * @@ -138,19 +138,19 @@ xinet_ntop(af, src, dst, size) */ static const char * inet_ntop4(src, dst, size) - const u_char *src; - char *dst; - size_t size; +const u_char *src; +char *dst; +size_t size; { - static const char fmt[] = "%u.%u.%u.%u"; - char tmp[sizeof "255.255.255.255"]; + static const char fmt[] = "%u.%u.%u.%u"; + char tmp[sizeof "255.255.255.255"]; - if (SPRINTF((tmp, fmt, src[0], src[1], src[2], src[3])) >= size) { - errno = ENOSPC; - return (NULL); - } - strcpy(dst, tmp); - return (dst); + if (SPRINTF((tmp, fmt, src[0], src[1], src[2], src[3])) >= size) { + errno = ENOSPC; + return (NULL); + } + strcpy(dst, tmp); + return (dst); } /* const char * @@ -161,96 +161,96 @@ inet_ntop4(src, dst, size) */ static const char * inet_ntop6(src, dst, size) - const u_char *src; - char *dst; - size_t size; +const u_char *src; +char *dst; +size_t size; { - /* - * Note that int32_t and int16_t need only be "at least" large enough - * to contain a value of the specified size. On some systems, like - * Crays, there is no such thing as an integer variable with 16 bits. - * Keep this in mind if you think this function should have been coded - * to use pointer overlays. All the world's not a VAX. - */ - char tmp[sizeof "ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255"], *tp; - struct { int base, len; } best, cur; - u_int words[NS_IN6ADDRSZ / NS_INT16SZ]; - int i; + /* + * Note that int32_t and int16_t need only be "at least" large enough + * to contain a value of the specified size. On some systems, like + * Crays, there is no such thing as an integer variable with 16 bits. + * Keep this in mind if you think this function should have been coded + * to use pointer overlays. All the world's not a VAX. + */ + char tmp[sizeof "ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255"], *tp; + struct { int base, len; } best, cur; + u_int words[NS_IN6ADDRSZ / NS_INT16SZ]; + int i; - /* - * Preprocess: - * Copy the input (bytewise) array into a wordwise array. - * Find the longest run of 0x00's in src[] for :: shorthanding. - */ - memset(words, '\0', sizeof words); - for (i = 0; i < NS_IN6ADDRSZ; i++) - words[i / 2] |= (src[i] << ((1 - (i % 2)) << 3)); - best.base = -1; - best.len = 0; - cur.base = -1; - cur.len = 0; - for (i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++) { - if (words[i] == 0) { - if (cur.base == -1) - cur.base = i, cur.len = 1; - else - cur.len++; - } else { - if (cur.base != -1) { - if (best.base == -1 || cur.len > best.len) - best = cur; - cur.base = -1; - } - } - } - if (cur.base != -1) { - if (best.base == -1 || cur.len > best.len) - best = cur; - } - if (best.base != -1 && best.len < 2) - best.base = -1; + /* + * Preprocess: + * Copy the input (bytewise) array into a wordwise array. + * Find the longest run of 0x00's in src[] for :: shorthanding. + */ + memset(words, '\0', sizeof words); + for (i = 0; i < NS_IN6ADDRSZ; i++) + words[i / 2] |= (src[i] << ((1 - (i % 2)) << 3)); + best.base = -1; + best.len = 0; + cur.base = -1; + cur.len = 0; + for (i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++) { + if (words[i] == 0) { + if (cur.base == -1) + cur.base = i, cur.len = 1; + else + cur.len++; + } else { + if (cur.base != -1) { + if (best.base == -1 || cur.len > best.len) + best = cur; + cur.base = -1; + } + } + } + if (cur.base != -1) { + if (best.base == -1 || cur.len > best.len) + best = cur; + } + if (best.base != -1 && best.len < 2) + best.base = -1; - /* - * Format the result. - */ - tp = tmp; - for (i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++) { - /* Are we inside the best run of 0x00's? */ - if (best.base != -1 && i >= best.base && - i < (best.base + best.len)) { - if (i == best.base) - *tp++ = ':'; - continue; - } - /* Are we following an initial run of 0x00s or any real hex? */ - if (i != 0) - *tp++ = ':'; - /* Is this address an encapsulated IPv4? */ - if (i == 6 && best.base == 0 && (best.len == 6 || - (best.len == 7 && words[7] != 0x0001) || - (best.len == 5 && words[5] == 0xffff))) { - if (!inet_ntop4(src+12, tp, sizeof tmp - (tp - tmp))) - return (NULL); - tp += strlen(tp); - break; - } - tp += SPRINTF((tp, "%x", words[i])); - } - /* Was it a trailing run of 0x00's? */ - if (best.base != -1 && (best.base + best.len) == - (NS_IN6ADDRSZ / NS_INT16SZ)) - *tp++ = ':'; - *tp++ = '\0'; + /* + * Format the result. + */ + tp = tmp; + for (i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++) { + /* Are we inside the best run of 0x00's? */ + if (best.base != -1 && i >= best.base && + i < (best.base + best.len)) { + if (i == best.base) + *tp++ = ':'; + continue; + } + /* Are we following an initial run of 0x00s or any real hex? */ + if (i != 0) + *tp++ = ':'; + /* Is this address an encapsulated IPv4? */ + if (i == 6 && best.base == 0 && (best.len == 6 || + (best.len == 7 && words[7] != 0x0001) || + (best.len == 5 && words[5] == 0xffff))) { + if (!inet_ntop4(src+12, tp, sizeof tmp - (tp - tmp))) + return (NULL); + tp += strlen(tp); + break; + } + tp += SPRINTF((tp, "%x", words[i])); + } + /* Was it a trailing run of 0x00's? */ + if (best.base != -1 && (best.base + best.len) == + (NS_IN6ADDRSZ / NS_INT16SZ)) + *tp++ = ':'; + *tp++ = '\0'; - /* - * Check for overflow, copy, and we're done. - */ - if ((size_t)(tp - tmp) > size) { - errno = ENOSPC; - return (NULL); - } - strcpy(dst, tmp); - return (dst); + /* + * Check for overflow, copy, and we're done. + */ + if ((size_t)(tp - tmp) > size) { + errno = ENOSPC; + return (NULL); + } + strcpy(dst, tmp); + return (dst); } #endif /* HAVE_INET_NTOP */ diff --git a/lib/inet_pton.c b/lib/inet_pton.c index dbdad403bb..55a4898a2a 100644 --- a/lib/inet_pton.c +++ b/lib/inet_pton.c @@ -20,7 +20,7 @@ #include "config.h" -#ifndef HAVE_INET_PTON +#ifndef HAVE_INET_PTON /* * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC") @@ -99,20 +99,20 @@ static int inet_pton6 (const char *src, u_char *dst); */ int xinet_pton(af, src, dst) - int af; - const char *src; - void *dst; +int af; +const char *src; +void *dst; { - switch (af) { - case AF_INET: - return (inet_pton4(src, dst)); - case AF_INET6: - return (inet_pton6(src, dst)); - default: - errno = EAFNOSUPPORT; - return (-1); - } - /* NOTREACHED */ + switch (af) { + case AF_INET: + return (inet_pton4(src, dst)); + case AF_INET6: + return (inet_pton6(src, dst)); + default: + errno = EAFNOSUPPORT; + return (-1); + } + /* NOTREACHED */ } /* int @@ -127,44 +127,44 @@ xinet_pton(af, src, dst) */ static int inet_pton4(src, dst) - const char *src; - u_char *dst; +const char *src; +u_char *dst; { - static const char digits[] = "0123456789"; - int saw_digit, octets, ch; - u_char tmp[NS_INADDRSZ], *tp; + static const char digits[] = "0123456789"; + int saw_digit, octets, ch; + u_char tmp[NS_INADDRSZ], *tp; - saw_digit = 0; - octets = 0; - *(tp = tmp) = 0; - while ((ch = *src++) != '\0') { - const char *pch; + saw_digit = 0; + octets = 0; + *(tp = tmp) = 0; + while ((ch = *src++) != '\0') { + const char *pch; - if ((pch = strchr(digits, ch)) != NULL) { - u_int new = *tp * 10 + (pch - digits); + if ((pch = strchr(digits, ch)) != NULL) { + u_int new = *tp * 10 + (pch - digits); - if (saw_digit && *tp == 0) - return (0); - if (new > 255) - return (0); - *tp = new; - if (!saw_digit) { - if (++octets > 4) - return (0); - saw_digit = 1; - } - } else if (ch == '.' && saw_digit) { - if (octets == 4) - return (0); - *++tp = 0; - saw_digit = 0; - } else - return (0); - } - if (octets < 4) - return (0); - memcpy(dst, tmp, NS_INADDRSZ); - return (1); + if (saw_digit && *tp == 0) + return (0); + if (new > 255) + return (0); + *tp = new; + if (!saw_digit) { + if (++octets > 4) + return (0); + saw_digit = 1; + } + } else if (ch == '.' && saw_digit) { + if (octets == 4) + return (0); + *++tp = 0; + saw_digit = 0; + } else + return (0); + } + if (octets < 4) + return (0); + memcpy(dst, tmp, NS_INADDRSZ); + return (1); } /* int @@ -182,90 +182,90 @@ inet_pton4(src, dst) */ static int inet_pton6(src, dst) - const char *src; - u_char *dst; +const char *src; +u_char *dst; { - static const char xdigits_l[] = "0123456789abcdef", - xdigits_u[] = "0123456789ABCDEF"; - u_char tmp[NS_IN6ADDRSZ], *tp, *endp, *colonp; - const char *xdigits, *curtok; - int ch, seen_xdigits; - u_int val; + static const char xdigits_l[] = "0123456789abcdef", + xdigits_u[] = "0123456789ABCDEF"; + u_char tmp[NS_IN6ADDRSZ], *tp, *endp, *colonp; + const char *xdigits, *curtok; + int ch, seen_xdigits; + u_int val; - memset((tp = tmp), '\0', NS_IN6ADDRSZ); - endp = tp + NS_IN6ADDRSZ; - colonp = NULL; - /* Leading :: requires some special handling. */ - if (*src == ':') - if (*++src != ':') - return (0); - curtok = src; - seen_xdigits = 0; - val = 0; - while ((ch = *src++) != '\0') { - const char *pch; + memset((tp = tmp), '\0', NS_IN6ADDRSZ); + endp = tp + NS_IN6ADDRSZ; + colonp = NULL; + /* Leading :: requires some special handling. */ + if (*src == ':') + if (*++src != ':') + return (0); + curtok = src; + seen_xdigits = 0; + val = 0; + while ((ch = *src++) != '\0') { + const char *pch; - if ((pch = strchr((xdigits = xdigits_l), ch)) == NULL) - pch = strchr((xdigits = xdigits_u), ch); - if (pch != NULL) { - val <<= 4; - val |= (pch - xdigits); - if (++seen_xdigits > 4) - return (0); - continue; - } - if (ch == ':') { - curtok = src; - if (!seen_xdigits) { - if (colonp) - return (0); - colonp = tp; - continue; - } else if (*src == '\0') { - return (0); - } - if (tp + NS_INT16SZ > endp) - return (0); - *tp++ = (u_char) (val >> 8) & 0xff; - *tp++ = (u_char) val & 0xff; - seen_xdigits = 0; - val = 0; - continue; - } - if (ch == '.' && ((tp + NS_INADDRSZ) <= endp) && - inet_pton4(curtok, tp) > 0) { - tp += NS_INADDRSZ; - seen_xdigits = 0; - break; /* '\0' was seen by inet_pton4(). */ - } - return (0); - } - if (seen_xdigits) { - if (tp + NS_INT16SZ > endp) - return (0); - *tp++ = (u_char) (val >> 8) & 0xff; - *tp++ = (u_char) val & 0xff; - } - if (colonp != NULL) { - /* - * Since some memmove()'s erroneously fail to handle - * overlapping regions, we'll do the shift by hand. - */ - const int n = tp - colonp; - int i; + if ((pch = strchr((xdigits = xdigits_l), ch)) == NULL) + pch = strchr((xdigits = xdigits_u), ch); + if (pch != NULL) { + val <<= 4; + val |= (pch - xdigits); + if (++seen_xdigits > 4) + return (0); + continue; + } + if (ch == ':') { + curtok = src; + if (!seen_xdigits) { + if (colonp) + return (0); + colonp = tp; + continue; + } else if (*src == '\0') { + return (0); + } + if (tp + NS_INT16SZ > endp) + return (0); + *tp++ = (u_char) (val >> 8) & 0xff; + *tp++ = (u_char) val & 0xff; + seen_xdigits = 0; + val = 0; + continue; + } + if (ch == '.' && ((tp + NS_INADDRSZ) <= endp) && + inet_pton4(curtok, tp) > 0) { + tp += NS_INADDRSZ; + seen_xdigits = 0; + break; /* '\0' was seen by inet_pton4(). */ + } + return (0); + } + if (seen_xdigits) { + if (tp + NS_INT16SZ > endp) + return (0); + *tp++ = (u_char) (val >> 8) & 0xff; + *tp++ = (u_char) val & 0xff; + } + if (colonp != NULL) { + /* + * Since some memmove()'s erroneously fail to handle + * overlapping regions, we'll do the shift by hand. + */ + const int n = tp - colonp; + int i; - if (tp == endp) - return (0); - for (i = 1; i <= n; i++) { - endp[- i] = colonp[n - i]; - colonp[n - i] = 0; - } - tp = endp; - } - if (tp != endp) - return (0); - memcpy(dst, tmp, NS_IN6ADDRSZ); - return (1); + if (tp == endp) + return (0); + for (i = 1; i <= n; i++) { + endp[- i] = colonp[n - i]; + colonp[n - i] = 0; + } + tp = endp; + } + if (tp != endp) + return (0); + memcpy(dst, tmp, NS_IN6ADDRSZ); + return (1); } #endif /* HAVE_INET_PTON */ diff --git a/lib/initgroups.c b/lib/initgroups.c index 8cc8b6a057..41f8e3f68b 100644 --- a/lib/initgroups.c +++ b/lib/initgroups.c @@ -38,16 +38,16 @@ int initgroups(const char *name, gid_t basegid) groups[index++] = basegid; while (index < NGROUPS_MAX && ((g = getgrent()) != NULL)) { - if (g->gr_gid != basegid) { - char **names; + if (g->gr_gid != basegid) { + char **names; - for (names = g->gr_mem; *names != NULL; ++names) { + for (names = g->gr_mem; *names != NULL; ++names) { - if (!strcmp(*names, name)) - groups[index++] = g->gr_gid; + if (!strcmp(*names, name)) + groups[index++] = g->gr_gid; - } - } + } + } } endgrent(); diff --git a/lib/iso3307.c b/lib/iso3307.c index 245c21b53b..2a99b02b06 100644 --- a/lib/iso3307.c +++ b/lib/iso3307.c @@ -30,16 +30,16 @@ time_t parse_iso3307_time(const char *buf) { -/* buf is an ISO 3307 style time: YYYYMMDDHHMMSS or YYYYMMDDHHMMSS.xxx */ + /* buf is an ISO 3307 style time: YYYYMMDDHHMMSS or YYYYMMDDHHMMSS.xxx */ struct tm tms; time_t t; while (*buf == ' ' || *buf == '\t') - buf++; + buf++; if ((int) strlen(buf) < 14) - return 0; + return 0; memset(&tms, '\0', sizeof(struct tm)); tms.tm_year = (ASCII_DIGIT(buf[0]) * 1000) + (ASCII_DIGIT(buf[1]) * 100) + - (ASCII_DIGIT(buf[2]) * 10) + ASCII_DIGIT(buf[3]) - 1900; + (ASCII_DIGIT(buf[2]) * 10) + ASCII_DIGIT(buf[3]) - 1900; tms.tm_mon = (ASCII_DIGIT(buf[4]) * 10) + ASCII_DIGIT(buf[5]) - 1; tms.tm_mday = (ASCII_DIGIT(buf[6]) * 10) + ASCII_DIGIT(buf[7]); tms.tm_hour = (ASCII_DIGIT(buf[8]) * 10) + ASCII_DIGIT(buf[9]); diff --git a/lib/libTrie/include/Trie.cci b/lib/libTrie/include/Trie.cci index ae77d501b8..87aead8c56 100644 --- a/lib/libTrie/include/Trie.cci +++ b/lib/libTrie/include/Trie.cci @@ -5,12 +5,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/lib/libTrie/include/Trie.h b/lib/libTrie/include/Trie.h index a69d5e7bbf..0b482aa421 100644 --- a/lib/libTrie/include/Trie.h +++ b/lib/libTrie/include/Trie.h @@ -5,12 +5,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -21,7 +21,7 @@ #define LIBTRIE_SQUID_H /* This is the header for libTrie. - * libTrie provides both C and C++ + * libTrie provides both C and C++ * bindings. libtrie itself is written in C++. */ @@ -83,7 +83,7 @@ public: */ bool add - (char const *, size_t, void *); + (char const *, size_t, void *); private: TrieNode *head; diff --git a/lib/libTrie/include/TrieCharTransform.h b/lib/libTrie/include/TrieCharTransform.h index bc3af9caaf..d4f18f86df 100644 --- a/lib/libTrie/include/TrieCharTransform.h +++ b/lib/libTrie/include/TrieCharTransform.h @@ -5,12 +5,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -21,8 +21,8 @@ #define LIBTRIE_TRIECHARTRANSFORM_H /* This is an internal header for libTrie. - * libTrie provides both limited C and full C++ - * bindings. + * libTrie provides both limited C and full C++ + * bindings. * libTrie itself is written in C++. * For C bindings see Trie.h */ diff --git a/lib/libTrie/include/TrieNode.cci b/lib/libTrie/include/TrieNode.cci index 3d33fe6252..6efe375150 100644 --- a/lib/libTrie/include/TrieNode.cci +++ b/lib/libTrie/include/TrieNode.cci @@ -5,12 +5,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/lib/libTrie/include/TrieNode.h b/lib/libTrie/include/TrieNode.h index 07c03f147d..548bda7827 100644 --- a/lib/libTrie/include/TrieNode.h +++ b/lib/libTrie/include/TrieNode.h @@ -5,12 +5,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -21,8 +21,8 @@ #define LIBTRIE_TRIENODE_H /* This is an internal header for libTrie. - * libTrie provides both C and C++ - * bindings. + * libTrie provides both C and C++ + * bindings. * libTrie itself is written in C++. * For C bindings see Trei.h */ @@ -71,7 +71,7 @@ public: */ bool add - (char const *, size_t, void *, TrieCharTransform *); + (char const *, size_t, void *, TrieCharTransform *); private: /* 256-way Trie */ diff --git a/lib/libTrie/src/Trie.cc b/lib/libTrie/src/Trie.cc index 150fb1716e..4d09503d37 100644 --- a/lib/libTrie/src/Trie.cc +++ b/lib/libTrie/src/Trie.cc @@ -5,12 +5,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -51,7 +51,7 @@ extern "C" void *TrieFind (void *aTrie, char const *aString, size_t theLength) bool Trie::add - (char const *aString, size_t theLength, void *privatedata) +(char const *aString, size_t theLength, void *privatedata) { if (!privatedata) return false; diff --git a/lib/libTrie/src/TrieNode.cc b/lib/libTrie/src/TrieNode.cc index b5ea508429..bc1af21a9f 100644 --- a/lib/libTrie/src/TrieNode.cc +++ b/lib/libTrie/src/TrieNode.cc @@ -5,12 +5,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -39,7 +39,7 @@ TrieNode::~TrieNode () bool TrieNode::add - (char const *aString, size_t theLength, void *privatedata, TrieCharTransform *transform) +(char const *aString, size_t theLength, void *privatedata, TrieCharTransform *transform) { /* We trust that privatedata and existant keys have already been checked */ diff --git a/lib/libTrie/test/trie-c.c b/lib/libTrie/test/trie-c.c index 8869874d08..649fb2e20c 100644 --- a/lib/libTrie/test/trie-c.c +++ b/lib/libTrie/test/trie-c.c @@ -5,12 +5,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -25,16 +25,16 @@ main (int argc, char **argv) { void *aTrie = TrieCreate(); if (!TrieAdd (aTrie, "User-Agent", 10, (void *)1)) { - fprintf(stderr,"Could not add User-Agent\n"); - return 1; + fprintf(stderr,"Could not add User-Agent\n"); + return 1; } if (TrieAdd (aTrie, "User-Agent", 10, (void *)2)) { - fprintf(stderr, "Could add duplicate User-Agent\n"); - return 1; + fprintf(stderr, "Could add duplicate User-Agent\n"); + return 1; } if (TrieFind (aTrie, "User-Agent", 10) != (void *)1) { - fprintf(stderr, "Could not find User-Agent\n"); - return 1; + fprintf(stderr, "Could not find User-Agent\n"); + return 1; } TrieDestroy (aTrie); return 0; diff --git a/lib/libTrie/test/trie.cc b/lib/libTrie/test/trie.cc index d3ace8871b..8e6924b600 100644 --- a/lib/libTrie/test/trie.cc +++ b/lib/libTrie/test/trie.cc @@ -5,12 +5,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/lib/md5-test.c b/lib/md5-test.c index 5c45232466..3615f3e711 100644 --- a/lib/md5-test.c +++ b/lib/md5-test.c @@ -33,7 +33,7 @@ MDPrint(unsigned char digest[16]) { unsigned int i; for (i = 0; i < 16; i++) - printf("%02x", digest[i]); + printf("%02x", digest[i]); } int @@ -46,9 +46,9 @@ main(int argc, char **argv) MDString("message digest"); MDString("abcdefghijklmnopqrstuvwxyz"); MDString - ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"); + ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"); MDString - ("1234567890123456789012345678901234567890\ + ("1234567890123456789012345678901234567890\ 1234567890123456789012345678901234567890"); return 0; } diff --git a/lib/md5.c b/lib/md5.c index 955c7aeefe..a8a9adec7b 100644 --- a/lib/md5.c +++ b/lib/md5.c @@ -47,9 +47,9 @@ static byteSwap(uint32_t * buf, unsigned words) uint8_t *p = (uint8_t *) buf; do { - *buf++ = (uint32_t) ((unsigned) p[3] << 8 | p[2]) << 16 | - ((unsigned) p[1] << 8 | p[0]); - p += 4; + *buf++ = (uint32_t) ((unsigned) p[3] << 8 | p[2]) << 16 | + ((unsigned) p[1] << 8 | p[0]); + p += 4; } while (--words); } #else @@ -86,12 +86,12 @@ SquidMD5Update(struct SquidMD5Context *ctx, const void *_buf, unsigned len) t = ctx->bytes[0]; if ((ctx->bytes[0] = t + len) < t) - ctx->bytes[1]++; /* Carry from low to high */ + ctx->bytes[1]++; /* Carry from low to high */ t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */ if (t > len) { - memcpy((uint8_t *) ctx->in + 64 - t, buf, len); - return; + memcpy((uint8_t *) ctx->in + 64 - t, buf, len); + return; } /* First chunk is an odd size */ memcpy((uint8_t *) ctx->in + 64 - t, buf, t); @@ -102,11 +102,11 @@ SquidMD5Update(struct SquidMD5Context *ctx, const void *_buf, unsigned len) /* Process data in 64-byte chunks */ while (len >= 64) { - memcpy(ctx->in, buf, 64); - byteSwap(ctx->in, 16); - SquidMD5Transform(ctx->buf, ctx->in); - buf += 64; - len -= 64; + memcpy(ctx->in, buf, 64); + byteSwap(ctx->in, 16); + SquidMD5Transform(ctx->buf, ctx->in); + buf += 64; + len -= 64; } /* Handle any remaining bytes of data. */ @@ -114,7 +114,7 @@ SquidMD5Update(struct SquidMD5Context *ctx, const void *_buf, unsigned len) } /* - * Final wrapup - pad to 64-byte boundary with the bit pattern + * Final wrapup - pad to 64-byte boundary with the bit pattern * 1 0* (64-bit count of bits processed, MSB-first) */ void @@ -130,11 +130,11 @@ SquidMD5Final(unsigned char digest[16], struct SquidMD5Context *ctx) count = 56 - 1 - count; if (count < 0) { /* Padding forces an extra block */ - memset(p, 0, count + 8); - byteSwap(ctx->in, 16); - SquidMD5Transform(ctx->buf, ctx->in); - p = (uint8_t *) ctx->in; - count = 56; + memset(p, 0, count + 8); + byteSwap(ctx->in, 16); + SquidMD5Transform(ctx->buf, ctx->in); + p = (uint8_t *) ctx->in; + count = 56; } memset(p, 0, count); byteSwap(ctx->in, 14); diff --git a/lib/ntlmauth.c b/lib/ntlmauth.c index 23ae8f680f..0cde3b928e 100644 --- a/lib/ntlmauth.c +++ b/lib/ntlmauth.c @@ -9,12 +9,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -40,26 +40,26 @@ void ntlm_dump_ntlmssp_flags(u_int32_t flags) { fprintf(stderr, "flags: %s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n", - (flags & NEGOTIATE_UNICODE ? "Unicode " : ""), - (flags & NEGOTIATE_ASCII ? "ASCII " : ""), - (flags & NEGOTIATE_REQUEST_TARGET ? "ReqTgt " : ""), - (flags & NEGOTIATE_REQUEST_SIGN ? "ReqSign " : ""), - (flags & NEGOTIATE_REQUEST_SEAL ? "ReqSeal " : ""), - (flags & NEGOTIATE_DATAGRAM_STYLE ? "Dgram " : ""), - (flags & NEGOTIATE_USE_LM ? "UseLM " : ""), - (flags & NEGOTIATE_USE_NETWARE ? "UseNW " : ""), - (flags & NEGOTIATE_USE_NTLM ? "UseNTLM " : ""), - (flags & NEGOTIATE_DOMAIN_SUPPLIED ? "HaveDomain " : ""), - (flags & NEGOTIATE_WORKSTATION_SUPPLIED ? "HaveWKS " : ""), - (flags & NEGOTIATE_THIS_IS_LOCAL_CALL ? "LocalCall " : ""), - (flags & NEGOTIATE_ALWAYS_SIGN ? "AlwaysSign " : ""), - (flags & CHALLENGE_TARGET_IS_DOMAIN ? "Tgt_is_domain" : ""), - (flags & CHALLENGE_TARGET_IS_SERVER ? "Tgt_is_server " : ""), - (flags & CHALLENGE_TARGET_IS_SHARE ? "Tgt_is_share " : ""), - (flags & REQUEST_INIT_RESPONSE ? "Req_init_response " : ""), - (flags & REQUEST_ACCEPT_RESPONSE ? "Req_accept_response " : ""), - (flags & REQUEST_NON_NT_SESSION_KEY ? "Req_nonnt_sesskey " : "") - ); + (flags & NEGOTIATE_UNICODE ? "Unicode " : ""), + (flags & NEGOTIATE_ASCII ? "ASCII " : ""), + (flags & NEGOTIATE_REQUEST_TARGET ? "ReqTgt " : ""), + (flags & NEGOTIATE_REQUEST_SIGN ? "ReqSign " : ""), + (flags & NEGOTIATE_REQUEST_SEAL ? "ReqSeal " : ""), + (flags & NEGOTIATE_DATAGRAM_STYLE ? "Dgram " : ""), + (flags & NEGOTIATE_USE_LM ? "UseLM " : ""), + (flags & NEGOTIATE_USE_NETWARE ? "UseNW " : ""), + (flags & NEGOTIATE_USE_NTLM ? "UseNTLM " : ""), + (flags & NEGOTIATE_DOMAIN_SUPPLIED ? "HaveDomain " : ""), + (flags & NEGOTIATE_WORKSTATION_SUPPLIED ? "HaveWKS " : ""), + (flags & NEGOTIATE_THIS_IS_LOCAL_CALL ? "LocalCall " : ""), + (flags & NEGOTIATE_ALWAYS_SIGN ? "AlwaysSign " : ""), + (flags & CHALLENGE_TARGET_IS_DOMAIN ? "Tgt_is_domain" : ""), + (flags & CHALLENGE_TARGET_IS_SERVER ? "Tgt_is_server " : ""), + (flags & CHALLENGE_TARGET_IS_SHARE ? "Tgt_is_share " : ""), + (flags & REQUEST_INIT_RESPONSE ? "Req_init_response " : ""), + (flags & REQUEST_ACCEPT_RESPONSE ? "Req_accept_response " : ""), + (flags & REQUEST_NON_NT_SESSION_KEY ? "Req_nonnt_sesskey " : "") + ); } #endif @@ -86,8 +86,8 @@ ntlm_fetch_string(char *packet, int32_t length, strhdr * str) /* debug("fetch_string(plength=%d,l=%d,o=%d)\n",length,l,o); */ if (l < 0 || l > MAX_FIELD_LENGTH || o + l > length || o == 0) { - /* debug("ntlmssp: insane data (l: %d, o: %d)\n", l,o); */ - return rv; + /* debug("ntlmssp: insane data (l: %d, o: %d)\n", l,o); */ + return rv; } rv.str = packet + o; rv.l = l; @@ -103,8 +103,8 @@ ntlm_fetch_string(char *packet, int32_t length, strhdr * str) */ void ntlm_add_to_payload(char *payload, int *payload_length, - strhdr * hdr, char *toadd, - int toadd_length, int base_offset) + strhdr * hdr, char *toadd, + int toadd_length, int base_offset) { int l = (*payload_length); @@ -124,7 +124,7 @@ ntlm_add_to_payload(char *payload, int *payload_length, */ const char * ntlm_make_challenge(char *domain, char *domain_controller, - char *challenge_nonce, int challenge_nonce_len) + char *challenge_nonce, int challenge_nonce_len) { ntlm_challenge ch; int pl = 0; @@ -133,16 +133,16 @@ ntlm_make_challenge(char *domain, char *domain_controller, memcpy(ch.signature, "NTLMSSP", 8); /* set the signature */ ch.type = htole32(NTLM_CHALLENGE); /* this is a challenge */ ntlm_add_to_payload(ch.payload, &pl, &ch.target, domain, strlen(domain), - NTLM_CHALLENGE_HEADER_OFFSET); + NTLM_CHALLENGE_HEADER_OFFSET); ch.flags = htole32( - REQUEST_NON_NT_SESSION_KEY | - CHALLENGE_TARGET_IS_DOMAIN | - NEGOTIATE_ALWAYS_SIGN | - NEGOTIATE_USE_NTLM | - NEGOTIATE_USE_LM | - NEGOTIATE_ASCII | - 0 - ); + REQUEST_NON_NT_SESSION_KEY | + CHALLENGE_TARGET_IS_DOMAIN | + NEGOTIATE_ALWAYS_SIGN | + NEGOTIATE_USE_NTLM | + NEGOTIATE_USE_LM | + NEGOTIATE_ASCII | + 0 + ); ch.context_low = 0; /* check this out */ ch.context_high = 0; memcpy(ch.challenge, challenge_nonce, challenge_nonce_len); diff --git a/lib/radix.c b/lib/radix.c index b476c2eaab..aa3fd4c181 100644 --- a/lib/radix.c +++ b/lib/radix.c @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -113,8 +113,7 @@ int squid_max_keylen; struct squid_radix_mask *squid_rn_mkfreelist; struct squid_radix_node_head *squid_mask_rnhead; static char *addmask_key; -static unsigned char normal_chars[] = -{0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xFF}; +static unsigned char normal_chars[] = {0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xFF}; static char *rn_zeros, *rn_ones; /* aliases */ @@ -159,18 +158,18 @@ static char *rn_zeros, *rn_ones; * We define the index of a route to associated with the mask to be * the first bit number in the mask where 0 occurs (with bit number 0 * representing the highest order bit). - * + * * We say a mask is normal if every bit is 0, past the index of the mask. * If a node n has a descendant (k, m) with index(m) == index(n) == rn_b, * and m is a normal mask, then the route applies to every descendant of n. * If the index(m) < rn_b, this implies the trailing last few bits of k * before bit b are all 0, (and hence consequently true of every descendant * of n), so the route applies to all descendants of the node as well. - * + * * Similar logic shows that a non-normal mask m such that * index(m) <= index(n) could potentially apply to many children of n. * Thus, for each non-host route, we attach its mask to a list at an internal - * node as high in the tree as we can go. + * node as high in the tree as we can go. * * The present version of the code makes use of normal routes in short- * circuiting an explict mask and compare operation when testing whether @@ -179,32 +178,30 @@ static char *rn_zeros, *rn_ones; */ struct squid_radix_node * -squid_rn_search(void *v_arg, struct squid_radix_node *head) -{ + squid_rn_search(void *v_arg, struct squid_radix_node *head) { register struct squid_radix_node *x; register caddr_t v; for (x = head, v = v_arg; x->rn_b >= 0;) { - if (x->rn_bmask & v[x->rn_off]) - x = x->rn_r; - else - x = x->rn_l; + if (x->rn_bmask & v[x->rn_off]) + x = x->rn_r; + else + x = x->rn_l; } return (x); } struct squid_radix_node * -squid_rn_search_m(void *v_arg, struct squid_radix_node *head, void *m_arg) -{ + squid_rn_search_m(void *v_arg, struct squid_radix_node *head, void *m_arg) { register struct squid_radix_node *x; register caddr_t v = v_arg, m = m_arg; for (x = head; x->rn_b >= 0;) { - if ((x->rn_bmask & m[x->rn_off]) && - (x->rn_bmask & v[x->rn_off])) - x = x->rn_r; - else - x = x->rn_l; + if ((x->rn_bmask & m[x->rn_off]) && + (x->rn_bmask & v[x->rn_off])) + x = x->rn_r; + else + x = x->rn_l; } return x; } @@ -218,38 +215,37 @@ squid_rn_refines(void *m_arg, void *n_arg) int masks_are_equal = 1; if (longer > 0) - lim -= longer; + lim -= longer; while (n < lim) { - if (*n & ~(*m)) - return 0; - if (*n++ != *m++) - masks_are_equal = 0; + if (*n & ~(*m)) + return 0; + if (*n++ != *m++) + masks_are_equal = 0; } while (n < lim2) - if (*n++) - return 0; + if (*n++) + return 0; if (masks_are_equal && (longer < 0)) - for (lim2 = m - longer; m < lim2;) - if (*m++) - return 1; + for (lim2 = m - longer; m < lim2;) + if (*m++) + return 1; return (!masks_are_equal); } struct squid_radix_node * -squid_rn_lookup(void *v_arg, void *m_arg, struct squid_radix_node_head *head) -{ + squid_rn_lookup(void *v_arg, void *m_arg, struct squid_radix_node_head *head) { register struct squid_radix_node *x; caddr_t netmask = 0; if (m_arg) { - if ((x = squid_rn_addmask(m_arg, 1, head->rnh_treetop->rn_off)) == 0) - return (0); - netmask = x->rn_key; + if ((x = squid_rn_addmask(m_arg, 1, head->rnh_treetop->rn_off)) == 0) + return (0); + netmask = x->rn_key; } x = squid_rn_match(v_arg, head); if (x && netmask) { - while (x && x->rn_mask != netmask) - x = x->rn_dupedkey; + while (x && x->rn_mask != netmask) + x = x->rn_dupedkey; } return x; } @@ -262,21 +258,20 @@ rn_satsifies_leaf(char *trial, register struct squid_radix_node *leaf, int skip) int length = min(*(u_char *) cp, *(u_char *) cp2); if (cp3 == 0) - cp3 = rn_ones; + cp3 = rn_ones; else - length = min(length, *(u_char *) cp3); + length = min(length, *(u_char *) cp3); cplim = cp + length; cp3 += skip; cp2 += skip; for (cp += skip; cp < cplim; cp++, cp2++, cp3++) - if ((*cp ^ *cp2) & *cp3) - return 0; + if ((*cp ^ *cp2) & *cp3) + return 0; return 1; } struct squid_radix_node * -squid_rn_match(void *v_arg, struct squid_radix_node_head *head) -{ + squid_rn_match(void *v_arg, struct squid_radix_node_head *head) { caddr_t v = v_arg; register struct squid_radix_node *t = head->rnh_treetop, *x; register caddr_t cp = v, cp2; @@ -290,10 +285,10 @@ squid_rn_match(void *v_arg, struct squid_radix_node_head *head) * subroutine call. */ for (; t->rn_b >= 0;) { - if (t->rn_bmask & cp[t->rn_off]) - t = t->rn_r; - else - t = t->rn_l; + if (t->rn_bmask & cp[t->rn_off]) + t = t->rn_r; + else + t = t->rn_l; } /* * See if we match exactly as a host destination @@ -307,24 +302,24 @@ squid_rn_match(void *v_arg, struct squid_radix_node_head *head) * are probably the most common case... */ if (t->rn_mask) - vlen = *(u_char *) t->rn_mask; + vlen = *(u_char *) t->rn_mask; cp += off; cp2 = t->rn_key + off; cplim = v + vlen; for (; cp < cplim; cp++, cp2++) - if (*cp != *cp2) - goto on1; + if (*cp != *cp2) + goto on1; /* * This extra grot is in case we are explicitly asked * to look up the default. Ugh! */ if ((t->rn_flags & RNF_ROOT) && t->rn_dupedkey) - t = t->rn_dupedkey; + t = t->rn_dupedkey; return t; - on1: +on1: test = (*cp ^ *cp2) & 0xff; /* find first bit that differs */ for (b = 7; (test >>= 1) > 0;) - b--; + b--; matched_off = cp - v; b += matched_off << 3; rn_b = -1 - b; @@ -332,44 +327,44 @@ squid_rn_match(void *v_arg, struct squid_radix_node_head *head) * If there is a host route in a duped-key chain, it will be first. */ if ((saved_t = t)->rn_mask == 0) - t = t->rn_dupedkey; + t = t->rn_dupedkey; for (; t; t = t->rn_dupedkey) - /* - * Even if we don't match exactly as a host, - * we may match if the leaf we wound up at is - * a route to a net. - */ - if (t->rn_flags & RNF_NORMAL) { - if (rn_b <= t->rn_b) - return t; - } else if (rn_satsifies_leaf(v, t, matched_off)) - return t; + /* + * Even if we don't match exactly as a host, + * we may match if the leaf we wound up at is + * a route to a net. + */ + if (t->rn_flags & RNF_NORMAL) { + if (rn_b <= t->rn_b) + return t; + } else if (rn_satsifies_leaf(v, t, matched_off)) + return t; t = saved_t; /* start searching up the tree */ do { - register struct squid_radix_mask *m; - t = t->rn_p; - if ((m = t->rn_mklist)) { - /* - * If non-contiguous masks ever become important - * we can restore the masking and open coding of - * the search and satisfaction test and put the - * calculation of "off" back before the "do". - */ - do { - if (m->rm_flags & RNF_NORMAL) { - if (rn_b <= m->rm_b) - return (m->rm_leaf); - } else { - off = min(t->rn_off, matched_off); - x = squid_rn_search_m(v, t, m->rm_mask); - while (x && x->rn_mask != m->rm_mask) - x = x->rn_dupedkey; - if (x && rn_satsifies_leaf(v, x, off)) - return x; - } - } while ((m = m->rm_mklist)); - } + register struct squid_radix_mask *m; + t = t->rn_p; + if ((m = t->rn_mklist)) { + /* + * If non-contiguous masks ever become important + * we can restore the masking and open coding of + * the search and satisfaction test and put the + * calculation of "off" back before the "do". + */ + do { + if (m->rm_flags & RNF_NORMAL) { + if (rn_b <= m->rm_b) + return (m->rm_leaf); + } else { + off = min(t->rn_off, matched_off); + x = squid_rn_search_m(v, t, m->rm_mask); + while (x && x->rn_mask != m->rm_mask) + x = x->rn_dupedkey; + if (x && rn_satsifies_leaf(v, x, off)) + return x; + } + } while ((m = m->rm_mklist)); + } } while (t != top); return 0; } @@ -382,8 +377,7 @@ int rn_debug = 1; #endif struct squid_radix_node * -squid_rn_newpair(void *v, int b, struct squid_radix_node nodes[2]) -{ + squid_rn_newpair(void *v, int b, struct squid_radix_node nodes[2]) { register struct squid_radix_node *tt = nodes, *t = tt + 1; t->rn_b = b; t->rn_bmask = 0x80 >> (b & 7); @@ -404,8 +398,7 @@ squid_rn_newpair(void *v, int b, struct squid_radix_node nodes[2]) } struct squid_radix_node * -squid_rn_insert(void *v_arg, struct squid_radix_node_head *head, int *dupentry, struct squid_radix_node nodes[2]) -{ + squid_rn_insert(void *v_arg, struct squid_radix_node_head *head, int *dupentry, struct squid_radix_node nodes[2]) { caddr_t v = v_arg; struct squid_radix_node *top = head->rnh_treetop; int head_off = top->rn_off, vlen = (int) *((u_char *) v); @@ -417,61 +410,60 @@ squid_rn_insert(void *v_arg, struct squid_radix_node_head *head, int *dupentry, * Find first bit at which v and t->rn_key differ */ { - register caddr_t cp2 = t->rn_key + head_off; - register int cmp_res; - caddr_t cplim = v + vlen; - - while (cp < cplim) - if (*cp2++ != *cp++) - goto on1; - *dupentry = 1; - return t; - on1: - *dupentry = 0; - cmp_res = (cp[-1] ^ cp2[-1]) & 0xff; - for (b = (cp - v) << 3; cmp_res; b--) - cmp_res >>= 1; + register caddr_t cp2 = t->rn_key + head_off; + register int cmp_res; + caddr_t cplim = v + vlen; + + while (cp < cplim) + if (*cp2++ != *cp++) + goto on1; + *dupentry = 1; + return t; +on1: + *dupentry = 0; + cmp_res = (cp[-1] ^ cp2[-1]) & 0xff; + for (b = (cp - v) << 3; cmp_res; b--) + cmp_res >>= 1; } { - register struct squid_radix_node *p, *x = top; - cp = v; - do { - p = x; - if (cp[x->rn_off] & x->rn_bmask) - x = x->rn_r; - else - x = x->rn_l; - } while (b > (unsigned) x->rn_b); /* x->rn_b < b && x->rn_b >= 0 */ + register struct squid_radix_node *p, *x = top; + cp = v; + do { + p = x; + if (cp[x->rn_off] & x->rn_bmask) + x = x->rn_r; + else + x = x->rn_l; + } while (b > (unsigned) x->rn_b); /* x->rn_b < b && x->rn_b >= 0 */ #ifdef RN_DEBUG - if (rn_debug) - fprintf(stderr, "squid_rn_insert: Going In:\n"); - traverse(p); + if (rn_debug) + fprintf(stderr, "squid_rn_insert: Going In:\n"); + traverse(p); #endif - t = squid_rn_newpair(v_arg, b, nodes); - tt = t->rn_l; - if ((cp[p->rn_off] & p->rn_bmask) == 0) - p->rn_l = t; - else - p->rn_r = t; - x->rn_p = t; - t->rn_p = p; /* frees x, p as temp vars below */ - if ((cp[t->rn_off] & t->rn_bmask) == 0) { - t->rn_r = x; - } else { - t->rn_r = tt; - t->rn_l = x; - } + t = squid_rn_newpair(v_arg, b, nodes); + tt = t->rn_l; + if ((cp[p->rn_off] & p->rn_bmask) == 0) + p->rn_l = t; + else + p->rn_r = t; + x->rn_p = t; + t->rn_p = p; /* frees x, p as temp vars below */ + if ((cp[t->rn_off] & t->rn_bmask) == 0) { + t->rn_r = x; + } else { + t->rn_r = tt; + t->rn_l = x; + } #ifdef RN_DEBUG - if (rn_debug) - log(LOG_DEBUG, "squid_rn_insert: Coming Out:\n"), traverse(p); + if (rn_debug) + log(LOG_DEBUG, "squid_rn_insert: Coming Out:\n"), traverse(p); #endif } return (tt); } struct squid_radix_node * -squid_rn_addmask(void *n_arg, int search, int skip) -{ + squid_rn_addmask(void *n_arg, int search, int skip) { caddr_t netmask = (caddr_t) n_arg; register struct squid_radix_node *x; register caddr_t cp, cplim; @@ -481,45 +473,45 @@ squid_rn_addmask(void *n_arg, int search, int skip) static int last_zeroed = 0; if ((mlen = *(u_char *) netmask) > squid_max_keylen) - mlen = squid_max_keylen; + mlen = squid_max_keylen; if (skip == 0) - skip = 1; + skip = 1; if (mlen <= skip) - return (squid_mask_rnhead->rnh_nodes); + return (squid_mask_rnhead->rnh_nodes); if (skip > 1) - memcpy(addmask_key + 1, rn_ones + 1, skip - 1); + memcpy(addmask_key + 1, rn_ones + 1, skip - 1); if ((m0 = mlen) > skip) - memcpy(addmask_key + skip, netmask + skip, mlen - skip); + memcpy(addmask_key + skip, netmask + skip, mlen - skip); /* * Trim trailing zeroes. */ for (cp = addmask_key + mlen; (cp > addmask_key) && cp[-1] == 0;) - cp--; + cp--; mlen = cp - addmask_key; if (mlen <= skip) { - if (m0 >= last_zeroed) - last_zeroed = mlen; - return (squid_mask_rnhead->rnh_nodes); + if (m0 >= last_zeroed) + last_zeroed = mlen; + return (squid_mask_rnhead->rnh_nodes); } if (m0 < last_zeroed) - memset(addmask_key + m0, '\0', last_zeroed - m0); + memset(addmask_key + m0, '\0', last_zeroed - m0); *addmask_key = last_zeroed = mlen; x = squid_rn_search(addmask_key, rn_masktop); if (memcmp(addmask_key, x->rn_key, mlen) != 0) - x = 0; + x = 0; if (x || search) - return (x); + return (x); squid_R_Malloc(x, struct squid_radix_node *, squid_max_keylen + 2 * sizeof(*x)); if ((saved_x = x) == 0) - return (0); + return (0); memset(x, '\0', squid_max_keylen + 2 * sizeof(*x)); netmask = cp = (caddr_t) (x + 2); memcpy(cp, addmask_key, mlen); x = squid_rn_insert(cp, squid_mask_rnhead, &maskduplicated, x); if (maskduplicated) { - fprintf(stderr, "squid_rn_addmask: mask impossibly already in tree"); - squid_Free(saved_x); - return (x); + fprintf(stderr, "squid_rn_addmask: mask impossibly already in tree"); + squid_Free(saved_x); + return (x); } /* * Calculate index of mask, and check for normalcy. @@ -527,17 +519,17 @@ squid_rn_addmask(void *n_arg, int search, int skip) cplim = netmask + mlen; isnormal = 1; for (cp = netmask + skip; (cp < cplim) && *(u_char *) cp == 0xff;) - cp++; + cp++; if (cp != cplim) { - for (j = 0x80; (j & *cp) != 0; j >>= 1) - b++; - if (*cp != normal_chars[b] || cp != (cplim - 1)) - isnormal = 0; + for (j = 0x80; (j & *cp) != 0; j >>= 1) + b++; + if (*cp != normal_chars[b] || cp != (cplim - 1)) + isnormal = 0; } b += (cp - netmask) << 3; x->rn_b = -1 - b; if (isnormal) - x->rn_flags |= RNF_NORMAL; + x->rn_flags |= RNF_NORMAL; return (x); } @@ -547,39 +539,37 @@ rn_lexobetter(void *m_arg, void *n_arg) register u_char *mp = m_arg, *np = n_arg, *lim; if (*mp > *np) - return 1; /* not really, but need to check longer one first */ + return 1; /* not really, but need to check longer one first */ if (*mp == *np) - for (lim = mp + *mp; mp < lim;) - if (*mp++ > *np++) - return 1; + for (lim = mp + *mp; mp < lim;) + if (*mp++ > *np++) + return 1; return 0; } static struct squid_radix_mask * -rn_new_radix_mask(struct squid_radix_node *tt, struct squid_radix_mask *next) -{ + rn_new_radix_mask(struct squid_radix_node *tt, struct squid_radix_mask *next) { register struct squid_radix_mask *m; squid_MKGet(m); if (m == 0) { - fprintf(stderr, "Mask for route not entered\n"); - return (0); + fprintf(stderr, "Mask for route not entered\n"); + return (0); } memset(m, '\0', sizeof *m); m->rm_b = tt->rn_b; m->rm_flags = tt->rn_flags; if (tt->rn_flags & RNF_NORMAL) - m->rm_leaf = tt; + m->rm_leaf = tt; else - m->rm_mask = tt->rn_mask; + m->rm_mask = tt->rn_mask; m->rm_mklist = next; tt->rn_mklist = m; return m; } struct squid_radix_node * -squid_rn_addroute(void *v_arg, void *n_arg, struct squid_radix_node_head *head, struct squid_radix_node treenodes[2]) -{ + squid_rn_addroute(void *v_arg, void *n_arg, struct squid_radix_node_head *head, struct squid_radix_node treenodes[2]) { caddr_t v = (caddr_t) v_arg, netmask = (caddr_t) n_arg; register struct squid_radix_node *t, *x = NULL, *tt; struct squid_radix_node *saved_tt, *top = head->rnh_treetop; @@ -596,106 +586,106 @@ squid_rn_addroute(void *v_arg, void *n_arg, struct squid_radix_node_head *head, * nodes and possibly save time in calculating indices. */ if (netmask) { - if ((x = squid_rn_addmask(netmask, 0, top->rn_off)) == 0) - return (0); - b_leaf = x->rn_b; - b = -1 - x->rn_b; - netmask = x->rn_key; + if ((x = squid_rn_addmask(netmask, 0, top->rn_off)) == 0) + return (0); + b_leaf = x->rn_b; + b = -1 - x->rn_b; + netmask = x->rn_key; } /* * Deal with duplicated keys: attach node to previous instance */ saved_tt = tt = squid_rn_insert(v, head, &keyduplicated, treenodes); if (keyduplicated) { - for (t = tt; tt; t = tt, tt = tt->rn_dupedkey) { - if (tt->rn_mask == netmask) - return (0); - if (netmask == 0 || - (tt->rn_mask && - ((b_leaf < tt->rn_b) || /* index(netmask) > node */ - squid_rn_refines(netmask, tt->rn_mask) || - rn_lexobetter(netmask, tt->rn_mask)))) - break; - } - /* - * If the mask is not duplicated, we wouldn't - * find it among possible duplicate key entries - * anyway, so the above test doesn't hurt. - * - * We sort the masks for a duplicated key the same way as - * in a masklist -- most specific to least specific. - * This may require the unfortunate nuisance of relocating - * the head of the list. - */ - if (tt == saved_tt) { - struct squid_radix_node *xx = x; - /* link in at head of list */ - (tt = treenodes)->rn_dupedkey = t; - tt->rn_flags = t->rn_flags; - tt->rn_p = x = t->rn_p; - if (x->rn_l == t) - x->rn_l = tt; - else - x->rn_r = tt; - saved_tt = tt; - x = xx; - } else { - (tt = treenodes)->rn_dupedkey = t->rn_dupedkey; - t->rn_dupedkey = tt; - } + for (t = tt; tt; t = tt, tt = tt->rn_dupedkey) { + if (tt->rn_mask == netmask) + return (0); + if (netmask == 0 || + (tt->rn_mask && + ((b_leaf < tt->rn_b) || /* index(netmask) > node */ + squid_rn_refines(netmask, tt->rn_mask) || + rn_lexobetter(netmask, tt->rn_mask)))) + break; + } + /* + * If the mask is not duplicated, we wouldn't + * find it among possible duplicate key entries + * anyway, so the above test doesn't hurt. + * + * We sort the masks for a duplicated key the same way as + * in a masklist -- most specific to least specific. + * This may require the unfortunate nuisance of relocating + * the head of the list. + */ + if (tt == saved_tt) { + struct squid_radix_node *xx = x; + /* link in at head of list */ + (tt = treenodes)->rn_dupedkey = t; + tt->rn_flags = t->rn_flags; + tt->rn_p = x = t->rn_p; + if (x->rn_l == t) + x->rn_l = tt; + else + x->rn_r = tt; + saved_tt = tt; + x = xx; + } else { + (tt = treenodes)->rn_dupedkey = t->rn_dupedkey; + t->rn_dupedkey = tt; + } #ifdef RN_DEBUG - t = tt + 1; - tt->rn_info = rn_nodenum++; - t->rn_info = rn_nodenum++; - tt->rn_twin = t; - tt->rn_ybro = rn_clist; - rn_clist = tt; + t = tt + 1; + tt->rn_info = rn_nodenum++; + t->rn_info = rn_nodenum++; + tt->rn_twin = t; + tt->rn_ybro = rn_clist; + rn_clist = tt; #endif - tt->rn_key = (caddr_t) v; - tt->rn_b = -1; - tt->rn_flags = RNF_ACTIVE; + tt->rn_key = (caddr_t) v; + tt->rn_b = -1; + tt->rn_flags = RNF_ACTIVE; } /* * Put mask in tree. */ if (netmask) { - tt->rn_mask = netmask; - tt->rn_b = x->rn_b; - tt->rn_flags |= x->rn_flags & RNF_NORMAL; + tt->rn_mask = netmask; + tt->rn_b = x->rn_b; + tt->rn_flags |= x->rn_flags & RNF_NORMAL; } t = saved_tt->rn_p; if (keyduplicated) - goto on2; + goto on2; b_leaf = -1 - t->rn_b; if (t->rn_r == saved_tt) - x = t->rn_l; + x = t->rn_l; else - x = t->rn_r; + x = t->rn_r; /* Promote general routes from below */ if (x->rn_b < 0) { - for (mp = &t->rn_mklist; x; x = x->rn_dupedkey) - if (x->rn_mask && (x->rn_b >= b_leaf) && x->rn_mklist == 0) { - if ((*mp = m = rn_new_radix_mask(x, 0))) - mp = &m->rm_mklist; - } + for (mp = &t->rn_mklist; x; x = x->rn_dupedkey) + if (x->rn_mask && (x->rn_b >= b_leaf) && x->rn_mklist == 0) { + if ((*mp = m = rn_new_radix_mask(x, 0))) + mp = &m->rm_mklist; + } } else if (x->rn_mklist) { - /* - * Skip over masks whose index is > that of new node - */ - for (mp = &x->rn_mklist; (m = *mp); mp = &m->rm_mklist) - if (m->rm_b >= b_leaf) - break; - t->rn_mklist = m; - *mp = 0; + /* + * Skip over masks whose index is > that of new node + */ + for (mp = &x->rn_mklist; (m = *mp); mp = &m->rm_mklist) + if (m->rm_b >= b_leaf) + break; + t->rn_mklist = m; + *mp = 0; } - on2: +on2: /* Add new route to highest possible ancestor's list */ if ((netmask == 0) || (b > t->rn_b)) - return tt; /* can't lift at all */ + return tt; /* can't lift at all */ b_leaf = tt->rn_b; do { - x = t; - t = t->rn_p; + x = t; + t = t->rn_p; } while (b <= t->rn_b && x != top); /* * Search through routes associated with node to @@ -704,34 +694,33 @@ squid_rn_addroute(void *v_arg, void *n_arg, struct squid_radix_node_head *head, * double loop on deletion. */ for (mp = &x->rn_mklist; (m = *mp); mp = &m->rm_mklist) { - if (m->rm_b < b_leaf) - continue; - if (m->rm_b > b_leaf) - break; - if (m->rm_flags & RNF_NORMAL) { - mmask = m->rm_leaf->rn_mask; - if (tt->rn_flags & RNF_NORMAL) { - fprintf(stderr, - "Non-unique normal route, mask not entered"); - return tt; - } - } else - mmask = m->rm_mask; - if (mmask == netmask) { - m->rm_refs++; - tt->rn_mklist = m; - return tt; - } - if (squid_rn_refines(netmask, mmask) || rn_lexobetter(netmask, mmask)) - break; + if (m->rm_b < b_leaf) + continue; + if (m->rm_b > b_leaf) + break; + if (m->rm_flags & RNF_NORMAL) { + mmask = m->rm_leaf->rn_mask; + if (tt->rn_flags & RNF_NORMAL) { + fprintf(stderr, + "Non-unique normal route, mask not entered"); + return tt; + } + } else + mmask = m->rm_mask; + if (mmask == netmask) { + m->rm_refs++; + tt->rn_mklist = m; + return tt; + } + if (squid_rn_refines(netmask, mmask) || rn_lexobetter(netmask, mmask)) + break; } *mp = rn_new_radix_mask(tt, *mp); return tt; } struct squid_radix_node * -squid_rn_delete(void *v_arg, void *netmask_arg, struct squid_radix_node_head *head) -{ + squid_rn_delete(void *v_arg, void *netmask_arg, struct squid_radix_node_head *head) { register struct squid_radix_node *t, *p, *x, *tt; struct squid_radix_mask *m, *saved_m, **mp; struct squid_radix_node *dupedkey, *saved_tt, *top; @@ -747,141 +736,141 @@ squid_rn_delete(void *v_arg, void *netmask_arg, struct squid_radix_node_head *he saved_tt = tt; top = x; if (tt == 0 || - memcmp(v + head_off, tt->rn_key + head_off, vlen - head_off)) - return (0); + memcmp(v + head_off, tt->rn_key + head_off, vlen - head_off)) + return (0); /* * Delete our route from mask lists. */ if (netmask) { - if ((x = squid_rn_addmask(netmask, 1, head_off)) == 0) - return (0); - netmask = x->rn_key; - while (tt->rn_mask != netmask) - if ((tt = tt->rn_dupedkey) == 0) - return (0); + if ((x = squid_rn_addmask(netmask, 1, head_off)) == 0) + return (0); + netmask = x->rn_key; + while (tt->rn_mask != netmask) + if ((tt = tt->rn_dupedkey) == 0) + return (0); } if (tt->rn_mask == 0 || (saved_m = m = tt->rn_mklist) == 0) - goto on1; + goto on1; if (tt->rn_flags & RNF_NORMAL) { - if (m->rm_leaf != tt || m->rm_refs > 0) { - fprintf(stderr, "squid_rn_delete: inconsistent annotation\n"); - return 0; /* dangling ref could cause disaster */ - } + if (m->rm_leaf != tt || m->rm_refs > 0) { + fprintf(stderr, "squid_rn_delete: inconsistent annotation\n"); + return 0; /* dangling ref could cause disaster */ + } } else { - if (m->rm_mask != tt->rn_mask) { - fprintf(stderr, "squid_rn_delete: inconsistent annotation\n"); - goto on1; - } - if (--m->rm_refs >= 0) - goto on1; + if (m->rm_mask != tt->rn_mask) { + fprintf(stderr, "squid_rn_delete: inconsistent annotation\n"); + goto on1; + } + if (--m->rm_refs >= 0) + goto on1; } b = -1 - tt->rn_b; t = saved_tt->rn_p; if (b > t->rn_b) - goto on1; /* Wasn't lifted at all */ + goto on1; /* Wasn't lifted at all */ do { - x = t; - t = t->rn_p; + x = t; + t = t->rn_p; } while (b <= t->rn_b && x != top); for (mp = &x->rn_mklist; (m = *mp); mp = &m->rm_mklist) - if (m == saved_m) { - *mp = m->rm_mklist; - squid_MKFree(m); - break; - } + if (m == saved_m) { + *mp = m->rm_mklist; + squid_MKFree(m); + break; + } if (m == 0) { - fprintf(stderr, "squid_rn_delete: couldn't find our annotation\n"); - if (tt->rn_flags & RNF_NORMAL) - return (0); /* Dangling ref to us */ + fprintf(stderr, "squid_rn_delete: couldn't find our annotation\n"); + if (tt->rn_flags & RNF_NORMAL) + return (0); /* Dangling ref to us */ } - on1: +on1: /* * Eliminate us from tree */ if (tt->rn_flags & RNF_ROOT) - return (0); + return (0); #ifdef RN_DEBUG /* Get us out of the creation list */ for (t = rn_clist; t && t->rn_ybro != tt; t = t->rn_ybro) { } if (t) - t->rn_ybro = tt->rn_ybro; + t->rn_ybro = tt->rn_ybro; #endif t = tt->rn_p; if ((dupedkey = saved_tt->rn_dupedkey)) { - if (tt == saved_tt) { - x = dupedkey; - x->rn_p = t; - if (t->rn_l == tt) - t->rn_l = x; - else - t->rn_r = x; - } else { - for (x = p = saved_tt; p && p->rn_dupedkey != tt;) - p = p->rn_dupedkey; - if (p) - p->rn_dupedkey = tt->rn_dupedkey; - else - fprintf(stderr, "squid_rn_delete: couldn't find us\n"); - } - t = tt + 1; - if (t->rn_flags & RNF_ACTIVE) { + if (tt == saved_tt) { + x = dupedkey; + x->rn_p = t; + if (t->rn_l == tt) + t->rn_l = x; + else + t->rn_r = x; + } else { + for (x = p = saved_tt; p && p->rn_dupedkey != tt;) + p = p->rn_dupedkey; + if (p) + p->rn_dupedkey = tt->rn_dupedkey; + else + fprintf(stderr, "squid_rn_delete: couldn't find us\n"); + } + t = tt + 1; + if (t->rn_flags & RNF_ACTIVE) { #ifndef RN_DEBUG - *++x = *t; - p = t->rn_p; + *++x = *t; + p = t->rn_p; #else - b = t->rn_info; - *++x = *t; - t->rn_info = b; - p = t->rn_p; + b = t->rn_info; + *++x = *t; + t->rn_info = b; + p = t->rn_p; #endif - if (p->rn_l == t) - p->rn_l = x; - else - p->rn_r = x; - x->rn_l->rn_p = x; - x->rn_r->rn_p = x; - } - goto out; + if (p->rn_l == t) + p->rn_l = x; + else + p->rn_r = x; + x->rn_l->rn_p = x; + x->rn_r->rn_p = x; + } + goto out; } if (t->rn_l == tt) - x = t->rn_r; + x = t->rn_r; else - x = t->rn_l; + x = t->rn_l; p = t->rn_p; if (p->rn_r == t) - p->rn_r = x; + p->rn_r = x; else - p->rn_l = x; + p->rn_l = x; x->rn_p = p; /* * Demote routes attached to us. */ if (t->rn_mklist) { - if (x->rn_b >= 0) { - for (mp = &x->rn_mklist; (m = *mp);) - mp = &m->rm_mklist; - *mp = t->rn_mklist; - } else { - /* If there are any key,mask pairs in a sibling - * duped-key chain, some subset will appear sorted - * in the same order attached to our mklist */ - for (m = t->rn_mklist; m && x; x = x->rn_dupedkey) - if (m == x->rn_mklist) { - struct squid_radix_mask *mm = m->rm_mklist; - x->rn_mklist = 0; - if (--(m->rm_refs) < 0) - squid_MKFree(m); - m = mm; - } + if (x->rn_b >= 0) { + for (mp = &x->rn_mklist; (m = *mp);) + mp = &m->rm_mklist; + *mp = t->rn_mklist; + } else { + /* If there are any key,mask pairs in a sibling + * duped-key chain, some subset will appear sorted + * in the same order attached to our mklist */ + for (m = t->rn_mklist; m && x; x = x->rn_dupedkey) + if (m == x->rn_mklist) { + struct squid_radix_mask *mm = m->rm_mklist; + x->rn_mklist = 0; + if (--(m->rm_refs) < 0) + squid_MKFree(m); + m = mm; + } #if RN_DEBUG - if (m) - fprintf(stderr, "%s %x at %x\n", - "squid_rn_delete: Orphaned Mask", (int) m, (int) x); + if (m) + fprintf(stderr, "%s %x at %x\n", + "squid_rn_delete: Orphaned Mask", (int) m, (int) x); #else - assert(m == NULL); + assert(m == NULL); #endif - } + } } /* * We may be holding an active internal node in the tree. @@ -889,21 +878,21 @@ squid_rn_delete(void *v_arg, void *netmask_arg, struct squid_radix_node_head *he x = tt + 1; if (t != x) { #ifndef RN_DEBUG - *t = *x; + *t = *x; #else - b = t->rn_info; - *t = *x; - t->rn_info = b; + b = t->rn_info; + *t = *x; + t->rn_info = b; #endif - t->rn_l->rn_p = t; - t->rn_r->rn_p = t; - p = x->rn_p; - if (p->rn_l == x) - p->rn_l = t; - else - p->rn_r = t; + t->rn_l->rn_p = t; + t->rn_r->rn_p = t; + p = x->rn_p; + if (p->rn_l == x) + p->rn_l = t; + else + p->rn_r = t; } - out: +out: tt->rn_flags &= ~RNF_ACTIVE; tt[1].rn_flags &= ~RNF_ACTIVE; return (tt); @@ -922,25 +911,25 @@ squid_rn_walktree(struct squid_radix_node_head *h, int (*f) (struct squid_radix_ */ /* First time through node, go left */ while (rn->rn_b >= 0) - rn = rn->rn_l; + rn = rn->rn_l; for (;;) { - base = rn; - /* If at right child go back up, otherwise, go right */ - while (rn->rn_p->rn_r == rn && (rn->rn_flags & RNF_ROOT) == 0) - rn = rn->rn_p; - /* Find the next *leaf* since next node might vanish, too */ - for (rn = rn->rn_p->rn_r; rn->rn_b >= 0;) - rn = rn->rn_l; - next = rn; - /* Process leaves */ - while ((rn = base)) { - base = rn->rn_dupedkey; - if (!(rn->rn_flags & RNF_ROOT) && (error = (*f) (rn, w))) - return (error); - } - rn = next; - if (rn->rn_flags & RNF_ROOT) - return (0); + base = rn; + /* If at right child go back up, otherwise, go right */ + while (rn->rn_p->rn_r == rn && (rn->rn_flags & RNF_ROOT) == 0) + rn = rn->rn_p; + /* Find the next *leaf* since next node might vanish, too */ + for (rn = rn->rn_p->rn_r; rn->rn_b >= 0;) + rn = rn->rn_l; + next = rn; + /* Process leaves */ + while ((rn = base)) { + base = rn->rn_dupedkey; + if (!(rn->rn_flags & RNF_ROOT) && (error = (*f) (rn, w))) + return (error); + } + rn = next; + if (rn->rn_flags & RNF_ROOT) + return (0); } /* NOTREACHED */ } @@ -951,10 +940,10 @@ squid_rn_inithead(struct squid_radix_node_head **head, int off) register struct squid_radix_node_head *rnh; register struct squid_radix_node *t, *tt, *ttt; if (*head) - return (1); + return (1); squid_R_Malloc(rnh, struct squid_radix_node_head *, sizeof(*rnh)); if (rnh == 0) - return (0); + return (0); memset(rnh, '\0', sizeof(*rnh)); *head = rnh; t = squid_rn_newpair(rn_zeros, off, rnh->rnh_nodes); @@ -983,26 +972,26 @@ squid_rn_init(void) struct domain *dom; for (dom = domains; dom; dom = dom->dom_next) - if (dom->dom_maxrtkey > squid_max_keylen) - squid_max_keylen = dom->dom_maxrtkey; + if (dom->dom_maxrtkey > squid_max_keylen) + squid_max_keylen = dom->dom_maxrtkey; #endif if (squid_max_keylen == 0) { - fprintf(stderr, - "squid_rn_init: radix functions require squid_max_keylen be set\n"); - return; + fprintf(stderr, + "squid_rn_init: radix functions require squid_max_keylen be set\n"); + return; } squid_R_Malloc(rn_zeros, char *, 3 * squid_max_keylen); if (rn_zeros == NULL) { - fprintf(stderr, "squid_rn_init failed.\n"); - exit(-1); + fprintf(stderr, "squid_rn_init failed.\n"); + exit(-1); } memset(rn_zeros, '\0', 3 * squid_max_keylen); rn_ones = cp = rn_zeros + squid_max_keylen; addmask_key = cplim = rn_ones + squid_max_keylen; while (cp < cplim) - *cp++ = -1; + *cp++ = -1; if (squid_rn_inithead(&squid_mask_rnhead, 0) == 0) { - fprintf(stderr, "rn_init2 failed.\n"); - exit(-1); + fprintf(stderr, "rn_init2 failed.\n"); + exit(-1); } } diff --git a/lib/rfc1035.c b/lib/rfc1035.c index 1929e43df2..bc8fa12836 100644 --- a/lib/rfc1035.c +++ b/lib/rfc1035.c @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -35,7 +35,7 @@ /* * KNOWN BUGS: - * + * * UDP replies with TC set should be retried via TCP */ @@ -88,7 +88,7 @@ const char *rfc1035_error_message; /* * rfc1035HeaderPack() - * + * * Packs a rfc1035_header structure into a buffer. * Returns number of octets packed (should always be 12) */ @@ -131,7 +131,7 @@ rfc1035HeaderPack(char *buf, size_t sz, rfc1035_message * hdr) /* * rfc1035LabelPack() - * + * * Packs a label into a buffer. The format of * a label is one octet specifying the number of character * bytes to follow. Labels must be smaller than 64 octets. @@ -143,9 +143,9 @@ rfc1035LabelPack(char *buf, size_t sz, const char *label) int off = 0; size_t len = label ? strlen(label) : 0; if (label) - assert(!strchr(label, '.')); + assert(!strchr(label, '.')); if (len > RFC1035_MAXLABELSZ) - len = RFC1035_MAXLABELSZ; + len = RFC1035_MAXLABELSZ; assert(sz >= len + 1); *(buf + off) = (char) len; off++; @@ -156,7 +156,7 @@ rfc1035LabelPack(char *buf, size_t sz, const char *label) /* * rfc1035NamePack() - * + * * Packs a name into a buffer. Names are packed as a * sequence of labels, terminated with NULL label. * Note message compression is not supported here. @@ -172,7 +172,7 @@ rfc1035NamePack(char *buf, size_t sz, const char *name) * NOTE: use of strtok here makes names like foo....com valid. */ for (t = strtok(copy, "."); t; t = strtok(NULL, ".")) - off += rfc1035LabelPack(buf + off, sz - off, t); + off += rfc1035LabelPack(buf + off, sz - off, t); xfree(copy); off += rfc1035LabelPack(buf + off, sz - off, NULL); assert(off <= sz); @@ -181,16 +181,16 @@ rfc1035NamePack(char *buf, size_t sz, const char *name) /* * rfc1035QuestionPack() - * + * * Packs a QUESTION section of a message. * Returns number of octets packed. */ int rfc1035QuestionPack(char *buf, - const size_t sz, - const char *name, - const unsigned short type, - const unsigned short _class) + const size_t sz, + const char *name, + const unsigned short type, + const unsigned short _class) { unsigned int off = 0; unsigned short s; @@ -207,7 +207,7 @@ rfc1035QuestionPack(char *buf, /* * rfc1035HeaderUnpack() - * + * * Unpacks a RFC1035 message header buffer into the header fields * of the rfc1035_message structure. * @@ -227,7 +227,7 @@ rfc1035HeaderUnpack(const char *buf, size_t sz, unsigned int *off, rfc1035_messa * is less than that. */ if (sz < 12) - return 1; + return 1; memcpy(&s, buf + (*off), sizeof(s)); (*off) += sizeof(s); h->id = ntohs(s); @@ -266,7 +266,7 @@ rfc1035HeaderUnpack(const char *buf, size_t sz, unsigned int *off, rfc1035_messa /* * rfc1035NameUnpack() - * + * * Unpacks a Name in a message buffer into a char*. * Note 'buf' points to the beginning of the whole message, * 'off' points to the spot where the Name begins, and 'sz' @@ -287,9 +287,9 @@ rfc1035NameUnpack(const char *buf, size_t sz, unsigned int *off, unsigned short size_t len; assert(ns > 0); do { - assert((*off) < sz); - c = *(buf + (*off)); - if (c > 191) { + assert((*off) < sz); + c = *(buf + (*off)); + if (c > 191) { /* blasted compression */ unsigned short s; unsigned int ptr; @@ -297,52 +297,52 @@ rfc1035NameUnpack(const char *buf, size_t sz, unsigned int *off, unsigned short RFC1035_UNPACK_DEBUG; return 1; } - memcpy(&s, buf + (*off), sizeof(s)); - s = ntohs(s); - (*off) += sizeof(s); - /* Sanity check */ + memcpy(&s, buf + (*off), sizeof(s)); + s = ntohs(s); + (*off) += sizeof(s); + /* Sanity check */ if ((*off) > sz) { RFC1035_UNPACK_DEBUG; - return 1; + return 1; } - ptr = s & 0x3FFF; - /* Make sure the pointer is inside this message */ + ptr = s & 0x3FFF; + /* Make sure the pointer is inside this message */ if (ptr >= sz) { RFC1035_UNPACK_DEBUG; - return 1; + return 1; } - return rfc1035NameUnpack(buf, sz, &ptr, rdlength, name + no, ns - no, rdepth + 1); - } else if (c > RFC1035_MAXLABELSZ) { - /* - * "(The 10 and 01 combinations are reserved for future use.)" - */ + return rfc1035NameUnpack(buf, sz, &ptr, rdlength, name + no, ns - no, rdepth + 1); + } else if (c > RFC1035_MAXLABELSZ) { + /* + * "(The 10 and 01 combinations are reserved for future use.)" + */ RFC1035_UNPACK_DEBUG; - return 1; - } else { - (*off)++; - len = (size_t) c; - if (len == 0) - break; - if (len > (ns - no - 1)) { /* label won't fit */ + return 1; + } else { + (*off)++; + len = (size_t) c; + if (len == 0) + break; + if (len > (ns - no - 1)) { /* label won't fit */ RFC1035_UNPACK_DEBUG; return 1; } - if ((*off) + len >= sz) { /* message is too short */ + if ((*off) + len >= sz) { /* message is too short */ RFC1035_UNPACK_DEBUG; return 1; } - memcpy(name + no, buf + (*off), len); - (*off) += len; - no += len; - *(name + (no++)) = '.'; - if (rdlength) - *rdlength += len + 1; - } + memcpy(name + no, buf + (*off), len); + (*off) += len; + no += len; + *(name + (no++)) = '.'; + if (rdlength) + *rdlength += len + 1; + } } while (c > 0 && no < ns); if (no) - *(name + no - 1) = '\0'; + *(name + no - 1) = '\0'; else - *name = '\0'; + *name = '\0'; /* make sure we didn't allow someone to overflow the name buffer */ assert(no <= ns); return 0; @@ -350,7 +350,7 @@ rfc1035NameUnpack(const char *buf, size_t sz, unsigned int *off, unsigned short /* * rfc1035RRUnpack() - * + * * Unpacks a RFC1035 Resource Record into 'RR' from a message buffer. * The caller must free RR->rdata! * @@ -366,18 +366,18 @@ rfc1035RRUnpack(const char *buf, size_t sz, unsigned int *off, rfc1035_rr * RR) unsigned short rdlength; unsigned int rdata_off; if (rfc1035NameUnpack(buf, sz, off, NULL, RR->name, RFC1035_MAXHOSTNAMESZ, 0)) { - RFC1035_UNPACK_DEBUG; - memset(RR, '\0', sizeof(*RR)); - return 1; + RFC1035_UNPACK_DEBUG; + memset(RR, '\0', sizeof(*RR)); + return 1; } /* * Make sure the remaining message has enough octets for the * rest of the RR fields. */ if ((*off) + 10 > sz) { - RFC1035_UNPACK_DEBUG; - memset(RR, '\0', sizeof(*RR)); - return 1; + RFC1035_UNPACK_DEBUG; + memset(RR, '\0', sizeof(*RR)); + return 1; } memcpy(&s, buf + (*off), sizeof(s)); (*off) += sizeof(s); @@ -392,13 +392,13 @@ rfc1035RRUnpack(const char *buf, size_t sz, unsigned int *off, rfc1035_rr * RR) (*off) += sizeof(s); rdlength = ntohs(s); if ((*off) + rdlength > sz) { - /* - * We got a truncated packet. 'dnscache' truncates UDP - * replies at 512 octets, as per RFC 1035. - */ - RFC1035_UNPACK_DEBUG; - memset(RR, '\0', sizeof(*RR)); - return 1; + /* + * We got a truncated packet. 'dnscache' truncates UDP + * replies at 512 octets, as per RFC 1035. + */ + RFC1035_UNPACK_DEBUG; + memset(RR, '\0', sizeof(*RR)); + return 1; } RR->rdlength = rdlength; switch (RR->type) { @@ -406,30 +406,30 @@ rfc1035RRUnpack(const char *buf, size_t sz, unsigned int *off, rfc1035_rr * RR) case RFC1035_TYPE_CNAME: #endif case RFC1035_TYPE_PTR: - RR->rdata = (char*)xmalloc(RFC1035_MAXHOSTNAMESZ); - rdata_off = *off; - RR->rdlength = 0; /* Filled in by rfc1035NameUnpack */ - if (rfc1035NameUnpack(buf, sz, &rdata_off, &RR->rdlength, RR->rdata, RFC1035_MAXHOSTNAMESZ, 0)) { + RR->rdata = (char*)xmalloc(RFC1035_MAXHOSTNAMESZ); + rdata_off = *off; + RR->rdlength = 0; /* Filled in by rfc1035NameUnpack */ + if (rfc1035NameUnpack(buf, sz, &rdata_off, &RR->rdlength, RR->rdata, RFC1035_MAXHOSTNAMESZ, 0)) { RFC1035_UNPACK_DEBUG; return 1; } - if (rdata_off > ((*off) + rdlength)) { - /* - * This probably doesn't happen for valid packets, but - * I want to make sure that NameUnpack doesn't go beyond - * the RDATA area. - */ - RFC1035_UNPACK_DEBUG; - xfree(RR->rdata); - memset(RR, '\0', sizeof(*RR)); - return 1; - } - break; + if (rdata_off > ((*off) + rdlength)) { + /* + * This probably doesn't happen for valid packets, but + * I want to make sure that NameUnpack doesn't go beyond + * the RDATA area. + */ + RFC1035_UNPACK_DEBUG; + xfree(RR->rdata); + memset(RR, '\0', sizeof(*RR)); + return 1; + } + break; case RFC1035_TYPE_A: default: - RR->rdata = (char*)xmalloc(rdlength); - memcpy(RR->rdata, buf + (*off), rdlength); - break; + RR->rdata = (char*)xmalloc(rdlength); + memcpy(RR->rdata, buf + (*off), rdlength); + break; } (*off) += rdlength; assert((*off) <= sz); @@ -441,35 +441,35 @@ rfc1035SetErrno(int n) { switch (rfc1035_errno = n) { case 0: - rfc1035_error_message = "No error condition"; - break; + rfc1035_error_message = "No error condition"; + break; case 1: - rfc1035_error_message = "Format Error: The name server was " - "unable to interpret the query."; - break; + rfc1035_error_message = "Format Error: The name server was " + "unable to interpret the query."; + break; case 2: - rfc1035_error_message = "Server Failure: The name server was " - "unable to process this query."; - break; + rfc1035_error_message = "Server Failure: The name server was " + "unable to process this query."; + break; case 3: - rfc1035_error_message = "Name Error: The domain name does " - "not exist."; - break; + rfc1035_error_message = "Name Error: The domain name does " + "not exist."; + break; case 4: - rfc1035_error_message = "Not Implemented: The name server does " - "not support the requested kind of query."; - break; + rfc1035_error_message = "Not Implemented: The name server does " + "not support the requested kind of query."; + break; case 5: - rfc1035_error_message = "Refused: The name server refuses to " - "perform the specified operation."; - break; + rfc1035_error_message = "Refused: The name server refuses to " + "perform the specified operation."; + break; case rfc1035_unpack_error: - rfc1035_error_message = "The DNS reply message is corrupt or could " - "not be safely parsed."; - break; + rfc1035_error_message = "The DNS reply message is corrupt or could " + "not be safely parsed."; + break; default: - rfc1035_error_message = "Unknown Error"; - break; + rfc1035_error_message = "Unknown Error"; + break; } } @@ -477,12 +477,12 @@ void rfc1035RRDestroy(rfc1035_rr ** rr, int n) { if (*rr == NULL || n < 1) { - return; + return; } while (n--) { - if ((*rr)[n].rdata) - xfree((*rr)[n].rdata); + if ((*rr)[n].rdata) + xfree((*rr)[n].rdata); } xfree(*rr); *rr = NULL; @@ -490,7 +490,7 @@ rfc1035RRDestroy(rfc1035_rr ** rr, int n) /* * rfc1035QueryUnpack() - * + * * Unpacks a RFC1035 Query Record into 'query' from a message buffer. * * Updates the new message buffer offset. @@ -502,14 +502,14 @@ rfc1035QueryUnpack(const char *buf, size_t sz, unsigned int *off, rfc1035_query { unsigned short s; if (rfc1035NameUnpack(buf, sz, off, NULL, query->name, RFC1035_MAXHOSTNAMESZ, 0)) { - RFC1035_UNPACK_DEBUG; - memset(query, '\0', sizeof(*query)); - return 1; + RFC1035_UNPACK_DEBUG; + memset(query, '\0', sizeof(*query)); + return 1; } if (*off + 4 > sz) { - RFC1035_UNPACK_DEBUG; - memset(query, '\0', sizeof(*query)); - return 1; + RFC1035_UNPACK_DEBUG; + memset(query, '\0', sizeof(*query)); + return 1; } memcpy(&s, buf + *off, 2); *off += 2; @@ -524,18 +524,18 @@ void rfc1035MessageDestroy(rfc1035_message ** msg) { if (!*msg) - return; + return; if ((*msg)->query) - xfree((*msg)->query); + xfree((*msg)->query); if ((*msg)->answer) - rfc1035RRDestroy(&(*msg)->answer, (*msg)->ancount); + rfc1035RRDestroy(&(*msg)->answer, (*msg)->ancount); xfree(*msg); *msg = NULL; } /* * rfc1035QueryCompare() - * + * * Compares two rfc1035_query entries * * Returns 0 (equal) or !=0 (different) @@ -545,20 +545,20 @@ rfc1035QueryCompare(const rfc1035_query * a, const rfc1035_query * b) { size_t la, lb; if (a->qtype != b->qtype) - return 1; + return 1; if (a->qclass != b->qclass) - return 1; + return 1; la = strlen(a->name); lb = strlen(b->name); if (la != lb) { - /* Trim root label(s) */ - while (la > 0 && a->name[la - 1] == '.') - la--; - while (lb > 0 && b->name[lb - 1] == '.') - lb--; + /* Trim root label(s) */ + while (la > 0 && a->name[la - 1] == '.') + la--; + while (lb > 0 && b->name[lb - 1] == '.') + lb--; } if (la != lb) - return 1; + return 1; return strncasecmp(a->name, b->name, la); } @@ -576,8 +576,8 @@ rfc1035QueryCompare(const rfc1035_query * a, const rfc1035_query * b) int rfc1035MessageUnpack(const char *buf, - size_t sz, - rfc1035_message ** answer) + size_t sz, + rfc1035_message ** answer) { unsigned int off = 0; unsigned int i, j; @@ -587,67 +587,67 @@ rfc1035MessageUnpack(const char *buf, rfc1035_query *querys = NULL; msg = (rfc1035_message*)xcalloc(1, sizeof(*msg)); if (rfc1035HeaderUnpack(buf + off, sz - off, &off, msg)) { - RFC1035_UNPACK_DEBUG; - rfc1035SetErrno(rfc1035_unpack_error); - xfree(msg); - return -rfc1035_unpack_error; + RFC1035_UNPACK_DEBUG; + rfc1035SetErrno(rfc1035_unpack_error); + xfree(msg); + return -rfc1035_unpack_error; } rfc1035_errno = 0; rfc1035_error_message = NULL; i = (unsigned int) msg->qdcount; if (i != 1) { - /* This can not be an answer to our queries.. */ - RFC1035_UNPACK_DEBUG; - rfc1035SetErrno(rfc1035_unpack_error); - xfree(msg); - return -rfc1035_unpack_error; + /* This can not be an answer to our queries.. */ + RFC1035_UNPACK_DEBUG; + rfc1035SetErrno(rfc1035_unpack_error); + xfree(msg); + return -rfc1035_unpack_error; } querys = msg->query = (rfc1035_query*)xcalloc(i, sizeof(*querys)); for (j = 0; j < i; j++) { - if (rfc1035QueryUnpack(buf, sz, &off, &querys[j])) { - RFC1035_UNPACK_DEBUG; - rfc1035SetErrno(rfc1035_unpack_error); - rfc1035MessageDestroy(&msg); - return -rfc1035_unpack_error; - } + if (rfc1035QueryUnpack(buf, sz, &off, &querys[j])) { + RFC1035_UNPACK_DEBUG; + rfc1035SetErrno(rfc1035_unpack_error); + rfc1035MessageDestroy(&msg); + return -rfc1035_unpack_error; + } } *answer = msg; if (msg->rcode) { - RFC1035_UNPACK_DEBUG; - rfc1035SetErrno((int) msg->rcode); - return -rfc1035_errno; + RFC1035_UNPACK_DEBUG; + rfc1035SetErrno((int) msg->rcode); + return -rfc1035_errno; } if (msg->ancount == 0) - return 0; + return 0; i = (unsigned int) msg->ancount; recs = msg->answer = (rfc1035_rr*)xcalloc(i, sizeof(*recs)); for (j = 0; j < i; j++) { - if (off >= sz) { /* corrupt packet */ - RFC1035_UNPACK_DEBUG; - break; - } - if (rfc1035RRUnpack(buf, sz, &off, &recs[j])) { /* corrupt RR */ - RFC1035_UNPACK_DEBUG; - break; - } - nr++; + if (off >= sz) { /* corrupt packet */ + RFC1035_UNPACK_DEBUG; + break; + } + if (rfc1035RRUnpack(buf, sz, &off, &recs[j])) { /* corrupt RR */ + RFC1035_UNPACK_DEBUG; + break; + } + nr++; } if (nr == 0) { - /* - * we expected to unpack some answers (ancount != 0), but - * didn't actually get any. - */ - rfc1035MessageDestroy(&msg); - *answer = NULL; - rfc1035SetErrno(rfc1035_unpack_error); - return -rfc1035_unpack_error; + /* + * we expected to unpack some answers (ancount != 0), but + * didn't actually get any. + */ + rfc1035MessageDestroy(&msg); + *answer = NULL; + rfc1035SetErrno(rfc1035_unpack_error); + return -rfc1035_unpack_error; } return nr; } /* * rfc1035BuildAQuery() - * + * * Builds a message buffer with a QUESTION to lookup A records * for a hostname. Caller must allocate 'buf' which should * probably be at least 512 octets. The 'szp' initially @@ -668,14 +668,14 @@ rfc1035BuildAQuery(const char *hostname, char *buf, size_t sz, unsigned short qi h.qdcount = (unsigned int) 1; offset += rfc1035HeaderPack(buf + offset, sz - offset, &h); offset += rfc1035QuestionPack(buf + offset, - sz - offset, - hostname, - RFC1035_TYPE_A, - RFC1035_CLASS_IN); + sz - offset, + hostname, + RFC1035_TYPE_A, + RFC1035_CLASS_IN); if (query) { - query->qtype = RFC1035_TYPE_A; - query->qclass = RFC1035_CLASS_IN; - xstrncpy(query->name, hostname, sizeof(query->name)); + query->qtype = RFC1035_TYPE_A; + query->qclass = RFC1035_CLASS_IN; + xstrncpy(query->name, hostname, sizeof(query->name)); } assert(offset <= sz); return offset; @@ -683,7 +683,7 @@ rfc1035BuildAQuery(const char *hostname, char *buf, size_t sz, unsigned short qi /* * rfc1035BuildPTRQuery() - * + * * Builds a message buffer with a QUESTION to lookup PTR records * for an address. Caller must allocate 'buf' which should * probably be at least 512 octets. The 'szp' initially @@ -701,10 +701,10 @@ rfc1035BuildPTRQuery(const struct in_addr addr, char *buf, size_t sz, unsigned s memset(&h, '\0', sizeof(h)); i = (unsigned int) ntohl(addr.s_addr); snprintf(rev, 32, "%u.%u.%u.%u.in-addr.arpa.", - i & 255, - (i >> 8) & 255, - (i >> 16) & 255, - (i >> 24) & 255); + i & 255, + (i >> 8) & 255, + (i >> 16) & 255, + (i >> 24) & 255); h.id = qid; h.qr = 0; h.rd = 1; @@ -712,14 +712,14 @@ rfc1035BuildPTRQuery(const struct in_addr addr, char *buf, size_t sz, unsigned s h.qdcount = (unsigned int) 1; offset += rfc1035HeaderPack(buf + offset, sz - offset, &h); offset += rfc1035QuestionPack(buf + offset, - sz - offset, - rev, - RFC1035_TYPE_PTR, - RFC1035_CLASS_IN); + sz - offset, + rev, + RFC1035_TYPE_PTR, + RFC1035_CLASS_IN); if (query) { - query->qtype = RFC1035_TYPE_PTR; - query->qclass = RFC1035_CLASS_IN; - xstrncpy(query->name, rev, sizeof(query->name)); + query->qtype = RFC1035_TYPE_PTR; + query->qclass = RFC1035_CLASS_IN; + xstrncpy(query->name, rev, sizeof(query->name)); } assert(offset <= sz); return offset; @@ -752,77 +752,77 @@ main(int argc, char *argv[]) int rl; struct sockaddr_in S; if (3 != argc) { - fprintf(stderr, "usage: %s ip port\n", argv[0]); - return 1; + fprintf(stderr, "usage: %s ip port\n", argv[0]); + return 1; } setbuf(stdout, NULL); setbuf(stderr, NULL); s = socket(PF_INET, SOCK_DGRAM, 0); if (s < 0) { - perror("socket"); - return 1; + perror("socket"); + return 1; } memset(&S, '\0', sizeof(S)); S.sin_family = AF_INET; S.sin_port = htons(atoi(argv[2])); S.sin_addr.s_addr = inet_addr(argv[1]); while (fgets(input, 512, stdin)) { - struct in_addr junk; - strtok(input, "\r\n"); - memset(buf, '\0', 512); - sz = 512; - if (inet_pton(AF_INET, input, &junk)) { - sid = rfc1035BuildPTRQuery(junk, buf, &sz); - } else { - sid = rfc1035BuildAQuery(input, buf, &sz); - } - sendto(s, buf, sz, 0, (struct sockaddr *) &S, sizeof(S)); - do { - fd_set R; - struct timeval to; - FD_ZERO(&R); - FD_SET(s, &R); - to.tv_sec = 10; - to.tv_usec = 0; - rl = select(s + 1, &R, NULL, NULL, &to); - } while (0); - if (rl < 1) { - printf("TIMEOUT\n"); - continue; - } - memset(rbuf, '\0', 512); - rl = recv(s, rbuf, 512, 0); - { - unsigned short rid = 0; - int i; - int n; - rfc1035_rr *answers = NULL; - n = rfc1035AnswersUnpack(rbuf, - rl, - &answers, - &rid); - if (n < 0) { - printf("ERROR %d\n", rfc1035_errno); - } else if (rid != sid) { - printf("ERROR, ID mismatch (%#hx, %#hx)\n", sid, rid); - } else { - printf("%d answers\n", n); - for (i = 0; i < n; i++) { - if (answers[i].type == RFC1035_TYPE_A) { - struct in_addr a; - memcpy(&a, answers[i].rdata, 4); - printf("A\t%d\t%s\n", answers[i].ttl, inet_ntoa(a)); - } else if (answers[i].type == RFC1035_TYPE_PTR) { - char ptr[128]; - strncpy(ptr, answers[i].rdata, answers[i].rdlength); - printf("PTR\t%d\t%s\n", answers[i].ttl, ptr); - } else { - fprintf(stderr, "can't print answer type %d\n", - (int) answers[i].type); - } - } - } - } + struct in_addr junk; + strtok(input, "\r\n"); + memset(buf, '\0', 512); + sz = 512; + if (inet_pton(AF_INET, input, &junk)) { + sid = rfc1035BuildPTRQuery(junk, buf, &sz); + } else { + sid = rfc1035BuildAQuery(input, buf, &sz); + } + sendto(s, buf, sz, 0, (struct sockaddr *) &S, sizeof(S)); + do { + fd_set R; + struct timeval to; + FD_ZERO(&R); + FD_SET(s, &R); + to.tv_sec = 10; + to.tv_usec = 0; + rl = select(s + 1, &R, NULL, NULL, &to); + } while (0); + if (rl < 1) { + printf("TIMEOUT\n"); + continue; + } + memset(rbuf, '\0', 512); + rl = recv(s, rbuf, 512, 0); + { + unsigned short rid = 0; + int i; + int n; + rfc1035_rr *answers = NULL; + n = rfc1035AnswersUnpack(rbuf, + rl, + &answers, + &rid); + if (n < 0) { + printf("ERROR %d\n", rfc1035_errno); + } else if (rid != sid) { + printf("ERROR, ID mismatch (%#hx, %#hx)\n", sid, rid); + } else { + printf("%d answers\n", n); + for (i = 0; i < n; i++) { + if (answers[i].type == RFC1035_TYPE_A) { + struct in_addr a; + memcpy(&a, answers[i].rdata, 4); + printf("A\t%d\t%s\n", answers[i].ttl, inet_ntoa(a)); + } else if (answers[i].type == RFC1035_TYPE_PTR) { + char ptr[128]; + strncpy(ptr, answers[i].rdata, answers[i].rdlength); + printf("PTR\t%d\t%s\n", answers[i].ttl, ptr); + } else { + fprintf(stderr, "can't print answer type %d\n", + (int) answers[i].type); + } + } + } + } } return 0; } diff --git a/lib/rfc1123.c b/lib/rfc1123.c index 6701e823cc..4174bf8589 100644 --- a/lib/rfc1123.c +++ b/lib/rfc1123.c @@ -2,7 +2,7 @@ /* * $Id: rfc1123.c,v 1.41 2007/12/06 02:37:15 amosjeffries Exp $ * - * DEBUG: + * DEBUG: * AUTHOR: Harvest Derived * * SQUID Web Proxy Cache http://www.squid-cache.org/ @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -71,8 +71,7 @@ static int make_month(const char *s); static int make_num(const char *s); -static const char *month_names[12] = -{ +static const char *month_names[12] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; @@ -82,9 +81,9 @@ static int make_num(const char *s) { if (*s >= '0' && *s <= '9') - return 10 * (*s - '0') + *(s + 1) - '0'; + return 10 * (*s - '0') + *(s + 1) - '0'; else - return *(s + 1) - '0'; + return *(s + 1) - '0'; } static int @@ -98,8 +97,8 @@ make_month(const char *s) month[2] = xtolower(*(s + 2)); for (i = 0; i < 12; i++) - if (!strncmp(month_names[i], month, 3)) - return i; + if (!strncmp(month_names[i], month, 3)) + return i; return -1; } @@ -107,54 +106,52 @@ static int tmSaneValues(struct tm *tm) { if (tm->tm_sec < 0 || tm->tm_sec > 59) - return 0; + return 0; if (tm->tm_min < 0 || tm->tm_min > 59) - return 0; + return 0; if (tm->tm_hour < 0 || tm->tm_hour > 23) - return 0; + return 0; if (tm->tm_mday < 1 || tm->tm_mday > 31) - return 0; + return 0; if (tm->tm_mon < 0 || tm->tm_mon > 11) - return 0; + return 0; return 1; } static struct tm * -parse_date_elements(const char *day, const char *month, const char *year, - const char *time, const char *zone) -{ + parse_date_elements(const char *day, const char *month, const char *year, + const char *time, const char *zone) { static struct tm tm; char *t; memset(&tm, 0, sizeof(tm)); if (!day || !month || !year || !time) - return NULL; + return NULL; tm.tm_mday = atoi(day); tm.tm_mon = make_month(month); if (tm.tm_mon < 0) - return NULL; + return NULL; tm.tm_year = atoi(year); if (strlen(year) == 4) - tm.tm_year -= 1900; + tm.tm_year -= 1900; else if (tm.tm_year < 70) - tm.tm_year += 100; + tm.tm_year += 100; else if (tm.tm_year > 19000) - tm.tm_year -= 19000; + tm.tm_year -= 19000; tm.tm_hour = make_num(time); t = strchr(time, ':'); if (!t) - return NULL; + return NULL; t++; tm.tm_min = atoi(t); t = strchr(t, ':'); if (t) - tm.tm_sec = atoi(t + 1); + tm.tm_sec = atoi(t + 1); return tmSaneValues(&tm) ? &tm : NULL; } static struct tm * -parse_date(const char *str) -{ + parse_date(const char *str) { struct tm *tm; static char tmp[64]; char *t; @@ -168,29 +165,29 @@ parse_date(const char *str) xstrncpy(tmp, str, 64); for (t = strtok(tmp, ", "); t; t = strtok(NULL, ", ")) { - if (xisdigit(*t)) { - if (!day) { - day = t; - t = strchr(t, '-'); - if (t) { - *t++ = '\0'; - month = t; - t = strchr(t, '-'); - if (!t) - return NULL; - *t++ = '\0'; - year = t; - } - } else if (strchr(t, ':')) - time = t; - else if (!year) - year = t; - } else if (!wday) - wday = t; - else if (!month) - month = t; - else if (!zone) - zone = t; + if (xisdigit(*t)) { + if (!day) { + day = t; + t = strchr(t, '-'); + if (t) { + *t++ = '\0'; + month = t; + t = strchr(t, '-'); + if (!t) + return NULL; + *t++ = '\0'; + year = t; + } + } else if (strchr(t, ':')) + time = t; + else if (!year) + year = t; + } else if (!wday) + wday = t; + else if (!month) + month = t; + else if (!zone) + zone = t; } tm = parse_date_elements(day, month, year, time, zone); @@ -203,24 +200,24 @@ parse_rfc1123(const char *str) struct tm *tm; time_t t; if (NULL == str) - return -1; + return -1; tm = parse_date(str); if (!tm) - return -1; + return -1; tm->tm_isdst = -1; #ifdef HAVE_TIMEGM t = timegm(tm); #elif HAVE_TM_TM_GMTOFF t = mktime(tm); if (t != -1) { - struct tm *local = localtime(&t); - t += local->tm_gmtoff; + struct tm *local = localtime(&t); + t += local->tm_gmtoff; } #else /* some systems do not have tm_gmtoff so we fake it */ t = mktime(tm); if (t != -1) { - time_t dst = 0; + time_t dst = 0; #if defined (_TIMEZONE) #elif defined (_timezone) #elif defined(_SQUID_AIX_) @@ -228,18 +225,18 @@ parse_rfc1123(const char *str) #elif defined(_SQUID_MSWIN_) #elif defined(_SQUID_SGI_) #else - extern long timezone; + extern long timezone; #endif - /* - * The following assumes a fixed DST offset of 1 hour, - * which is probably wrong. - */ - if (tm->tm_isdst > 0) - dst = -3600; + /* + * The following assumes a fixed DST offset of 1 hour, + * which is probably wrong. + */ + if (tm->tm_isdst > 0) + dst = -3600; #if defined ( _timezone) || defined(_SQUID_WIN32_) - t -= (_timezone + dst); + t -= (_timezone + dst); #else - t -= (timezone + dst); + t -= (timezone + dst); #endif } #endif @@ -281,17 +278,17 @@ mkhttpdlogtime(const time_t * t) day_offset = lt->tm_yday - gmt_yday; /* wrap round on end of year */ if (day_offset > 1) - day_offset = -1; + day_offset = -1; else if (day_offset < -1) - day_offset = 1; + day_offset = 1; min_offset = day_offset * 1440 + (lt->tm_hour - gmt_hour) * 60 - + (lt->tm_min - gmt_min); + + (lt->tm_min - gmt_min); len = strftime(buf, 127 - 5, "%d/%b/%Y:%H:%M:%S ", lt); snprintf(buf + len, 128 - len, "%+03d%02d", - (min_offset / 60) % 24, - min_offset % 60); + (min_offset / 60) % 24, + min_offset % 60); #else /* USE_GMT */ buf[0] = '\0'; strftime(buf, 127, "%d/%b/%Y:%H:%M:%S -000", gmt); diff --git a/lib/rfc1738.c b/lib/rfc1738.c index 1ea1a765e7..a3c35a68da 100644 --- a/lib/rfc1738.c +++ b/lib/rfc1738.c @@ -1,7 +1,7 @@ /* * $Id: rfc1738.c,v 1.28 2007/12/06 02:37:15 amosjeffries Exp $ * - * DEBUG: + * DEBUG: * AUTHOR: Harvest Derived * * SQUID Web Proxy Cache http://www.squid-cache.org/ @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -43,12 +43,11 @@ #include "util.h" -/* +/* * RFC 1738 defines that these characters should be escaped, as well * any non-US-ASCII character or anything between 0x00 - 0x1F. */ -static char rfc1738_unsafe_chars[] = -{ +static char rfc1738_unsafe_chars[] = { (char) 0x3C, /* < */ (char) 0x3E, /* > */ (char) 0x22, /* " */ @@ -69,8 +68,7 @@ static char rfc1738_unsafe_chars[] = (char) 0x20 /* space */ }; -static char rfc1738_reserved_chars[] = -{ +static char rfc1738_reserved_chars[] = { (char) 0x3b, /* ; */ (char) 0x2f, /* / */ (char) 0x3f, /* ? */ @@ -81,7 +79,7 @@ static char rfc1738_reserved_chars[] = }; /* - * rfc1738_escape - Returns a static buffer contains the RFC 1738 + * rfc1738_escape - Returns a static buffer contains the RFC 1738 * compliant, escaped version of the given url. */ static char * @@ -94,52 +92,52 @@ rfc1738_do_escape(const char *url, int encode_reserved) unsigned int i, do_escape; if (buf == NULL || strlen(url) * 3 > bufsize) { - xfree(buf); - bufsize = strlen(url) * 3 + 1; - buf = xcalloc(bufsize, 1); + xfree(buf); + bufsize = strlen(url) * 3 + 1; + buf = xcalloc(bufsize, 1); } for (p = url, q = buf; *p != '\0' && q < (buf + bufsize - 1); p++, q++) { - do_escape = 0; + do_escape = 0; - /* RFC 1738 defines these chars as unsafe */ - for (i = 0; i < sizeof(rfc1738_unsafe_chars); i++) { - if (*p == rfc1738_unsafe_chars[i]) { - do_escape = 1; - break; - } - } - /* Handle % separately */ - if (encode_reserved >= 0 && *p == '%') - do_escape = 1; - /* RFC 1738 defines these chars as reserved */ - for (i = 0; i < sizeof(rfc1738_reserved_chars) && encode_reserved > 0; i++) { - if (*p == rfc1738_reserved_chars[i]) { - do_escape = 1; - break; - } - } - /* RFC 1738 says any control chars (0x00-0x1F) are encoded */ - if ((unsigned char) *p <= (unsigned char) 0x1F) { - do_escape = 1; - } - /* RFC 1738 says 0x7f is encoded */ - if (*p == (char) 0x7F) { - do_escape = 1; - } - /* RFC 1738 says any non-US-ASCII are encoded */ - if (((unsigned char) *p >= (unsigned char) 0x80)) { - do_escape = 1; - } - /* Do the triplet encoding, or just copy the char */ - /* note: we do not need snprintf here as q is appropriately - * allocated - KA */ + /* RFC 1738 defines these chars as unsafe */ + for (i = 0; i < sizeof(rfc1738_unsafe_chars); i++) { + if (*p == rfc1738_unsafe_chars[i]) { + do_escape = 1; + break; + } + } + /* Handle % separately */ + if (encode_reserved >= 0 && *p == '%') + do_escape = 1; + /* RFC 1738 defines these chars as reserved */ + for (i = 0; i < sizeof(rfc1738_reserved_chars) && encode_reserved > 0; i++) { + if (*p == rfc1738_reserved_chars[i]) { + do_escape = 1; + break; + } + } + /* RFC 1738 says any control chars (0x00-0x1F) are encoded */ + if ((unsigned char) *p <= (unsigned char) 0x1F) { + do_escape = 1; + } + /* RFC 1738 says 0x7f is encoded */ + if (*p == (char) 0x7F) { + do_escape = 1; + } + /* RFC 1738 says any non-US-ASCII are encoded */ + if (((unsigned char) *p >= (unsigned char) 0x80)) { + do_escape = 1; + } + /* Do the triplet encoding, or just copy the char */ + /* note: we do not need snprintf here as q is appropriately + * allocated - KA */ - if (do_escape == 1) { - (void) sprintf(q, "%%%02X", (unsigned char) *p); - q += sizeof(char) * 2; - } else { - *q = *p; - } + if (do_escape == 1) { + (void) sprintf(q, "%%%02X", (unsigned char) *p); + q += sizeof(char) * 2; + } else { + *q = *p; + } } *q = '\0'; return (buf); @@ -176,7 +174,7 @@ rfc1738_escape_part(const char *url) } /* - * rfc1738_unescape() - Converts escaped characters (%xy numbers) in + * rfc1738_unescape() - Converts escaped characters (%xy numbers) in * given the string. %% is a %. %ab is the 8-bit hexadecimal number "ab" */ void @@ -186,26 +184,26 @@ rfc1738_unescape(char *s) int i, j; /* i is write, j is read */ unsigned int x; for (i = j = 0; s[j]; i++, j++) { - s[i] = s[j]; - if (s[i] != '%') - continue; - if (s[j + 1] == '%') { /* %% case */ - j++; - continue; - } - if (s[j + 1] && s[j + 2]) { - if (s[j + 1] == '0' && s[j + 2] == '0') { /* %00 case */ - j += 2; - continue; - } - hexnum[0] = s[j + 1]; - hexnum[1] = s[j + 2]; - hexnum[2] = '\0'; - if (1 == sscanf(hexnum, "%x", &x)) { - s[i] = (char) (0x0ff & x); - j += 2; - } - } + s[i] = s[j]; + if (s[i] != '%') + continue; + if (s[j + 1] == '%') { /* %% case */ + j++; + continue; + } + if (s[j + 1] && s[j + 2]) { + if (s[j + 1] == '0' && s[j + 2] == '0') { /* %00 case */ + j += 2; + continue; + } + hexnum[0] = s[j + 1]; + hexnum[1] = s[j + 2]; + hexnum[2] = '\0'; + if (1 == sscanf(hexnum, "%x", &x)) { + s[i] = (char) (0x0ff & x); + j += 2; + } + } } s[i] = '\0'; } diff --git a/lib/rfc2617.c b/lib/rfc2617.c index 34f6b92cf2..9d9259bc3f 100644 --- a/lib/rfc2617.c +++ b/lib/rfc2617.c @@ -1,10 +1,10 @@ -/* The source in this file is derived from the reference implementation - * in RFC 2617. +/* The source in this file is derived from the reference implementation + * in RFC 2617. * RFC 2617 is Copyright (C) The Internet Society (1999). All Rights Reserved. * - * The following copyright and licence statement covers all changes made to the + * The following copyright and licence statement covers all changes made to the * reference implementation. - * + * * Key changes were: alteration to a plain C layout. * Create CvtBin function * Allow CalcHA1 to make use of precaculated username:password:realm hash's @@ -58,16 +58,16 @@ CvtHex(const HASH Bin, HASHHEX Hex) unsigned char j; for (i = 0; i < HASHLEN; i++) { - j = (Bin[i] >> 4) & 0xf; - if (j <= 9) - Hex[i * 2] = (j + '0'); - else - Hex[i * 2] = (j + 'a' - 10); - j = Bin[i] & 0xf; - if (j <= 9) - Hex[i * 2 + 1] = (j + '0'); - else - Hex[i * 2 + 1] = (j + 'a' - 10); + j = (Bin[i] >> 4) & 0xf; + if (j <= 9) + Hex[i * 2] = (j + '0'); + else + Hex[i * 2] = (j + 'a' - 10); + j = Bin[i] & 0xf; + if (j <= 9) + Hex[i * 2 + 1] = (j + '0'); + else + Hex[i * 2 + 1] = (j + 'a' - 10); } Hex[HASHHEXLEN] = '\0'; } @@ -79,23 +79,23 @@ CvtBin(const HASHHEX Hex, HASH Bin) unsigned char j; for (i = 0; i < HASHHEXLEN; i++) { - unsigned char n; - j = Hex[i]; - if (('0' <= j) && (j <= '9')) - n = j - '0'; - else if (('a' <= j) && (j <= 'f')) - n = j - 'a' + 10; - else if (('A' <= j) && (j <= 'F')) - n = j - 'A' + 10; - else - continue; - if (i % 2 == 0) - Bin[i / 2] = n << 4; - else - Bin[i / 2] |= n; + unsigned char n; + j = Hex[i]; + if (('0' <= j) && (j <= '9')) + n = j - '0'; + else if (('a' <= j) && (j <= 'f')) + n = j - 'a' + 10; + else if (('A' <= j) && (j <= 'F')) + n = j - 'A' + 10; + else + continue; + if (i % 2 == 0) + Bin[i / 2] = n << 4; + else + Bin[i / 2] |= n; } for (i = i / 2; i < HASHLEN; i++) { - Bin[i] = '\0'; + Bin[i] = '\0'; } } @@ -116,24 +116,24 @@ DigestCalcHA1( SquidMD5_CTX Md5Ctx; if (pszUserName) { - SquidMD5Init(&Md5Ctx); - SquidMD5Update(&Md5Ctx, pszUserName, strlen(pszUserName)); - SquidMD5Update(&Md5Ctx, ":", 1); - SquidMD5Update(&Md5Ctx, pszRealm, strlen(pszRealm)); - SquidMD5Update(&Md5Ctx, ":", 1); - SquidMD5Update(&Md5Ctx, pszPassword, strlen(pszPassword)); - SquidMD5Final((unsigned char *) HA1, &Md5Ctx); + SquidMD5Init(&Md5Ctx); + SquidMD5Update(&Md5Ctx, pszUserName, strlen(pszUserName)); + SquidMD5Update(&Md5Ctx, ":", 1); + SquidMD5Update(&Md5Ctx, pszRealm, strlen(pszRealm)); + SquidMD5Update(&Md5Ctx, ":", 1); + SquidMD5Update(&Md5Ctx, pszPassword, strlen(pszPassword)); + SquidMD5Final((unsigned char *) HA1, &Md5Ctx); } if (strcasecmp(pszAlg, "md5-sess") == 0) { - HASHHEX HA1Hex; - CvtHex(HA1, HA1Hex); /* RFC2617 errata */ - SquidMD5Init(&Md5Ctx); - SquidMD5Update(&Md5Ctx, HA1Hex, HASHHEXLEN); - SquidMD5Update(&Md5Ctx, ":", 1); - SquidMD5Update(&Md5Ctx, pszNonce, strlen(pszNonce)); - SquidMD5Update(&Md5Ctx, ":", 1); - SquidMD5Update(&Md5Ctx, pszCNonce, strlen(pszCNonce)); - SquidMD5Final((unsigned char *) HA1, &Md5Ctx); + HASHHEX HA1Hex; + CvtHex(HA1, HA1Hex); /* RFC2617 errata */ + SquidMD5Init(&Md5Ctx); + SquidMD5Update(&Md5Ctx, HA1Hex, HASHHEXLEN); + SquidMD5Update(&Md5Ctx, ":", 1); + SquidMD5Update(&Md5Ctx, pszNonce, strlen(pszNonce)); + SquidMD5Update(&Md5Ctx, ":", 1); + SquidMD5Update(&Md5Ctx, pszCNonce, strlen(pszCNonce)); + SquidMD5Final((unsigned char *) HA1, &Md5Ctx); } CvtHex(HA1, SessionKey); } @@ -164,8 +164,8 @@ DigestCalcResponse( SquidMD5Update(&Md5Ctx, ":", 1); SquidMD5Update(&Md5Ctx, pszDigestUri, strlen(pszDigestUri)); if (strcasecmp(pszQop, "auth-int") == 0) { - SquidMD5Update(&Md5Ctx, ":", 1); - SquidMD5Update(&Md5Ctx, HEntity, HASHHEXLEN); + SquidMD5Update(&Md5Ctx, ":", 1); + SquidMD5Update(&Md5Ctx, HEntity, HASHHEXLEN); } SquidMD5Final((unsigned char *) HA2, &Md5Ctx); CvtHex(HA2, HA2Hex); @@ -178,12 +178,12 @@ DigestCalcResponse( SquidMD5Update(&Md5Ctx, pszNonce, strlen(pszNonce)); SquidMD5Update(&Md5Ctx, ":", 1); if (*pszQop) { - SquidMD5Update(&Md5Ctx, pszNonceCount, strlen(pszNonceCount)); - SquidMD5Update(&Md5Ctx, ":", 1); - SquidMD5Update(&Md5Ctx, pszCNonce, strlen(pszCNonce)); - SquidMD5Update(&Md5Ctx, ":", 1); - SquidMD5Update(&Md5Ctx, pszQop, strlen(pszQop)); - SquidMD5Update(&Md5Ctx, ":", 1); + SquidMD5Update(&Md5Ctx, pszNonceCount, strlen(pszNonceCount)); + SquidMD5Update(&Md5Ctx, ":", 1); + SquidMD5Update(&Md5Ctx, pszCNonce, strlen(pszCNonce)); + SquidMD5Update(&Md5Ctx, ":", 1); + SquidMD5Update(&Md5Ctx, pszQop, strlen(pszQop)); + SquidMD5Update(&Md5Ctx, ":", 1); } SquidMD5Update(&Md5Ctx, HA2Hex, HASHHEXLEN); SquidMD5Final((unsigned char *) RespHash, &Md5Ctx); diff --git a/lib/rfc3596.c b/lib/rfc3596.c index e806d9e3f0..291aced623 100644 --- a/lib/rfc3596.c +++ b/lib/rfc3596.c @@ -25,12 +25,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -39,17 +39,17 @@ /* * KNOWN BUGS: - * + * * UDP replies with TC set should be retried via TCP */ /** * April 2007 - * + * * Provides RFC3596 functions to handle purely IPv6 DNS. * Adds AAAA and IPv6 PTR records. * Other IPv6 records are not mentioned by this RFC. - * + * * IPv4 equivalents are taken care of by the RFC1035 library. * Where one protocol lookup must be followed by another, the caller * is resposible for the order and handling of the lookups. @@ -191,8 +191,7 @@ rfc3596BuildPTRQuery6(const struct in6_addr addr, char *buf, size_t sz, unsigned /* work from the raw addr field. anything else may have representation changes. */ /* The sin6_port and sin6_addr members shall be in network byte order. */ - for(i = 15; i >= 0; i--, p+=4) - { + for (i = 15; i >= 0; i--, p+=4) { snprintf(p, 5, "%1x.%1x.", ((r[i]>>4)&0xf), (r[i])&0xf ); } @@ -234,10 +233,10 @@ main(int argc, char *argv[]) setbuf(stdout, NULL); setbuf(stderr, NULL); - if(argv[var][0] == '-') { - if(argv[var][1] == '4') + if (argv[var][0] == '-') { + if (argv[var][1] == '4') prefer = AF_INET; - else if(argv[var][1] == '6') + else if (argv[var][1] == '6') prefer = AF_INET6; else { fprintf(stderr, "usage: %s [-6|-4] ip port\n", argv[0]); @@ -257,119 +256,122 @@ main(int argc, char *argv[]) memset(&S, '\0', sizeof(S)); - if(prefer == 6) { + if (prefer == 6) { S = (struct sockaddr *) new sockaddr_in6; memset(S,0,sizeof(struct sockaddr_in6)); ((struct sockaddr_in6 *)S)->sin6_family = AF_INET6; ((struct sockaddr_in6 *)S)->sin6_port = htons(atoi(argv[var+1])); - if( ! xinet_pton(AF_INET6, argv[var], &((struct sockaddr_in6 *)S)->sin6_addr.s_addr) ) + if ( ! xinet_pton(AF_INET6, argv[var], &((struct sockaddr_in6 *)S)->sin6_addr.s_addr) ) perror("listen address"); - return 1; - } + return 1; + } - s = socket(PF_INET6, SOCK_DGRAM, 0); - } else { - S = (struct sockaddr *) new sockaddr_in; - memset(S,0,sizeof(struct sockaddr_in)); + s = socket(PF_INET6, SOCK_DGRAM, 0); +} +else +{ + S = (struct sockaddr *) new sockaddr_in; + memset(S,0,sizeof(struct sockaddr_in)); - ((struct sockaddr_in *)S)->sin_family = AF_INET; - ((struct sockaddr_in *)S)->sin_port = htons(atoi(argv[var+1])); + ((struct sockaddr_in *)S)->sin_family = AF_INET; + ((struct sockaddr_in *)S)->sin_port = htons(atoi(argv[var+1])); - if( ! xinet_pton(AF_INET, argv[var], &((struct sockaddr_in *)S)->sin_addr.s_addr) ) - perror("listen address"); - return 1; - } - } + if ( ! xinet_pton(AF_INET, argv[var], &((struct sockaddr_in *)S)->sin_addr.s_addr) ) + perror("listen address"); + return 1; +} +} - while (fgets(input, 512, stdin)) { +while (fgets(input, 512, stdin)) +{ - struct in6_addr junk6; + struct in6_addr junk6; - struct in_addr junk4; - strtok(input, "\r\n"); - memset(buf, '\0', 512); - sz = 512; + struct in_addr junk4; + strtok(input, "\r\n"); + memset(buf, '\0', 512); + sz = 512; - if (xinet_pton(AF_INET6, input, &junk6)) { - sid = rfc1035BuildPTRQuery6(junk6, buf, &sz); - sidb=0; - } else if (xinet_pton(AF_INET, input, &junk4)) { - sid = rfc1035BuildPTRQuery4(junk4, buf, &sz); - sidb=0; - } else { - sid = rfc1035BuildAAAAQuery(input, buf, &sz); - sidb = rfc1035BuildAQuery(input, buf, &sz); - } + if (xinet_pton(AF_INET6, input, &junk6)) { + sid = rfc1035BuildPTRQuery6(junk6, buf, &sz); + sidb=0; + } else if (xinet_pton(AF_INET, input, &junk4)) { + sid = rfc1035BuildPTRQuery4(junk4, buf, &sz); + sidb=0; + } else { + sid = rfc1035BuildAAAAQuery(input, buf, &sz); + sidb = rfc1035BuildAQuery(input, buf, &sz); + } - sendto(s, buf, sz, 0, S, sizeof(*S)); + sendto(s, buf, sz, 0, S, sizeof(*S)); - do { - fd_set R; + do { + fd_set R; - struct timeval to; - FD_ZERO(&R); - FD_SET(s, &R); - to.tv_sec = 10; - to.tv_usec = 0; - rl = select(s + 1, &R, NULL, NULL, &to); - } while (0); + struct timeval to; + FD_ZERO(&R); + FD_SET(s, &R); + to.tv_sec = 10; + to.tv_usec = 0; + rl = select(s + 1, &R, NULL, NULL, &to); + } while (0); - if (rl < 1) { - printf("TIMEOUT\n"); - continue; - } + if (rl < 1) { + printf("TIMEOUT\n"); + continue; + } - memset(rbuf, '\0', 512); - rl = recv(s, rbuf, 512, 0); - { - unsigned short rid = 0; - int i; - int n; - rfc1035_rr *answers = NULL; - n = rfc1035AnswersUnpack(rbuf, - rl, - &answers, - &rid); - - if (n < 0) { - printf("ERROR %d\n", rfc1035_errno); - } else if (rid != sid && rid != sidb) { - printf("ERROR, ID mismatch (%#hx, %#hx)\n", sid, rid); - printf("ERROR, ID mismatch (%#hx, %#hx)\n", sidb, rid); - } else { - printf("%d answers\n", n); - - for (i = 0; i < n; i++) { - if (answers[i].type == RFC1035_TYPE_A) { - - struct in_addr a; - memcpy(&a, answers[i].rdata, 4); - printf("A\t%d\t%s\n", answers[i].ttl, inet_ntoa(a)); - } else if (answers[i].type == RFC1035_TYPE_AAAA) { - - struct in6_addr a; - memcpy(&a, answers[i].rdata, 16); - printf("AAAA\t%d\t%s\n", answers[i].ttl, inet_ntoa(a)); - } else if (answers[i].type == RFC1035_TYPE_PTR) { - char ptr[RFC1035_MAXHOSTNAMESZ]; - strncpy(ptr, answers[i].rdata, answers[i].rdlength); - printf("PTR\t%d\t%s\n", answers[i].ttl, ptr); - } else if (answers[i].type == RFC1035_TYPE_CNAME) { - char ptr[RFC1035_MAXHOSTNAMESZ]; - strncpy(ptr, answers[i].rdata, answers[i].rdlength); - printf("CNAME\t%d\t%s\n", answers[i].ttl, ptr); - } else { - fprintf(stderr, "can't print answer type %d\n", - (int) answers[i].type); - } + memset(rbuf, '\0', 512); + rl = recv(s, rbuf, 512, 0); + { + unsigned short rid = 0; + int i; + int n; + rfc1035_rr *answers = NULL; + n = rfc1035AnswersUnpack(rbuf, + rl, + &answers, + &rid); + + if (n < 0) { + printf("ERROR %d\n", rfc1035_errno); + } else if (rid != sid && rid != sidb) { + printf("ERROR, ID mismatch (%#hx, %#hx)\n", sid, rid); + printf("ERROR, ID mismatch (%#hx, %#hx)\n", sidb, rid); + } else { + printf("%d answers\n", n); + + for (i = 0; i < n; i++) { + if (answers[i].type == RFC1035_TYPE_A) { + + struct in_addr a; + memcpy(&a, answers[i].rdata, 4); + printf("A\t%d\t%s\n", answers[i].ttl, inet_ntoa(a)); + } else if (answers[i].type == RFC1035_TYPE_AAAA) { + + struct in6_addr a; + memcpy(&a, answers[i].rdata, 16); + printf("AAAA\t%d\t%s\n", answers[i].ttl, inet_ntoa(a)); + } else if (answers[i].type == RFC1035_TYPE_PTR) { + char ptr[RFC1035_MAXHOSTNAMESZ]; + strncpy(ptr, answers[i].rdata, answers[i].rdlength); + printf("PTR\t%d\t%s\n", answers[i].ttl, ptr); + } else if (answers[i].type == RFC1035_TYPE_CNAME) { + char ptr[RFC1035_MAXHOSTNAMESZ]; + strncpy(ptr, answers[i].rdata, answers[i].rdlength); + printf("CNAME\t%d\t%s\n", answers[i].ttl, ptr); + } else { + fprintf(stderr, "can't print answer type %d\n", + (int) answers[i].type); } } } } - - return 0; } +return 0; + } + #endif diff --git a/lib/sspwin32.c b/lib/sspwin32.c index 6933f5f6d5..534dd74d96 100644 --- a/lib/sspwin32.c +++ b/lib/sspwin32.c @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -83,12 +83,12 @@ QUERY_CONTEXT_ATTRIBUTES_FN_A _QueryContextAttributes = NULL; void UnloadSecurityDll(void) { if (NTLM_asServer.fHaveCtxtHandle) - _DeleteSecurityContext(&NTLM_asServer.hctxt); + _DeleteSecurityContext(&NTLM_asServer.hctxt); if (NTLM_asServer.fHaveCredHandle) _FreeCredentialsHandle(&NTLM_asServer.hcred); if (hModule) - FreeLibrary(hModule); + FreeLibrary(hModule); xfree(SSP_Package_InUse); xfree(pClientBuf); @@ -108,118 +108,117 @@ void UnloadSecurityDll(void) } -HMODULE LoadSecurityDll(int mode, char * SSP_Package) +HMODULE LoadSecurityDll(int mode, char * SSP_Package) { TCHAR lpszDLL[MAX_PATH]; OSVERSIONINFO VerInfo; PSecPkgInfo pSPI = NULL; - /* - * Find out which security DLL to use, depending on - * whether we are on NT or 2000 or XP or 2003 Server - * We have to use security.dll on Windows NT 4.0. - * All other operating systems, we have to use Secur32.dll - */ + /* + * Find out which security DLL to use, depending on + * whether we are on NT or 2000 or XP or 2003 Server + * We have to use security.dll on Windows NT 4.0. + * All other operating systems, we have to use Secur32.dll + */ hModule = NULL; if ((mode != SSP_BASIC) && (mode != SSP_NTLM)) - return hModule; + return hModule; NTLM_mode = mode; VerInfo.dwOSVersionInfoSize = sizeof (OSVERSIONINFO); if (!GetVersionEx (&VerInfo)) { /* If this fails, something has gone wrong */ - return hModule; + return hModule; } if (VerInfo.dwPlatformId == VER_PLATFORM_WIN32_NT && - VerInfo.dwMajorVersion == 4 && - VerInfo.dwMinorVersion == 0) - { - lstrcpy (lpszDLL, _T(WINNT_SECURITY_DLL)); + VerInfo.dwMajorVersion == 4 && + VerInfo.dwMinorVersion == 0) { + lstrcpy (lpszDLL, _T(WINNT_SECURITY_DLL)); } else { - lstrcpy (lpszDLL, _T(WIN2K_SECURITY_DLL)); + lstrcpy (lpszDLL, _T(WIN2K_SECURITY_DLL)); } hModule = LoadLibrary(lpszDLL); if (!hModule) - return hModule; - _AcceptSecurityContext = (ACCEPT_SECURITY_CONTEXT_FN) - GetProcAddress(hModule, "AcceptSecurityContext"); + return hModule; + _AcceptSecurityContext = (ACCEPT_SECURITY_CONTEXT_FN) + GetProcAddress(hModule, "AcceptSecurityContext"); if (!_AcceptSecurityContext) { - UnloadSecurityDll(); - hModule = NULL; - return hModule; + UnloadSecurityDll(); + hModule = NULL; + return hModule; } #ifdef UNICODE _AcquireCredentialsHandle = (ACQUIRE_CREDENTIALS_HANDLE_FN) - GetProcAddress(hModule, "AcquireCredentialsHandleW"); + GetProcAddress(hModule, "AcquireCredentialsHandleW"); #else _AcquireCredentialsHandle = (ACQUIRE_CREDENTIALS_HANDLE_FN) - GetProcAddress(hModule, "AcquireCredentialsHandleA"); + GetProcAddress(hModule, "AcquireCredentialsHandleA"); #endif if (!_AcquireCredentialsHandle) { - UnloadSecurityDll(); - hModule = NULL; - return hModule; + UnloadSecurityDll(); + hModule = NULL; + return hModule; } - _CompleteAuthToken = (COMPLETE_AUTH_TOKEN_FN) - GetProcAddress(hModule, "CompleteAuthToken"); + _CompleteAuthToken = (COMPLETE_AUTH_TOKEN_FN) + GetProcAddress(hModule, "CompleteAuthToken"); if (!_CompleteAuthToken) { - UnloadSecurityDll(); - hModule = NULL; - return hModule; + UnloadSecurityDll(); + hModule = NULL; + return hModule; } - _DeleteSecurityContext = (DELETE_SECURITY_CONTEXT_FN) - GetProcAddress(hModule, "DeleteSecurityContext"); + _DeleteSecurityContext = (DELETE_SECURITY_CONTEXT_FN) + GetProcAddress(hModule, "DeleteSecurityContext"); if (!_DeleteSecurityContext) { - UnloadSecurityDll(); - hModule = NULL; - return hModule; + UnloadSecurityDll(); + hModule = NULL; + return hModule; } - _FreeContextBuffer = (FREE_CONTEXT_BUFFER_FN) - GetProcAddress(hModule, "FreeContextBuffer"); + _FreeContextBuffer = (FREE_CONTEXT_BUFFER_FN) + GetProcAddress(hModule, "FreeContextBuffer"); if (!_FreeContextBuffer) { - UnloadSecurityDll(); - hModule = NULL; - return hModule; + UnloadSecurityDll(); + hModule = NULL; + return hModule; } - _FreeCredentialsHandle = (FREE_CREDENTIALS_HANDLE_FN) - GetProcAddress(hModule, "FreeCredentialsHandle"); + _FreeCredentialsHandle = (FREE_CREDENTIALS_HANDLE_FN) + GetProcAddress(hModule, "FreeCredentialsHandle"); if (!_FreeCredentialsHandle) { - UnloadSecurityDll(); - hModule = NULL; - return hModule; + UnloadSecurityDll(); + hModule = NULL; + return hModule; } #ifdef UNICODE _InitializeSecurityContext = (INITIALIZE_SECURITY_CONTEXT_FN) - GetProcAddress(hModule, "InitializeSecurityContextW"); + GetProcAddress(hModule, "InitializeSecurityContextW"); #else - _InitializeSecurityContext = (INITIALIZE_SECURITY_CONTEXT_FN) - GetProcAddress(hModule, "InitializeSecurityContextA"); + _InitializeSecurityContext = (INITIALIZE_SECURITY_CONTEXT_FN) + GetProcAddress(hModule, "InitializeSecurityContextA"); #endif if (!_InitializeSecurityContext) { - UnloadSecurityDll(); - hModule = NULL; - return hModule; + UnloadSecurityDll(); + hModule = NULL; + return hModule; } #ifdef UNICODE - _QuerySecurityPackageInfo = (QUERY_SECURITY_PACKAGE_INFO_FN) - GetProcAddress(hModule, "QuerySecurityPackageInfoW"); + _QuerySecurityPackageInfo = (QUERY_SECURITY_PACKAGE_INFO_FN) + GetProcAddress(hModule, "QuerySecurityPackageInfoW"); #else _QuerySecurityPackageInfo = (QUERY_SECURITY_PACKAGE_INFO_FN) - GetProcAddress(hModule, "QuerySecurityPackageInfoA"); + GetProcAddress(hModule, "QuerySecurityPackageInfoA"); #endif if (!_QuerySecurityPackageInfo) { - UnloadSecurityDll(); - hModule = NULL; + UnloadSecurityDll(); + hModule = NULL; } #ifdef UNICODE - _QueryContextAttributes = (QUERY_CONTEXT_ATTRIBUTES_FN_W) - GetProcAddress(hModule, "QueryContextAttributesW"); + _QueryContextAttributes = (QUERY_CONTEXT_ATTRIBUTES_FN_W) + GetProcAddress(hModule, "QueryContextAttributesW"); #else _QueryContextAttributes = (QUERY_CONTEXT_ATTRIBUTES_FN_A) - GetProcAddress(hModule, "QueryContextAttributesA"); + GetProcAddress(hModule, "QueryContextAttributesA"); #endif if (!_QueryContextAttributes) { - UnloadSecurityDll(); - hModule = NULL; + UnloadSecurityDll(); + hModule = NULL; } /* Get max token size */ @@ -237,18 +236,18 @@ HMODULE LoadSecurityDll(int mode, char * SSP_Package) BOOL GenClientContext(PAUTH_SEQ pAS, PSEC_WINNT_AUTH_IDENTITY pAuthIdentity, - PVOID pIn, DWORD cbIn, PVOID pOut, PDWORD pcbOut, PBOOL pfDone) + PVOID pIn, DWORD cbIn, PVOID pOut, PDWORD pcbOut, PBOOL pfDone) { -/* - * Routine Description: - * - * Optionally takes an input buffer coming from the server and returns - * a buffer of information to send back to the server. Also returns - * an indication of whether or not the context is complete. - * - * Return Value: - * Returns TRUE if successful; otherwise FALSE. - */ + /* + * Routine Description: + * + * Optionally takes an input buffer coming from the server and returns + * a buffer of information to send back to the server. Also returns + * an indication of whether or not the context is complete. + * + * Return Value: + * Returns TRUE if successful; otherwise FALSE. + */ TimeStamp tsExpiry; SecBufferDesc sbdOut; SecBuffer sbOut; @@ -257,14 +256,14 @@ BOOL GenClientContext(PAUTH_SEQ pAS, PSEC_WINNT_AUTH_IDENTITY pAuthIdentity, ULONG fContextAttr; if (!pAS->fInitialized) { - SecurityStatus = _AcquireCredentialsHandle(NULL, (SEC_CHAR*) _T(SSP_Package_InUse), - SECPKG_CRED_OUTBOUND, NULL, (NTLM_mode == SSP_NTLM) ? NULL : pAuthIdentity, NULL, NULL, - &pAS->hcred, &tsExpiry); - if (SecurityStatus < 0) - return FALSE; - pAS->fHaveCredHandle = TRUE; + SecurityStatus = _AcquireCredentialsHandle(NULL, (SEC_CHAR*) _T(SSP_Package_InUse), + SECPKG_CRED_OUTBOUND, NULL, (NTLM_mode == SSP_NTLM) ? NULL : pAuthIdentity, NULL, NULL, + &pAS->hcred, &tsExpiry); + if (SecurityStatus < 0) + return FALSE; + pAS->fHaveCredHandle = TRUE; } - + /* Prepare output buffer */ sbdOut.ulVersion = 0; sbdOut.cBuffers = 1; @@ -272,53 +271,53 @@ BOOL GenClientContext(PAUTH_SEQ pAS, PSEC_WINNT_AUTH_IDENTITY pAuthIdentity, sbOut.cbBuffer = *pcbOut; sbOut.BufferType = SECBUFFER_TOKEN; sbOut.pvBuffer = pOut; - + /* Prepare input buffer */ if (pAS->fInitialized) { - sbdIn.ulVersion = 0; - sbdIn.cBuffers = 1; - sbdIn.pBuffers = &sbIn; - sbIn.cbBuffer = cbIn; - sbIn.BufferType = SECBUFFER_TOKEN; - sbIn.pvBuffer = pIn; + sbdIn.ulVersion = 0; + sbdIn.cBuffers = 1; + sbdIn.pBuffers = &sbIn; + sbIn.cbBuffer = cbIn; + sbIn.BufferType = SECBUFFER_TOKEN; + sbIn.pvBuffer = pIn; } - SecurityStatus = _InitializeSecurityContext(&pAS->hcred, - pAS->fInitialized ? &pAS->hctxt : NULL, NULL, 0, 0, - SECURITY_NATIVE_DREP, pAS->fInitialized ? &sbdIn : NULL, - 0, &pAS->hctxt, &sbdOut, &fContextAttr, &tsExpiry); - if (SecurityStatus < 0) - return FALSE; + SecurityStatus = _InitializeSecurityContext(&pAS->hcred, + pAS->fInitialized ? &pAS->hctxt : NULL, NULL, 0, 0, + SECURITY_NATIVE_DREP, pAS->fInitialized ? &sbdIn : NULL, + 0, &pAS->hctxt, &sbdOut, &fContextAttr, &tsExpiry); + if (SecurityStatus < 0) + return FALSE; pAS->fHaveCtxtHandle = TRUE; - + /* If necessary, complete token */ if (SecurityStatus == SEC_I_COMPLETE_NEEDED || SecurityStatus == SEC_I_COMPLETE_AND_CONTINUE) { - SecurityStatus = _CompleteAuthToken(&pAS->hctxt, &sbdOut); - if (SecurityStatus < 0) - return FALSE; + SecurityStatus = _CompleteAuthToken(&pAS->hctxt, &sbdOut); + if (SecurityStatus < 0) + return FALSE; } *pcbOut = sbOut.cbBuffer; if (!pAS->fInitialized) - pAS->fInitialized = TRUE; - *pfDone = !(SecurityStatus == SEC_I_CONTINUE_NEEDED - || SecurityStatus == SEC_I_COMPLETE_AND_CONTINUE ); + pAS->fInitialized = TRUE; + *pfDone = !(SecurityStatus == SEC_I_CONTINUE_NEEDED + || SecurityStatus == SEC_I_COMPLETE_AND_CONTINUE ); return TRUE; } -BOOL GenServerContext(PAUTH_SEQ pAS, PVOID pIn, DWORD cbIn, PVOID pOut, - PDWORD pcbOut, PBOOL pfDone, char * credentials) +BOOL GenServerContext(PAUTH_SEQ pAS, PVOID pIn, DWORD cbIn, PVOID pOut, + PDWORD pcbOut, PBOOL pfDone, char * credentials) { -/* - * Routine Description: - * - * Takes an input buffer coming from the client and returns a buffer - * to be sent to the client. Also returns an indication of whether or - * not the context is complete. - * - * Return Value: - * - * Returns TRUE if successful; otherwise FALSE. - */ + /* + * Routine Description: + * + * Takes an input buffer coming from the client and returns a buffer + * to be sent to the client. Also returns an indication of whether or + * not the context is complete. + * + * Return Value: + * + * Returns TRUE if successful; otherwise FALSE. + */ SecBufferDesc sbdOut; SecBuffer sbOut; @@ -328,21 +327,21 @@ BOOL GenServerContext(PAUTH_SEQ pAS, PVOID pIn, DWORD cbIn, PVOID pOut, SecPkgContext_Names namebuffer; if (!pAS->fInitialized) { - SecurityStatus = _AcquireCredentialsHandle(NULL, (SEC_CHAR*) _T(SSP_Package_InUse), - SECPKG_CRED_INBOUND, NULL, NULL, NULL, NULL, &pAS->hcred, - &pAS->hcredLifeTime); + SecurityStatus = _AcquireCredentialsHandle(NULL, (SEC_CHAR*) _T(SSP_Package_InUse), + SECPKG_CRED_INBOUND, NULL, NULL, NULL, NULL, &pAS->hcred, + &pAS->hcredLifeTime); #if SSP_DEBUG fprintf(stderr, "AcquireCredentialsHandle returned: %x\n", SecurityStatus); #endif - if (SecurityStatus < 0) { + if (SecurityStatus < 0) { #if SSP_DEBUG fprintf(stderr, "AcquireCredentialsHandle failed: %x\n", SecurityStatus); #endif - return FALSE; + return FALSE; } - pAS->fHaveCredHandle = TRUE; + pAS->fHaveCredHandle = TRUE; } - + /* Prepare output buffer */ sbdOut.ulVersion = 0; sbdOut.cBuffers = 1; @@ -358,10 +357,10 @@ BOOL GenServerContext(PAUTH_SEQ pAS, PVOID pIn, DWORD cbIn, PVOID pOut, sbIn.cbBuffer = cbIn; sbIn.BufferType = SECBUFFER_TOKEN; sbIn.pvBuffer = pIn; - SecurityStatus = _AcceptSecurityContext(&pAS->hcred, - pAS->fInitialized ? &pAS->hctxt : NULL, &sbdIn, (NTLM_mode == SSP_NTLM) ? ASC_REQ_DELEGATE : 0, - SECURITY_NATIVE_DREP, &pAS->hctxt, &sbdOut, &fContextAttr, - &pAS->hctxtLifeTime); + SecurityStatus = _AcceptSecurityContext(&pAS->hcred, + pAS->fInitialized ? &pAS->hctxt : NULL, &sbdIn, (NTLM_mode == SSP_NTLM) ? ASC_REQ_DELEGATE : 0, + SECURITY_NATIVE_DREP, &pAS->hctxt, &sbdOut, &fContextAttr, + &pAS->hctxtLifeTime); #if SSP_DEBUG fprintf(stderr, "AcceptSecurityContext returned: %x\n", SecurityStatus); #endif @@ -369,13 +368,13 @@ BOOL GenServerContext(PAUTH_SEQ pAS, PVOID pIn, DWORD cbIn, PVOID pOut, #if SSP_DEBUG fprintf(stderr, "AcceptSecurityContext failed: %x\n", SecurityStatus); #endif - return FALSE; + return FALSE; } pAS->fHaveCtxtHandle = TRUE; - + /* If necessary, complete token */ if (SecurityStatus == SEC_I_COMPLETE_NEEDED || SecurityStatus == SEC_I_COMPLETE_AND_CONTINUE) { - SecurityStatus = _CompleteAuthToken(&pAS->hctxt, &sbdOut); + SecurityStatus = _CompleteAuthToken(&pAS->hctxt, &sbdOut); #if SSP_DEBUG fprintf(stderr, "CompleteAuthToken returned: %x\n", SecurityStatus); #endif @@ -383,12 +382,12 @@ BOOL GenServerContext(PAUTH_SEQ pAS, PVOID pIn, DWORD cbIn, PVOID pOut, #if SSP_DEBUG fprintf(stderr, "CompleteAuthToken failed: %x\n", SecurityStatus); #endif - return FALSE; + return FALSE; } } - if ((credentials != NULL) && - !(SecurityStatus == SEC_I_CONTINUE_NEEDED || SecurityStatus == SEC_I_COMPLETE_AND_CONTINUE)) { + if ((credentials != NULL) && + !(SecurityStatus == SEC_I_CONTINUE_NEEDED || SecurityStatus == SEC_I_COMPLETE_AND_CONTINUE)) { SecurityStatus = _QueryContextAttributes(&pAS->hctxt, SECPKG_ATTR_NAMES, &namebuffer); #if SSP_DEBUG fprintf(stderr, "QueryContextAttributes returned: %x\n", SecurityStatus); @@ -397,21 +396,21 @@ BOOL GenServerContext(PAUTH_SEQ pAS, PVOID pIn, DWORD cbIn, PVOID pOut, #if SSP_DEBUG fprintf(stderr, "QueryContextAttributes failed: %x\n", SecurityStatus); #endif - return FALSE; + return FALSE; } strncpy(credentials, namebuffer.sUserName, SSP_MAX_CRED_LEN); } *pcbOut = sbOut.cbBuffer; if (!pAS->fInitialized) - pAS->fInitialized = TRUE; - *pfDone = !(SecurityStatus == SEC_I_CONTINUE_NEEDED - || SecurityStatus == SEC_I_COMPLETE_AND_CONTINUE); + pAS->fInitialized = TRUE; + *pfDone = !(SecurityStatus == SEC_I_CONTINUE_NEEDED + || SecurityStatus == SEC_I_COMPLETE_AND_CONTINUE); return TRUE; } -BOOL WINAPI SSP_LogonUser(PTSTR szUser, PTSTR szPassword, PTSTR szDomain) +BOOL WINAPI SSP_LogonUser(PTSTR szUser, PTSTR szPassword, PTSTR szDomain) { AUTH_SEQ asServer = {0}; AUTH_SEQ asClient = {0}; @@ -419,69 +418,69 @@ BOOL WINAPI SSP_LogonUser(PTSTR szUser, PTSTR szPassword, PTSTR szDomain) BOOL fResult = FALSE; DWORD cbOut = 0; DWORD cbIn = 0; - + SEC_WINNT_AUTH_IDENTITY ai; do { - if (!hModule) - break; + if (!hModule) + break; /* Initialize auth identity structure */ - ZeroMemory(&ai, sizeof(ai)); - ai.Domain = (void *)szDomain; - ai.DomainLength = lstrlen(szDomain); - ai.User = (void *)szUser; - ai.UserLength = lstrlen(szUser); - ai.Password = (void *)szPassword; - ai.PasswordLength = lstrlen(szPassword); + ZeroMemory(&ai, sizeof(ai)); + ai.Domain = (void *)szDomain; + ai.DomainLength = lstrlen(szDomain); + ai.User = (void *)szUser; + ai.UserLength = lstrlen(szUser); + ai.Password = (void *)szPassword; + ai.PasswordLength = lstrlen(szPassword); #if defined(UNICODE) || defined(_UNICODE) - ai.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE; -#else - ai.Flags = SEC_WINNT_AUTH_IDENTITY_ANSI; + ai.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE; +#else + ai.Flags = SEC_WINNT_AUTH_IDENTITY_ANSI; #endif - /* Prepare client message (negotiate) */ - cbOut = cbMaxToken; - if (!GenClientContext(&asClient, &ai, NULL, 0, pClientBuf, &cbOut, &fDone)) - break; - - /* Prepare server message (challenge) */ - cbIn = cbOut; - cbOut = cbMaxToken; - if (!GenServerContext(&asServer, pClientBuf, cbIn, pServerBuf, &cbOut, - &fDone, NULL)) - break; -/* Most likely failure: AcceptServerContext fails with SEC_E_LOGON_DENIED - * in the case of bad szUser or szPassword. - * Unexpected Result: Logon will succeed if you pass in a bad szUser and - * the guest account is enabled in the specified domain. - */ + /* Prepare client message (negotiate) */ + cbOut = cbMaxToken; + if (!GenClientContext(&asClient, &ai, NULL, 0, pClientBuf, &cbOut, &fDone)) + break; + + /* Prepare server message (challenge) */ + cbIn = cbOut; + cbOut = cbMaxToken; + if (!GenServerContext(&asServer, pClientBuf, cbIn, pServerBuf, &cbOut, + &fDone, NULL)) + break; + /* Most likely failure: AcceptServerContext fails with SEC_E_LOGON_DENIED + * in the case of bad szUser or szPassword. + * Unexpected Result: Logon will succeed if you pass in a bad szUser and + * the guest account is enabled in the specified domain. + */ + + /* Prepare client message (authenticate) */ + cbIn = cbOut; + cbOut = cbMaxToken; + if (!GenClientContext(&asClient, &ai, pServerBuf, cbIn, pClientBuf, &cbOut, + &fDone)) + break; - /* Prepare client message (authenticate) */ - cbIn = cbOut; - cbOut = cbMaxToken; - if (!GenClientContext(&asClient, &ai, pServerBuf, cbIn, pClientBuf, &cbOut, - &fDone)) - break; - - /* Prepare server message (authentication) */ - cbIn = cbOut; - cbOut = cbMaxToken; - if (!GenServerContext(&asServer, pClientBuf, cbIn, pServerBuf, &cbOut, - &fDone, NULL)) - break; - fResult = TRUE; - } while(0); + /* Prepare server message (authentication) */ + cbIn = cbOut; + cbOut = cbMaxToken; + if (!GenServerContext(&asServer, pClientBuf, cbIn, pServerBuf, &cbOut, + &fDone, NULL)) + break; + fResult = TRUE; + } while (0); /* Clean up resources */ if (asClient.fHaveCtxtHandle) - _DeleteSecurityContext(&asClient.hctxt); + _DeleteSecurityContext(&asClient.hctxt); if (asClient.fHaveCredHandle) - _FreeCredentialsHandle(&asClient.hcred); + _FreeCredentialsHandle(&asClient.hcred); if (asServer.fHaveCtxtHandle) - _DeleteSecurityContext(&asServer.hctxt); + _DeleteSecurityContext(&asServer.hctxt); if (asServer.fHaveCredHandle) - _FreeCredentialsHandle(&asServer.hcred); + _FreeCredentialsHandle(&asServer.hcred); return fResult; } @@ -494,10 +493,10 @@ const char * WINAPI SSP_MakeChallenge(PVOID PNegotiateBuf, int NegotiateLen) DWORD cbOut = 0; DWORD cbIn = 0; ntlm_challenge * challenge; - const char * encoded = NULL; + const char * encoded = NULL; if (NTLM_asServer.fHaveCtxtHandle) - _DeleteSecurityContext(&NTLM_asServer.hctxt); + _DeleteSecurityContext(&NTLM_asServer.hctxt); if (NTLM_asServer.fHaveCredHandle) _FreeCredentialsHandle(&NTLM_asServer.hcred); @@ -507,17 +506,17 @@ const char * WINAPI SSP_MakeChallenge(PVOID PNegotiateBuf, int NegotiateLen) ZeroMemory(pServerBuf, cbMaxToken); ZeroMemory(&NTLM_asServer, sizeof(NTLM_asServer)); do { - if (!hModule) - break; - - /* Prepare server message (challenge) */ - cbIn = NegotiateLen; - cbOut = cbMaxToken; - if (!GenServerContext(&NTLM_asServer, pClientBuf, cbIn, pServerBuf, &cbOut, - &fDone, NULL)) - break; - fResult = pServerBuf; - } while(0); + if (!hModule) + break; + + /* Prepare server message (challenge) */ + cbIn = NegotiateLen; + cbOut = cbMaxToken; + if (!GenServerContext(&NTLM_asServer, pClientBuf, cbIn, pServerBuf, &cbOut, + &fDone, NULL)) + break; + fResult = pServerBuf; + } while (0); if (fResult != NULL) { challenge = (ntlm_challenge *) fResult; Use_Unicode = NEGOTIATE_UNICODE & challenge->flags; @@ -538,17 +537,17 @@ BOOL WINAPI SSP_ValidateNTLMCredentials(PVOID PAutenticateBuf, int AutenticateLe memcpy(pClientBuf, PAutenticateBuf, AutenticateLen); ZeroMemory(pServerBuf, cbMaxToken); do { - if (!hModule) - break; + if (!hModule) + break; /* Prepare server message (authentication) */ cbIn = AutenticateLen; - cbOut = cbMaxToken; - if (!GenServerContext(&NTLM_asServer, pClientBuf, cbIn, pServerBuf, &cbOut, - &fDone, credentials)) - break; - fResult = TRUE; - } while(0); + cbOut = cbMaxToken; + if (!GenServerContext(&NTLM_asServer, pClientBuf, cbIn, pServerBuf, &cbOut, + &fDone, credentials)) + break; + fResult = TRUE; + } while (0); return fResult; } @@ -558,10 +557,10 @@ const char * WINAPI SSP_MakeNegotiateBlob(PVOID PNegotiateBuf, int NegotiateLen, { DWORD cbOut = 0; DWORD cbIn = 0; - const char * encoded = NULL; + const char * encoded = NULL; if (NTLM_asServer.fHaveCtxtHandle) - _DeleteSecurityContext(&NTLM_asServer.hctxt); + _DeleteSecurityContext(&NTLM_asServer.hctxt); if (NTLM_asServer.fHaveCredHandle) _FreeCredentialsHandle(&NTLM_asServer.hcred); @@ -569,19 +568,19 @@ const char * WINAPI SSP_MakeNegotiateBlob(PVOID PNegotiateBuf, int NegotiateLen, ZeroMemory(pServerBuf, cbMaxToken); ZeroMemory(&NTLM_asServer, sizeof(NTLM_asServer)); do { - if (!hModule) - break; - - /* Prepare server message (challenge) */ - cbIn = NegotiateLen; - cbOut = cbMaxToken; - if (!GenServerContext(&NTLM_asServer, pClientBuf, cbIn, pServerBuf, &cbOut, - fDone, credentials)) { - *Status = SSP_ERROR; - break; + if (!hModule) + break; + + /* Prepare server message (challenge) */ + cbIn = NegotiateLen; + cbOut = cbMaxToken; + if (!GenServerContext(&NTLM_asServer, pClientBuf, cbIn, pServerBuf, &cbOut, + fDone, credentials)) { + *Status = SSP_ERROR; + break; } - *Status = SSP_OK; - } while(0); + *Status = SSP_OK; + } while (0); if (pServerBuf != NULL && cbOut > 0) encoded = base64_encode_bin((char *) pServerBuf, cbOut); return encoded; @@ -592,24 +591,24 @@ const char * WINAPI SSP_ValidateNegotiateCredentials(PVOID PAutenticateBuf, int { DWORD cbOut = 0; DWORD cbIn = 0; - const char * encoded = NULL; + const char * encoded = NULL; memcpy(pClientBuf, PAutenticateBuf, AutenticateLen); ZeroMemory(pServerBuf, cbMaxToken); do { - if (!hModule) - break; + if (!hModule) + break; /* Prepare server message (authentication) */ cbIn = AutenticateLen; - cbOut = cbMaxToken; - if (!GenServerContext(&NTLM_asServer, pClientBuf, cbIn, pServerBuf, &cbOut, - fDone, credentials)) { - *Status = SSP_ERROR; - break; + cbOut = cbMaxToken; + if (!GenServerContext(&NTLM_asServer, pClientBuf, cbIn, pServerBuf, &cbOut, + fDone, credentials)) { + *Status = SSP_ERROR; + break; } - *Status = SSP_OK; - } while(0); + *Status = SSP_OK; + } while (0); if (pServerBuf != NULL && cbOut > 0) encoded = base64_encode_bin((char *) pServerBuf, cbOut); return encoded; diff --git a/lib/strerror.c b/lib/strerror.c index 5c92771381..e461a0faa5 100644 --- a/lib/strerror.c +++ b/lib/strerror.c @@ -1,7 +1,7 @@ /* * $Id: strerror.c,v 1.7 2003/01/23 00:37:02 robertc Exp $ * - * DEBUG: + * DEBUG: * AUTHOR: Duane Wessels * * SQUID Web Proxy Cache http://www.squid-cache.org/ @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/lib/strnstr.cc b/lib/strnstr.cc index 3c6ee4513e..4d7676fdb6 100644 --- a/lib/strnstr.cc +++ b/lib/strnstr.cc @@ -72,24 +72,24 @@ const char * squid_strnstr(const char *s, const char *find, size_t slen) { - char c, sc; - size_t len; + char c, sc; + size_t len; - if ((c = *find++) != '\0') { - len = strlen(find); - do { - do { - if (slen < 1 || (sc = *s) == '\0') - return (NULL); - --slen; - ++s; - } while (sc != c); - if (len > slen) - return (NULL); - } while (strncmp(s, find, len) != 0); - s--; - } - return s; + if ((c = *find++) != '\0') { + len = strlen(find); + do { + do { + if (slen < 1 || (sc = *s) == '\0') + return (NULL); + --slen; + ++s; + } while (sc != c); + if (len > slen) + return (NULL); + } while (strncmp(s, find, len) != 0); + s--; + } + return s; } #endif /* !HAVE_STRNSTR */ diff --git a/lib/strsep.c b/lib/strsep.c index 62a475bcc5..9ac9e55c40 100644 --- a/lib/strsep.c +++ b/lib/strsep.c @@ -33,26 +33,24 @@ char * strsep (char **stringp, const char *delim) { - char *start = *stringp; - char *ptr; - - if (!start) - return NULL; - - if (!*delim) - ptr = start + strlen (start); - else - { - ptr = strpbrk (start, delim); - if (!ptr) - { - *stringp = NULL; - return start; - } + char *start = *stringp; + char *ptr; + + if (!start) + return NULL; + + if (!*delim) + ptr = start + strlen (start); + else { + ptr = strpbrk (start, delim); + if (!ptr) { + *stringp = NULL; + return start; + } } - *ptr = '\0'; - *stringp = ptr + 1; + *ptr = '\0'; + *stringp = ptr + 1; - return start; + return start; } diff --git a/lib/strtoll.c b/lib/strtoll.c index e3e4b476be..50f705da9b 100644 --- a/lib/strtoll.c +++ b/lib/strtoll.c @@ -77,85 +77,77 @@ int64_t strtoll (const char *nptr, char **endptr, int base) { - register const char *s = nptr; - register u_int64_t acc; - register int c; - register u_int64_t cutoff; - register int neg = 0, any, cutlim; - - /* - * Skip white space and pick up leading +/- sign if any. - * If base is 0, allow 0x for hex and 0 for octal, else - * assume decimal; if base is already 16, allow 0x. - */ - do - { - c = *s++; + register const char *s = nptr; + register u_int64_t acc; + register int c; + register u_int64_t cutoff; + register int neg = 0, any, cutlim; + + /* + * Skip white space and pick up leading +/- sign if any. + * If base is 0, allow 0x for hex and 0 for octal, else + * assume decimal; if base is already 16, allow 0x. + */ + do { + c = *s++; } while (xisspace(c)); - if (c == '-') - { - neg = 1; - c = *s++; - } - else if (c == '+') - c = *s++; - if ((base == 0 || base == 16) && c == '0' && (*s == 'x' || *s == 'X')) - { - c = s[1]; - s += 2; - base = 16; + if (c == '-') { + neg = 1; + c = *s++; + } else if (c == '+') + c = *s++; + if ((base == 0 || base == 16) && c == '0' && (*s == 'x' || *s == 'X')) { + c = s[1]; + s += 2; + base = 16; } - if (base == 0) - base = c == '0' ? 8 : 10; - - /* - * Compute the cutoff value between legal numbers and illegal - * numbers. That is the largest legal value, divided by the - * base. An input number that is greater than this value, if - * followed by a legal input character, is too big. One that - * is equal to this value may be valid or not; the limit - * between valid and invalid numbers is then based on the last - * digit. For instance, if the range for longs is - * [-2147483648..2147483647] and the input base is 10, - * cutoff will be set to 214748364 and cutlim to either - * 7 (neg==0) or 8 (neg==1), meaning that if we have accumulated - * a value > 214748364, or equal but the next digit is > 7 (or 8), - * the number is too big, and we will return a range error. - * - * Set any if any `digits' consumed; make it negative to indicate - * overflow. - */ - cutoff = neg ? -(u_int64_t) INT64_MIN : INT64_MAX; - cutlim = cutoff % (u_int64_t) base; - cutoff /= (u_int64_t) base; - for (acc = 0, any = 0;; c = *s++) - { - if (xisdigit(c)) - c -= '0'; - else if (xisalpha(c)) - c -= xisupper(c) ? 'A' - 10 : 'a' - 10; - else - break; - if (c >= base) - break; - if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim)) - any = -1; - else - { - any = 1; - acc *= base; - acc += c; + if (base == 0) + base = c == '0' ? 8 : 10; + + /* + * Compute the cutoff value between legal numbers and illegal + * numbers. That is the largest legal value, divided by the + * base. An input number that is greater than this value, if + * followed by a legal input character, is too big. One that + * is equal to this value may be valid or not; the limit + * between valid and invalid numbers is then based on the last + * digit. For instance, if the range for longs is + * [-2147483648..2147483647] and the input base is 10, + * cutoff will be set to 214748364 and cutlim to either + * 7 (neg==0) or 8 (neg==1), meaning that if we have accumulated + * a value > 214748364, or equal but the next digit is > 7 (or 8), + * the number is too big, and we will return a range error. + * + * Set any if any `digits' consumed; make it negative to indicate + * overflow. + */ + cutoff = neg ? -(u_int64_t) INT64_MIN : INT64_MAX; + cutlim = cutoff % (u_int64_t) base; + cutoff /= (u_int64_t) base; + for (acc = 0, any = 0;; c = *s++) { + if (xisdigit(c)) + c -= '0'; + else if (xisalpha(c)) + c -= xisupper(c) ? 'A' - 10 : 'a' - 10; + else + break; + if (c >= base) + break; + if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim)) + any = -1; + else { + any = 1; + acc *= base; + acc += c; } } - if (any < 0) - { - acc = neg ? INT64_MIN : INT64_MAX; - errno = ERANGE; - } - else if (neg) - acc = -acc; - if (endptr != 0) - *endptr = (char *) (any ? s - 1 : nptr); - return acc; + if (any < 0) { + acc = neg ? INT64_MIN : INT64_MAX; + errno = ERANGE; + } else if (neg) + acc = -acc; + if (endptr != 0) + *endptr = (char *) (any ? s - 1 : nptr); + return acc; } diff --git a/lib/tempnam.c b/lib/tempnam.c index 6695d40e80..6ef32c0352 100644 --- a/lib/tempnam.c +++ b/lib/tempnam.c @@ -61,10 +61,10 @@ _tmpnam(void) { static const char digits[] = #if (L_tmpnam >= L_tmpmin + LONG_BIT / 4) - "0123456789abcdef"; + "0123456789abcdef"; #define TMP_BASE 16 #else - "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-"; + "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-"; #define TMP_BASE 64 #endif static unsigned long lastcount = 0; @@ -74,42 +74,42 @@ _tmpnam(void) pid_t pid = getpid(); if (sizeof(_tmp) - 1 != lengthof_tmp) - abort(); /* Consistency error. */ + abort(); /* Consistency error. */ for (;;) { - register int i = L_tmpnam; - register unsigned long c; - register unsigned int p; - - /* Build filename. (the hard way) */ - s += i; - *s = '\0'; - - c = (count == TMP_MAX) ? 0 : ++count; - do { - *--s = digits[c % TMP_BASE]; - c /= TMP_BASE; - } while (--i > L_tmpmin); - - p = (unsigned int) pid; - do { - *--s = digits[p % 10]; - p /= 10; - } while (--i > lengthof_tmp); - - do { - *--s = _tmp[--i]; - } while (i > 0); - - /* Check that the file doesn't exist. */ - if (access(s, 0) != 0) - break; - - /* It exists; retry unless we tried them all. */ - if (count == lastcount) { - s = NULL; - break; - } + register int i = L_tmpnam; + register unsigned long c; + register unsigned int p; + + /* Build filename. (the hard way) */ + s += i; + *s = '\0'; + + c = (count == TMP_MAX) ? 0 : ++count; + do { + *--s = digits[c % TMP_BASE]; + c /= TMP_BASE; + } while (--i > L_tmpmin); + + p = (unsigned int) pid; + do { + *--s = digits[p % 10]; + p /= 10; + } while (--i > lengthof_tmp); + + do { + *--s = _tmp[--i]; + } while (i > 0); + + /* Check that the file doesn't exist. */ + if (access(s, 0) != 0) + break; + + /* It exists; retry unless we tried them all. */ + if (count == lastcount) { + s = NULL; + break; + } } lastcount = count; @@ -130,9 +130,9 @@ main() char *t; int n = 0; while ((t = tempnam(NULL, NULL))) { - printf("%s\n", t); - if (++n == 1000) - break; + printf("%s\n", t); + if (++n == 1000) + break; } return 1; } diff --git a/lib/tests/testArray.cc b/lib/tests/testArray.cc index 8e67660d96..8e08cebe7f 100644 --- a/lib/tests/testArray.cc +++ b/lib/tests/testArray.cc @@ -11,7 +11,7 @@ CPPUNIT_TEST_SUITE_REGISTRATION( testArray ); void testArray::all() { - CPPUNIT_ASSERT( 1 == 1 ); + CPPUNIT_ASSERT( 1 == 1 ); Vector aArray; CPPUNIT_ASSERT (aArray.size() == 0); aArray.push_back(2); diff --git a/lib/tests/testArray.h b/lib/tests/testArray.h index 26f19d6ffc..1c9955693e 100644 --- a/lib/tests/testArray.h +++ b/lib/tests/testArray.h @@ -4,7 +4,7 @@ #include -/* +/* * A test case that is designed to produce * example errors and failures * @@ -12,14 +12,14 @@ class testArray : public CPPUNIT_NS::TestFixture { - CPPUNIT_TEST_SUITE( testArray ); - CPPUNIT_TEST( all ); - CPPUNIT_TEST_SUITE_END(); + CPPUNIT_TEST_SUITE( testArray ); + CPPUNIT_TEST( all ); + CPPUNIT_TEST_SUITE_END(); public: protected: - void all(); + void all(); }; diff --git a/lib/tests/testIPAddress.cc b/lib/tests/testIPAddress.cc index ae8a01a397..3151e32a95 100644 --- a/lib/tests/testIPAddress.cc +++ b/lib/tests/testIPAddress.cc @@ -295,38 +295,38 @@ testIPAddress::testBooleans() valLow.s_addr = htonl(0xC0A8640C); valHigh.s_addr = htonl(0xC0A8640F); - /* test equality */ - lhsIPA = valLow; - rhsIPA = valLow; - CPPUNIT_ASSERT( lhsIPA.matchIPAddr(rhsIPA) == 0 ); - CPPUNIT_ASSERT( ( lhsIPA == rhsIPA ) ); - CPPUNIT_ASSERT( !( lhsIPA != rhsIPA ) ); - CPPUNIT_ASSERT( ( lhsIPA >= rhsIPA ) ); - CPPUNIT_ASSERT( !( lhsIPA > rhsIPA ) ); - CPPUNIT_ASSERT( ( lhsIPA <= rhsIPA ) ); - CPPUNIT_ASSERT( !( lhsIPA < rhsIPA ) ); - - /* test inequality (less than) */ - lhsIPA = valLow; - rhsIPA = valHigh; - CPPUNIT_ASSERT( lhsIPA.matchIPAddr(rhsIPA) < 0 ); - CPPUNIT_ASSERT( !( lhsIPA == rhsIPA ) ); - CPPUNIT_ASSERT( ( lhsIPA != rhsIPA ) ); - CPPUNIT_ASSERT( !( lhsIPA >= rhsIPA ) ); - CPPUNIT_ASSERT( !( lhsIPA > rhsIPA ) ); - CPPUNIT_ASSERT( ( lhsIPA <= rhsIPA ) ); - CPPUNIT_ASSERT( ( lhsIPA < rhsIPA ) ); - - /* test inequality (greater than) */ - lhsIPA = valHigh; - rhsIPA = valLow; - CPPUNIT_ASSERT( lhsIPA.matchIPAddr(rhsIPA) > 0 ); - CPPUNIT_ASSERT( !( lhsIPA == rhsIPA ) ); - CPPUNIT_ASSERT( ( lhsIPA != rhsIPA ) ); - CPPUNIT_ASSERT( ( lhsIPA >= rhsIPA ) ); - CPPUNIT_ASSERT( ( lhsIPA > rhsIPA ) ); - CPPUNIT_ASSERT( !( lhsIPA <= rhsIPA ) ); - CPPUNIT_ASSERT( !( lhsIPA < rhsIPA ) ); + /* test equality */ + lhsIPA = valLow; + rhsIPA = valLow; + CPPUNIT_ASSERT( lhsIPA.matchIPAddr(rhsIPA) == 0 ); + CPPUNIT_ASSERT( ( lhsIPA == rhsIPA ) ); + CPPUNIT_ASSERT( !( lhsIPA != rhsIPA ) ); + CPPUNIT_ASSERT( ( lhsIPA >= rhsIPA ) ); + CPPUNIT_ASSERT( !( lhsIPA > rhsIPA ) ); + CPPUNIT_ASSERT( ( lhsIPA <= rhsIPA ) ); + CPPUNIT_ASSERT( !( lhsIPA < rhsIPA ) ); + + /* test inequality (less than) */ + lhsIPA = valLow; + rhsIPA = valHigh; + CPPUNIT_ASSERT( lhsIPA.matchIPAddr(rhsIPA) < 0 ); + CPPUNIT_ASSERT( !( lhsIPA == rhsIPA ) ); + CPPUNIT_ASSERT( ( lhsIPA != rhsIPA ) ); + CPPUNIT_ASSERT( !( lhsIPA >= rhsIPA ) ); + CPPUNIT_ASSERT( !( lhsIPA > rhsIPA ) ); + CPPUNIT_ASSERT( ( lhsIPA <= rhsIPA ) ); + CPPUNIT_ASSERT( ( lhsIPA < rhsIPA ) ); + + /* test inequality (greater than) */ + lhsIPA = valHigh; + rhsIPA = valLow; + CPPUNIT_ASSERT( lhsIPA.matchIPAddr(rhsIPA) > 0 ); + CPPUNIT_ASSERT( !( lhsIPA == rhsIPA ) ); + CPPUNIT_ASSERT( ( lhsIPA != rhsIPA ) ); + CPPUNIT_ASSERT( ( lhsIPA >= rhsIPA ) ); + CPPUNIT_ASSERT( ( lhsIPA > rhsIPA ) ); + CPPUNIT_ASSERT( !( lhsIPA <= rhsIPA ) ); + CPPUNIT_ASSERT( !( lhsIPA < rhsIPA ) ); } @@ -365,7 +365,8 @@ testIPAddress::testNtoA() void testIPAddress::testToURL_fromInAddr() { - char buf[MAX_IPSTRLEN]; buf[0] = '\0'; + char buf[MAX_IPSTRLEN]; + buf[0] = '\0'; struct in_addr inval; inval.s_addr = htonl(0xC0A8640C); @@ -534,8 +535,8 @@ testIPAddress::testMasking() anIPA.SetNoAddr(); maskIPA.SetNoAddr(); - /* IPv6 masks MUST be CIDR representations. */ - /* however as with IPv4 they can technically be represented as a bitmask */ + /* IPv6 masks MUST be CIDR representations. */ + /* however as with IPv4 they can technically be represented as a bitmask */ maskIPA = "ffff:ffff:fff0::"; CPPUNIT_ASSERT( !maskIPA.IsAnyAddr() ); CPPUNIT_ASSERT( !maskIPA.IsNoAddr() ); @@ -546,7 +547,7 @@ testIPAddress::testMasking() anIPA.SetNoAddr(); maskIPA.SetNoAddr(); - /* IPv4 masks represented in IPv6 as IPv4 bitmasks. */ + /* IPv4 masks represented in IPv6 as IPv4 bitmasks. */ maskIPA = "::ffff:ffff:f000"; CPPUNIT_ASSERT( !maskIPA.IsAnyAddr() ); CPPUNIT_ASSERT( !maskIPA.IsNoAddr() ); @@ -584,11 +585,11 @@ testIPAddress::testAddrInfo() unsigned int *p; p = (unsigned int*)expect; printf("\nSYS-ADDRINFO: %x %x %x %x %x %x ", - p[0],p[1],p[2],p[3],p[4],p[5] ); + p[0],p[1],p[2],p[3],p[4],p[5] ); p = (unsigned int*)ipval; printf("\nSQD-ADDRINFO: %x %x %x %x %x %x ", - p[0],p[1],p[2],p[3],p[4],p[5] ); + p[0],p[1],p[2],p[3],p[4],p[5] ); printf("\n"); // check the addrinfo object core. (BUT not the two ptrs at the tail) @@ -621,7 +622,7 @@ testIPAddress::testBugNullingDisplay() IPAddress anIPA = "192.168.100.12"; - /* test stored values */ + /* test stored values */ CPPUNIT_ASSERT( !anIPA.IsAnyAddr() ); CPPUNIT_ASSERT( !anIPA.IsNoAddr() ); CPPUNIT_ASSERT( anIPA.IsIPv4() ); @@ -632,10 +633,10 @@ testIPAddress::testBugNullingDisplay() CPPUNIT_ASSERT( memcmp( &expectval, &outval, sizeof(struct in_addr)) == 0 ); - /* POKE NtoA display function to see what it is doing */ + /* POKE NtoA display function to see what it is doing */ anIPA.NtoA(ntoabuf,MAX_IPSTRLEN); CPPUNIT_ASSERT( !anIPA.IsAnyAddr() ); - /* test stored values */ + /* test stored values */ CPPUNIT_ASSERT( !anIPA.IsAnyAddr() ); CPPUNIT_ASSERT( !anIPA.IsNoAddr() ); CPPUNIT_ASSERT( anIPA.IsIPv4() ); @@ -647,10 +648,10 @@ testIPAddress::testBugNullingDisplay() - /* POKE ToHostname display function to see what it is doing */ + /* POKE ToHostname display function to see what it is doing */ anIPA.ToHostname(hostbuf,MAX_IPSTRLEN); CPPUNIT_ASSERT( !anIPA.IsAnyAddr() ); - /* test stored values */ + /* test stored values */ CPPUNIT_ASSERT( !anIPA.IsAnyAddr() ); CPPUNIT_ASSERT( !anIPA.IsNoAddr() ); CPPUNIT_ASSERT( anIPA.IsIPv4() ); @@ -661,10 +662,10 @@ testIPAddress::testBugNullingDisplay() CPPUNIT_ASSERT( memcmp( &expectval, &outval, sizeof(struct in_addr)) == 0 ); - /* POKE ToURL display function to see what it is doing */ + /* POKE ToURL display function to see what it is doing */ anIPA.ToURL(urlbuf,MAX_IPSTRLEN); CPPUNIT_ASSERT( !anIPA.IsAnyAddr() ); - /* test stored values */ + /* test stored values */ CPPUNIT_ASSERT( !anIPA.IsAnyAddr() ); CPPUNIT_ASSERT( !anIPA.IsNoAddr() ); CPPUNIT_ASSERT( anIPA.IsIPv4() ); diff --git a/lib/tests/testMain.cc b/lib/tests/testMain.cc index 06c1fc4bba..b3288e7acd 100644 --- a/lib/tests/testMain.cc +++ b/lib/tests/testMain.cc @@ -9,27 +9,27 @@ int main( int argc, char* argv[] ) { - // Create the event manager and test controller - CPPUNIT_NS::TestResult controller; + // Create the event manager and test controller + CPPUNIT_NS::TestResult controller; - // Add a listener that colllects test result - CPPUNIT_NS::TestResultCollector result; - controller.addListener( &result ); + // Add a listener that colllects test result + CPPUNIT_NS::TestResultCollector result; + controller.addListener( &result ); - // Add a listener that print dots as test run. - CPPUNIT_NS::BriefTestProgressListener progress; - controller.addListener( &progress ); + // Add a listener that print dots as test run. + CPPUNIT_NS::BriefTestProgressListener progress; + controller.addListener( &progress ); - // Add the top suite to the test runner - CPPUNIT_NS::TestRunner runner; - runner.addTest( CPPUNIT_NS::TestFactoryRegistry::getRegistry().makeTest() ); - runner.run( controller ); + // Add the top suite to the test runner + CPPUNIT_NS::TestRunner runner; + runner.addTest( CPPUNIT_NS::TestFactoryRegistry::getRegistry().makeTest() ); + runner.run( controller ); - // Print test in a compiler compatible format. - CPPUNIT_NS::CompilerOutputter outputter( &result, std::cerr ); - outputter.write(); + // Print test in a compiler compatible format. + CPPUNIT_NS::CompilerOutputter outputter( &result, std::cerr ); + outputter.write(); - return result.wasSuccessful() ? 0 : 1; + return result.wasSuccessful() ? 0 : 1; } diff --git a/lib/tests/testRFC1035.cc b/lib/tests/testRFC1035.cc index 642d9589a5..b181c2329d 100644 --- a/lib/tests/testRFC1035.cc +++ b/lib/tests/testRFC1035.cc @@ -17,57 +17,58 @@ CPPUNIT_TEST_SUITE_REGISTRATION( testRFC1035 ); void testRFC1035::testHeaderUnpack() { - /* Setup a buffer with the known-content packet */ + /* Setup a buffer with the known-content packet */ const char *buf = "\x76\xb1\x81\x80\x00\x01\x00\x01\x00\x02\x00\x02\x03\x77\x77\x77\x07\x67\x61\x6d\x65\x64\x65\x76\x03\x6e\x65\x74\x00\x00\x01\x00\x01\xc0\x0c\x00\x01\x00\x01\x00\x00\x00\xef\x00\x04\xd8\xb9\x60\xea\xc0\x10\x00\x02\x00\x01\x00\x00\x00\xef\x00\x0f\x03\x6e\x73\x32\x05\x7a\x77\x61\x76\x65\x03\x63\x6f\x6d\x00\xc0\x10\x00\x02\x00\x01\x00\x00\x00\xef\x00\x06\x03\x6e\x73\x31\xc0\x41\xc0\x3d\x00\x01\x00\x01\x00\x00\x29\x6b\x00\x04\xd8\xea\xee\x4a\xc0\x58\x00\x01\x00\x01\x00\x00\x29\x6b\x00\x04\xd8\xea\xee\x4b"; size_t len = 126; rfc1035_message *msg = NULL; int res = 0; unsigned int off = 0; - /* Test the HeaderUnpack function */ + /* Test the HeaderUnpack function */ msg = new rfc1035_message; res = rfc1035HeaderUnpack(buf, len, &off, msg); CPPUNIT_ASSERT(res == 0); CPPUNIT_ASSERT_EQUAL((short unsigned int)0x76b1, msg->id); CPPUNIT_ASSERT(msg->qr == 1); - /* flags */ + /* flags */ CPPUNIT_ASSERT_EQUAL((unsigned int)0, msg->opcode); CPPUNIT_ASSERT_EQUAL((unsigned int)0, msg->aa); CPPUNIT_ASSERT_EQUAL((unsigned int)0, msg->tc); CPPUNIT_ASSERT_EQUAL((unsigned int)1, msg->rd); CPPUNIT_ASSERT_EQUAL((unsigned int)1, msg->ra); CPPUNIT_ASSERT_EQUAL((unsigned int)0, msg->rcode); - /* RR counts */ + /* RR counts */ CPPUNIT_ASSERT_EQUAL((unsigned short)1, msg->qdcount); CPPUNIT_ASSERT_EQUAL((unsigned short)1, msg->ancount); CPPUNIT_ASSERT_EQUAL((unsigned short)2, msg->nscount); CPPUNIT_ASSERT_EQUAL((unsigned short)2, msg->arcount); - /* cleanup */ - delete msg; msg = NULL; + /* cleanup */ + delete msg; + msg = NULL; } void testRFC1035::testParseAPacket() { - /* Setup a buffer with the known-content packet */ + /* Setup a buffer with the known-content packet */ const char *buf = "\x76\xb1\x81\x80\x00\x01\x00\x01\x00\x02\x00\x02\x03\x77\x77\x77\x07\x67\x61\x6d\x65\x64\x65\x76\x03\x6e\x65\x74\x00\x00\x01\x00\x01\xc0\x0c\x00\x01\x00\x01\x00\x00\x00\xef\x00\x04\xd8\xb9\x60\xea\xc0\x10\x00\x02\x00\x01\x00\x00\x00\xef\x00\x0f\x03\x6e\x73\x32\x05\x7a\x77\x61\x76\x65\x03\x63\x6f\x6d\x00\xc0\x10\x00\x02\x00\x01\x00\x00\x00\xef\x00\x06\x03\x6e\x73\x31\xc0\x41\xc0\x3d\x00\x01\x00\x01\x00\x00\x29\x6b\x00\x04\xd8\xea\xee\x4a\xc0\x58\x00\x01\x00\x01\x00\x00\x29\x6b\x00\x04\xd8\xea\xee\x4b"; size_t len = 126; rfc1035_message *msg = NULL; int res = 0; - /* Test the MessageUnpack function itself */ + /* Test the MessageUnpack function itself */ res = rfc1035MessageUnpack(buf, len, &msg); CPPUNIT_ASSERT_EQUAL(1, res); CPPUNIT_ASSERT(msg != NULL); - /* cleanup */ + /* cleanup */ rfc1035MessageDestroy(&msg); CPPUNIT_ASSERT(msg == NULL); } void testRFC1035::testBugPacketEndingOnCompressionPtr() { - /* Setup a buffer with the known-to-fail packet */ + /* Setup a buffer with the known-to-fail packet */ const char *buf = "\xec\x7b\x81\x80\x00\x01\x00\x01\x00\x00\x00\x00\x05\x62\x75\x72\x73\x74\x02\x74\x65\x06\x74\x61\x63\x6f\x64\x61\x03\x6e\x65\x74\x00\x00\x1c\x00\x01\xc0\x0c\x00\x05\x00\x01\x00\x00\x19\xe5\x00\x0a\x02\x74\x65\x04\x67\x73\x6c\x62\xc0\x15"; size_t len = 59; rfc1035_message *msg = NULL; @@ -75,32 +76,33 @@ void testRFC1035::testBugPacketEndingOnCompressionPtr() unsigned int off = 0; - /* Test the HeaderUnpack function results */ + /* Test the HeaderUnpack function results */ msg = new rfc1035_message; res = rfc1035HeaderUnpack(buf, len, &off, msg); CPPUNIT_ASSERT(0 == res); CPPUNIT_ASSERT(0xec7b == msg->id); CPPUNIT_ASSERT(1 == msg->qr); - /* flags */ + /* flags */ CPPUNIT_ASSERT(0 == msg->opcode); CPPUNIT_ASSERT(0 == msg->aa); CPPUNIT_ASSERT(0 == msg->tc); CPPUNIT_ASSERT(1 == msg->rd); CPPUNIT_ASSERT(1 == msg->ra); CPPUNIT_ASSERT(0 == msg->rcode); - /* RR counts */ + /* RR counts */ CPPUNIT_ASSERT(1 == msg->qdcount); CPPUNIT_ASSERT(1 == msg->ancount); CPPUNIT_ASSERT(0 == msg->nscount); CPPUNIT_ASSERT(0 == msg->arcount); CPPUNIT_ASSERT(12 == off); printf("\n Header : OK"); - /* cleanup */ - delete msg; msg = NULL; + /* cleanup */ + delete msg; + msg = NULL; // TODO explicitly test RR and Name unpack functions for this packet. - /* Test the MessageUnpack function itself */ + /* Test the MessageUnpack function itself */ res = rfc1035MessageUnpack(buf, len, &msg); CPPUNIT_ASSERT_EQUAL((const char*)NULL, rfc1035_error_message); diff --git a/lib/util.c b/lib/util.c index 8f48a267f4..1d3e825863 100644 --- a/lib/util.c +++ b/lib/util.c @@ -2,7 +2,7 @@ /* * $Id: util.c,v 1.98 2007/12/06 02:37:15 amosjeffries Exp $ * - * DEBUG: + * DEBUG: * AUTHOR: Harvest Derived * * SQUID Web Proxy Cache http://www.squid-cache.org/ @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -843,7 +843,7 @@ tvSubDsec(struct timeval t1, struct timeval t2) /* * xstrncpy() - similar to strncpy(3) but terminates string - * always with '\0' if (n != 0 and dst != NULL), + * always with '\0' if (n != 0 and dst != NULL), * and doesn't do padding */ char * @@ -931,8 +931,8 @@ xint64toa(int64_t num) void default_failure_notify(const char *message) { - if(write(2, message, strlen(message))) {} - if(write(2, "\n", 1)) {} + if (write(2, message, strlen(message))) {} + if (write(2, "\n", 1)) {} abort(); } diff --git a/lib/uudecode.c b/lib/uudecode.c index a193a8937c..2189d530bb 100644 --- a/lib/uudecode.c +++ b/lib/uudecode.c @@ -8,8 +8,7 @@ extern char **environ; /* aaaack but it's fast and const should make it shared text page. */ -const int pr2six[256] = -{ +const int pr2six[256] = { 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 62, 64, 64, 64, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 64, 64, 64, 64, 64, 64, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, @@ -35,7 +34,7 @@ uudecode(const char *bufcoded) /* Strip leading whitespace. */ while (*bufcoded == ' ' || *bufcoded == '\t') - bufcoded++; + bufcoded++; /* Figure out how many characters are in the input buffer. * Allocate this many from the per-transaction pool for the result. @@ -50,21 +49,21 @@ uudecode(const char *bufcoded) bufin = (const unsigned char *) bufcoded; while (nprbytes > 0) { - *(bufout++) = - (unsigned char) (pr2six[*bufin] << 2 | pr2six[bufin[1]] >> 4); - *(bufout++) = - (unsigned char) (pr2six[bufin[1]] << 4 | pr2six[bufin[2]] >> 2); - *(bufout++) = - (unsigned char) (pr2six[bufin[2]] << 6 | pr2six[bufin[3]]); - bufin += 4; - nprbytes -= 4; + *(bufout++) = + (unsigned char) (pr2six[*bufin] << 2 | pr2six[bufin[1]] >> 4); + *(bufout++) = + (unsigned char) (pr2six[bufin[1]] << 4 | pr2six[bufin[2]] >> 2); + *(bufout++) = + (unsigned char) (pr2six[bufin[2]] << 6 | pr2six[bufin[3]]); + bufin += 4; + nprbytes -= 4; } if (nprbytes & 03) { - if (pr2six[bufin[-2]] > 63) - nbytesdecoded -= 2; - else - nbytesdecoded -= 1; + if (pr2six[bufin[-2]] > 63) + nbytesdecoded -= 2; + else + nbytesdecoded -= 1; } bufplain[nbytesdecoded] = '\0'; return bufplain; diff --git a/lib/win32lib.c b/lib/win32lib.c index 58b130dc94..e12da3bbfa 100644 --- a/lib/win32lib.c +++ b/lib/win32lib.c @@ -22,12 +22,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -60,77 +60,77 @@ LPCRITICAL_SECTION dbg_mutex = NULL; void GetProcessName(pid_t, char *); #if defined(_MSC_VER) /* Microsoft C Compiler ONLY */ -size_t +size_t getpagesize() { static DWORD system_pagesize = 0; if (!system_pagesize) { - SYSTEM_INFO system_info; - GetSystemInfo(&system_info); - system_pagesize = system_info.dwPageSize; + SYSTEM_INFO system_info; + GetSystemInfo(&system_info); + system_pagesize = system_info.dwPageSize; } return system_pagesize; } #endif -uid_t +uid_t geteuid(void) { return 100; } -uid_t +uid_t getuid(void) { return 100; } -int +int setuid(uid_t uid) { return 0; } -int +int seteuid(uid_t euid) { return 0; } -gid_t +gid_t getegid(void) { return 100; } -gid_t +gid_t getgid(void) { return 100; } -int +int setgid(gid_t gid) { return 0; } -int +int setegid(gid_t egid) { return 0; } -int +int chroot(const char *dirname) { if (SetCurrentDirectory(dirname)) - return 0; + return 0; else - return GetLastError(); + return GetLastError(); } -void +void GetProcessName(pid_t pid, char *ProcessName) { HANDLE hProcess; @@ -139,26 +139,26 @@ GetProcessName(pid_t pid, char *ProcessName) #if HAVE_WIN32_PSAPI /* Get a handle to the process. */ hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | - PROCESS_VM_READ, - FALSE, pid); + PROCESS_VM_READ, + FALSE, pid); /* Get the process name. */ if (NULL != hProcess) { - HMODULE hMod; - DWORD cbNeeded; - - if (EnumProcessModules(hProcess, &hMod, sizeof(hMod), &cbNeeded)) - GetModuleBaseName(hProcess, hMod, ProcessName, sizeof(ProcessName)); - else { - CloseHandle(hProcess); - return; - } + HMODULE hMod; + DWORD cbNeeded; + + if (EnumProcessModules(hProcess, &hMod, sizeof(hMod), &cbNeeded)) + GetModuleBaseName(hProcess, hMod, ProcessName, sizeof(ProcessName)); + else { + CloseHandle(hProcess); + return; + } } else - return; + return; CloseHandle(hProcess); #endif } -int +int kill(pid_t pid, int sig) { HANDLE hProcess; @@ -166,24 +166,24 @@ kill(pid_t pid, int sig) char ProcessNameToCheck[MAX_PATH]; if (sig == 0) { - if ((hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | - PROCESS_VM_READ, - FALSE, pid)) == NULL) - return -1; - else { - CloseHandle(hProcess); - GetProcessName(getpid(), MyProcessName); - GetProcessName(pid, ProcessNameToCheck); - if (strcmp(MyProcessName, ProcessNameToCheck) == 0) - return 0; - return -1; - } + if ((hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | + PROCESS_VM_READ, + FALSE, pid)) == NULL) + return -1; + else { + CloseHandle(hProcess); + GetProcessName(getpid(), MyProcessName); + GetProcessName(pid, ProcessNameToCheck); + if (strcmp(MyProcessName, ProcessNameToCheck) == 0) + return 0; + return -1; + } } else - return 0; + return 0; } #ifndef HAVE_GETTIMEOFDAY -int +int gettimeofday(struct timeval *pcur_time, void *tzp) { struct _timeb current; @@ -194,14 +194,14 @@ gettimeofday(struct timeval *pcur_time, void *tzp) pcur_time->tv_sec = current.time; pcur_time->tv_usec = current.millitm * 1000L; if (tz) { - tz->tz_minuteswest = current.timezone; /* minutes west of Greenwich */ - tz->tz_dsttime = current.dstflag; /* type of dst correction */ + tz->tz_minuteswest = current.timezone; /* minutes west of Greenwich */ + tz->tz_dsttime = current.dstflag; /* type of dst correction */ } return 0; } #endif -int +int statfs(const char *path, struct statfs *sfs) { char drive[4]; @@ -209,20 +209,20 @@ statfs(const char *path, struct statfs *sfs) DWORD vsn, maxlen, flags; if (!sfs) { - errno = EINVAL; - return -1; + errno = EINVAL; + return -1; } strncpy(drive, path, 2); drive[2] = '\0'; strcat(drive, "\\"); if (!GetDiskFreeSpace(drive, &spc, &bps, &freec, &totalc)) { - errno = ENOENT; - return -1; + errno = ENOENT; + return -1; } if (!GetVolumeInformation(drive, NULL, 0, &vsn, &maxlen, &flags, NULL, 0)) { - errno = ENOENT; - return -1; + errno = ENOENT; + return -1; } sfs->f_type = flags; sfs->f_bsize = spc * bps; @@ -242,30 +242,30 @@ WIN32_ftruncate(int fd, off_t size) unsigned int curpos; if (fd < 0) - return -1; + return -1; hfile = (HANDLE) _get_osfhandle(fd); curpos = SetFilePointer(hfile, 0, NULL, FILE_CURRENT); if (curpos == 0xFFFFFFFF - || SetFilePointer(hfile, size, NULL, FILE_BEGIN) == 0xFFFFFFFF - || !SetEndOfFile(hfile)) { - int error = GetLastError(); - - switch (error) { - case ERROR_INVALID_HANDLE: - errno = EBADF; - break; - default: - errno = EIO; - break; - } - - return -1; + || SetFilePointer(hfile, size, NULL, FILE_BEGIN) == 0xFFFFFFFF + || !SetEndOfFile(hfile)) { + int error = GetLastError(); + + switch (error) { + case ERROR_INVALID_HANDLE: + errno = EBADF; + break; + default: + errno = EIO; + break; + } + + return -1; } return 0; } -int +int WIN32_truncate(const char *pathname, off_t length) { int fd; @@ -274,10 +274,10 @@ WIN32_truncate(const char *pathname, off_t length) fd = open(pathname, O_RDWR); if (fd == -1) - errno = EBADF; + errno = EBADF; else { - res = WIN32_ftruncate(fd, length); - _close(fd); + res = WIN32_ftruncate(fd, length); + _close(fd); } return res; @@ -290,178 +290,178 @@ static struct _wsaerrtext { } _wsaerrtext[] = { { - WSA_E_CANCELLED, "WSA_E_CANCELLED", "Lookup cancelled." + WSA_E_CANCELLED, "WSA_E_CANCELLED", "Lookup cancelled." }, { - WSA_E_NO_MORE, "WSA_E_NO_MORE", "No more data available." + WSA_E_NO_MORE, "WSA_E_NO_MORE", "No more data available." }, { - WSAEACCES, "WSAEACCES", "Permission denied." + WSAEACCES, "WSAEACCES", "Permission denied." }, { - WSAEADDRINUSE, "WSAEADDRINUSE", "Address already in use." + WSAEADDRINUSE, "WSAEADDRINUSE", "Address already in use." }, { - WSAEADDRNOTAVAIL, "WSAEADDRNOTAVAIL", "Cannot assign requested address." + WSAEADDRNOTAVAIL, "WSAEADDRNOTAVAIL", "Cannot assign requested address." }, { - WSAEAFNOSUPPORT, "WSAEAFNOSUPPORT", "Address family not supported by protocol family." + WSAEAFNOSUPPORT, "WSAEAFNOSUPPORT", "Address family not supported by protocol family." }, { - WSAEALREADY, "WSAEALREADY", "Operation already in progress." + WSAEALREADY, "WSAEALREADY", "Operation already in progress." }, { - WSAEBADF, "WSAEBADF", "Bad file number." + WSAEBADF, "WSAEBADF", "Bad file number." }, { - WSAECANCELLED, "WSAECANCELLED", "Operation cancelled." + WSAECANCELLED, "WSAECANCELLED", "Operation cancelled." }, { - WSAECONNABORTED, "WSAECONNABORTED", "Software caused connection abort." + WSAECONNABORTED, "WSAECONNABORTED", "Software caused connection abort." }, { - WSAECONNREFUSED, "WSAECONNREFUSED", "Connection refused." + WSAECONNREFUSED, "WSAECONNREFUSED", "Connection refused." }, { - WSAECONNRESET, "WSAECONNRESET", "Connection reset by peer." + WSAECONNRESET, "WSAECONNRESET", "Connection reset by peer." }, { - WSAEDESTADDRREQ, "WSAEDESTADDRREQ", "Destination address required." + WSAEDESTADDRREQ, "WSAEDESTADDRREQ", "Destination address required." }, { - WSAEDQUOT, "WSAEDQUOT", "Disk quota exceeded." + WSAEDQUOT, "WSAEDQUOT", "Disk quota exceeded." }, { - WSAEFAULT, "WSAEFAULT", "Bad address." + WSAEFAULT, "WSAEFAULT", "Bad address." }, { - WSAEHOSTDOWN, "WSAEHOSTDOWN", "Host is down." + WSAEHOSTDOWN, "WSAEHOSTDOWN", "Host is down." }, { - WSAEHOSTUNREACH, "WSAEHOSTUNREACH", "No route to host." + WSAEHOSTUNREACH, "WSAEHOSTUNREACH", "No route to host." }, { - WSAEINPROGRESS, "WSAEINPROGRESS", "Operation now in progress." + WSAEINPROGRESS, "WSAEINPROGRESS", "Operation now in progress." }, { - WSAEINTR, "WSAEINTR", "Interrupted function call." + WSAEINTR, "WSAEINTR", "Interrupted function call." }, { - WSAEINVAL, "WSAEINVAL", "Invalid argument." + WSAEINVAL, "WSAEINVAL", "Invalid argument." }, { - WSAEINVALIDPROCTABLE, "WSAEINVALIDPROCTABLE", "Invalid procedure table from service provider." + WSAEINVALIDPROCTABLE, "WSAEINVALIDPROCTABLE", "Invalid procedure table from service provider." }, { - WSAEINVALIDPROVIDER, "WSAEINVALIDPROVIDER", "Invalid service provider version number." + WSAEINVALIDPROVIDER, "WSAEINVALIDPROVIDER", "Invalid service provider version number." }, { - WSAEISCONN, "WSAEISCONN", "Socket is already connected." + WSAEISCONN, "WSAEISCONN", "Socket is already connected." }, { - WSAELOOP, "WSAELOOP", "Too many levels of symbolic links." + WSAELOOP, "WSAELOOP", "Too many levels of symbolic links." }, { - WSAEMFILE, "WSAEMFILE", "Too many open files." + WSAEMFILE, "WSAEMFILE", "Too many open files." }, { - WSAEMSGSIZE, "WSAEMSGSIZE", "Message too long." + WSAEMSGSIZE, "WSAEMSGSIZE", "Message too long." }, { - WSAENAMETOOLONG, "WSAENAMETOOLONG", "File name is too long." + WSAENAMETOOLONG, "WSAENAMETOOLONG", "File name is too long." }, { - WSAENETDOWN, "WSAENETDOWN", "Network is down." + WSAENETDOWN, "WSAENETDOWN", "Network is down." }, { - WSAENETRESET, "WSAENETRESET", "Network dropped connection on reset." + WSAENETRESET, "WSAENETRESET", "Network dropped connection on reset." }, { - WSAENETUNREACH, "WSAENETUNREACH", "Network is unreachable." + WSAENETUNREACH, "WSAENETUNREACH", "Network is unreachable." }, { - WSAENOBUFS, "WSAENOBUFS", "No buffer space available." + WSAENOBUFS, "WSAENOBUFS", "No buffer space available." }, { - WSAENOMORE, "WSAENOMORE", "No more data available." + WSAENOMORE, "WSAENOMORE", "No more data available." }, { - WSAENOPROTOOPT, "WSAENOPROTOOPT", "Bad protocol option." + WSAENOPROTOOPT, "WSAENOPROTOOPT", "Bad protocol option." }, { - WSAENOTCONN, "WSAENOTCONN", "Socket is not connected." + WSAENOTCONN, "WSAENOTCONN", "Socket is not connected." }, { - WSAENOTEMPTY, "WSAENOTEMPTY", "Directory is not empty." + WSAENOTEMPTY, "WSAENOTEMPTY", "Directory is not empty." }, { - WSAENOTSOCK, "WSAENOTSOCK", "Socket operation on nonsocket." + WSAENOTSOCK, "WSAENOTSOCK", "Socket operation on nonsocket." }, { - WSAEOPNOTSUPP, "WSAEOPNOTSUPP", "Operation not supported." + WSAEOPNOTSUPP, "WSAEOPNOTSUPP", "Operation not supported." }, { - WSAEPFNOSUPPORT, "WSAEPFNOSUPPORT", "Protocol family not supported." + WSAEPFNOSUPPORT, "WSAEPFNOSUPPORT", "Protocol family not supported." }, { - WSAEPROCLIM, "WSAEPROCLIM", "Too many processes." + WSAEPROCLIM, "WSAEPROCLIM", "Too many processes." }, { - WSAEPROTONOSUPPORT, "WSAEPROTONOSUPPORT", "Protocol not supported." + WSAEPROTONOSUPPORT, "WSAEPROTONOSUPPORT", "Protocol not supported." }, { - WSAEPROTOTYPE, "WSAEPROTOTYPE", "Protocol wrong type for socket." + WSAEPROTOTYPE, "WSAEPROTOTYPE", "Protocol wrong type for socket." }, { - WSAEPROVIDERFAILEDINIT, "WSAEPROVIDERFAILEDINIT", "Unable to initialise a service provider." + WSAEPROVIDERFAILEDINIT, "WSAEPROVIDERFAILEDINIT", "Unable to initialise a service provider." }, { - WSAEREFUSED, "WSAEREFUSED", "Refused." + WSAEREFUSED, "WSAEREFUSED", "Refused." }, { - WSAEREMOTE, "WSAEREMOTE", "Too many levels of remote in path." + WSAEREMOTE, "WSAEREMOTE", "Too many levels of remote in path." }, { - WSAESHUTDOWN, "WSAESHUTDOWN", "Cannot send after socket shutdown." + WSAESHUTDOWN, "WSAESHUTDOWN", "Cannot send after socket shutdown." }, { - WSAESOCKTNOSUPPORT, "WSAESOCKTNOSUPPORT", "Socket type not supported." + WSAESOCKTNOSUPPORT, "WSAESOCKTNOSUPPORT", "Socket type not supported." }, { - WSAESTALE, "WSAESTALE", "Stale NFS file handle." + WSAESTALE, "WSAESTALE", "Stale NFS file handle." }, { - WSAETIMEDOUT, "WSAETIMEDOUT", "Connection timed out." + WSAETIMEDOUT, "WSAETIMEDOUT", "Connection timed out." }, { - WSAETOOMANYREFS, "WSAETOOMANYREFS", "Too many references." + WSAETOOMANYREFS, "WSAETOOMANYREFS", "Too many references." }, { - WSAEUSERS, "WSAEUSERS", "Too many users." + WSAEUSERS, "WSAEUSERS", "Too many users." }, { - WSAEWOULDBLOCK, "WSAEWOULDBLOCK", "Resource temporarily unavailable." + WSAEWOULDBLOCK, "WSAEWOULDBLOCK", "Resource temporarily unavailable." }, { - WSANOTINITIALISED, "WSANOTINITIALISED", "Successful WSAStartup not yet performed." + WSANOTINITIALISED, "WSANOTINITIALISED", "Successful WSAStartup not yet performed." }, { - WSASERVICE_NOT_FOUND, "WSASERVICE_NOT_FOUND", "Service not found." + WSASERVICE_NOT_FOUND, "WSASERVICE_NOT_FOUND", "Service not found." }, { - WSASYSCALLFAILURE, "WSASYSCALLFAILURE", "System call failure." + WSASYSCALLFAILURE, "WSASYSCALLFAILURE", "System call failure." }, { - WSASYSNOTREADY, "WSASYSNOTREADY", "Network subsystem is unavailable." + WSASYSNOTREADY, "WSASYSNOTREADY", "Network subsystem is unavailable." }, { - WSATYPE_NOT_FOUND, "WSATYPE_NOT_FOUND", "Class type not found." + WSATYPE_NOT_FOUND, "WSATYPE_NOT_FOUND", "Class type not found." }, { - WSAVERNOTSUPPORTED, "WSAVERNOTSUPPORTED", "Winsock.dll version out of range." + WSAVERNOTSUPPORTED, "WSAVERNOTSUPPORTED", "Winsock.dll version out of range." }, { - WSAEDISCON, "WSAEDISCON", "Graceful shutdown in progress." + WSAEDISCON, "WSAEDISCON", "Graceful shutdown in progress." } }; @@ -475,33 +475,29 @@ wsastrerror(int err) int i, errind = -1; if (err == 0) - return "(0) No error."; + return "(0) No error."; for (i = 0; i < sizeof(_wsaerrtext) / sizeof(struct _wsaerrtext); i++) { - if (_wsaerrtext[i].err != err) - continue; - errind = i; - break; + if (_wsaerrtext[i].err != err) + continue; + errind = i; + break; } if (errind == -1) - snprintf(xwsaerror_buf, BUFSIZ, "Unknown"); + snprintf(xwsaerror_buf, BUFSIZ, "Unknown"); else - snprintf(xwsaerror_buf, BUFSIZ, "%s, %s", _wsaerrtext[errind].errconst, _wsaerrtext[errind].errdesc); + snprintf(xwsaerror_buf, BUFSIZ, "%s, %s", _wsaerrtext[errind].errconst, _wsaerrtext[errind].errdesc); return xwsaerror_buf; } struct passwd * -getpwnam(char *unused) -{ - static struct passwd pwd = - {NULL, NULL, 100, 100, NULL, NULL, NULL}; + getpwnam(char *unused) { + static struct passwd pwd = {NULL, NULL, 100, 100, NULL, NULL, NULL}; return &pwd; } struct group * -getgrnam(char *unused) -{ - static struct group grp = - {NULL, NULL, 100, NULL}; + getgrnam(char *unused) { + static struct group grp = {NULL, NULL, 100, NULL}; return &grp; } @@ -514,36 +510,36 @@ WIN32_strerror(int err) static char xbstrerror_buf[BUFSIZ]; if (err < 0 || err >= sys_nerr) - strncpy(xbstrerror_buf, wsastrerror(err), BUFSIZ); + strncpy(xbstrerror_buf, wsastrerror(err), BUFSIZ); else - strncpy(xbstrerror_buf, strerror(err), BUFSIZ); + strncpy(xbstrerror_buf, strerror(err), BUFSIZ); return xbstrerror_buf; } #if defined(__MINGW32__) /* MinGW environment */ -int +int _free_osfhnd(int filehandle) { if (((unsigned) filehandle < SQUID_MAXFD) && - (_osfile(filehandle) & FOPEN) && - (_osfhnd(filehandle) != (long) INVALID_HANDLE_VALUE)) { - switch (filehandle) { - case 0: - SetStdHandle(STD_INPUT_HANDLE, NULL); - break; - case 1: - SetStdHandle(STD_OUTPUT_HANDLE, NULL); - break; - case 2: - SetStdHandle(STD_ERROR_HANDLE, NULL); - break; - } - _osfhnd(filehandle) = (long) INVALID_HANDLE_VALUE; - return (0); + (_osfile(filehandle) & FOPEN) && + (_osfhnd(filehandle) != (long) INVALID_HANDLE_VALUE)) { + switch (filehandle) { + case 0: + SetStdHandle(STD_INPUT_HANDLE, NULL); + break; + case 1: + SetStdHandle(STD_OUTPUT_HANDLE, NULL); + break; + case 2: + SetStdHandle(STD_ERROR_HANDLE, NULL); + break; + } + _osfhnd(filehandle) = (long) INVALID_HANDLE_VALUE; + return (0); } else { - errno = EBADF; /* bad handle */ - _doserrno = 0L; /* not an OS error */ - return -1; + errno = EBADF; /* bad handle */ + _doserrno = 0L; /* not an OS error */ + return -1; } } #endif @@ -553,8 +549,7 @@ struct errorentry { int POSIX_errno; }; -static struct errorentry errortable[] = -{ +static struct errorentry errortable[] = { {ERROR_INVALID_FUNCTION, EINVAL}, {ERROR_FILE_NOT_FOUND, ENOENT}, {ERROR_PATH_NOT_FOUND, ENOENT}, @@ -608,23 +603,23 @@ static struct errorentry errortable[] = #define MIN_EACCES_RANGE ERROR_WRITE_PROTECT #define MAX_EACCES_RANGE ERROR_SHARING_BUFFER_EXCEEDED -void +void WIN32_maperror(unsigned long WIN32_oserrno) { int i; _doserrno = WIN32_oserrno; for (i = 0; i < (sizeof(errortable) / sizeof(struct errorentry)); ++i) { - if (WIN32_oserrno == errortable[i].WIN32_code) { - errno = errortable[i].POSIX_errno; - return; - } + if (WIN32_oserrno == errortable[i].WIN32_code) { + errno = errortable[i].POSIX_errno; + return; + } } if (WIN32_oserrno >= MIN_EACCES_RANGE && WIN32_oserrno <= MAX_EACCES_RANGE) - errno = EACCES; + errno = EACCES; else if (WIN32_oserrno >= MIN_EXEC_ERROR && WIN32_oserrno <= MAX_EXEC_ERROR) - errno = ENOEXEC; + errno = ENOEXEC; else - errno = EINVAL; + errno = EINVAL; } #endif diff --git a/scripts/formater.pl b/scripts/formater.pl index 1f8478ea77..40a92a1032 100755 --- a/scripts/formater.pl +++ b/scripts/formater.pl @@ -25,7 +25,8 @@ use IPC::Open2; # # NP: The Squid code requires astyle version 1.22 or later # -$ASTYLE_BIN="/usr/local/bin/astyle"; +#$ASTYLE_BIN="/usr/local/bin/astyle"; +$ASTYLE_BIN="/usr/bin/astyle"; #$ASTYLE_BIN="/usr/local/src/astyle-1.22/bin/astyle"; $ASTYLE_ARGS ="--mode=c -s4 -O -l"; diff --git a/scripts/srcformat.sh b/scripts/srcformat.sh index ce9fd9b9b1..0b3e8c1fb4 100755 --- a/scripts/srcformat.sh +++ b/scripts/srcformat.sh @@ -1,3 +1,6 @@ +#!/bin/bash +# +# Would be used on squid-cache. But FreeBSD astyle version is too old. #!/usr/local/bin/bash # # A checker to recursively reformat all source files: .h .c .cc .cci diff --git a/snmplib/asn1.c b/snmplib/asn1.c index e0dde7fb78..6cc84d0dbb 100644 --- a/snmplib/asn1.c +++ b/snmplib/asn1.c @@ -10,9 +10,9 @@ /*************************************************************************** * * Copyright 1997 by Carnegie Mellon University - * + * * All Rights Reserved - * + * * Permission to use, copy, modify, and distribute this software and its * documentation for any purpose and without fee is hereby granted, * provided that the above copyright notice appear in all copies and that @@ -20,7 +20,7 @@ * supporting documentation, and that the name of CMU not be * used in advertising or publicity pertaining to distribution of the * software without specific, written prior permission. - * + * * CMU DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING * ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL * CMU BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR @@ -28,7 +28,7 @@ * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS * SOFTWARE. - * + * ***************************************************************************/ #include "config.h" @@ -86,10 +86,10 @@ u_char * asn_build_header(u_char * data, /* IN - ptr to start of object */ - int *datalength, /* IN/OUT - # of valid bytes */ - /* left in buffer */ - u_char type, /* IN - ASN type of object */ - int length) + int *datalength, /* IN/OUT - # of valid bytes */ + /* left in buffer */ + u_char type, /* IN - ASN type of object */ + int length) { /* IN - length of object */ /* Truth is 0 'cause we don't know yet */ return (asn_build_header_with_truth(data, datalength, type, length, 0)); @@ -108,12 +108,12 @@ asn_build_header(u_char * data, /* IN - ptr to start of object */ */ u_char * asn_parse_int(u_char * data, int *datalength, - u_char * type, int *intp, int intsize) - /* u_char *data; IN - pointer to start of object */ - /* int *datalength; IN/OUT - # of valid bytes left in buffer */ - /* u_char *type; OUT - asn type of object */ - /* int *intp; IN/OUT - pointer to start of output buffer */ - /* int intsize; IN - size of output buffer */ + u_char * type, int *intp, int intsize) +/* u_char *data; IN - pointer to start of object */ +/* int *datalength; IN/OUT - # of valid bytes left in buffer */ +/* u_char *type; OUT - asn type of object */ +/* int *intp; IN/OUT - pointer to start of output buffer */ +/* int intsize; IN - size of output buffer */ { /* * ASN.1 integer ::= 0x02 asnlength byte {byte}* @@ -124,8 +124,8 @@ asn_parse_int(u_char * data, int *datalength, /* Room to store int? */ if (intsize != sizeof(int)) { - snmp_set_api_error(SNMPERR_ASN_DECODE); - return (NULL); + snmp_set_api_error(SNMPERR_ASN_DECODE); + return (NULL); } /* Type */ *type = *bufp++; @@ -133,28 +133,28 @@ asn_parse_int(u_char * data, int *datalength, /* Extract length */ bufp = asn_parse_length(bufp, &asn_length); if (bufp == NULL) - return (NULL); + return (NULL); /* Make sure the entire int is in the buffer */ if (asn_length + (bufp - data) > *datalength) { - snmp_set_api_error(SNMPERR_ASN_DECODE); - return (NULL); + snmp_set_api_error(SNMPERR_ASN_DECODE); + return (NULL); } /* Can we store this int? */ if (asn_length > intsize) { - snmp_set_api_error(SNMPERR_ASN_DECODE); - return (NULL); + snmp_set_api_error(SNMPERR_ASN_DECODE); + return (NULL); } /* Remaining data */ *datalength -= (int) asn_length + (bufp - data); /* Is the int negative? */ if (*bufp & 0x80) - value = -1; /* integer is negative */ + value = -1; /* integer is negative */ /* Extract the bytes */ while (asn_length--) - value = (value << 8) | *bufp++; + value = (value << 8) | *bufp++; /* That's it! */ *intp = value; @@ -173,12 +173,12 @@ asn_parse_int(u_char * data, int *datalength, */ u_char * asn_parse_unsigned_int(u_char * data, int *datalength, - u_char * type, u_int * intp, int intsize) - /* u_char *data; IN - pointer to start of object */ - /* int *datalength; IN/OUT - # of valid bytes left in buffer */ - /* u_char *type; OUT - asn type of object */ - /* u_int *intp; IN/OUT - pointer to start of output buffer */ - /* int intsize; IN - size of output buffer */ + u_char * type, u_int * intp, int intsize) +/* u_char *data; IN - pointer to start of object */ +/* int *datalength; IN/OUT - # of valid bytes left in buffer */ +/* u_char *type; OUT - asn type of object */ +/* u_int *intp; IN/OUT - pointer to start of output buffer */ +/* int intsize; IN - size of output buffer */ { /* * ASN.1 integer ::= 0x02 asnlength byte {byte}* @@ -189,8 +189,8 @@ asn_parse_unsigned_int(u_char * data, int *datalength, /* Room to store int? */ if (intsize != sizeof(int)) { - snmp_set_api_error(SNMPERR_ASN_DECODE); - return (NULL); + snmp_set_api_error(SNMPERR_ASN_DECODE); + return (NULL); } /* Type */ *type = *bufp++; @@ -198,29 +198,29 @@ asn_parse_unsigned_int(u_char * data, int *datalength, /* Extract length */ bufp = asn_parse_length(bufp, &asn_length); if (bufp == NULL) - return (NULL); + return (NULL); /* Make sure the entire int is in the buffer */ if (asn_length + (bufp - data) > *datalength) { - snmp_set_api_error(SNMPERR_ASN_DECODE); - return (NULL); + snmp_set_api_error(SNMPERR_ASN_DECODE); + return (NULL); } /* Can we store this int? */ if ((asn_length > (intsize + 1)) || - ((asn_length == intsize + 1) && *bufp != 0x00)) { - snmp_set_api_error(SNMPERR_ASN_DECODE); - return (NULL); + ((asn_length == intsize + 1) && *bufp != 0x00)) { + snmp_set_api_error(SNMPERR_ASN_DECODE); + return (NULL); } /* Remaining data */ *datalength -= (int) asn_length + (bufp - data); /* Is the int negative? */ if (*bufp & 0x80) - value = -1; /* integer is negative */ + value = -1; /* integer is negative */ /* Extract the bytes */ while (asn_length--) - value = (value << 8) | *bufp++; + value = (value << 8) | *bufp++; /* That's it! */ *intp = value; @@ -239,12 +239,12 @@ asn_parse_unsigned_int(u_char * data, int *datalength, */ u_char * asn_build_int(u_char * data, int *datalength, - u_char type, int *intp, int intsize) - /* u_char *data; IN - pointer to start of output buffer */ - /* int *datalength; IN/OUT - # of valid bytes left in buffer */ - /* u_char type; IN - asn type of object */ - /* int *intp; IN - pointer to start of integer */ - /* int intsize; IN - size of *intp */ + u_char type, int *intp, int intsize) +/* u_char *data; IN - pointer to start of output buffer */ +/* int *datalength; IN/OUT - # of valid bytes left in buffer */ +/* u_char type; IN - asn type of object */ +/* int *intp; IN - pointer to start of integer */ +/* int intsize; IN - size of *intp */ { /* * ASN.1 integer ::= 0x02 asnlength byte {byte}* @@ -253,8 +253,8 @@ asn_build_int(u_char * data, int *datalength, u_int mask; if (intsize != sizeof(int)) { - snmp_set_api_error(SNMPERR_ASN_ENCODE); - return (NULL); + snmp_set_api_error(SNMPERR_ASN_ENCODE); + return (NULL); } integer = *intp; @@ -268,27 +268,27 @@ asn_build_int(u_char * data, int *datalength, /* mask is 0xFF800000 on a big-endian machine */ while ((((integer & mask) == 0) || ((integer & mask) == mask)) - && intsize > 1) { - intsize--; - integer <<= 8; + && intsize > 1) { + intsize--; + integer <<= 8; } data = asn_build_header_with_truth(data, datalength, type, intsize, 1); if (data == NULL) - return (NULL); + return (NULL); /* Enough room for what we just encoded? */ if (*datalength < intsize) { - snmp_set_api_error(SNMPERR_ASN_ENCODE); - return (NULL); + snmp_set_api_error(SNMPERR_ASN_ENCODE); + return (NULL); } /* Insert it */ *datalength -= intsize; mask = (u_int) 0xFF << (8 * (sizeof(int) - 1)); /* mask is 0xFF000000 on a big-endian machine */ while (intsize--) { - *data++ = (u_char) ((integer & mask) >> (8 * (sizeof(int) - 1))); - integer <<= 8; + *data++ = (u_char) ((integer & mask) >> (8 * (sizeof(int) - 1))); + integer <<= 8; } return (data); } @@ -305,12 +305,12 @@ asn_build_int(u_char * data, int *datalength, */ u_char * asn_build_unsigned_int(u_char * data, int *datalength, - u_char type, u_int * intp, int intsize) - /* u_char *data; IN - pointer to start of output buffer */ - /* int *datalength; IN/OUT - # of valid bytes left in buffer */ - /* u_char type; IN - asn type of object */ - /* u_int *intp; IN - pointer to start of integer */ - /* int intsize; IN - size of *intp */ + u_char type, u_int * intp, int intsize) +/* u_char *data; IN - pointer to start of output buffer */ +/* int *datalength; IN/OUT - # of valid bytes left in buffer */ +/* u_char type; IN - asn type of object */ +/* u_int *intp; IN - pointer to start of integer */ +/* int intsize; IN - size of *intp */ { /* * ASN.1 integer ::= 0x02 asnlength byte {byte}* @@ -320,20 +320,20 @@ asn_build_unsigned_int(u_char * data, int *datalength, int add_null_byte = 0; if (intsize != sizeof(int)) { - snmp_set_api_error(SNMPERR_ASN_ENCODE); - return (NULL); + snmp_set_api_error(SNMPERR_ASN_ENCODE); + return (NULL); } integer = *intp; mask = (u_int) 0x80 << (8 * (sizeof(int) - 1)); /* mask is 0x80000000 on a big-endian machine */ if ((integer & mask) != 0) { - /* add a null byte if MSB is set, to prevent sign extension */ - add_null_byte = 1; - intsize++; + /* add a null byte if MSB is set, to prevent sign extension */ + add_null_byte = 1; + intsize++; } /* * Truncate "unnecessary" bytes off of the most significant end of - * this 2's complement integer. + * this 2's complement integer. * There should be no sequence of 9 consecutive 1's or 0's at the * most significant end of the integer. * The 1's case is taken care of above by adding a null byte. @@ -341,28 +341,28 @@ asn_build_unsigned_int(u_char * data, int *datalength, mask = (u_int) 0x1FF << ((8 * (sizeof(int) - 1)) - 1); /* mask is 0xFF800000 on a big-endian machine */ while (((integer & mask) == 0) && intsize > 1) { - intsize--; - integer <<= 8; + intsize--; + integer <<= 8; } data = asn_build_header_with_truth(data, datalength, type, intsize, 1); if (data == NULL) - return (NULL); + return (NULL); if (*datalength < intsize) { - snmp_set_api_error(SNMPERR_ASN_ENCODE); - return (NULL); + snmp_set_api_error(SNMPERR_ASN_ENCODE); + return (NULL); } *datalength -= intsize; if (add_null_byte == 1) { - *data++ = '\0'; - intsize--; + *data++ = '\0'; + intsize--; } mask = (u_int) 0xFF << (8 * (sizeof(int) - 1)); /* mask is 0xFF000000 on a big-endian machine */ while (intsize--) { - *data++ = (u_char) ((integer & mask) >> (8 * (sizeof(int) - 1))); - integer <<= 8; + *data++ = (u_char) ((integer & mask) >> (8 * (sizeof(int) - 1))); + integer <<= 8; } return (data); } @@ -381,12 +381,12 @@ asn_build_unsigned_int(u_char * data, int *datalength, */ u_char * asn_parse_string(u_char * data, int *datalength, - u_char * type, u_char * string, int *strlength) - /* u_char *data; IN - pointer to start of object */ - /* int *datalength; IN/OUT - # of valid bytes left in buffer */ - /* u_char *type; OUT - asn type of object */ - /* u_char *string; IN/OUT - pointer to start of output buffer */ - /* int *strlength; IN/OUT - size of output buffer */ + u_char * type, u_char * string, int *strlength) +/* u_char *data; IN - pointer to start of object */ +/* int *datalength; IN/OUT - # of valid bytes left in buffer */ +/* u_char *type; OUT - asn type of object */ +/* u_char *string; IN/OUT - pointer to start of output buffer */ +/* int *strlength; IN/OUT - size of output buffer */ { /* * ASN.1 octet string ::= primstring | cmpdstring @@ -399,15 +399,15 @@ asn_parse_string(u_char * data, int *datalength, *type = *bufp++; bufp = asn_parse_length(bufp, &asn_length); if (bufp == NULL) - return (NULL); + return (NULL); if (asn_length + (bufp - data) > *datalength) { - snmp_set_api_error(SNMPERR_ASN_DECODE); - return (NULL); + snmp_set_api_error(SNMPERR_ASN_DECODE); + return (NULL); } if (asn_length > *strlength) { - snmp_set_api_error(SNMPERR_ASN_DECODE); - return (NULL); + snmp_set_api_error(SNMPERR_ASN_DECODE); + return (NULL); } xmemcpy((char *) string, (char *) bufp, (int) asn_length); *strlength = (int) asn_length; @@ -417,7 +417,7 @@ asn_parse_string(u_char * data, int *datalength, /* * asn_build_string - Builds an ASN octet string object containing the input - * string. On entry, datalength is input as the number of valid bytes + * string. On entry, datalength is input as the number of valid bytes * following "data". On exit, it is returned as the number of valid bytes * following the beginning of the next object. * @@ -427,12 +427,12 @@ asn_parse_string(u_char * data, int *datalength, */ u_char * asn_build_string(u_char * data, int *datalength, - u_char type, u_char * string, int strlength) - /* u_char *data; IN - pointer to start of object */ - /* int *datalength; IN/OUT - # of valid bytes left in buf */ - /* u_char type; IN - ASN type of string */ - /* u_char *string; IN - pointer to start of input buffer */ - /* int strlength; IN - size of input buffer */ + u_char type, u_char * string, int strlength) +/* u_char *data; IN - pointer to start of object */ +/* int *datalength; IN/OUT - # of valid bytes left in buf */ +/* u_char type; IN - ASN type of string */ +/* u_char *string; IN - pointer to start of input buffer */ +/* int strlength; IN - size of input buffer */ { /* * ASN.1 octet string ::= primstring | cmpdstring @@ -442,11 +442,11 @@ asn_build_string(u_char * data, int *datalength, */ data = asn_build_header_with_truth(data, datalength, type, strlength, 1); if (data == NULL) - return (NULL); + return (NULL); if (*datalength < strlength) { - snmp_set_api_error(SNMPERR_ASN_DECODE); - return (NULL); + snmp_set_api_error(SNMPERR_ASN_DECODE); + return (NULL); } xmemcpy((char *) data, (char *) string, strlength); *datalength -= strlength; @@ -465,9 +465,9 @@ asn_build_string(u_char * data, int *datalength, */ u_char * asn_parse_header(u_char * data, int *datalength, u_char * type) - /* u_char *data; IN - pointer to start of object */ - /* int *datalength; IN/OUT - # of valid bytes left in buffer */ - /* u_char *type; OUT - ASN type of object */ +/* u_char *data; IN - pointer to start of object */ +/* int *datalength; IN/OUT - # of valid bytes left in buffer */ +/* u_char *type; OUT - ASN type of object */ { u_char *bufp = data; int header_len; @@ -475,18 +475,18 @@ asn_parse_header(u_char * data, int *datalength, u_char * type) /* this only works on data types < 30, i.e. no extension octets */ if (IS_EXTENSION_ID(*bufp)) { - snmp_set_api_error(SNMPERR_ASN_DECODE); - return (NULL); + snmp_set_api_error(SNMPERR_ASN_DECODE); + return (NULL); } *type = *bufp; bufp = asn_parse_length(bufp + 1, &asn_length); if (bufp == NULL) - return (NULL); + return (NULL); header_len = bufp - data; if (header_len + asn_length > *datalength || asn_length > (u_int)(2 << 18) ) { - snmp_set_api_error(SNMPERR_ASN_DECODE); - return (NULL); + snmp_set_api_error(SNMPERR_ASN_DECODE); + return (NULL); } *datalength = (int) asn_length; return (bufp); @@ -508,16 +508,16 @@ asn_parse_header(u_char * data, int *datalength, u_char * type) u_char * asn_build_header_with_truth(u_char * data, int *datalength, - u_char type, int length, int truth) - /* u_char *data; IN - pointer to start of object */ - /* int *datalength; IN/OUT - # of valid bytes left in buffer */ - /* u_char type; IN - ASN type of object */ - /* int length; IN - length of object */ - /* int truth; IN - Whether length is truth */ + u_char type, int length, int truth) +/* u_char *data; IN - pointer to start of object */ +/* int *datalength; IN/OUT - # of valid bytes left in buffer */ +/* u_char type; IN - ASN type of object */ +/* int length; IN - length of object */ +/* int truth; IN - Whether length is truth */ { if (*datalength < 1) { - snmp_set_api_error(SNMPERR_ASN_ENCODE); - return (NULL); + snmp_set_api_error(SNMPERR_ASN_ENCODE); + return (NULL); } *data++ = type; (*datalength)--; @@ -540,17 +540,17 @@ asn_build_header_with_truth(u_char * data, int *datalength, */ u_char * asn_build_sequence(u_char * data, int *datalength, - u_char type, int length) - /* u_char *data; IN - pointer to start of object */ - /* int *datalength; IN/OUT - # of valid bytes left in buffer */ - /* u_char type; IN - ASN type of object */ - /* int length; IN - length of object */ + u_char type, int length) +/* u_char *data; IN - pointer to start of object */ +/* int *datalength; IN/OUT - # of valid bytes left in buffer */ +/* u_char type; IN - ASN type of object */ +/* int length; IN - length of object */ { *datalength -= 4; if (*datalength < 0) { - *datalength += 4; /* fix up before punting */ - snmp_set_api_error(SNMPERR_ASN_ENCODE); - return (NULL); + *datalength += 4; /* fix up before punting */ + snmp_set_api_error(SNMPERR_ASN_ENCODE); + return (NULL); } *data++ = type; *data++ = (u_char) (0x02 | ASN_LONG_LEN); @@ -570,27 +570,27 @@ asn_build_sequence(u_char * data, int *datalength, */ u_char * asn_parse_length(u_char * data, u_int * length) - /* u_char *data; IN - pointer to start of length field */ - /* u_int *length; OUT - value of length field */ +/* u_char *data; IN - pointer to start of length field */ +/* u_int *length; OUT - value of length field */ { u_char lengthbyte = *data; if (lengthbyte & ASN_LONG_LEN) { - lengthbyte &= ~ASN_LONG_LEN; /* turn MSb off */ - - if (lengthbyte == 0) { - snmp_set_api_error(SNMPERR_ASN_DECODE); - return (NULL); - } - if (lengthbyte > sizeof(int)) { - snmp_set_api_error(SNMPERR_ASN_DECODE); - return (NULL); - } - *length = (u_int) 0; - xmemcpy((char *) (length), (char *) data + 1, (int) lengthbyte); - *length = ntohl(*length); - *length >>= (8 * ((sizeof *length) - lengthbyte)); - return (data + lengthbyte + 1); + lengthbyte &= ~ASN_LONG_LEN; /* turn MSb off */ + + if (lengthbyte == 0) { + snmp_set_api_error(SNMPERR_ASN_DECODE); + return (NULL); + } + if (lengthbyte > sizeof(int)) { + snmp_set_api_error(SNMPERR_ASN_DECODE); + return (NULL); + } + *length = (u_int) 0; + xmemcpy((char *) (length), (char *) data + 1, (int) lengthbyte); + *length = ntohl(*length); + *length >>= (8 * ((sizeof *length) - lengthbyte)); + return (data + lengthbyte + 1); } /* short asnlength */ @@ -602,53 +602,53 @@ asn_parse_length(u_char * data, u_int * length) u_char * asn_build_length(u_char * data, int *datalength, - int length, int truth) - /* u_char *data; IN - pointer to start of object */ - /* int *datalength; IN/OUT - # of valid bytes left in buf */ - /* int length; IN - length of object */ - /* int truth; IN - If 1, this is the true len. */ + int length, int truth) +/* u_char *data; IN - pointer to start of object */ +/* int *datalength; IN/OUT - # of valid bytes left in buf */ +/* int length; IN - length of object */ +/* int truth; IN - If 1, this is the true len. */ { u_char *start_data = data; if (truth) { - /* no indefinite lengths sent */ - if (length < 0x80) { - if (*datalength < 1) { - snmp_set_api_error(SNMPERR_ASN_ENCODE); - return (NULL); - } - *data++ = (u_char) length; - - } else if (length <= 0xFF) { - if (*datalength < 2) { - snmp_set_api_error(SNMPERR_ASN_ENCODE); - return (NULL); - } - *data++ = (u_char) (0x01 | ASN_LONG_LEN); - *data++ = (u_char) length; - } else { /* 0xFF < length <= 0xFFFF */ - if (*datalength < 3) { - snmp_set_api_error(SNMPERR_ASN_ENCODE); - return (NULL); - } - *data++ = (u_char) (0x02 | ASN_LONG_LEN); - *data++ = (u_char) ((length >> 8) & 0xFF); - *data++ = (u_char) (length & 0xFF); - } + /* no indefinite lengths sent */ + if (length < 0x80) { + if (*datalength < 1) { + snmp_set_api_error(SNMPERR_ASN_ENCODE); + return (NULL); + } + *data++ = (u_char) length; + + } else if (length <= 0xFF) { + if (*datalength < 2) { + snmp_set_api_error(SNMPERR_ASN_ENCODE); + return (NULL); + } + *data++ = (u_char) (0x01 | ASN_LONG_LEN); + *data++ = (u_char) length; + } else { /* 0xFF < length <= 0xFFFF */ + if (*datalength < 3) { + snmp_set_api_error(SNMPERR_ASN_ENCODE); + return (NULL); + } + *data++ = (u_char) (0x02 | ASN_LONG_LEN); + *data++ = (u_char) ((length >> 8) & 0xFF); + *data++ = (u_char) (length & 0xFF); + } } else { - /* Don't know if this is the true length. Make sure it's large - * enough for later. - */ - if (*datalength < 3) { - snmp_set_api_error(SNMPERR_ASN_ENCODE); - return (NULL); - } - *data++ = (u_char) (0x02 | ASN_LONG_LEN); - *data++ = (u_char) ((length >> 8) & 0xFF); - *data++ = (u_char) (length & 0xFF); + /* Don't know if this is the true length. Make sure it's large + * enough for later. + */ + if (*datalength < 3) { + snmp_set_api_error(SNMPERR_ASN_ENCODE); + return (NULL); + } + *data++ = (u_char) (0x02 | ASN_LONG_LEN); + *data++ = (u_char) ((length >> 8) & 0xFF); + *data++ = (u_char) (length & 0xFF); } *datalength -= (data - start_data); @@ -670,12 +670,12 @@ asn_build_length(u_char * data, int *datalength, */ u_char * asn_parse_objid(u_char * data, int *datalength, - u_char * type, oid * objid, int *objidlength) - /* u_char *data; IN - pointer to start of object */ - /* int *datalength; IN/OUT - # of valid bytes left in buf */ - /* u_char *type; OUT - ASN type of object */ - /* oid *objid; IN/OUT - pointer to start of output buffer */ - /* int *objidlength; IN/OUT - number of sub-id's in objid */ + u_char * type, oid * objid, int *objidlength) +/* u_char *data; IN - pointer to start of object */ +/* int *datalength; IN/OUT - # of valid bytes left in buf */ +/* u_char *type; OUT - ASN type of object */ +/* oid *objid; IN/OUT - pointer to start of output buffer */ +/* int *objidlength; IN/OUT - number of sub-id's in objid */ { /* * ASN.1 objid ::= 0x06 asnlength subidentifier {subidentifier}* @@ -692,35 +692,35 @@ asn_parse_objid(u_char * data, int *datalength, *type = *bufp++; bufp = asn_parse_length(bufp, &asn_length); if (bufp == NULL) - return (NULL); + return (NULL); if (asn_length + (bufp - data) > *datalength) { - snmp_set_api_error(SNMPERR_ASN_DECODE); - return (NULL); + snmp_set_api_error(SNMPERR_ASN_DECODE); + return (NULL); } *datalength -= (int) asn_length + (bufp - data); /* Handle invalid object identifier encodings of the form 06 00 robustly */ if (asn_length == 0) - objid[0] = objid[1] = 0; + objid[0] = objid[1] = 0; length = asn_length; (*objidlength)--; /* account for expansion of first byte */ while (length > 0 && (*objidlength)-- > 0) { - subidentifier = 0; + subidentifier = 0; - do { /* shift and add in low order 7 bits */ - subidentifier = (subidentifier << 7) - + (*(u_char *) bufp & ~ASN_BIT8); - length--; - } while (*(u_char *) bufp++ & ASN_BIT8); + do { /* shift and add in low order 7 bits */ + subidentifier = (subidentifier << 7) + + (*(u_char *) bufp & ~ASN_BIT8); + length--; + } while (*(u_char *) bufp++ & ASN_BIT8); - /* while last byte has high bit clear */ - if (subidentifier > (u_int) MAX_SUBID) { - snmp_set_api_error(SNMPERR_ASN_DECODE); - return (NULL); - } - *oidp++ = (oid) subidentifier; + /* while last byte has high bit clear */ + if (subidentifier > (u_int) MAX_SUBID) { + snmp_set_api_error(SNMPERR_ASN_DECODE); + return (NULL); + } + *oidp++ = (oid) subidentifier; } /* @@ -731,11 +731,11 @@ asn_parse_objid(u_char * data, int *datalength, */ subidentifier = (u_int) objid[1]; if (subidentifier == 0x2B) { - objid[0] = 1; - objid[1] = 3; + objid[0] = 1; + objid[1] = 3; } else { - objid[1] = (u_char) (subidentifier % 40); - objid[0] = (u_char) ((subidentifier - objid[1]) / 40); + objid[1] = (u_char) (subidentifier % 40); + objid[0] = (u_char) ((subidentifier - objid[1]) / 40); } *objidlength = (int) (oidp - objid); @@ -755,12 +755,12 @@ asn_parse_objid(u_char * data, int *datalength, */ u_char * asn_build_objid(u_char * data, int *datalength, - u_char type, oid * objid, int objidlength) - /* u_char *data; IN - pointer to start of object */ - /* int *datalength; IN/OUT - # of valid bytes left in buf */ - /* u_char type; IN - ASN type of object */ - /* oid *objid; IN - pointer to start of input buffer */ - /* int objidlength; IN - number of sub-id's in objid */ + u_char type, oid * objid, int objidlength) +/* u_char *data; IN - pointer to start of object */ +/* int *datalength; IN/OUT - # of valid bytes left in buf */ +/* u_char type; IN - ASN type of object */ +/* oid *objid; IN - pointer to start of input buffer */ +/* int objidlength; IN - number of sub-id's in objid */ { /* * ASN.1 objid ::= 0x06 asnlength subidentifier {subidentifier}* @@ -776,47 +776,47 @@ asn_build_objid(u_char * data, int *datalength, int bits, testbits; if (objidlength < 2) { - *bp++ = 0; - objidlength = 0; + *bp++ = 0; + objidlength = 0; } else { - *bp++ = op[1] + (op[0] * 40); - objidlength -= 2; - op += 2; + *bp++ = op[1] + (op[0] * 40); + objidlength -= 2; + op += 2; } while (objidlength-- > 0) { - subid = *op++; - if (subid < 127) { /* off by one? */ - *bp++ = subid; - } else { - mask = 0x7F; /* handle subid == 0 case */ - bits = 0; - /* testmask *MUST* !!!! be of an unsigned type */ - for (testmask = 0x7F, testbits = 0; testmask != 0; - testmask <<= 7, testbits += 7) { - if (subid & testmask) { /* if any bits set */ - mask = testmask; - bits = testbits; - } - } - /* mask can't be zero here */ - for (; mask != 0x7F; mask >>= 7, bits -= 7) { - /* fix a mask that got truncated above */ - if (mask == 0x1E00000) - mask = 0xFE00000; - *bp++ = (u_char) (((subid & mask) >> bits) | ASN_BIT8); - } - *bp++ = (u_char) (subid & mask); - } + subid = *op++; + if (subid < 127) { /* off by one? */ + *bp++ = subid; + } else { + mask = 0x7F; /* handle subid == 0 case */ + bits = 0; + /* testmask *MUST* !!!! be of an unsigned type */ + for (testmask = 0x7F, testbits = 0; testmask != 0; + testmask <<= 7, testbits += 7) { + if (subid & testmask) { /* if any bits set */ + mask = testmask; + bits = testbits; + } + } + /* mask can't be zero here */ + for (; mask != 0x7F; mask >>= 7, bits -= 7) { + /* fix a mask that got truncated above */ + if (mask == 0x1E00000) + mask = 0xFE00000; + *bp++ = (u_char) (((subid & mask) >> bits) | ASN_BIT8); + } + *bp++ = (u_char) (subid & mask); + } } asnlength = bp - buf; data = asn_build_header_with_truth(data, datalength, type, asnlength, 1); if (data == NULL) - return (NULL); + return (NULL); if (*datalength < asnlength) { - snmp_set_api_error(SNMPERR_ASN_DECODE); - return (NULL); + snmp_set_api_error(SNMPERR_ASN_DECODE); + return (NULL); } xmemcpy((char *) data, (char *) buf, asnlength); *datalength -= asnlength; @@ -836,9 +836,9 @@ asn_build_objid(u_char * data, int *datalength, */ u_char * asn_parse_null(u_char * data, int *datalength, u_char * type) - /* u_char *data; IN - pointer to start of object */ - /* int *datalength; IN/OUT - # of valid bytes left in buf */ - /* u_char *type; OUT - ASN type of object */ +/* u_char *data; IN - pointer to start of object */ +/* int *datalength; IN/OUT - # of valid bytes left in buf */ +/* u_char *type; OUT - ASN type of object */ { /* * ASN.1 null ::= 0x05 0x00 @@ -849,11 +849,11 @@ asn_parse_null(u_char * data, int *datalength, u_char * type) *type = *bufp++; bufp = asn_parse_length(bufp, &asn_length); if (bufp == NULL) - return (NULL); + return (NULL); if (asn_length != 0) { - snmp_set_api_error(SNMPERR_ASN_DECODE); - return (NULL); + snmp_set_api_error(SNMPERR_ASN_DECODE); + return (NULL); } *datalength -= (bufp - data); return (bufp + asn_length); @@ -872,9 +872,9 @@ asn_parse_null(u_char * data, int *datalength, u_char * type) */ u_char * asn_build_null(u_char * data, int *datalength, u_char type) - /* u_char *data; IN - pointer to start of object */ - /* int *datalength; IN/OUT - # of valid bytes left in buf */ - /* u_char type; IN - ASN type of object */ +/* u_char *data; IN - pointer to start of object */ +/* int *datalength; IN/OUT - # of valid bytes left in buf */ +/* u_char type; IN - ASN type of object */ { /* * ASN.1 null ::= 0x05 0x00 @@ -898,12 +898,12 @@ asn_build_null(u_char * data, int *datalength, u_char type) */ u_char * asn_parse_bitstring(u_char * data, int *datalength, - u_char * type, u_char * string, int *strlength) - /* u_char *data; IN - pointer to start of object */ - /* int *datalength; IN/OUT - # of valid bytes left in buf */ - /* u_char *type; OUT - asn type of object */ - /* u_char *string; IN/OUT - pointer to start of output buf */ - /* int *strlength; IN/OUT - size of output buffer */ + u_char * type, u_char * string, int *strlength) +/* u_char *data; IN - pointer to start of object */ +/* int *datalength; IN/OUT - # of valid bytes left in buf */ +/* u_char *type; OUT - asn type of object */ +/* u_char *string; IN/OUT - pointer to start of output buf */ +/* int *strlength; IN/OUT - size of output buffer */ { /* * bitstring ::= 0x03 asnlength unused {byte}* @@ -914,23 +914,23 @@ asn_parse_bitstring(u_char * data, int *datalength, *type = *bufp++; bufp = asn_parse_length(bufp, &asn_length); if (bufp == NULL) - return (NULL); + return (NULL); if (asn_length + (bufp - data) > *datalength) { - snmp_set_api_error(SNMPERR_ASN_DECODE); - return (NULL); + snmp_set_api_error(SNMPERR_ASN_DECODE); + return (NULL); } if (asn_length > *strlength) { - snmp_set_api_error(SNMPERR_ASN_DECODE); - return (NULL); + snmp_set_api_error(SNMPERR_ASN_DECODE); + return (NULL); } if (asn_length < 1) { - snmp_set_api_error(SNMPERR_ASN_DECODE); - return (NULL); + snmp_set_api_error(SNMPERR_ASN_DECODE); + return (NULL); } if ((int) (*(char *) bufp) < 0 || (int) (*bufp) > 7) { - snmp_set_api_error(SNMPERR_ASN_DECODE); - return (NULL); + snmp_set_api_error(SNMPERR_ASN_DECODE); + return (NULL); } xmemcpy((char *) string, (char *) bufp, (int) asn_length); *strlength = (int) asn_length; @@ -951,27 +951,27 @@ asn_parse_bitstring(u_char * data, int *datalength, */ u_char * asn_build_bitstring(u_char * data, int *datalength, - u_char type, u_char * string, int strlength) - /* u_char *data; IN - pointer to start of object */ - /* int *datalength; IN/OUT - # of valid bytes left in buf */ - /* u_char type; IN - ASN type of string */ - /* u_char *string; IN - pointer to start of input buffer */ - /* int strlength; IN - size of input buffer */ + u_char type, u_char * string, int strlength) +/* u_char *data; IN - pointer to start of object */ +/* int *datalength; IN/OUT - # of valid bytes left in buf */ +/* u_char type; IN - ASN type of string */ +/* u_char *string; IN - pointer to start of input buffer */ +/* int strlength; IN - size of input buffer */ { /* * ASN.1 bit string ::= 0x03 asnlength unused {byte}* */ if ((strlength < 1) || ((*(char *) string) < 0) || ((*string) > 7)) { - snmp_set_api_error(SNMPERR_ASN_ENCODE); - return (NULL); + snmp_set_api_error(SNMPERR_ASN_ENCODE); + return (NULL); } data = asn_build_header_with_truth(data, datalength, type, strlength, 1); if (data == NULL) - return (NULL); + return (NULL); if (*datalength < strlength) { - snmp_set_api_error(SNMPERR_ASN_ENCODE); - return (NULL); + snmp_set_api_error(SNMPERR_ASN_ENCODE); + return (NULL); } xmemcpy((char *) data, (char *) string, strlength); *datalength -= strlength; @@ -981,7 +981,7 @@ asn_build_bitstring(u_char * data, int *datalength, #endif /* - * To do: Write an asn_parse_exception function to go with the new + * To do: Write an asn_parse_exception function to go with the new * asn_build_exception function below so that the exceptional values can * be handled in input packets aswell as output ones. */ @@ -996,7 +996,7 @@ asn_build_bitstring(u_char * data, int *datalength, * of this object (i.e. the start of the next object). * Returns NULL on any error. * - * ASN.1 variable exception ::= 0x8i 0x00, where 'i' is one of these + * ASN.1 variable exception ::= 0x8i 0x00, where 'i' is one of these * exception identifiers: * 0 -- noSuchObject * 1 -- noSuchInstance @@ -1004,9 +1004,9 @@ asn_build_bitstring(u_char * data, int *datalength, */ u_char * asn_build_exception(u_char * data, int *datalength, u_char type) - /* u_char *data; IN - pointer to start of object */ - /* int *datalength; IN/OUT - # of valid bytes left in buf */ - /* u_char type; IN - ASN type of object */ +/* u_char *data; IN - pointer to start of object */ +/* int *datalength; IN/OUT - # of valid bytes left in buf */ +/* u_char type; IN - ASN type of object */ { return (asn_build_header_with_truth(data, datalength, type, 0, 1)); } diff --git a/snmplib/coexistance.c b/snmplib/coexistance.c index e196f3e801..89a8702012 100644 --- a/snmplib/coexistance.c +++ b/snmplib/coexistance.c @@ -4,9 +4,9 @@ /********************************************************************** * * Copyright 1997 by Carnegie Mellon University - * + * * All Rights Reserved - * + * * Permission to use, copy, modify, and distribute this software and its * documentation for any purpose and without fee is hereby granted, * provided that the above copyright notice appear in all copies and that @@ -14,7 +14,7 @@ * supporting documentation, and that the name of CMU not be * used in advertising or publicity pertaining to distribution of the * software without specific, written prior permission. - * + * * CMU DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING * ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL * CMU BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR @@ -22,9 +22,9 @@ * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS * SOFTWARE. - * + * * Author: Ryan Troll - * + * **********************************************************************/ #include "config.h" @@ -96,7 +96,7 @@ * V2 PDUs from an ** MANAGER ** to V1 PDUs for an ** AGENT ** * * We will never convert V1 information from a manager into V2 PDUs. V1 - * requests are always honored by V2 agents, and the responses will be + * requests are always honored by V2 agents, and the responses will be * valid V1 responses. (I think. XXXXX) * */ @@ -112,19 +112,19 @@ snmp_coexist_V2toV1(struct snmp_pdu *PDU) #ifdef SNMP_PDU_SET case SNMP_PDU_SET: #endif - return (1); - break; + return (1); + break; case SNMP_PDU_GETBULK: - PDU->non_repeaters = 0; - PDU->max_repetitions = 0; - PDU->command = SNMP_PDU_GETNEXT; - return (1); - break; + PDU->non_repeaters = 0; + PDU->max_repetitions = 0; + PDU->command = SNMP_PDU_GETNEXT; + return (1); + break; default: - snmplib_debug(2, "Unable to translate PDU %d to SNMPv1!\n", PDU->command); - snmp_set_api_error(SNMPERR_PDU_TRANSLATION); - return (0); + snmplib_debug(2, "Unable to translate PDU %d to SNMPv1!\n", PDU->command); + snmp_set_api_error(SNMPERR_PDU_TRANSLATION); + return (0); } } diff --git a/snmplib/mib.c b/snmplib/mib.c index ff47510dee..160e4a22bb 100644 --- a/snmplib/mib.c +++ b/snmplib/mib.c @@ -4,13 +4,13 @@ All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the name of CMU not be used in advertising or publicity pertaining to distribution of the -software without specific, written prior permission. +software without specific, written prior permission. CMU DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL @@ -84,8 +84,7 @@ SOFTWARE. static struct snmp_mib_tree *get_symbol(oid *objid, int objidlen, struct snmp_mib_tree *subtree, char *buf); -oid RFC1066_MIB[] = -{1, 3, 6, 1, 2, 1}; +oid RFC1066_MIB[] = {1, 3, 6, 1, 2, 1}; unsigned char RFC1066_MIB_text[] = ".iso.org.dod.internet.mgmt.mib"; struct snmp_mib_tree *Mib; @@ -93,29 +92,28 @@ void init_mib(char *file) { if (Mib != NULL) - return; + return; if (file != NULL) - Mib = read_mib(file); + Mib = read_mib(file); } static struct snmp_mib_tree * -find_rfc1066_mib(struct snmp_mib_tree *root) -{ + find_rfc1066_mib(struct snmp_mib_tree *root) { oid *op = RFC1066_MIB; struct snmp_mib_tree *tp; int len; for (len = sizeof(RFC1066_MIB) / sizeof(oid); len; len--, op++) { - for (tp = root; tp; tp = tp->next_peer) { - if (tp->subid == *op) { - root = tp->child_list; - break; - } - } - if (tp == NULL) - return NULL; + for (tp = root; tp; tp = tp->next_peer) { + if (tp->subid == *op) { + root = tp->child_list; + break; + } + } + if (tp == NULL) + return NULL; } return root; } @@ -126,24 +124,24 @@ lc_cmp(const char *s1, const char *s2) char c1, c2; while (*s1 && *s2) { - if (xisupper(*s1)) - c1 = xtolower(*s1); - else - c1 = *s1; - if (xisupper(*s2)) - c2 = xtolower(*s2); - else - c2 = *s2; - if (c1 != c2) - return ((c1 - c2) > 0 ? 1 : -1); - s1++; - s2++; + if (xisupper(*s1)) + c1 = xtolower(*s1); + else + c1 = *s1; + if (xisupper(*s2)) + c2 = xtolower(*s2); + else + c2 = *s2; + if (c1 != c2) + return ((c1 - c2) > 0 ? 1 : -1); + s1++; + s2++; } if (*s1) - return -1; + return -1; if (*s2) - return 1; + return 1; return 0; } @@ -159,100 +157,100 @@ parse_subtree(struct snmp_mib_tree *subtree, char *input, oid *output, int *out_ * in a row, i.e. "..". */ if ((*input == '\0') || - (*input == '.')) - return (0); + (*input == '.')) + return (0); if (xisdigit(*input)) { - /* - * Read the number, then try to find it in the subtree. - */ - while (xisdigit(*input)) { - subid *= 10; - subid += *input++ - '0'; - } - for (tp = subtree; tp; tp = tp->next_peer) { - if (tp->subid == subid) - goto found; - } - tp = NULL; + /* + * Read the number, then try to find it in the subtree. + */ + while (xisdigit(*input)) { + subid *= 10; + subid += *input++ - '0'; + } + for (tp = subtree; tp; tp = tp->next_peer) { + if (tp->subid == subid) + goto found; + } + tp = NULL; } else { - /* - * Read the name into a buffer. - */ - while ((*input != '\0') && - (*input != '.')) { - *to++ = *input++; - } - *to = '\0'; - - /* - * Find the name in the subtree; - */ - for (tp = subtree; tp; tp = tp->next_peer) { - if (lc_cmp(tp->label, buf) == 0) { - subid = tp->subid; - goto found; - } - } - - /* - * If we didn't find the entry, punt... - */ - if (tp == NULL) { - snmplib_debug(0, "sub-identifier not found: %s\n", buf); - return (0); - } + /* + * Read the name into a buffer. + */ + while ((*input != '\0') && + (*input != '.')) { + *to++ = *input++; + } + *to = '\0'; + + /* + * Find the name in the subtree; + */ + for (tp = subtree; tp; tp = tp->next_peer) { + if (lc_cmp(tp->label, buf) == 0) { + subid = tp->subid; + goto found; + } + } + + /* + * If we didn't find the entry, punt... + */ + if (tp == NULL) { + snmplib_debug(0, "sub-identifier not found: %s\n", buf); + return (0); + } } - found: +found: if (subid > (u_int) MAX_SUBID) { - snmplib_debug(0, "sub-identifier too large: %s\n", buf); - return (0); + snmplib_debug(0, "sub-identifier too large: %s\n", buf); + return (0); } if ((*out_len)-- <= 0) { - snmplib_debug(0, "object identifier too long\n"); - return (0); + snmplib_debug(0, "object identifier too long\n"); + return (0); } *output++ = subid; if (*input != '.') - return (1); + return (1); if ((*out_len = - parse_subtree(tp ? tp->child_list : NULL, ++input, output, out_len)) == 0) - return (0); + parse_subtree(tp ? tp->child_list : NULL, ++input, output, out_len)) == 0) + return (0); return (++*out_len); } int read_objid(input, output, out_len) - char *input; - oid *output; - int *out_len; /* number of subid's in "output" */ +char *input; +oid *output; +int *out_len; /* number of subid's in "output" */ { struct snmp_mib_tree *root = Mib; oid *op = output; int i; if (*input == '.') - input++; + input++; else { - root = find_rfc1066_mib(root); - for (i = 0; i < sizeof(RFC1066_MIB) / sizeof(oid); i++) { - if ((*out_len)-- > 0) - *output++ = RFC1066_MIB[i]; - else { - snmplib_debug(0, "object identifier too long\n"); - return (0); - } - } + root = find_rfc1066_mib(root); + for (i = 0; i < sizeof(RFC1066_MIB) / sizeof(oid); i++) { + if ((*out_len)-- > 0) + *output++ = RFC1066_MIB[i]; + else { + snmplib_debug(0, "object identifier too long\n"); + return (0); + } + } } if (root == NULL) { - snmplib_debug(0, "Mib not initialized.\n"); - return 0; + snmplib_debug(0, "Mib not initialized.\n"); + return 0; } if ((*out_len = parse_subtree(root, input, output, out_len)) == 0) - return (0); + return (0); *out_len += output - op; return (1); @@ -260,8 +258,8 @@ read_objid(input, output, out_len) void print_objid(objid, objidlen) - oid *objid; - int objidlen; /* number of subidentifiers */ +oid *objid; +int objidlen; /* number of subidentifiers */ { char buf[256]; struct snmp_mib_tree *subtree = Mib; @@ -274,9 +272,9 @@ print_objid(objid, objidlen) void sprint_objid(buf, objid, objidlen) - char *buf; - oid *objid; - int objidlen; /* number of subidentifiers */ +char *buf; +oid *objid; +int objidlen; /* number of subidentifiers */ { struct snmp_mib_tree *subtree = Mib; @@ -285,42 +283,42 @@ sprint_objid(buf, objid, objidlen) } static struct snmp_mib_tree * -get_symbol(objid, objidlen, subtree, buf) - oid *objid; - int objidlen; - struct snmp_mib_tree *subtree; - char *buf; + get_symbol(objid, objidlen, subtree, buf) + oid *objid; +int objidlen; +struct snmp_mib_tree *subtree; +char *buf; { struct snmp_mib_tree *return_tree = NULL; for (; subtree; subtree = subtree->next_peer) { - if (*objid == subtree->subid) { - strcpy(buf, subtree->label); - goto found; - } + if (*objid == subtree->subid) { + strcpy(buf, subtree->label); + goto found; + } } /* subtree not found */ while (objidlen--) { /* output rest of name, uninterpreted */ - sprintf(buf, "%u.", *objid++); - while (*buf) - buf++; + sprintf(buf, "%u.", *objid++); + while (*buf) + buf++; } *(buf - 1) = '\0'; /* remove trailing dot */ return NULL; - found: +found: if (objidlen > 1) { - while (*buf) - buf++; - *buf++ = '.'; - *buf = '\0'; - return_tree = get_symbol(objid + 1, objidlen - 1, subtree->child_list, buf); + while (*buf) + buf++; + *buf++ = '.'; + *buf = '\0'; + return_tree = get_symbol(objid + 1, objidlen - 1, subtree->child_list, buf); } if (return_tree != NULL) - return return_tree; + return return_tree; else - return subtree; + return subtree; } void @@ -329,5 +327,5 @@ print_oid_nums(oid * O, int len) int x; for (x = 0; x < len; x++) - printf(".%u", O[x]); + printf(".%u", O[x]); } diff --git a/snmplib/parse.c b/snmplib/parse.c index 98dd796dc2..69335fa1b2 100644 --- a/snmplib/parse.c +++ b/snmplib/parse.c @@ -3,13 +3,13 @@ All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in +both that copyright notice and this permission notice appear in supporting documentation, and that the name of CMU not be used in advertising or publicity pertaining to distribution of the -software without specific, written prior permission. +software without specific, written prior permission. CMU DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL @@ -162,8 +162,7 @@ struct tok { }; -struct tok tokens[] = -{ +struct tok tokens[] = { {"obsolete", sizeof("obsolete") - 1, OBSOLETE}, {"Opaque", sizeof("Opaque") - 1, SNMP_OPAQUE}, {"recommended", sizeof("recommended") - 1, RECOMMENDED}, @@ -175,10 +174,10 @@ struct tok tokens[] = {"read-write", sizeof("read-write") - 1, READWRITE}, {"TimeTicks", sizeof("TimeTicks") - 1, TIMETICKS}, {"OBJECTIDENTIFIER", sizeof("OBJECTIDENTIFIER") - 1, OBJID}, - /* - * This CONTINUE appends the next word onto OBJECT, - * hopefully matching OBJECTIDENTIFIER above. - */ + /* + * This CONTINUE appends the next word onto OBJECT, + * hopefully matching OBJECTIDENTIFIER above. + */ {"OBJECT", sizeof("OBJECT") - 1, CONTINUE}, {"NetworkAddress", sizeof("NetworkAddress") - 1, NETADDR}, {"Gauge", sizeof("Gauge") - 1, GAUGE}, @@ -206,7 +205,7 @@ struct tok tokens[] = {"INDEX", sizeof("INDEX") - 1, INDEX}, {"\"", sizeof("\"") - 1, QUOTE}, {"END", sizeof("END") - 1, ENDOFFILE}, -/* Hacks for easier MIBFILE coercing */ + /* Hacks for easier MIBFILE coercing */ {"read-create", sizeof("read-create") - 1, READWRITE}, {NULL} }; @@ -226,13 +225,13 @@ hash_init(void) memset((char *) buckets, '\0', sizeof(buckets)); for (tp = tokens; tp->name; tp++) { - for (h = 0, cp = tp->name; *cp; cp++) - h += *cp; - tp->hash = h; - b = BUCKET(h); - if (buckets[b]) - tp->next = buckets[b]; /* BUG ??? */ - buckets[b] = tp; + for (h = 0, cp = tp->name; *cp; cp++) + h += *cp; + tp->hash = h; + b = BUCKET(h); + if (buckets[b]) + tp->next = buckets[b]; /* BUG ??? */ + buckets[b] = tp; } } @@ -249,13 +248,13 @@ init_node_hash(struct node *nodes) memset((char *) nbuckets, '\0', sizeof(nbuckets)); for (np = nodes; np;) { - nextp = np->next; - hash = 0; - for (cp = np->parent; *cp; cp++) - hash += *cp; - np->next = nbuckets[NBUCKET(hash)]; - nbuckets[NBUCKET(hash)] = np; - np = nextp; + nextp = np->next; + hash = 0; + for (cp = np->parent; *cp; cp++) + hash += *cp; + np->next = nbuckets[NBUCKET(hash)]; + nbuckets[NBUCKET(hash)] = np; + np = nextp; } } @@ -265,32 +264,32 @@ print_error(const char *string, const char *token, int type) { assert(string != NULL); if (type == ENDOFFILE) - snmplib_debug(0, "%s(EOF): On or around line %d\n", string, Line); + snmplib_debug(0, "%s(EOF): On or around line %d\n", string, Line); else if (token) - snmplib_debug(0, "%s(%s): On or around line %d\n", string, token, Line); + snmplib_debug(0, "%s(%s): On or around line %d\n", string, token, Line); else - snmplib_debug(0, "%s: On or around line %d\n", string, Line); + snmplib_debug(0, "%s: On or around line %d\n", string, Line); } #ifdef TEST print_subtree(tree, count) - struct snmp_mib_tree *tree; - int count; +struct snmp_mib_tree *tree; +int count; { struct snmp_mib_tree *tp; int i; for (i = 0; i < count; i++) - printf(" "); + printf(" "); printf("Children of %s:\n", tree->label); count++; for (tp = tree->child_list; tp; tp = tp->next_peer) { - for (i = 0; i < count; i++) - printf(" "); - printf("%s\n", tp->label); + for (i = 0; i < count; i++) + printf(" "); + printf("%s\n", tp->label); } for (tp = tree->child_list; tp; tp = tp->next_peer) { - print_subtree(tp, count); + print_subtree(tp, count); } } #endif /* TEST */ @@ -303,41 +302,41 @@ build_translation_table(void) int count; for (count = 0; count < 40; count++) { - switch (count) { - case OBJID: - translation_table[count] = TYPE_OBJID; - break; - case OCTETSTR: - translation_table[count] = TYPE_OCTETSTR; - break; - case INTEGER: - translation_table[count] = TYPE_INTEGER; - break; - case NETADDR: - translation_table[count] = TYPE_IPADDR; - break; - case IPADDR: - translation_table[count] = TYPE_IPADDR; - break; - case COUNTER: - translation_table[count] = TYPE_COUNTER; - break; - case GAUGE: - translation_table[count] = TYPE_GAUGE; - break; - case TIMETICKS: - translation_table[count] = TYPE_TIMETICKS; - break; - case SNMP_OPAQUE: - translation_table[count] = TYPE_OPAQUE; - break; - case NUL: - translation_table[count] = TYPE_NULL; - break; - default: - translation_table[count] = TYPE_OTHER; - break; - } + switch (count) { + case OBJID: + translation_table[count] = TYPE_OBJID; + break; + case OCTETSTR: + translation_table[count] = TYPE_OCTETSTR; + break; + case INTEGER: + translation_table[count] = TYPE_INTEGER; + break; + case NETADDR: + translation_table[count] = TYPE_IPADDR; + break; + case IPADDR: + translation_table[count] = TYPE_IPADDR; + break; + case COUNTER: + translation_table[count] = TYPE_COUNTER; + break; + case GAUGE: + translation_table[count] = TYPE_GAUGE; + break; + case TIMETICKS: + translation_table[count] = TYPE_TIMETICKS; + break; + case SNMP_OPAQUE: + translation_table[count] = TYPE_OPAQUE; + break; + case NUL: + translation_table[count] = TYPE_NULL; + break; + default: + translation_table[count] = TYPE_OTHER; + break; + } } } @@ -358,79 +357,78 @@ do_subtree(struct snmp_mib_tree *root, struct node **nodes) tp = root; hash = 0; for (cp = tp->label; *cp; cp++) - hash += *cp; + hash += *cp; headp = &nbuckets[NBUCKET(hash)]; /* * Search each of the nodes for one whose parent is root, and * move each into a separate list. */ for (np = *headp; np; np = np->next) { - if ((*tp->label != *np->parent) || strcmp(tp->label, np->parent)) { - if ((*tp->label == *np->label) && !strcmp(tp->label, np->label)) { - /* if there is another node with the same label, assume that - * any children after this point in the list belong to the other node. - * This adds some scoping to the table and allows vendors to - * reuse names such as "ip". - */ - break; - } - oldnp = np; - } else { - if (child_list == NULL) { - child_list = childp = np; /* first entry in child list */ - } else { - childp->next = np; - childp = np; - } - /* take this node out of the node list */ - if (oldnp == NULL) { - *headp = np->next; /* fix root of node list */ - } else { - oldnp->next = np->next; /* link around this node */ - } - } + if ((*tp->label != *np->parent) || strcmp(tp->label, np->parent)) { + if ((*tp->label == *np->label) && !strcmp(tp->label, np->label)) { + /* if there is another node with the same label, assume that + * any children after this point in the list belong to the other node. + * This adds some scoping to the table and allows vendors to + * reuse names such as "ip". + */ + break; + } + oldnp = np; + } else { + if (child_list == NULL) { + child_list = childp = np; /* first entry in child list */ + } else { + childp->next = np; + childp = np; + } + /* take this node out of the node list */ + if (oldnp == NULL) { + *headp = np->next; /* fix root of node list */ + } else { + oldnp->next = np->next; /* link around this node */ + } + } } if (childp) - childp->next = 0; /* re-terminate list */ + childp->next = 0; /* re-terminate list */ /* * Take each element in the child list and place it into the tree. */ for (np = child_list; np; np = np->next) { - tp = (struct snmp_mib_tree *) xmalloc(sizeof(struct snmp_mib_tree)); - tp->parent = root; - tp->next_peer = NULL; - tp->child_list = NULL; - strcpy(tp->label, np->label); - tp->subid = np->subid; - tp->type = translation_table[np->type]; - tp->enums = np->enums; - np->enums = NULL; /* so we don't free them later */ - if (root->child_list == NULL) { - root->child_list = tp; - } else { - peer->next_peer = tp; - } - peer = tp; -/* if (tp->type == TYPE_OTHER) */ - do_subtree(tp, nodes); /* recurse on this child if it isn't an end node */ + tp = (struct snmp_mib_tree *) xmalloc(sizeof(struct snmp_mib_tree)); + tp->parent = root; + tp->next_peer = NULL; + tp->child_list = NULL; + strcpy(tp->label, np->label); + tp->subid = np->subid; + tp->type = translation_table[np->type]; + tp->enums = np->enums; + np->enums = NULL; /* so we don't free them later */ + if (root->child_list == NULL) { + root->child_list = tp; + } else { + peer->next_peer = tp; + } + peer = tp; + /* if (tp->type == TYPE_OTHER) */ + do_subtree(tp, nodes); /* recurse on this child if it isn't an end node */ } /* free all nodes that were copied into tree */ oldnp = NULL; for (np = child_list; np; np = np->next) { - if (oldnp) - xfree(oldnp); - oldnp = np; + if (oldnp) + xfree(oldnp); + oldnp = np; } if (oldnp) - xfree(oldnp); + xfree(oldnp); } #ifndef TEST static #endif struct snmp_mib_tree * -build_tree(struct node *nodes) -{ + build_tree(struct node *nodes) { struct node *np; struct snmp_mib_tree *tp; int bucket, nodes_left = 0; @@ -454,20 +452,20 @@ build_tree(struct node *nodes) #endif /* TEST */ /* If any nodes are left, the tree is probably inconsistent */ for (bucket = 0; bucket < NHASHSIZE; bucket++) { - if (nbuckets[bucket]) { - nodes_left = 1; - break; - } + if (nbuckets[bucket]) { + nodes_left = 1; + break; + } } if (nodes_left) { - snmplib_debug(0, "The mib description doesn't seem to be consistent.\n"); - snmplib_debug(0, "Some nodes couldn't be linked under the \"iso\" tree.\n"); - snmplib_debug(0, "these nodes are left:\n"); - for (bucket = 0; bucket < NHASHSIZE; bucket++) { - for (np = nbuckets[bucket]; np; np = np->next) - snmplib_debug(5, "%s ::= { %s %d } (%d)\n", np->label, np->parent, np->subid, - np->type); - } + snmplib_debug(0, "The mib description doesn't seem to be consistent.\n"); + snmplib_debug(0, "Some nodes couldn't be linked under the \"iso\" tree.\n"); + snmplib_debug(0, "these nodes are left:\n"); + for (bucket = 0; bucket < NHASHSIZE; bucket++) { + for (np = nbuckets[bucket]; np; np = np->next) + snmplib_debug(5, "%s ::= { %s %d } (%d)\n", np->label, np->parent, np->subid, + np->type); + } } return tp; } @@ -491,12 +489,12 @@ get_token(register FILE *fp, register char *token) ch = (unsigned char)last; /* skip all white space */ while (xisspace(ch) && ch != -1) { - ch = getc(fp); - if (ch == '\n') - Line++; + ch = getc(fp); + if (ch == '\n') + Line++; } if (ch == -1) - return ENDOFFILE; + return ENDOFFILE; /* * Accumulate characters until end of token is found. Then attempt to match this @@ -504,51 +502,51 @@ get_token(register FILE *fp, register char *token) * a label. */ do { - if (ch == '\n') - Line++; - if (xisspace(ch) || ch == '(' || ch == ')' || - ch == '{' || ch == '}' || ch == ',' || - ch == '"') { - if (!xisspace(ch) && *token == 0) { - hash += ch; - *cp++ = ch; - last = ' '; - } else { - last = ch; - } - *cp = '\0'; - - for (tp = buckets[BUCKET(hash)]; tp; tp = tp->next) { - if ((tp->hash == hash) && (strcmp(tp->name, token) == 0)) - break; - } - if (tp) { - if (tp->token == CONTINUE) - continue; - return (tp->token); - } - if (token[0] == '-' && token[1] == '-') { - /* strip comment */ - while ((ch = getc(fp)) != -1) - if (ch == '\n') { - Line++; - break; - } - if (ch == -1) - return ENDOFFILE; - last = ch; - return get_token(fp, token); - } - for (cp = token; *cp; cp++) - if (!xisdigit(*cp)) - return LABEL; - return NUMBER; - } else { - hash += ch; - *cp++ = ch; - if (ch == '\n') - Line++; - } + if (ch == '\n') + Line++; + if (xisspace(ch) || ch == '(' || ch == ')' || + ch == '{' || ch == '}' || ch == ',' || + ch == '"') { + if (!xisspace(ch) && *token == 0) { + hash += ch; + *cp++ = ch; + last = ' '; + } else { + last = ch; + } + *cp = '\0'; + + for (tp = buckets[BUCKET(hash)]; tp; tp = tp->next) { + if ((tp->hash == hash) && (strcmp(tp->name, token) == 0)) + break; + } + if (tp) { + if (tp->token == CONTINUE) + continue; + return (tp->token); + } + if (token[0] == '-' && token[1] == '-') { + /* strip comment */ + while ((ch = getc(fp)) != -1) + if (ch == '\n') { + Line++; + break; + } + if (ch == -1) + return ENDOFFILE; + last = ch; + return get_token(fp, token); + } + for (cp = token; *cp; cp++) + if (!xisdigit(*cp)) + return LABEL; + return NUMBER; + } else { + hash += ch; + *cp++ = ch; + if (ch == '\n') + Line++; + } } while ((ch = getc(fp)) != -1); return ENDOFFILE; @@ -571,45 +569,45 @@ getoid(register FILE *fp, register struct subid *SubOid, int length) register char *cp; if ((type = get_token(fp, token)) != LEFTBRACKET) { - print_error("Expected \"{\"", token, type); - return 0; + print_error("Expected \"{\"", token, type); + return 0; } type = get_token(fp, token); for (count = 0; count < length; count++, SubOid++) { - SubOid->label = 0; - SubOid->subid = -1; - if (type == RIGHTBRACKET) { - return count; - } else if (type != LABEL && type != NUMBER) { - print_error("Not valid for object identifier", token, type); - return 0; - } - if (type == LABEL) { - /* this entry has a label */ - cp = (char *) xmalloc((unsigned) strlen(token) + 1); - strcpy(cp, token); - SubOid->label = cp; - type = get_token(fp, token); - if (type == LEFTPAREN) { - type = get_token(fp, token); - if (type == NUMBER) { - SubOid->subid = atoi(token); - if ((type = get_token(fp, token)) != RIGHTPAREN) { - print_error("Unexpected a closing parenthesis", token, type); - return 0; - } - } else { - print_error("Expected a number", token, type); - return 0; - } - } else { - continue; - } - } else { - /* this entry has just an integer sub-identifier */ - SubOid->subid = atoi(token); - } - type = get_token(fp, token); + SubOid->label = 0; + SubOid->subid = -1; + if (type == RIGHTBRACKET) { + return count; + } else if (type != LABEL && type != NUMBER) { + print_error("Not valid for object identifier", token, type); + return 0; + } + if (type == LABEL) { + /* this entry has a label */ + cp = (char *) xmalloc((unsigned) strlen(token) + 1); + strcpy(cp, token); + SubOid->label = cp; + type = get_token(fp, token); + if (type == LEFTPAREN) { + type = get_token(fp, token); + if (type == NUMBER) { + SubOid->subid = atoi(token); + if ((type = get_token(fp, token)) != RIGHTPAREN) { + print_error("Unexpected a closing parenthesis", token, type); + return 0; + } + } else { + print_error("Expected a number", token, type); + return 0; + } + } else { + continue; + } + } else { + /* this entry has just an integer sub-identifier */ + SubOid->subid = atoi(token); + } + type = get_token(fp, token); } return count; @@ -623,9 +621,9 @@ free_node(struct node *np) ep = np->enums; while (ep) { - tep = ep; - ep = ep->next; - xfree((char *) tep); + tep = ep; + ep = ep->next; + xfree((char *) tep); } xfree((char *) np); } @@ -637,8 +635,7 @@ free_node(struct node *np) * Returns 0 on error. */ static struct node * -parse_objectid(FILE *fp, char *name) -{ + parse_objectid(FILE *fp, char *name) { int type; char token[64]; register int count; @@ -649,73 +646,73 @@ parse_objectid(FILE *fp, char *name) type = get_token(fp, token); if (type != EQUALS) { - print_error("Bad format", token, type); - return 0; + print_error("Bad format", token, type); + return 0; } if ((length = getoid(fp, SubOid, 32)) != 0) { - np = root = (struct node *) xmalloc(sizeof(struct node)); - memset((char *) np, '\0', sizeof(struct node)); - /* - * For each parent-child subid pair in the subid array, - * create a node and link it into the node list. - */ - for (count = 0, op = SubOid, nop = SubOid + 1; count < (length - 2); count++, - op++, nop++) { - /* every node must have parent's name and child's name or number */ - if (op->label && (nop->label || (nop->subid != -1))) { - strcpy(np->parent, op->label); - if (nop->label) - strcpy(np->label, nop->label); - if (nop->subid != -1) - np->subid = nop->subid; - np->type = 0; - np->enums = 0; - /* set up next entry */ - np->next = (struct node *) xmalloc(sizeof(*np->next)); - memset((char *) np->next, '\0', sizeof(struct node)); - oldnp = np; - np = np->next; - } - } - np->next = (struct node *) NULL; - /* - * The above loop took care of all but the last pair. This pair is taken - * care of here. The name for this node is taken from the label for this - * entry. - * np still points to an unused entry. - */ - if (count == (length - 2)) { - if (op->label) { - strcpy(np->parent, op->label); - strcpy(np->label, name); - if (nop->subid != -1) - np->subid = nop->subid; - else - print_error("Warning: This entry is pretty silly", np->label, type); - } else { - free_node(np); - if (oldnp) - oldnp->next = NULL; - else - return NULL; - } - } else { - print_error("Missing end of oid", (char *) NULL, type); - free_node(np); /* the last node allocated wasn't used */ - if (oldnp) - oldnp->next = NULL; - return NULL; - } - /* free the oid array */ - for (count = 0, op = SubOid; count < length; count++, op++) { - if (op->label) - xfree(op->label); - op->label = 0; - } - return root; + np = root = (struct node *) xmalloc(sizeof(struct node)); + memset((char *) np, '\0', sizeof(struct node)); + /* + * For each parent-child subid pair in the subid array, + * create a node and link it into the node list. + */ + for (count = 0, op = SubOid, nop = SubOid + 1; count < (length - 2); count++, + op++, nop++) { + /* every node must have parent's name and child's name or number */ + if (op->label && (nop->label || (nop->subid != -1))) { + strcpy(np->parent, op->label); + if (nop->label) + strcpy(np->label, nop->label); + if (nop->subid != -1) + np->subid = nop->subid; + np->type = 0; + np->enums = 0; + /* set up next entry */ + np->next = (struct node *) xmalloc(sizeof(*np->next)); + memset((char *) np->next, '\0', sizeof(struct node)); + oldnp = np; + np = np->next; + } + } + np->next = (struct node *) NULL; + /* + * The above loop took care of all but the last pair. This pair is taken + * care of here. The name for this node is taken from the label for this + * entry. + * np still points to an unused entry. + */ + if (count == (length - 2)) { + if (op->label) { + strcpy(np->parent, op->label); + strcpy(np->label, name); + if (nop->subid != -1) + np->subid = nop->subid; + else + print_error("Warning: This entry is pretty silly", np->label, type); + } else { + free_node(np); + if (oldnp) + oldnp->next = NULL; + else + return NULL; + } + } else { + print_error("Missing end of oid", (char *) NULL, type); + free_node(np); /* the last node allocated wasn't used */ + if (oldnp) + oldnp->next = NULL; + return NULL; + } + /* free the oid array */ + for (count = 0, op = SubOid; count < length; count++, op++) { + if (op->label) + xfree(op->label); + op->label = 0; + } + return root; } else { - print_error("Bad object identifier", (char *) NULL, type); - return 0; + print_error("Bad object identifier", (char *) NULL, type); + return 0; } } @@ -731,12 +728,12 @@ parse_asntype(FILE *fp) type = get_token(fp, token); if (type != SEQUENCE) { - print_error("Not a sequence", token, type); /* should we handle this */ - return ENDOFFILE; + print_error("Not a sequence", token, type); /* should we handle this */ + return ENDOFFILE; } while ((type = get_token(fp, token)) != ENDOFFILE) { - if (type == RIGHTBRACKET) - return type; + if (type == RIGHTBRACKET) + return type; } print_error("Expected \"}\"", token, type); return ENDOFFILE; @@ -747,8 +744,7 @@ parse_asntype(FILE *fp) * Returns 0 on error. */ static struct node * -parse_objecttype(register FILE *fp, char *name) -{ + parse_objecttype(register FILE *fp, char *name) { register int type; char token[64]; int count, length; @@ -761,8 +757,8 @@ parse_objecttype(register FILE *fp, char *name) type = get_token(fp, token); if (type != SYNTAX) { - print_error("Bad format for OBJECT TYPE", token, type); - return 0; + print_error("Bad format for OBJECT TYPE", token, type); + return 0; } np = (struct node *) xmalloc(sizeof(struct node)); np->next = 0; @@ -772,71 +768,71 @@ parse_objecttype(register FILE *fp, char *name) np->type = type; switch (type) { case SEQUENCE: - strcpy(syntax, token); - if (nexttype == OF) { - strcat(syntax, " "); - strcat(syntax, nexttoken); - nexttype = get_token(fp, nexttoken); - strcat(syntax, " "); - strcat(syntax, nexttoken); - nexttype = get_token(fp, nexttoken); - } - break; + strcpy(syntax, token); + if (nexttype == OF) { + strcat(syntax, " "); + strcat(syntax, nexttoken); + nexttype = get_token(fp, nexttoken); + strcat(syntax, " "); + strcat(syntax, nexttoken); + nexttype = get_token(fp, nexttoken); + } + break; case INTEGER: - strcpy(syntax, token); - if (nexttype == LEFTBRACKET) { - /* if there is an enumeration list, parse it */ - while ((type = get_token(fp, token)) != ENDOFFILE) { - if (type == RIGHTBRACKET) - break; - if (type == LABEL) { - /* this is an enumerated label */ - if (np->enums == 0) { - ep = np->enums = (struct enum_list *) - xmalloc(sizeof(struct enum_list)); - } else { - ep->next = (struct enum_list *) - xmalloc(sizeof(struct enum_list)); - ep = ep->next; - } - ep->next = 0; - /* a reasonable approximation for the length */ - ep->label = (char *) xmalloc((unsigned) strlen(token) + 1); - strcpy(ep->label, token); - type = get_token(fp, token); - if (type != LEFTPAREN) { - print_error("Expected \"(\"", token, type); - free_node(np); - return 0; - } - type = get_token(fp, token); - if (type != NUMBER) { - print_error("Expected integer", token, type); - free_node(np); - return 0; - } - ep->value = atoi(token); - type = get_token(fp, token); - if (type != RIGHTPAREN) { - print_error("Expected \")\"", token, type); - free_node(np); - return 0; - } - } - } - if (type == ENDOFFILE) { - print_error("Expected \"}\"", token, type); - free_node(np); - return 0; - } - nexttype = get_token(fp, nexttoken); - } else if (nexttype == LEFTPAREN) { - /* ignore the "constrained integer" for now */ - nexttype = get_token(fp, nexttoken); - nexttype = get_token(fp, nexttoken); - nexttype = get_token(fp, nexttoken); - } - break; + strcpy(syntax, token); + if (nexttype == LEFTBRACKET) { + /* if there is an enumeration list, parse it */ + while ((type = get_token(fp, token)) != ENDOFFILE) { + if (type == RIGHTBRACKET) + break; + if (type == LABEL) { + /* this is an enumerated label */ + if (np->enums == 0) { + ep = np->enums = (struct enum_list *) + xmalloc(sizeof(struct enum_list)); + } else { + ep->next = (struct enum_list *) + xmalloc(sizeof(struct enum_list)); + ep = ep->next; + } + ep->next = 0; + /* a reasonable approximation for the length */ + ep->label = (char *) xmalloc((unsigned) strlen(token) + 1); + strcpy(ep->label, token); + type = get_token(fp, token); + if (type != LEFTPAREN) { + print_error("Expected \"(\"", token, type); + free_node(np); + return 0; + } + type = get_token(fp, token); + if (type != NUMBER) { + print_error("Expected integer", token, type); + free_node(np); + return 0; + } + ep->value = atoi(token); + type = get_token(fp, token); + if (type != RIGHTPAREN) { + print_error("Expected \")\"", token, type); + free_node(np); + return 0; + } + } + } + if (type == ENDOFFILE) { + print_error("Expected \"}\"", token, type); + free_node(np); + return 0; + } + nexttype = get_token(fp, nexttoken); + } else if (nexttype == LEFTPAREN) { + /* ignore the "constrained integer" for now */ + nexttype = get_token(fp, nexttoken); + nexttype = get_token(fp, nexttoken); + nexttype = get_token(fp, nexttoken); + } + break; case OBJID: case OCTETSTR: case NETADDR: @@ -847,36 +843,36 @@ parse_objecttype(register FILE *fp, char *name) case SNMP_OPAQUE: case NUL: case LABEL: - strcpy(syntax, token); - break; + strcpy(syntax, token); + break; default: - print_error("Bad syntax", token, type); - free_node(np); - return 0; + print_error("Bad syntax", token, type); + free_node(np); + return 0; } if (nexttype != ACCESS) { - print_error("Should be ACCESS", nexttoken, nexttype); - free_node(np); - return 0; + print_error("Should be ACCESS", nexttoken, nexttype); + free_node(np); + return 0; } type = get_token(fp, token); if (type != READONLY && type != READWRITE && type != WRITEONLY - && type != NOACCESS) { - print_error("Bad access type", nexttoken, nexttype); - free_node(np); - return 0; + && type != NOACCESS) { + print_error("Bad access type", nexttoken, nexttype); + free_node(np); + return 0; } type = get_token(fp, token); if (type != SNMP_STATUS) { - print_error("Should be STATUS", token, nexttype); - free_node(np); - return 0; + print_error("Should be STATUS", token, nexttype); + free_node(np); + return 0; } type = get_token(fp, token); if (type != MANDATORY && type != SNMP_OPTIONAL && type != OBSOLETE && type != RECOMMENDED) { - print_error("Bad status", token, type); - free_node(np); - return 0; + print_error("Bad status", token, type); + free_node(np); + return 0; } /* Fetch next token. Either: * @@ -885,90 +881,90 @@ parse_objecttype(register FILE *fp, char *name) */ type = get_token(fp, token); if ((type != DESCRIPTION) && (type != INDEX) && (type != EQUALS)) { - print_error("Should be DESCRIPTION, INDEX, or EQUALS", token, nexttype); - free_node(np); - return 0; + print_error("Should be DESCRIPTION, INDEX, or EQUALS", token, nexttype); + free_node(np); + return 0; } if (type == DESCRIPTION) { - type = get_token(fp, token); - if (type != QUOTE) { - print_error("Should be Description open quote", token, nexttype); - free_node(np); - return 0; - } - /* Fetch description string */ - { - int ReadChar; - - ReadChar = last; - /* skip everything until closing quote */ - while ((ReadChar != '"') && (ReadChar != -1)) { - ReadChar = getc(fp); - if (ReadChar == '\n') - Line++; - } - last = ' '; - } - /* ASSERT: Done with description. */ - type = get_token(fp, token); + type = get_token(fp, token); + if (type != QUOTE) { + print_error("Should be Description open quote", token, nexttype); + free_node(np); + return 0; + } + /* Fetch description string */ + { + int ReadChar; + + ReadChar = last; + /* skip everything until closing quote */ + while ((ReadChar != '"') && (ReadChar != -1)) { + ReadChar = getc(fp); + if (ReadChar == '\n') + Line++; + } + last = ' '; + } + /* ASSERT: Done with description. */ + type = get_token(fp, token); } if ((type != INDEX) && (type != EQUALS)) { - print_error("Should be INDEX, or EQUALS", token, nexttype); - free_node(np); - return 0; + print_error("Should be INDEX, or EQUALS", token, nexttype); + free_node(np); + return 0; } if (type == INDEX) { - /* Scarf INDEX */ - - type = get_token(fp, token); - if (type != LEFTBRACKET) { - print_error("Should be INDEX left brace", token, type); - free_node(np); - return 0; - } - /* Fetch description string */ - { - int ReadChar; - - ReadChar = last; - /* skip everything until closing quote */ - while ((ReadChar != '}') && (ReadChar != -1)) { - ReadChar = getc(fp); - if (ReadChar == '\n') - Line++; - } - last = ' '; - } - /* ASSERT: Done with INDEX. */ - type = get_token(fp, token); + /* Scarf INDEX */ + + type = get_token(fp, token); + if (type != LEFTBRACKET) { + print_error("Should be INDEX left brace", token, type); + free_node(np); + return 0; + } + /* Fetch description string */ + { + int ReadChar; + + ReadChar = last; + /* skip everything until closing quote */ + while ((ReadChar != '}') && (ReadChar != -1)) { + ReadChar = getc(fp); + if (ReadChar == '\n') + Line++; + } + last = ' '; + } + /* ASSERT: Done with INDEX. */ + type = get_token(fp, token); } if (type != EQUALS) { - print_error("Bad format", token, type); - free_node(np); - return 0; + print_error("Bad format", token, type); + free_node(np); + return 0; } length = getoid(fp, SubOid, 32); if (length > 1 && length <= 32) { - /* just take the last pair in the oid list */ - if (SubOid[length - 2].label) - strncpy(np->parent, SubOid[length - 2].label, 64); - strcpy(np->label, name); - if (SubOid[length - 1].subid != -1) - np->subid = SubOid[length - 1].subid; - else - print_error("Warning: This entry is pretty silly", np->label, type); + /* just take the last pair in the oid list */ + if (SubOid[length - 2].label) + strncpy(np->parent, SubOid[length - 2].label, 64); + strcpy(np->label, name); + if (SubOid[length - 1].subid != -1) + np->subid = SubOid[length - 1].subid; + else + print_error("Warning: This entry is pretty silly", np->label, type); } else { - print_error("No end to oid", (char *) NULL, type); - free_node(np); - np = 0; + print_error("No end to oid", (char *) NULL, type); + free_node(np); + np = 0; } /* free oid array */ for (count = 0; count < length; count++) { - if (SubOid[count].label) - xfree(SubOid[count].label); - SubOid[count].label = 0; + if (SubOid[count].label) + xfree(SubOid[count].label); + SubOid[count].label = 0; } return np; } @@ -982,8 +978,7 @@ parse_objecttype(register FILE *fp, char *name) static #endif struct node * -parse(FILE *fp) -{ + parse(FILE *fp) { char token[64]; char name[64]; int type = 1; @@ -992,83 +987,82 @@ parse(FILE *fp) hash_init(); while (type != ENDOFFILE) { - type = get_token(fp, token); - if (type != LABEL) { - if (type == ENDOFFILE) { - return root; - } - print_error(token, "is a reserved word", type); - return NULL; - } - strncpy(name, token, 64); - type = get_token(fp, token); - if (type == OBJTYPE) { - if (root == NULL) { - /* first link in chain */ - np = root = parse_objecttype(fp, name); - if (np == NULL) { - print_error("Bad parse of object type", (char *) NULL, type); - return NULL; - } - } else { - np->next = parse_objecttype(fp, name); - if (np->next == NULL) { - print_error("Bad parse of objecttype", (char *) NULL, type); - return NULL; - } - } - /* now find end of chain */ - while (np->next) - np = np->next; - } else if (type == OBJID) { - if (root == NULL) { - /* first link in chain */ - np = root = parse_objectid(fp, name); - if (np == NULL) { - print_error("Bad parse of object id", (char *) NULL, type); - return NULL; - } - } else { - np->next = parse_objectid(fp, name); - if (np->next == NULL) { - print_error("Bad parse of object type", (char *) NULL, type); - return NULL; - } - } - /* now find end of chain */ - while (np->next) - np = np->next; - } else if (type == EQUALS) { - type = parse_asntype(fp); - } else if (type == ENDOFFILE) { - break; - } else { - print_error("Bad operator", (char *) NULL, type); - return NULL; - } + type = get_token(fp, token); + if (type != LABEL) { + if (type == ENDOFFILE) { + return root; + } + print_error(token, "is a reserved word", type); + return NULL; + } + strncpy(name, token, 64); + type = get_token(fp, token); + if (type == OBJTYPE) { + if (root == NULL) { + /* first link in chain */ + np = root = parse_objecttype(fp, name); + if (np == NULL) { + print_error("Bad parse of object type", (char *) NULL, type); + return NULL; + } + } else { + np->next = parse_objecttype(fp, name); + if (np->next == NULL) { + print_error("Bad parse of objecttype", (char *) NULL, type); + return NULL; + } + } + /* now find end of chain */ + while (np->next) + np = np->next; + } else if (type == OBJID) { + if (root == NULL) { + /* first link in chain */ + np = root = parse_objectid(fp, name); + if (np == NULL) { + print_error("Bad parse of object id", (char *) NULL, type); + return NULL; + } + } else { + np->next = parse_objectid(fp, name); + if (np->next == NULL) { + print_error("Bad parse of object type", (char *) NULL, type); + return NULL; + } + } + /* now find end of chain */ + while (np->next) + np = np->next; + } else if (type == EQUALS) { + type = parse_asntype(fp); + } else if (type == ENDOFFILE) { + break; + } else { + print_error("Bad operator", (char *) NULL, type); + return NULL; + } } #ifdef TEST { - struct enum_list *ep; - - for (np = root; np; np = np->next) { - printf("%s ::= { %s %d } (%d)\n", np->label, np->parent, np->subid, - np->type); - if (np->enums) { - printf("Enums: \n"); - for (ep = np->enums; ep; ep = ep->next) { - printf("%s(%d)\n", ep->label, ep->value); - } - } - } + struct enum_list *ep; + + for (np = root; np; np = np->next) { + printf("%s ::= { %s %d } (%d)\n", np->label, np->parent, np->subid, + np->type); + if (np->enums) { + printf("Enums: \n"); + for (ep = np->enums; ep; ep = ep->next) { + printf("%s(%d)\n", ep->label, ep->value); + } + } + } } #endif /* TEST */ return root; } struct snmp_mib_tree * -read_mib(char *filename) -{ + read_mib(char *filename) { FILE *fp; struct node *nodes; struct snmp_mib_tree *tree; @@ -1077,24 +1071,24 @@ read_mib(char *filename) fp = fopen(filename, "r"); if (fp == NULL) { - snmplib_debug(1, "init_mib: %s: %s\n", filename, xstrerror()); - return (NULL); + snmplib_debug(1, "init_mib: %s: %s\n", filename, xstrerror()); + return (NULL); } mbuf[0] = '\0'; while ((p = fgets(mbuf, 256, fp)) && strncmp(mbuf, "DUMMY", - strlen("DUMMY"))); + strlen("DUMMY"))); if (!p) { - snmplib_debug(0, "Bad MIB version or tag missing, install original!\n"); - return NULL; + snmplib_debug(0, "Bad MIB version or tag missing, install original!\n"); + return NULL; } if (!strcmp(mbuf, "DUMMY")) { - snmplib_debug(0, "You need to update your MIB!\n"); - return NULL; + snmplib_debug(0, "You need to update your MIB!\n"); + return NULL; } nodes = parse(fp); if (!nodes) { - snmplib_debug(0, "Mib table is bad. Exiting\n"); - return NULL; + snmplib_debug(0, "Mib table is bad. Exiting\n"); + return NULL; } tree = build_tree(nodes); fclose(fp); diff --git a/snmplib/snmp_api.c b/snmplib/snmp_api.c index ebe1145662..5e6d5081dd 100644 --- a/snmplib/snmp_api.c +++ b/snmplib/snmp_api.c @@ -3,9 +3,9 @@ /********************************************************************** * * Copyright 1997 by Carnegie Mellon University - * + * * All Rights Reserved - * + * * Permission to use, copy, modify, and distribute this software and its * documentation for any purpose and without fee is hereby granted, * provided that the above copyright notice appear in all copies and that @@ -13,7 +13,7 @@ * supporting documentation, and that the name of CMU not be * used in advertising or publicity pertaining to distribution of the * software without specific, written prior permission. - * + * * CMU DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING * ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL * CMU BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR @@ -21,7 +21,7 @@ * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS * SOFTWARE. - * + * **********************************************************************/ #include "config.h" @@ -100,22 +100,22 @@ */ int snmp_build(session, pdu, packet, out_length) - struct snmp_session *session; - struct snmp_pdu *pdu; - u_char *packet; - int *out_length; +struct snmp_session *session; +struct snmp_pdu *pdu; +u_char *packet; +int *out_length; { u_char *bufp; bufp = snmp_msg_Encode(packet, out_length, - session->community, session->community_len, - session->Version, - pdu); + session->community, session->community_len, + session->Version, + pdu); snmplib_debug(8, "LIBSNMP: snmp_build(): Packet len %d (requid %d)\n", - *out_length, pdu->reqid); + *out_length, pdu->reqid); if (bufp == NULL) - return (-1); + return (-1); return (0); } @@ -127,9 +127,9 @@ snmp_build(session, pdu, packet, out_length) */ u_char * snmp_parse(struct snmp_session * session, - struct snmp_pdu * pdu, - u_char * data, - int length) + struct snmp_pdu * pdu, + u_char * data, + int length) { u_char Community[128]; u_char *bufp; @@ -137,14 +137,14 @@ snmp_parse(struct snmp_session * session, /* Decode the entire message. */ data = snmp_msg_Decode(data, &length, - Community, &CommunityLen, - &session->Version, pdu); + Community, &CommunityLen, + &session->Version, pdu); if (data == NULL) - return (NULL); + return (NULL); bufp = (u_char *) xmalloc(CommunityLen + 1); if (bufp == NULL) - return (NULL); + return (NULL); strncpy((char *) bufp, (char *) Community, CommunityLen); bufp[CommunityLen] = '\0'; diff --git a/snmplib/snmp_api_error.c b/snmplib/snmp_api_error.c index fc4c9eade4..260117e951 100644 --- a/snmplib/snmp_api_error.c +++ b/snmplib/snmp_api_error.c @@ -7,9 +7,9 @@ /*************************************************************************** * * Copyright 1997 by Carnegie Mellon University - * + * * All Rights Reserved - * + * * Permission to use, copy, modify, and distribute this software and its * documentation for any purpose and without fee is hereby granted, * provided that the above copyright notice appear in all copies and that @@ -17,7 +17,7 @@ * supporting documentation, and that the name of CMU not be * used in advertising or publicity pertaining to distribution of the * software without specific, written prior permission. - * + * * CMU DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING * ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL * CMU BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR @@ -25,9 +25,9 @@ * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS * SOFTWARE. - * + * * Author: Ryan Troll - * + * ***************************************************************************/ #ifdef HAVE_CONFIG_H @@ -44,8 +44,7 @@ int snmp_errno = 0; -static const char *api_errors[17] = -{ +static const char *api_errors[17] = { "Unknown Error", "Generic Error", "Invalid local port", @@ -80,8 +79,8 @@ snmp_api_error(int err) { int foo = (err * -1); if ((foo < SNMPERR_GENERR) || - (foo > SNMPERR_LAST)) - foo = 0; + (foo > SNMPERR_LAST)) + foo = 0; return (api_errors[foo]); } diff --git a/snmplib/snmp_error.c b/snmplib/snmp_error.c index 470fa432f9..3fc747fce3 100644 --- a/snmplib/snmp_error.c +++ b/snmplib/snmp_error.c @@ -5,9 +5,9 @@ /********************************************************************** * * Copyright 1997 by Carnegie Mellon University - * + * * All Rights Reserved - * + * * Permission to use, copy, modify, and distribute this software and its * documentation for any purpose and without fee is hereby granted, * provided that the above copyright notice appear in all copies and that @@ -15,7 +15,7 @@ * supporting documentation, and that the name of CMU not be * used in advertising or publicity pertaining to distribution of the * software without specific, written prior permission. - * + * * CMU DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING * ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL * CMU BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR @@ -23,7 +23,7 @@ * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS * SOFTWARE. - * + * **********************************************************************/ #include "config.h" @@ -33,8 +33,7 @@ #include "snmp_error.h" -static const char *error_string[19] = -{ +static const char *error_string[19] = { "No Error", "Response message would have been too large.", "There is no such variable name in this MIB.", @@ -42,7 +41,7 @@ static const char *error_string[19] = "This variable is read only", "A general failure occured", - /* SNMPv2 Errors */ + /* SNMPv2 Errors */ "NOACCESS", "WRONGTYPE", "WRONGLENGTH", @@ -63,9 +62,9 @@ const char * snmp_errstring(int errstat) { if ((errstat <= (SNMP_ERR_INCONSISTENTNAME)) && - (errstat >= (SNMP_ERR_NOERROR))) { - return error_string[errstat]; + (errstat >= (SNMP_ERR_NOERROR))) { + return error_string[errstat]; } else { - return "Unknown Error"; + return "Unknown Error"; } } diff --git a/snmplib/snmp_msg.c b/snmplib/snmp_msg.c index 9dea7b31b4..bc8ef64128 100644 --- a/snmplib/snmp_msg.c +++ b/snmplib/snmp_msg.c @@ -10,9 +10,9 @@ /********************************************************************** * * Copyright 1997 by Carnegie Mellon University - * + * * All Rights Reserved - * + * * Permission to use, copy, modify, and distribute this software and its * documentation for any purpose and without fee is hereby granted, * provided that the above copyright notice appear in all copies and that @@ -20,7 +20,7 @@ * supporting documentation, and that the name of CMU not be * used in advertising or publicity pertaining to distribution of the * software without specific, written prior permission. - * + * * CMU DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING * ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL * CMU BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR @@ -28,9 +28,9 @@ * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS * SOFTWARE. - * + * * Author: Ryan Troll - * + * **********************************************************************/ #include "config.h" @@ -89,7 +89,7 @@ #include "snmp_msg.h" -/* +/* * RFC 1901: Introduction to Community-based SNMPv2 * * Message ::= @@ -126,9 +126,9 @@ u_char * snmp_msg_Encode(u_char * Buffer, int *BufLenP, - u_char * Community, int CommLen, - int Version, - struct snmp_pdu *PDU) + u_char * Community, int CommLen, + int Version, + struct snmp_pdu *PDU) { u_char *bufp, *tmp; u_char *PDUHeaderPtr, *VARHeaderPtr; @@ -137,105 +137,105 @@ snmp_msg_Encode(u_char * Buffer, int *BufLenP, int FakeArg = 1024; snmplib_debug(4, "Buffer=%p BufLenP=%p, buflen=%d\n", Buffer, BufLenP, - *BufLenP); + *BufLenP); /* Header for the entire thing, with a false, large length */ bufp = asn_build_header(Buffer, BufLenP, - (u_char) (ASN_SEQUENCE | - ASN_CONSTRUCTOR), - (*BufLenP)); + (u_char) (ASN_SEQUENCE | + ASN_CONSTRUCTOR), + (*BufLenP)); if (bufp == NULL) { - snmplib_debug(4, "snmp_msg_Encode:Error encoding SNMP Message Header (Header)!\n"); - return (NULL); + snmplib_debug(4, "snmp_msg_Encode:Error encoding SNMP Message Header (Header)!\n"); + return (NULL); } MsgPtr = bufp; /* Version */ bufp = asn_build_int(bufp, BufLenP, - (u_char) (ASN_UNIVERSAL | - ASN_PRIMITIVE | - ASN_INTEGER), - (int *) (&Version), sizeof(Version)); + (u_char) (ASN_UNIVERSAL | + ASN_PRIMITIVE | + ASN_INTEGER), + (int *) (&Version), sizeof(Version)); if (bufp == NULL) { - snmplib_debug(4, "snmp_msg_Encode:Error encoding SNMP Message Header (Version)!\n"); - return (NULL); + snmplib_debug(4, "snmp_msg_Encode:Error encoding SNMP Message Header (Version)!\n"); + return (NULL); } snmplib_debug(8, "snmp_msg_Encode: Encoding community (%s) (%d)\n", Community, CommLen); /* Community */ bufp = asn_build_string(bufp, BufLenP, - (u_char) (ASN_UNIVERSAL | - ASN_PRIMITIVE | - ASN_OCTET_STR), - Community, CommLen); + (u_char) (ASN_UNIVERSAL | + ASN_PRIMITIVE | + ASN_OCTET_STR), + Community, CommLen); if (bufp == NULL) { - snmplib_debug(4, "snmp_msg_Encode:Error encoding SNMP Message Header (Community)!\n"); - return (NULL); + snmplib_debug(4, "snmp_msg_Encode:Error encoding SNMP Message Header (Community)!\n"); + return (NULL); } /* Encode the rest. */ - /* A nice header for this PDU. + /* A nice header for this PDU. * Encoded with the wrong length. We'll fix it later. */ snmplib_debug(8, "snmp_msg_Encode:Encoding PDU Header at 0x%p (fake len %d) (%d bytes so far)\n", - bufp, *BufLenP, *BufLenP); + bufp, *BufLenP, *BufLenP); PDUHeaderPtr = bufp; bufp = asn_build_header(bufp, BufLenP, - (u_char) (ASN_SEQUENCE | ASN_CONSTRUCTOR), - (*BufLenP)); + (u_char) (ASN_SEQUENCE | ASN_CONSTRUCTOR), + (*BufLenP)); if (bufp == NULL) - return (NULL); + return (NULL); /* Encode this PDU. */ PDUDataStart = bufp; bufp = snmp_pdu_encode(bufp, BufLenP, PDU); if (bufp == NULL) - return (NULL); /* snmp_pdu_encode registered failure */ + return (NULL); /* snmp_pdu_encode registered failure */ VARHeaderPtr = bufp; bufp = asn_build_header(bufp, BufLenP, - (u_char) (ASN_SEQUENCE | ASN_CONSTRUCTOR), - FakeArg); + (u_char) (ASN_SEQUENCE | ASN_CONSTRUCTOR), + FakeArg); if (bufp == NULL) - return (NULL); + return (NULL); VARDataStart = bufp; /* And build the variables */ bufp = snmp_var_EncodeVarBind(bufp, BufLenP, PDU->variables, Version); if (bufp == NULL) - return (NULL); /* snmp_var_EncodeVarBind registered failure */ + return (NULL); /* snmp_var_EncodeVarBind registered failure */ /* Cool. Now insert the appropriate lengths. */ #ifdef DEBUG_MSG_ENCODE snmplib_debug(9, "Msg: Vars returned 0x%x. PDU Started at 0x%x\n", - bufp, PDUHeaderPtr); + bufp, PDUHeaderPtr); snmplib_debug(9, "MSG: Entire PDU length is %d (0x%x - 0x%x)\n", - (int) (bufp - PDUDataStart), PDUHeaderPtr, bufp); + (int) (bufp - PDUDataStart), PDUHeaderPtr, bufp); #endif tmp = asn_build_header(PDUHeaderPtr, &FakeArg, - (u_char) PDU->command, - (int) (bufp - PDUDataStart)); + (u_char) PDU->command, + (int) (bufp - PDUDataStart)); /* Length of the PDU and Vars */ if (tmp == NULL) - return (NULL); + return (NULL); #ifdef DEBUG_MSG_ENCODE snmplib_debug(9, "MSG: Entire message length is %d (0x%x - 0x%x)\n", - (int) (bufp - MsgPtr), MsgPtr, bufp); + (int) (bufp - MsgPtr), MsgPtr, bufp); #endif tmp = asn_build_header(Buffer, - &FakeArg, - (u_char) (ASN_SEQUENCE | ASN_CONSTRUCTOR), - (bufp - MsgPtr)); /* Length of everything */ + &FakeArg, + (u_char) (ASN_SEQUENCE | ASN_CONSTRUCTOR), + (bufp - MsgPtr)); /* Length of everything */ if (tmp == NULL) - return (NULL); + return (NULL); tmp = asn_build_header(VARHeaderPtr, - &FakeArg, - (u_char) (ASN_SEQUENCE | ASN_CONSTRUCTOR), - (bufp - VARDataStart)); /* Length of everything */ + &FakeArg, + (u_char) (ASN_SEQUENCE | ASN_CONSTRUCTOR), + (bufp - VARDataStart)); /* Length of everything */ if (tmp == NULL) - return (NULL); + return (NULL); *BufLenP = (bufp - Buffer); return (u_char *) bufp; @@ -245,54 +245,54 @@ snmp_msg_Encode(u_char * Buffer, int *BufLenP, u_char * snmp_msg_Decode(u_char * Packet, int *PacketLenP, - u_char * Community, int *CommLenP, - int *Version, struct snmp_pdu * PDU) + u_char * Community, int *CommLenP, + int *Version, struct snmp_pdu * PDU) { u_char *bufp; u_char type; bufp = asn_parse_header(Packet, PacketLenP, &type); if (bufp == NULL) { - snmplib_debug(4, "snmp_msg_Decode:Error decoding SNMP Messsage Header (Header)!\n"); - ASN_PARSE_ERROR(NULL); + snmplib_debug(4, "snmp_msg_Decode:Error decoding SNMP Messsage Header (Header)!\n"); + ASN_PARSE_ERROR(NULL); } if (type != (ASN_SEQUENCE | ASN_CONSTRUCTOR)) { - snmplib_debug(4, "snmp_msg_Decode:Error decoding SNMP Messsage Header (Header)!\n"); - ASN_PARSE_ERROR(NULL); + snmplib_debug(4, "snmp_msg_Decode:Error decoding SNMP Messsage Header (Header)!\n"); + ASN_PARSE_ERROR(NULL); } bufp = asn_parse_int(bufp, PacketLenP, - &type, - (int *) Version, sizeof(*Version)); + &type, + (int *) Version, sizeof(*Version)); if (bufp == NULL) { - snmplib_debug(4, "snmp_msg_Decode:Error decoding SNMP Messsage Header (Version)!\n"); - ASN_PARSE_ERROR(NULL); + snmplib_debug(4, "snmp_msg_Decode:Error decoding SNMP Messsage Header (Version)!\n"); + ASN_PARSE_ERROR(NULL); } bufp = asn_parse_string(bufp, PacketLenP, &type, Community, CommLenP); if (bufp == NULL) { - snmplib_debug(4, "snmp_msg_Decode:Error decoding SNMP Messsage Header (Community)!\n"); - ASN_PARSE_ERROR(NULL); + snmplib_debug(4, "snmp_msg_Decode:Error decoding SNMP Messsage Header (Community)!\n"); + ASN_PARSE_ERROR(NULL); } Community[*CommLenP] = '\0'; if ((*Version != SNMP_VERSION_1) && - (*Version != SNMP_VERSION_2)) { + (*Version != SNMP_VERSION_2)) { - /* Don't know how to handle this one. */ - snmplib_debug(4, "snmp_msg_Decode:Unable to parse Version %u\n", *Version); - snmplib_debug(4, "snmp_msg_Decode:Continuing anyway\n"); + /* Don't know how to handle this one. */ + snmplib_debug(4, "snmp_msg_Decode:Unable to parse Version %u\n", *Version); + snmplib_debug(4, "snmp_msg_Decode:Continuing anyway\n"); } /* Now that we know the header, decode the PDU */ /* XXXXX -- More than one PDU? */ bufp = snmp_pdu_decode(bufp, PacketLenP, PDU); if (bufp == NULL) - /* snmp_pdu_decode registered failure */ - return (NULL); + /* snmp_pdu_decode registered failure */ + return (NULL); bufp = snmp_var_DecodeVarBind(bufp, PacketLenP, &(PDU->variables), *Version); if (bufp == NULL) - /* snmp_var_DecodeVarBind registered failure */ - return (NULL); + /* snmp_var_DecodeVarBind registered failure */ + return (NULL); return (u_char *) bufp; } diff --git a/snmplib/snmp_pdu.c b/snmplib/snmp_pdu.c index 6cea0a59e1..84aa88d2ce 100644 --- a/snmplib/snmp_pdu.c +++ b/snmplib/snmp_pdu.c @@ -10,9 +10,9 @@ /********************************************************************** * * Copyright 1997 by Carnegie Mellon University - * + * * All Rights Reserved - * + * * Permission to use, copy, modify, and distribute this software and its * documentation for any purpose and without fee is hereby granted, * provided that the above copyright notice appear in all copies and that @@ -20,7 +20,7 @@ * supporting documentation, and that the name of CMU not be * used in advertising or publicity pertaining to distribution of the * software without specific, written prior permission. - * + * * CMU DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING * ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL * CMU BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR @@ -28,9 +28,9 @@ * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS * SOFTWARE. - * + * * Author: Ryan Troll - * + * **********************************************************************/ #include "config.h" @@ -104,8 +104,7 @@ */ struct snmp_pdu * -snmp_pdu_create(int command) -{ + snmp_pdu_create(int command) { struct snmp_pdu *pdu; #ifdef DEBUG_PDU @@ -114,8 +113,8 @@ snmp_pdu_create(int command) pdu = (struct snmp_pdu *) xmalloc(sizeof(struct snmp_pdu)); if (pdu == NULL) { - snmp_set_api_error(SNMPERR_OS_ERR); - return (NULL); + snmp_set_api_error(SNMPERR_OS_ERR); + return (NULL); } memset((char *) pdu, '\0', sizeof(struct snmp_pdu)); @@ -139,8 +138,7 @@ snmp_pdu_create(int command) /* Clone an existing PDU. */ struct snmp_pdu * -snmp_pdu_clone(struct snmp_pdu *Src) -{ + snmp_pdu_clone(struct snmp_pdu *Src) { struct snmp_pdu *Dest; #ifdef DEBUG_PDU @@ -149,8 +147,8 @@ snmp_pdu_clone(struct snmp_pdu *Src) Dest = (struct snmp_pdu *) xmalloc(sizeof(struct snmp_pdu)); if (Dest == NULL) { - snmp_set_api_error(SNMPERR_OS_ERR); - return (NULL); + snmp_set_api_error(SNMPERR_OS_ERR); + return (NULL); } xmemcpy((char *) Dest, (char *) Src, sizeof(struct snmp_pdu)); @@ -174,14 +172,12 @@ snmp_pdu_clone(struct snmp_pdu *Src) * be returned. */ struct snmp_pdu * -snmp_pdu_fix(struct snmp_pdu *pdu, int command) -{ + snmp_pdu_fix(struct snmp_pdu *pdu, int command) { return (snmp_fix_pdu(pdu, command)); } struct snmp_pdu * -snmp_fix_pdu(struct snmp_pdu *pdu, int command) -{ + snmp_fix_pdu(struct snmp_pdu *pdu, int command) { struct variable_list *var, *newvar; struct snmp_pdu *newpdu; int i; @@ -189,19 +185,19 @@ snmp_fix_pdu(struct snmp_pdu *pdu, int command) #ifdef DEBUG_PDU snmplib_debug(8, "PDU %x: Fixing. Err index is %d\n", - (unsigned int) pdu, (unsigned int) pdu->errindex); + (unsigned int) pdu, (unsigned int) pdu->errindex); #endif if (pdu->command != SNMP_PDU_RESPONSE || - pdu->errstat == SNMP_ERR_NOERROR || - pdu->errindex <= 0) { - snmp_set_api_error(SNMPERR_UNABLE_TO_FIX); - return (NULL); + pdu->errstat == SNMP_ERR_NOERROR || + pdu->errindex <= 0) { + snmp_set_api_error(SNMPERR_UNABLE_TO_FIX); + return (NULL); } /* clone the pdu */ newpdu = snmp_pdu_clone(pdu); if (newpdu == NULL) - return (NULL); + return (NULL); newpdu->variables = 0; newpdu->command = command; @@ -216,53 +212,53 @@ snmp_fix_pdu(struct snmp_pdu *pdu, int command) /* skip first variable if necessary */ if (pdu->errindex == i) { - var = var->next_variable; - i++; + var = var->next_variable; + i++; } if (var != NULL) { - /* VAR is the first uncopied variable */ - - /* Clone this variable */ - newpdu->variables = snmp_var_clone(var); - if (newpdu->variables == NULL) { - snmp_pdu_free(newpdu); - return (NULL); - } - copied++; - - newvar = newpdu->variables; - - /* VAR has been copied to NEWVAR. */ - while (var->next_variable) { - - /* Skip the item that was bad */ - if (++i == pdu->errindex) { - var = var->next_variable; - continue; - } - /* Copy this var */ - newvar->next_variable = snmp_var_clone(var->next_variable); - if (newvar->next_variable == NULL) { - snmp_pdu_free(newpdu); - return (NULL); - } - /* Move to the next one */ - newvar = newvar->next_variable; - var = var->next_variable; - copied++; - } - newvar->next_variable = NULL; + /* VAR is the first uncopied variable */ + + /* Clone this variable */ + newpdu->variables = snmp_var_clone(var); + if (newpdu->variables == NULL) { + snmp_pdu_free(newpdu); + return (NULL); + } + copied++; + + newvar = newpdu->variables; + + /* VAR has been copied to NEWVAR. */ + while (var->next_variable) { + + /* Skip the item that was bad */ + if (++i == pdu->errindex) { + var = var->next_variable; + continue; + } + /* Copy this var */ + newvar->next_variable = snmp_var_clone(var->next_variable); + if (newvar->next_variable == NULL) { + snmp_pdu_free(newpdu); + return (NULL); + } + /* Move to the next one */ + newvar = newvar->next_variable; + var = var->next_variable; + copied++; + } + newvar->next_variable = NULL; } /* If we didn't copy anything, free the new pdu. */ if (i < pdu->errindex || copied == 0) { - snmp_free_pdu(newpdu); - snmp_set_api_error(SNMPERR_UNABLE_TO_FIX); - return (NULL); + snmp_free_pdu(newpdu); + snmp_set_api_error(SNMPERR_UNABLE_TO_FIX); + return (NULL); } #ifdef DEBUG_PDU snmplib_debug(8, "PDU %x: Fixed PDU is %x\n", - (unsigned int) pdu, (unsigned int) newpdu); + (unsigned int) pdu, (unsigned int) newpdu); #endif return (newpdu); } @@ -286,13 +282,13 @@ snmp_free_pdu(struct snmp_pdu *pdu) vp = pdu->variables; while (vp) { - ovp = vp; - vp = vp->next_variable; - snmp_var_free(ovp); + ovp = vp; + vp = vp->next_variable; + snmp_var_free(ovp); } if (pdu->enterprise) - xfree((char *) pdu->enterprise); + xfree((char *) pdu->enterprise); xfree((char *) pdu); } @@ -307,7 +303,7 @@ snmp_free_pdu(struct snmp_pdu *pdu) /* * RFC 1902: Structure of Management Information for SNMPv2 * - * PDU ::= + * PDU ::= * SEQUENCE { * request-id INTEGER32 * error-status INTEGER @@ -327,7 +323,7 @@ snmp_free_pdu(struct snmp_pdu *pdu) /* * RFC 1157: A Simple Network Management Protocol (SNMP) * - * PDU ::= + * PDU ::= * SEQUENCE { * request-id INTEGER * error-status INTEGER @@ -347,7 +343,7 @@ snmp_free_pdu(struct snmp_pdu *pdu) u_char * snmp_pdu_encode(u_char * DestBuf, int *DestBufLen, - struct snmp_pdu *PDU) + struct snmp_pdu *PDU) { u_char *bufp; @@ -358,117 +354,117 @@ snmp_pdu_encode(u_char * DestBuf, int *DestBufLen, /* ASN.1 Header */ switch (PDU->command) { -/**********************************************************************/ + /**********************************************************************/ #ifdef TRP_REQ_MSG case TRP_REQ_MSG: - /* SNMPv1 Trap */ - - /* enterprise */ - bufp = asn_build_objid(DestBuf, DestBufLen, - (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_OBJECT_ID), - (oid *) PDU->enterprise, PDU->enterprise_length); - if (bufp == NULL) - return (NULL); - - /* agent-addr */ - bufp = asn_build_string(bufp, DestBufLen, - (u_char) (SMI_IPADDRESS | ASN_PRIMITIVE), - (u_char *) & PDU->agent_addr.sin_addr.s_addr, - sizeof(PDU->agent_addr.sin_addr.s_addr)); - if (bufp == NULL) - return (NULL); - - /* generic trap */ - bufp = asn_build_int(bufp, DestBufLen, - (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_INTEGER), - (int *) &PDU->trap_type, sizeof(PDU->trap_type)); - if (bufp == NULL) - return (NULL); - - /* specific trap */ - bufp = asn_build_int(bufp, DestBufLen, - (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_INTEGER), - (int *) &PDU->specific_type, - sizeof(PDU->specific_type)); - if (bufp == NULL) - return (NULL); - - /* timestamp */ - bufp = asn_build_unsigned_int(bufp, DestBufLen, - (u_char) (SMI_TIMETICKS | ASN_PRIMITIVE), - &PDU->time, sizeof(PDU->time)); - if (bufp == NULL) - return (NULL); - break; + /* SNMPv1 Trap */ + + /* enterprise */ + bufp = asn_build_objid(DestBuf, DestBufLen, + (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_OBJECT_ID), + (oid *) PDU->enterprise, PDU->enterprise_length); + if (bufp == NULL) + return (NULL); + + /* agent-addr */ + bufp = asn_build_string(bufp, DestBufLen, + (u_char) (SMI_IPADDRESS | ASN_PRIMITIVE), + (u_char *) & PDU->agent_addr.sin_addr.s_addr, + sizeof(PDU->agent_addr.sin_addr.s_addr)); + if (bufp == NULL) + return (NULL); + + /* generic trap */ + bufp = asn_build_int(bufp, DestBufLen, + (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_INTEGER), + (int *) &PDU->trap_type, sizeof(PDU->trap_type)); + if (bufp == NULL) + return (NULL); + + /* specific trap */ + bufp = asn_build_int(bufp, DestBufLen, + (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_INTEGER), + (int *) &PDU->specific_type, + sizeof(PDU->specific_type)); + if (bufp == NULL) + return (NULL); + + /* timestamp */ + bufp = asn_build_unsigned_int(bufp, DestBufLen, + (u_char) (SMI_TIMETICKS | ASN_PRIMITIVE), + &PDU->time, sizeof(PDU->time)); + if (bufp == NULL) + return (NULL); + break; #endif -/**********************************************************************/ + /**********************************************************************/ case SNMP_PDU_GETBULK: - /* SNMPv2 Bulk Request */ - - /* request id */ - bufp = asn_build_int(DestBuf, DestBufLen, - (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_INTEGER), - &PDU->reqid, sizeof(PDU->reqid)); - if (bufp == NULL) - return (NULL); - - /* non-repeaters */ - bufp = asn_build_int(bufp, DestBufLen, - (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_INTEGER), - &PDU->non_repeaters, - sizeof(PDU->non_repeaters)); - if (bufp == NULL) - return (NULL); - - /* max-repetitions */ - bufp = asn_build_int(bufp, DestBufLen, - (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_INTEGER), - &PDU->max_repetitions, - sizeof(PDU->max_repetitions)); - if (bufp == NULL) - return (NULL); - break; - -/**********************************************************************/ + /* SNMPv2 Bulk Request */ + + /* request id */ + bufp = asn_build_int(DestBuf, DestBufLen, + (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_INTEGER), + &PDU->reqid, sizeof(PDU->reqid)); + if (bufp == NULL) + return (NULL); + + /* non-repeaters */ + bufp = asn_build_int(bufp, DestBufLen, + (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_INTEGER), + &PDU->non_repeaters, + sizeof(PDU->non_repeaters)); + if (bufp == NULL) + return (NULL); + + /* max-repetitions */ + bufp = asn_build_int(bufp, DestBufLen, + (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_INTEGER), + &PDU->max_repetitions, + sizeof(PDU->max_repetitions)); + if (bufp == NULL) + return (NULL); + break; + + /**********************************************************************/ default: - /* Normal PDU Encoding */ + /* Normal PDU Encoding */ - /* request id */ + /* request id */ #ifdef DEBUG_PDU_ENCODE - snmplib_debug(8, "PDU: Request ID %d (0x%x)\n", PDU->reqid, DestBuf); + snmplib_debug(8, "PDU: Request ID %d (0x%x)\n", PDU->reqid, DestBuf); #endif - bufp = asn_build_int(DestBuf, DestBufLen, - (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_INTEGER), - &PDU->reqid, sizeof(PDU->reqid)); - if (bufp == NULL) - return (NULL); + bufp = asn_build_int(DestBuf, DestBufLen, + (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_INTEGER), + &PDU->reqid, sizeof(PDU->reqid)); + if (bufp == NULL) + return (NULL); - /* error status */ + /* error status */ #ifdef DEBUG_PDU_ENCODE - snmplib_debug(8, "PDU: Error Status %d (0x%x)\n", PDU->errstat, bufp); + snmplib_debug(8, "PDU: Error Status %d (0x%x)\n", PDU->errstat, bufp); #endif - bufp = asn_build_int(bufp, DestBufLen, - (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_INTEGER), - &PDU->errstat, sizeof(PDU->errstat)); - if (bufp == NULL) - return (NULL); + bufp = asn_build_int(bufp, DestBufLen, + (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_INTEGER), + &PDU->errstat, sizeof(PDU->errstat)); + if (bufp == NULL) + return (NULL); - /* error index */ + /* error index */ #ifdef DEBUG_PDU_ENCODE - snmplib_debug(8, "PDU: Error index %d (0x%x)\n", PDU->errindex, bufp); + snmplib_debug(8, "PDU: Error index %d (0x%x)\n", PDU->errindex, bufp); #endif - bufp = asn_build_int(bufp, DestBufLen, - (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_INTEGER), - &PDU->errindex, sizeof(PDU->errindex)); - if (bufp == NULL) - return (NULL); - break; + bufp = asn_build_int(bufp, DestBufLen, + (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_INTEGER), + &PDU->errindex, sizeof(PDU->errindex)); + if (bufp == NULL) + return (NULL); + break; } /* End of encoding */ return (bufp); @@ -483,8 +479,8 @@ snmp_pdu_encode(u_char * DestBuf, int *DestBufLen, */ u_char * snmp_pdu_decode(u_char * Packet, /* data */ - int *Length, /* &length */ - struct snmp_pdu * PDU) + int *Length, /* &length */ + struct snmp_pdu * PDU) { /* pdu */ u_char *bufp; u_char PDUType; @@ -496,7 +492,7 @@ snmp_pdu_decode(u_char * Packet, /* data */ bufp = asn_parse_header(Packet, Length, &PDUType); if (bufp == NULL) - ASN_PARSE_ERROR(NULL); + ASN_PARSE_ERROR(NULL); #ifdef DEBUG_PDU_DECODE snmplib_debug(8, "PDU Type: %d\n", PDUType); @@ -508,125 +504,125 @@ snmp_pdu_decode(u_char * Packet, /* data */ #ifdef TRP_REQ_MSG case TRP_REQ_MSG: - /* SNMPv1 Trap Message */ - - /* enterprise */ - PDU->enterprise_length = MAX_NAME_LEN; - bufp = asn_parse_objid(bufp, Length, - &ASNType, objid, &PDU->enterprise_length); - if (bufp == NULL) - ASN_PARSE_ERROR(NULL); - - PDU->enterprise = (oid *) xmalloc(PDU->enterprise_length * sizeof(oid)); - if (PDU->enterprise == NULL) { - snmp_set_api_error(SNMPERR_OS_ERR); - return (NULL); - } - xmemcpy((char *) PDU->enterprise, (char *) objid, - PDU->enterprise_length * sizeof(oid)); - - /* Agent-addr */ - four = 4; - bufp = asn_parse_string(bufp, Length, - &ASNType, - (u_char *) & PDU->agent_addr.sin_addr.s_addr, - &four); - if (bufp == NULL) - ASN_PARSE_ERROR(NULL); - - /* Generic trap */ - bufp = asn_parse_int(bufp, Length, - &ASNType, - (int *) &PDU->trap_type, - sizeof(PDU->trap_type)); - if (bufp == NULL) - ASN_PARSE_ERROR(NULL); - - /* Specific Trap */ - bufp = asn_parse_int(bufp, Length, - &ASNType, - (int *) &PDU->specific_type, - sizeof(PDU->specific_type)); - if (bufp == NULL) - ASN_PARSE_ERROR(NULL); - - /* Timestamp */ - bufp = asn_parse_unsigned_int(bufp, Length, - &ASNType, - &PDU->time, sizeof(PDU->time)); - if (bufp == NULL) - ASN_PARSE_ERROR(NULL); - break; + /* SNMPv1 Trap Message */ + + /* enterprise */ + PDU->enterprise_length = MAX_NAME_LEN; + bufp = asn_parse_objid(bufp, Length, + &ASNType, objid, &PDU->enterprise_length); + if (bufp == NULL) + ASN_PARSE_ERROR(NULL); + + PDU->enterprise = (oid *) xmalloc(PDU->enterprise_length * sizeof(oid)); + if (PDU->enterprise == NULL) { + snmp_set_api_error(SNMPERR_OS_ERR); + return (NULL); + } + xmemcpy((char *) PDU->enterprise, (char *) objid, + PDU->enterprise_length * sizeof(oid)); + + /* Agent-addr */ + four = 4; + bufp = asn_parse_string(bufp, Length, + &ASNType, + (u_char *) & PDU->agent_addr.sin_addr.s_addr, + &four); + if (bufp == NULL) + ASN_PARSE_ERROR(NULL); + + /* Generic trap */ + bufp = asn_parse_int(bufp, Length, + &ASNType, + (int *) &PDU->trap_type, + sizeof(PDU->trap_type)); + if (bufp == NULL) + ASN_PARSE_ERROR(NULL); + + /* Specific Trap */ + bufp = asn_parse_int(bufp, Length, + &ASNType, + (int *) &PDU->specific_type, + sizeof(PDU->specific_type)); + if (bufp == NULL) + ASN_PARSE_ERROR(NULL); + + /* Timestamp */ + bufp = asn_parse_unsigned_int(bufp, Length, + &ASNType, + &PDU->time, sizeof(PDU->time)); + if (bufp == NULL) + ASN_PARSE_ERROR(NULL); + break; #endif -/**********************************************************************/ + /**********************************************************************/ case SNMP_PDU_GETBULK: - /* SNMPv2 Bulk Request */ - - /* request id */ - bufp = asn_parse_int(bufp, Length, - &ASNType, - &PDU->reqid, sizeof(PDU->reqid)); - if (bufp == NULL) - ASN_PARSE_ERROR(NULL); - - /* non-repeaters */ - bufp = asn_parse_int(bufp, Length, - &ASNType, - &PDU->non_repeaters, sizeof(PDU->non_repeaters)); - if (bufp == NULL) - ASN_PARSE_ERROR(NULL); - - /* max-repetitions */ - bufp = asn_parse_int(bufp, Length, - &ASNType, - &PDU->max_repetitions, sizeof(PDU->max_repetitions)); - if (bufp == NULL) - ASN_PARSE_ERROR(NULL); - break; + /* SNMPv2 Bulk Request */ -/**********************************************************************/ + /* request id */ + bufp = asn_parse_int(bufp, Length, + &ASNType, + &PDU->reqid, sizeof(PDU->reqid)); + if (bufp == NULL) + ASN_PARSE_ERROR(NULL); + + /* non-repeaters */ + bufp = asn_parse_int(bufp, Length, + &ASNType, + &PDU->non_repeaters, sizeof(PDU->non_repeaters)); + if (bufp == NULL) + ASN_PARSE_ERROR(NULL); + + /* max-repetitions */ + bufp = asn_parse_int(bufp, Length, + &ASNType, + &PDU->max_repetitions, sizeof(PDU->max_repetitions)); + if (bufp == NULL) + ASN_PARSE_ERROR(NULL); + break; + + /**********************************************************************/ default: - /* Normal PDU Encoding */ + /* Normal PDU Encoding */ - /* request id */ - bufp = asn_parse_int(bufp, Length, - &ASNType, - &PDU->reqid, sizeof(PDU->reqid)); - if (bufp == NULL) - ASN_PARSE_ERROR(NULL); + /* request id */ + bufp = asn_parse_int(bufp, Length, + &ASNType, + &PDU->reqid, sizeof(PDU->reqid)); + if (bufp == NULL) + ASN_PARSE_ERROR(NULL); #ifdef DEBUG_PDU_DECODE - snmplib_debug(8, "PDU Request ID: %d\n", PDU->reqid); + snmplib_debug(8, "PDU Request ID: %d\n", PDU->reqid); #endif - /* error status */ - bufp = asn_parse_int(bufp, Length, - &ASNType, - &PDU->errstat, sizeof(PDU->errstat)); - if (bufp == NULL) - ASN_PARSE_ERROR(NULL); + /* error status */ + bufp = asn_parse_int(bufp, Length, + &ASNType, + &PDU->errstat, sizeof(PDU->errstat)); + if (bufp == NULL) + ASN_PARSE_ERROR(NULL); #ifdef DEBUG_PDU_DECODE - snmplib_debug(8, "PDU Error Status: %d\n", PDU->errstat); + snmplib_debug(8, "PDU Error Status: %d\n", PDU->errstat); #endif - /* error index */ - bufp = asn_parse_int(bufp, Length, - &ASNType, - &PDU->errindex, sizeof(PDU->errindex)); - if (bufp == NULL) - ASN_PARSE_ERROR(NULL); + /* error index */ + bufp = asn_parse_int(bufp, Length, + &ASNType, + &PDU->errindex, sizeof(PDU->errindex)); + if (bufp == NULL) + ASN_PARSE_ERROR(NULL); #ifdef DEBUG_PDU_DECODE - snmplib_debug(8, "PDU Error Index: %d\n", PDU->errindex); + snmplib_debug(8, "PDU Error Index: %d\n", PDU->errindex); #endif - break; + break; } return (bufp); @@ -644,19 +640,19 @@ snmp_add_null_var(struct snmp_pdu *pdu, oid * name, int name_length) vars = snmp_var_new(name, name_length); if (vars == NULL) { - perror("snmp_add_null_var:xmalloc"); - return; + perror("snmp_add_null_var:xmalloc"); + return; } if (pdu->variables == NULL) { - pdu->variables = vars; + pdu->variables = vars; } else { - /* Insert at the end */ - for (ptr = pdu->variables; - ptr->next_variable; - ptr = ptr->next_variable) - /*EXIT */ ; - ptr->next_variable = vars; + /* Insert at the end */ + for (ptr = pdu->variables; + ptr->next_variable; + ptr = ptr->next_variable) + /*EXIT */ ; + ptr->next_variable = vars; } return; diff --git a/snmplib/snmp_vars.c b/snmplib/snmp_vars.c index d66edf1797..f781e1e6c2 100644 --- a/snmplib/snmp_vars.c +++ b/snmplib/snmp_vars.c @@ -9,9 +9,9 @@ /********************************************************************** * * Copyright 1997 by Carnegie Mellon University - * + * * All Rights Reserved - * + * * Permission to use, copy, modify, and distribute this software and its * documentation for any purpose and without fee is hereby granted, * provided that the above copyright notice appear in all copies and that @@ -19,7 +19,7 @@ * supporting documentation, and that the name of CMU not be * used in advertising or publicity pertaining to distribution of the * software without specific, written prior permission. - * + * * CMU DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING * ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL * CMU BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR @@ -27,9 +27,9 @@ * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS * SOFTWARE. - * + * * Author: Ryan Troll - * + * **********************************************************************/ #include "config.h" @@ -105,8 +105,7 @@ */ struct variable_list * -snmp_var_new(oid * Name, int Len) -{ + snmp_var_new(oid * Name, int Len) { struct variable_list *New; #ifdef DEBUG_VARS @@ -116,8 +115,8 @@ snmp_var_new(oid * Name, int Len) New = xmalloc(sizeof(*New)); /* XXX xmalloc never returns NULL */ if (New == NULL) { - snmp_set_api_error(SNMPERR_OS_ERR); - return (NULL); + snmp_set_api_error(SNMPERR_OS_ERR); + return (NULL); } memset(New, '\0', sizeof(struct variable_list)); /* New->next_variable = NULL; */ @@ -126,15 +125,15 @@ snmp_var_new(oid * Name, int Len) New->name_length = Len; if (New->name_length == 0) { - New->name = NULL; - return (New); + New->name = NULL; + return (New); } New->name = (oid *) xmalloc(Len * sizeof(oid)); /* XXX xmalloc never returns NULL */ if (New->name == NULL) { - xfree(New); - snmp_set_api_error(SNMPERR_OS_ERR); - return (NULL); + xfree(New); + snmp_set_api_error(SNMPERR_OS_ERR); + return (NULL); } #ifdef DEBUG_VARS printf("VARS: Copying name, size (%d)\n", Len); @@ -142,14 +141,13 @@ snmp_var_new(oid * Name, int Len) /* Only copy a name if it was specified. */ if (Name) - xmemcpy((char *) New->name, (char *) Name, Len * sizeof(oid)); + xmemcpy((char *) New->name, (char *) Name, Len * sizeof(oid)); return (New); } struct variable_list * -snmp_var_new_integer(oid * Name, int Len, int ival, unsigned char type) -{ + snmp_var_new_integer(oid * Name, int Len, int ival, unsigned char type) { variable_list *v = snmp_var_new(Name, Len); v->val_len = sizeof(int); v->val.integer = xmalloc(sizeof(int)); @@ -164,8 +162,7 @@ snmp_var_new_integer(oid * Name, int Len, int ival, unsigned char type) */ struct variable_list * -snmp_var_clone(struct variable_list *Src) -{ + snmp_var_clone(struct variable_list *Src) { struct variable_list *Dest; #ifdef DEBUG_VARS @@ -174,43 +171,43 @@ snmp_var_clone(struct variable_list *Src) Dest = (struct variable_list *) xmalloc(sizeof(struct variable_list)); if (Dest == NULL) { - snmp_set_api_error(SNMPERR_OS_ERR); - return (NULL); + snmp_set_api_error(SNMPERR_OS_ERR); + return (NULL); } #ifdef DEBUG_VARS printf("VARS: Copying entire variable list. (Size %d)\n", - sizeof(struct variable_list)); + sizeof(struct variable_list)); #endif xmemcpy((char *) Dest, (char *) Src, sizeof(struct variable_list)); if (Src->name != NULL) { - Dest->name = (oid *) xmalloc(Src->name_length * sizeof(oid)); - if (Dest->name == NULL) { - snmp_set_api_error(SNMPERR_OS_ERR); - xfree(Dest); - return (NULL); - } + Dest->name = (oid *) xmalloc(Src->name_length * sizeof(oid)); + if (Dest->name == NULL) { + snmp_set_api_error(SNMPERR_OS_ERR); + xfree(Dest); + return (NULL); + } #ifdef DEBUG_VARS - printf("VARS: Copying name OID. (Size %d)\n", Src->name_length); + printf("VARS: Copying name OID. (Size %d)\n", Src->name_length); #endif - xmemcpy((char *) Dest->name, (char *) Src->name, - Src->name_length * sizeof(oid)); + xmemcpy((char *) Dest->name, (char *) Src->name, + Src->name_length * sizeof(oid)); } /* CISCO Catalyst 2900 returns NULL strings as data of length 0. */ if ((Src->val.string != NULL) && - (Src->val_len)) { - Dest->val.string = (u_char *) xmalloc(Src->val_len); - if (Dest->val.string == NULL) { - snmp_set_api_error(SNMPERR_OS_ERR); - xfree(Dest->name); - xfree(Dest); - return (NULL); - } + (Src->val_len)) { + Dest->val.string = (u_char *) xmalloc(Src->val_len); + if (Dest->val.string == NULL) { + snmp_set_api_error(SNMPERR_OS_ERR); + xfree(Dest->name); + xfree(Dest); + return (NULL); + } #ifdef DEBUG_VARS - printf("VARS: Copying value (Size %d)\n", Src->val_len); + printf("VARS: Copying value (Size %d)\n", Src->val_len); #endif - xmemcpy((char *) Dest->val.string, (char *) Src->val.string, Src->val_len); + xmemcpy((char *) Dest->val.string, (char *) Src->val.string, Src->val_len); } #ifdef DEBUG_VARS printf("VARS: Cloned %x.\n", (unsigned int) Dest); @@ -229,12 +226,12 @@ void snmp_var_free(struct variable_list *Ptr) { if (Ptr->name) - xfree((char *) Ptr->name); + xfree((char *) Ptr->name); if (Ptr->val.string) - xfree((char *) Ptr->val.string); + xfree((char *) Ptr->val.string); else if (Ptr->val.integer) - xfree((char *) Ptr->val.integer); + xfree((char *) Ptr->val.integer); xfree(Ptr); } @@ -245,7 +242,7 @@ snmp_var_free(struct variable_list *Ptr) * * RFC 1905: Protocol Operations for SNMPv2 * - * VarBind ::= + * VarBind ::= * SEQUENCE { * name ObjectName * CHOICE { @@ -259,8 +256,8 @@ snmp_var_free(struct variable_list *Ptr) */ u_char * snmp_var_EncodeVarBind(u_char * Buffer, int *BufLenP, - variable_list * VarList, - int Version) + variable_list * VarList, + int Version) { struct variable_list *Vars; u_char *bufp; @@ -272,92 +269,92 @@ snmp_var_EncodeVarBind(u_char * Buffer, int *BufLenP, for (Vars = VarList; Vars; Vars = Vars->next_variable) { - /* Build the header for this variable - * - * Use Maximum size. - */ - HeaderStart = bufp; - HeaderEnd = asn_build_header(HeaderStart, BufLenP, - (u_char) (ASN_SEQUENCE | ASN_CONSTRUCTOR), - FakeArg); - if (HeaderEnd == NULL) - return (NULL); - - /* Now, let's put the Object Identifier into the buffer */ - bufp = asn_build_objid(HeaderEnd, BufLenP, - (u_char) (ASN_UNIVERSAL | - ASN_PRIMITIVE | - ASN_OBJECT_ID), - Vars->name, Vars->name_length); - if (bufp == NULL) - return (NULL); - - /* Now put the data in */ - switch (Vars->type) { - - case ASN_INTEGER: - bufp = asn_build_int(bufp, - BufLenP, Vars->type, - (int *) Vars->val.integer, Vars->val_len); - break; - - case SMI_COUNTER32: - case SMI_GAUGE32: - /* case SMI_UNSIGNED32: */ - case SMI_TIMETICKS: - bufp = asn_build_unsigned_int(bufp, BufLenP, - Vars->type, - (u_int *) Vars->val.integer, Vars->val_len); - break; - - case ASN_OCTET_STR: - case SMI_IPADDRESS: - case SMI_OPAQUE: - bufp = asn_build_string(bufp, BufLenP, Vars->type, - Vars->val.string, Vars->val_len); - break; - - case ASN_OBJECT_ID: - bufp = asn_build_objid(bufp, BufLenP, Vars->type, - (oid *) Vars->val.objid, Vars->val_len / sizeof(oid)); - break; - - case SMI_NOSUCHINSTANCE: - case SMI_NOSUCHOBJECT: - case SMI_ENDOFMIBVIEW: - if (Version == SNMP_VERSION_1) { - /* SNMP Version 1 does not support these error codes. */ - bufp = asn_build_null(bufp, BufLenP, SMI_NOSUCHOBJECT); - } else { - bufp = asn_build_exception(bufp, BufLenP, Vars->type); - } - break; - - case ASN_NULL: - bufp = asn_build_null(bufp, BufLenP, Vars->type); - break; - - case SMI_COUNTER64: - snmplib_debug(2, "Unable to encode type SMI_COUNTER64!\n"); - /* Fall through */ - - default: - snmp_set_api_error(SNMPERR_UNSUPPORTED_TYPE); - return (NULL); - } - - /* ASSERT: bufp should now point to the next valid byte. */ - if (bufp == NULL) - return (NULL); - - /* Rebuild the header with the appropriate length */ - HeaderEnd = asn_build_header(HeaderStart, &FakeArg, - (u_char) (ASN_SEQUENCE | ASN_CONSTRUCTOR), - (bufp - HeaderEnd)); - - /* Returns NULL */ - if (HeaderEnd == NULL) - return (NULL); + /* Build the header for this variable + * + * Use Maximum size. + */ + HeaderStart = bufp; + HeaderEnd = asn_build_header(HeaderStart, BufLenP, + (u_char) (ASN_SEQUENCE | ASN_CONSTRUCTOR), + FakeArg); + if (HeaderEnd == NULL) + return (NULL); + + /* Now, let's put the Object Identifier into the buffer */ + bufp = asn_build_objid(HeaderEnd, BufLenP, + (u_char) (ASN_UNIVERSAL | + ASN_PRIMITIVE | + ASN_OBJECT_ID), + Vars->name, Vars->name_length); + if (bufp == NULL) + return (NULL); + + /* Now put the data in */ + switch (Vars->type) { + + case ASN_INTEGER: + bufp = asn_build_int(bufp, + BufLenP, Vars->type, + (int *) Vars->val.integer, Vars->val_len); + break; + + case SMI_COUNTER32: + case SMI_GAUGE32: + /* case SMI_UNSIGNED32: */ + case SMI_TIMETICKS: + bufp = asn_build_unsigned_int(bufp, BufLenP, + Vars->type, + (u_int *) Vars->val.integer, Vars->val_len); + break; + + case ASN_OCTET_STR: + case SMI_IPADDRESS: + case SMI_OPAQUE: + bufp = asn_build_string(bufp, BufLenP, Vars->type, + Vars->val.string, Vars->val_len); + break; + + case ASN_OBJECT_ID: + bufp = asn_build_objid(bufp, BufLenP, Vars->type, + (oid *) Vars->val.objid, Vars->val_len / sizeof(oid)); + break; + + case SMI_NOSUCHINSTANCE: + case SMI_NOSUCHOBJECT: + case SMI_ENDOFMIBVIEW: + if (Version == SNMP_VERSION_1) { + /* SNMP Version 1 does not support these error codes. */ + bufp = asn_build_null(bufp, BufLenP, SMI_NOSUCHOBJECT); + } else { + bufp = asn_build_exception(bufp, BufLenP, Vars->type); + } + break; + + case ASN_NULL: + bufp = asn_build_null(bufp, BufLenP, Vars->type); + break; + + case SMI_COUNTER64: + snmplib_debug(2, "Unable to encode type SMI_COUNTER64!\n"); + /* Fall through */ + + default: + snmp_set_api_error(SNMPERR_UNSUPPORTED_TYPE); + return (NULL); + } + + /* ASSERT: bufp should now point to the next valid byte. */ + if (bufp == NULL) + return (NULL); + + /* Rebuild the header with the appropriate length */ + HeaderEnd = asn_build_header(HeaderStart, &FakeArg, + (u_char) (ASN_SEQUENCE | ASN_CONSTRUCTOR), + (bufp - HeaderEnd)); + + /* Returns NULL */ + if (HeaderEnd == NULL) + return (NULL); } @@ -371,8 +368,8 @@ snmp_var_EncodeVarBind(u_char * Buffer, int *BufLenP, /* Parse all Vars from the buffer */ u_char * snmp_var_DecodeVarBind(u_char * Buffer, int *BufLen, - struct variable_list ** VarP, - int Version) + struct variable_list ** VarP, + int Version) { struct variable_list *Var = NULL, **VarLastP; u_char *bufp, *tmp; @@ -392,11 +389,11 @@ snmp_var_DecodeVarBind(u_char * Buffer, int *BufLen, /* Now parse the variables */ bufp = asn_parse_header(Buffer, &AllVarLen, &VarBindType); if (bufp == NULL) - return (NULL); + return (NULL); if (VarBindType != (u_char) (ASN_SEQUENCE | ASN_CONSTRUCTOR)) { - snmp_set_api_error(SNMPERR_PDU_PARSE); - return (NULL); + snmp_set_api_error(SNMPERR_PDU_PARSE); + return (NULL); } #ifdef DEBUG_VARS_DECODE printf("VARS: All Variable length %d\n", AllVarLen); @@ -407,166 +404,166 @@ snmp_var_DecodeVarBind(u_char * Buffer, int *BufLen, /* We know how long the variable list is. Parse it. */ while ((int) AllVarLen > 0) { - /* Create a new variable */ - Var = snmp_var_new(NULL, MAX_NAME_LEN); - if (Var == NULL) - return (NULL); - - /* Parse the header to find out the length of this variable. */ - ThisVarLen = AllVarLen; - tmp = asn_parse_header(bufp, &ThisVarLen, &VarBindType); - if (tmp == NULL) - PARSE_ERROR; - - /* Now that we know the length , figure out how it relates to - * the entire variable list - */ - AllVarLen = AllVarLen - (ThisVarLen + (tmp - bufp)); - bufp = tmp; - - /* Is it valid? */ - if (VarBindType != (u_char) (ASN_SEQUENCE | ASN_CONSTRUCTOR)) { - snmp_set_api_error(SNMPERR_PDU_PARSE); - PARSE_ERROR; - } + /* Create a new variable */ + Var = snmp_var_new(NULL, MAX_NAME_LEN); + if (Var == NULL) + return (NULL); + + /* Parse the header to find out the length of this variable. */ + ThisVarLen = AllVarLen; + tmp = asn_parse_header(bufp, &ThisVarLen, &VarBindType); + if (tmp == NULL) + PARSE_ERROR; + + /* Now that we know the length , figure out how it relates to + * the entire variable list + */ + AllVarLen = AllVarLen - (ThisVarLen + (tmp - bufp)); + bufp = tmp; + + /* Is it valid? */ + if (VarBindType != (u_char) (ASN_SEQUENCE | ASN_CONSTRUCTOR)) { + snmp_set_api_error(SNMPERR_PDU_PARSE); + PARSE_ERROR; + } #ifdef DEBUG_VARS_DECODE - printf("VARS: Header type 0x%x (%d bytes left)\n", VarBindType, ThisVarLen); + printf("VARS: Header type 0x%x (%d bytes left)\n", VarBindType, ThisVarLen); #endif - /* Parse the OBJID */ - bufp = asn_parse_objid(bufp, &ThisVarLen, &VarBindType, - Var->name, &(Var->name_length)); - if (bufp == NULL) - PARSE_ERROR; + /* Parse the OBJID */ + bufp = asn_parse_objid(bufp, &ThisVarLen, &VarBindType, + Var->name, &(Var->name_length)); + if (bufp == NULL) + PARSE_ERROR; - if (VarBindType != (u_char) (ASN_UNIVERSAL | - ASN_PRIMITIVE | - ASN_OBJECT_ID)) { - snmp_set_api_error(SNMPERR_PDU_PARSE); - PARSE_ERROR; - } + if (VarBindType != (u_char) (ASN_UNIVERSAL | + ASN_PRIMITIVE | + ASN_OBJECT_ID)) { + snmp_set_api_error(SNMPERR_PDU_PARSE); + PARSE_ERROR; + } #ifdef DEBUG_VARS_DECODE - printf("VARS: Decoded OBJID (%d bytes). (%d bytes left)\n", - Var->name_length, ThisVarLen); + printf("VARS: Decoded OBJID (%d bytes). (%d bytes left)\n", + Var->name_length, ThisVarLen); #endif - /* Keep a pointer to this object */ - DataPtr = bufp; - DataLen = ThisVarLen; + /* Keep a pointer to this object */ + DataPtr = bufp; + DataLen = ThisVarLen; - /* find out type of object */ - bufp = asn_parse_header(bufp, &ThisVarLen, &(Var->type)); - if (bufp == NULL) - PARSE_ERROR; - ThisVarLen = DataLen; + /* find out type of object */ + bufp = asn_parse_header(bufp, &ThisVarLen, &(Var->type)); + if (bufp == NULL) + PARSE_ERROR; + ThisVarLen = DataLen; #ifdef DEBUG_VARS_DECODE - printf("VARS: Data type %d\n", Var->type); + printf("VARS: Data type %d\n", Var->type); #endif - /* Parse the type */ + /* Parse the type */ - switch ((short) Var->type) { + switch ((short) Var->type) { - case ASN_INTEGER: - Var->val.integer = (int *) xmalloc(sizeof(int)); - if (Var->val.integer == NULL) { - snmp_set_api_error(SNMPERR_OS_ERR); - PARSE_ERROR; - } - Var->val_len = sizeof(int); - bufp = asn_parse_int(DataPtr, &ThisVarLen, - &Var->type, (int *) Var->val.integer, - Var->val_len); + case ASN_INTEGER: + Var->val.integer = (int *) xmalloc(sizeof(int)); + if (Var->val.integer == NULL) { + snmp_set_api_error(SNMPERR_OS_ERR); + PARSE_ERROR; + } + Var->val_len = sizeof(int); + bufp = asn_parse_int(DataPtr, &ThisVarLen, + &Var->type, (int *) Var->val.integer, + Var->val_len); #ifdef DEBUG_VARS_DECODE - printf("VARS: Decoded integer '%d' (%d bytes left)\n", - *(Var->val.integer), ThisVarLen); -#endif - break; - - case SMI_COUNTER32: - case SMI_GAUGE32: - /* case SMI_UNSIGNED32: */ - case SMI_TIMETICKS: - Var->val.integer = (int *) xmalloc(sizeof(u_int)); - if (Var->val.integer == NULL) { - snmp_set_api_error(SNMPERR_OS_ERR); - PARSE_ERROR; - } - Var->val_len = sizeof(u_int); - bufp = asn_parse_unsigned_int(DataPtr, &ThisVarLen, - &Var->type, (u_int *) Var->val.integer, - Var->val_len); + printf("VARS: Decoded integer '%d' (%d bytes left)\n", + *(Var->val.integer), ThisVarLen); +#endif + break; + + case SMI_COUNTER32: + case SMI_GAUGE32: + /* case SMI_UNSIGNED32: */ + case SMI_TIMETICKS: + Var->val.integer = (int *) xmalloc(sizeof(u_int)); + if (Var->val.integer == NULL) { + snmp_set_api_error(SNMPERR_OS_ERR); + PARSE_ERROR; + } + Var->val_len = sizeof(u_int); + bufp = asn_parse_unsigned_int(DataPtr, &ThisVarLen, + &Var->type, (u_int *) Var->val.integer, + Var->val_len); #ifdef DEBUG_VARS_DECODE - printf("VARS: Decoded timeticks '%d' (%d bytes left)\n", - *(Var->val.integer), ThisVarLen); -#endif - break; - - case ASN_OCTET_STR: - case SMI_IPADDRESS: - case SMI_OPAQUE: - Var->val_len = *&ThisVarLen; /* String is this at most */ - Var->val.string = (u_char *) xmalloc((unsigned) Var->val_len); - if (Var->val.string == NULL) { - snmp_set_api_error(SNMPERR_OS_ERR); - PARSE_ERROR; - } - bufp = asn_parse_string(DataPtr, &ThisVarLen, - &Var->type, Var->val.string, - &Var->val_len); + printf("VARS: Decoded timeticks '%d' (%d bytes left)\n", + *(Var->val.integer), ThisVarLen); +#endif + break; + + case ASN_OCTET_STR: + case SMI_IPADDRESS: + case SMI_OPAQUE: + Var->val_len = *&ThisVarLen; /* String is this at most */ + Var->val.string = (u_char *) xmalloc((unsigned) Var->val_len); + if (Var->val.string == NULL) { + snmp_set_api_error(SNMPERR_OS_ERR); + PARSE_ERROR; + } + bufp = asn_parse_string(DataPtr, &ThisVarLen, + &Var->type, Var->val.string, + &Var->val_len); #ifdef DEBUG_VARS_DECODE - printf("VARS: Decoded string '%s' (length %d) (%d bytes left)\n", - (Var->val.string), Var->val_len, ThisVarLen); -#endif - break; - - case ASN_OBJECT_ID: - Var->val_len = MAX_NAME_LEN; - bufp = asn_parse_objid(DataPtr, &ThisVarLen, - &Var->type, TmpBuf, &Var->val_len); - Var->val_len *= sizeof(oid); - Var->val.objid = (oid *) xmalloc((unsigned) Var->val_len); - if (Var->val.integer == NULL) { - snmp_set_api_error(SNMPERR_OS_ERR); - PARSE_ERROR; - } - /* Only copy if we successfully decoded something */ - if (bufp) { - xmemcpy((char *) Var->val.objid, (char *) TmpBuf, Var->val_len); - } + printf("VARS: Decoded string '%s' (length %d) (%d bytes left)\n", + (Var->val.string), Var->val_len, ThisVarLen); +#endif + break; + + case ASN_OBJECT_ID: + Var->val_len = MAX_NAME_LEN; + bufp = asn_parse_objid(DataPtr, &ThisVarLen, + &Var->type, TmpBuf, &Var->val_len); + Var->val_len *= sizeof(oid); + Var->val.objid = (oid *) xmalloc((unsigned) Var->val_len); + if (Var->val.integer == NULL) { + snmp_set_api_error(SNMPERR_OS_ERR); + PARSE_ERROR; + } + /* Only copy if we successfully decoded something */ + if (bufp) { + xmemcpy((char *) Var->val.objid, (char *) TmpBuf, Var->val_len); + } #ifdef DEBUG_VARS_DECODE - printf("VARS: Decoded OBJID (length %d) (%d bytes left)\n", - Var->val_len, ThisVarLen); + printf("VARS: Decoded OBJID (length %d) (%d bytes left)\n", + Var->val_len, ThisVarLen); #endif - break; + break; - case ASN_NULL: - case SMI_NOSUCHINSTANCE: - case SMI_NOSUCHOBJECT: - case SMI_ENDOFMIBVIEW: - break; + case ASN_NULL: + case SMI_NOSUCHINSTANCE: + case SMI_NOSUCHOBJECT: + case SMI_ENDOFMIBVIEW: + break; - case SMI_COUNTER64: - snmplib_debug(2, "Unable to parse type SMI_COUNTER64!\n"); - snmp_set_api_error(SNMPERR_UNSUPPORTED_TYPE); - PARSE_ERROR; + case SMI_COUNTER64: + snmplib_debug(2, "Unable to parse type SMI_COUNTER64!\n"); + snmp_set_api_error(SNMPERR_UNSUPPORTED_TYPE); + PARSE_ERROR; - default: - snmplib_debug(2, "bad type returned (%x)\n", Var->type); - snmp_set_api_error(SNMPERR_PDU_PARSE); - PARSE_ERROR; - } /* End of var type switch */ + default: + snmplib_debug(2, "bad type returned (%x)\n", Var->type); + snmp_set_api_error(SNMPERR_PDU_PARSE); + PARSE_ERROR; + } /* End of var type switch */ - if (bufp == NULL) - PARSE_ERROR; + if (bufp == NULL) + PARSE_ERROR; #ifdef DEBUG_VARS_DECODE - printf("VARS: Adding to list.\n"); + printf("VARS: Adding to list.\n"); #endif - /* Add variable to the list */ - *VarLastP = Var; - VarLastP = &(Var->next_variable); + /* Add variable to the list */ + *VarLastP = Var; + VarLastP = &(Var->next_variable); } #undef PARSE_ERROR diff --git a/snmplib/snmplib_debug.c b/snmplib/snmplib_debug.c index 9b3ada60b3..63ca248f97 100644 --- a/snmplib/snmplib_debug.c +++ b/snmplib/snmplib_debug.c @@ -21,15 +21,14 @@ void (*snmplib_debug_hook) (va_alist) = NULL; extern void #if STDC_HEADERS -snmplib_debug(int lvl, const char *fmt,...) + snmplib_debug(int lvl, const char *fmt,...) { char buf[BUFSIZ]; va_list args; va_start(args, fmt); #else -snmplib_debug(va_alist) - va_dcl -{ + snmplib_debug(va_alist) + va_dcl { va_list args; int lvl; char char *fmt; @@ -39,10 +38,10 @@ snmplib_debug(va_alist) fmt = va_arg(args, char *); #endif if (snmplib_debug_hook != NULL) { - vsnprintf(buf, BUFSIZ, fmt, args); - snmplib_debug_hook(lvl, buf); + vsnprintf(buf, BUFSIZ, fmt, args); + snmplib_debug_hook(lvl, buf); } else { - vfprintf(stderr, fmt, args); + vfprintf(stderr, fmt, args); } va_end(args); } diff --git a/src/ACL.h b/src/ACL.h index 7aa35d5b3f..f88ba4e74f 100644 --- a/src/ACL.h +++ b/src/ACL.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLARP.cc b/src/ACLARP.cc index 58918ff9ac..32b749b6c2 100644 --- a/src/ACLARP.cc +++ b/src/ACLARP.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -44,8 +44,7 @@ #ifdef _SQUID_WIN32_ -struct arpreq -{ +struct arpreq { IPAddress arp_pa; /* protocol address */ @@ -134,17 +133,17 @@ ACLARP::empty () const * Subject: Another Squid patch... :) * Date: Thu, 04 Dec 1997 19:55:01 +0300 * ============================================================================ - * + * * Working on setting up a proper firewall for a network containing some * Win'95 computers at our Univ, I've discovered that some smart students * avoid the restrictions easily just changing their IP addresses in Win'95 * Contol Panel... It has been getting boring, so I took Squid-1.1.18 * sources and added a new acl type for hard-wired access control: - * + * * acl arp ... - * + * * For example, - * + * * acl students arp 00:00:21:55:ed:22 00:00:21:ff:55:38 * * NOTE: Linux code by David Luyer . @@ -231,8 +230,7 @@ int ACLARP::match(ACLChecklist *checklist) { /* IPv6 does not do ARP */ - if(!checklist->src_addr.IsIPv4()) - { + if (!checklist->src_addr.IsIPv4()) { debugs(14, 3, "ACLARP::match: IPv4 Required for ARP Lookups. Skipping " << checklist->src_addr ); return 0; } @@ -263,10 +261,10 @@ aclMatchArp(SplayNode **dataptr, IPAddress &c) /* * The linux kernel 2.2 maintains per interface ARP caches and * thus requires an interface name when doing ARP queries. - * + * * The older 2.0 kernels appear to use a unified ARP cache, * and require an empty interface name - * + * * To support both, we attempt the lookup with a blank interface * name first. If that does not succeed, the try each interface * in turn diff --git a/src/ACLARP.h b/src/ACLARP.h index a25eb5bed4..7a7a3a1ad0 100644 --- a/src/ACLARP.h +++ b/src/ACLARP.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -40,8 +40,7 @@ #include "splay.h" /// \ingroup ACLAPI -struct acl_arp_data -{ +struct acl_arp_data { char eth[6]; }; diff --git a/src/ACLASN.cc b/src/ACLASN.cc index b410b21fdc..61fbc4d098 100644 --- a/src/ACLASN.cc +++ b/src/ACLASN.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLASN.h b/src/ACLASN.h index d6223adb2e..a2bffe626e 100644 --- a/src/ACLASN.h +++ b/src/ACLASN.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLBrowser.cc b/src/ACLBrowser.cc index 4ce7d5ca5e..1a2712f17e 100644 --- a/src/ACLBrowser.cc +++ b/src/ACLBrowser.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLBrowser.h b/src/ACLBrowser.h index 65e9d89608..659c94b1ec 100644 --- a/src/ACLBrowser.h +++ b/src/ACLBrowser.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLCertificate.cc b/src/ACLCertificate.cc index e3966c9589..92b3cfb0b8 100644 --- a/src/ACLCertificate.cc +++ b/src/ACLCertificate.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLCertificate.h b/src/ACLCertificate.h index b608db469a..7986fa03a1 100644 --- a/src/ACLCertificate.h +++ b/src/ACLCertificate.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -55,7 +55,7 @@ public: private: static ACLCertificateStrategy Instance_; - ACLCertificateStrategy(){} + ACLCertificateStrategy() {} ACLCertificateStrategy&operator=(ACLCertificateStrategy const &); }; diff --git a/src/ACLCertificateData.cc b/src/ACLCertificateData.cc index bf5b9efb94..05cf5be035 100644 --- a/src/ACLCertificateData.cc +++ b/src/ACLCertificateData.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLCertificateData.h b/src/ACLCertificateData.h index efc5ca7d3f..30c5ec3527 100644 --- a/src/ACLCertificateData.h +++ b/src/ACLCertificateData.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLChecklist.cc b/src/ACLChecklist.cc index e41ebb01c8..37ea646b6b 100644 --- a/src/ACLChecklist.cc +++ b/src/ACLChecklist.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -78,7 +78,7 @@ ACLChecklist::authenticated() AuthUserRequest *old_auth_user_request = auth_user_request; auth_acl_t result = AuthUserRequest::tryToAuthenticateAndSetAuthUser (&auth_user_request, headertype, request, conn(), src_addr); if (auth_user_request) - AUTHUSERREQUESTLOCK(auth_user_request, "ACLChecklist"); + AUTHUSERREQUESTLOCK(auth_user_request, "ACLChecklist"); AUTHUSERREQUESTUNLOCK(old_auth_user_request, "old ACLChecklist"); switch (result) { @@ -129,8 +129,8 @@ ACLChecklist::check() currentAnswer(ACCESS_DENIED); if (callerGone()) { - checkCallback(currentAnswer()); - return; + checkCallback(currentAnswer()); + return; } /* NOTE: This holds a cbdata reference to the current access_list @@ -253,15 +253,15 @@ ACLChecklist::checkCallback(allow_t answer) if (auth_user_request) { /* the checklist lock */ - AUTHUSERREQUESTUNLOCK(auth_user_request, "ACLChecklist"); + AUTHUSERREQUESTUNLOCK(auth_user_request, "ACLChecklist"); /* it might have been connection based */ assert(conn() != NULL); - /* - * DPW 2007-05-08 - * yuck, this make me uncomfortable. why do this here? - * ConnStateData will do its own unlocking. - */ - AUTHUSERREQUESTUNLOCK(conn()->auth_user_request, "conn via ACLChecklist"); + /* + * DPW 2007-05-08 + * yuck, this make me uncomfortable. why do this here? + * ConnStateData will do its own unlocking. + */ + AUTHUSERREQUESTUNLOCK(conn()->auth_user_request, "conn via ACLChecklist"); conn()->auth_type = AUTH_BROKEN; } @@ -294,10 +294,10 @@ ACLChecklist::matchAclList(const ACLList * head, bool const fast) if (fast) changeState(NullState::Instance()); - if (finished()) { - PROF_stop(aclMatchAclList); - return; - } + if (finished()) { + PROF_stop(aclMatchAclList); + return; + } if (!nodeMatched || state_ != NullState::Instance()) { debugs(28, 3, "aclmatchAclList: " << this << " returning false (AND list entry failed to match)"); @@ -311,12 +311,12 @@ ACLChecklist::matchAclList(const ACLList * head, bool const fast) " nodeMatched=" << (nodeMatched ? 1 : 0) << " async_in_progress=" << (async_in_progress ? 1 : 0) << " lastACLResult() = " << (lastACLResult() ? 1 : 0) << - " finished() = " << finished()); + " finished() = " << finished()); - if (finished()) { - PROF_stop(aclMatchAclList); - return; - } + if (finished()) { + PROF_stop(aclMatchAclList); + return; + } if (async && nodeMatched && !asyncInProgress() && lastACLResult()) { // async acl, but using cached response, and it was a match @@ -449,7 +449,7 @@ ACLChecklist::NullState::Instance() void ACLChecklist::NullState::checkForAsync(ACLChecklist *) const - {} +{} ACLChecklist::NullState ACLChecklist::NullState::_instance; @@ -582,8 +582,7 @@ aclChecklistCreate(const acl_access * A, HttpRequest * request, const char *iden if (A) checklist->accessList = cbdataReference(A); - if (request != NULL) - { + if (request != NULL) { checklist->request = HTTPMSGLOCK(request); #if FOLLOW_X_FORWARDED_FOR if (Config.onoff.acl_uses_indirect_client) diff --git a/src/ACLChecklist.cci b/src/ACLChecklist.cci index 898729b005..2de22fe5d3 100644 --- a/src/ACLChecklist.cci +++ b/src/ACLChecklist.cci @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLChecklist.h b/src/ACLChecklist.h index bd7cc340e4..72a0cced07 100644 --- a/src/ACLChecklist.h +++ b/src/ACLChecklist.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -72,7 +72,7 @@ public: void changeState (ACLChecklist *, AsyncState *) const; }; -class NullState : public AsyncState + class NullState : public AsyncState { public: diff --git a/src/ACLData.h b/src/ACLData.h index d8e887665b..dfb97c8152 100644 --- a/src/ACLData.h +++ b/src/ACLData.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLDestinationASN.h b/src/ACLDestinationASN.h index ada67cb327..0c2dd11d8f 100644 --- a/src/ACLDestinationASN.h +++ b/src/ACLDestinationASN.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -59,7 +59,7 @@ public: private: static ACLDestinationASNStrategy Instance_; - ACLDestinationASNStrategy(){} + ACLDestinationASNStrategy() {} ACLDestinationASNStrategy&operator=(ACLDestinationASNStrategy const &); }; diff --git a/src/ACLDestinationDomain.cc b/src/ACLDestinationDomain.cc index 4e8ef75516..f85ee54900 100644 --- a/src/ACLDestinationDomain.cc +++ b/src/ACLDestinationDomain.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLDestinationDomain.h b/src/ACLDestinationDomain.h index 6e11db0e27..e8f1312eb3 100644 --- a/src/ACLDestinationDomain.h +++ b/src/ACLDestinationDomain.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -47,7 +47,7 @@ class ACLDestinationDomainStrategy : public ACLStrategy public: virtual int match (ACLData * &, ACLChecklist *); static ACLDestinationDomainStrategy *Instance(); - + /** * Not implemented to prevent copies of the instance. \par @@ -58,7 +58,7 @@ public: private: static ACLDestinationDomainStrategy Instance_; - ACLDestinationDomainStrategy(){} + ACLDestinationDomainStrategy() {} ACLDestinationDomainStrategy&operator=(ACLDestinationDomainStrategy const &); }; diff --git a/src/ACLDestinationIP.cc b/src/ACLDestinationIP.cc index 4f0042e2fd..c04ad0e30d 100644 --- a/src/ACLDestinationIP.cc +++ b/src/ACLDestinationIP.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLDestinationIP.h b/src/ACLDestinationIP.h index d0bdb94684..8d18545213 100644 --- a/src/ACLDestinationIP.h +++ b/src/ACLDestinationIP.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLDomainData.cc b/src/ACLDomainData.cc index fb173eb20b..81051ab338 100644 --- a/src/ACLDomainData.cc +++ b/src/ACLDomainData.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLDomainData.h b/src/ACLDomainData.h index 32702aa511..c1ceecd3a0 100644 --- a/src/ACLDomainData.h +++ b/src/ACLDomainData.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLExtUser.cc b/src/ACLExtUser.cc index 18936f214b..58140e1295 100644 --- a/src/ACLExtUser.cc +++ b/src/ACLExtUser.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLExtUser.h b/src/ACLExtUser.h index 50ba252c6e..5222aef64f 100644 --- a/src/ACLExtUser.h +++ b/src/ACLExtUser.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLHTTPHeaderData.cc b/src/ACLHTTPHeaderData.cc index 9cd09df1ae..3bda497c15 100644 --- a/src/ACLHTTPHeaderData.cc +++ b/src/ACLHTTPHeaderData.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -46,7 +46,7 @@ /* Construct an ACLHTTPHeaderData that uses an ACLRegex rule with the value of the * selected header from a given request. * - * TODO: This can be generalised by making the type of the regex_rule into a + * TODO: This can be generalised by making the type of the regex_rule into a * template parameter - so that we can use different rules types in future. */ ACLHTTPHeaderData::ACLHTTPHeaderData() : hdrId(HDR_BAD_HDR), regex_rule(new ACLRegexData) diff --git a/src/ACLHTTPHeaderData.h b/src/ACLHTTPHeaderData.h index af3a760721..06a60e5793 100644 --- a/src/ACLHTTPHeaderData.h +++ b/src/ACLHTTPHeaderData.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLHTTPRepHeader.cc b/src/ACLHTTPRepHeader.cc index 1623ad8679..a67a791421 100644 --- a/src/ACLHTTPRepHeader.cc +++ b/src/ACLHTTPRepHeader.cc @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLHTTPRepHeader.h b/src/ACLHTTPRepHeader.h index 0415945d00..603dfb1217 100644 --- a/src/ACLHTTPRepHeader.h +++ b/src/ACLHTTPRepHeader.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLHTTPReqHeader.cc b/src/ACLHTTPReqHeader.cc index 5dde2458dc..24a59c402a 100644 --- a/src/ACLHTTPReqHeader.cc +++ b/src/ACLHTTPReqHeader.cc @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLHTTPReqHeader.h b/src/ACLHTTPReqHeader.h index a4b2f7d467..08413430a1 100644 --- a/src/ACLHTTPReqHeader.h +++ b/src/ACLHTTPReqHeader.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLHTTPStatus.cc b/src/ACLHTTPStatus.cc index 4040f80a89..52bf9c87f9 100644 --- a/src/ACLHTTPStatus.cc +++ b/src/ACLHTTPStatus.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLHTTPStatus.h b/src/ACLHTTPStatus.h index 2d67f3b480..df458a0e7c 100644 --- a/src/ACLHTTPStatus.h +++ b/src/ACLHTTPStatus.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -40,8 +40,7 @@ #include "splay.h" /// \ingroup ACLAPI -struct acl_httpstatus_data -{ +struct acl_httpstatus_data { int status1, status2; acl_httpstatus_data(int); acl_httpstatus_data(int, int); diff --git a/src/ACLIP.cc b/src/ACLIP.cc index 28c6534879..9206ee47f9 100644 --- a/src/ACLIP.cc +++ b/src/ACLIP.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -96,24 +96,24 @@ acl_ip_data::toStr(char *buf, int len) const b2 = buf + rlen; if (!addr2.IsAnyAddr()) { - b2[0] = '-'; rlen++; + b2[0] = '-'; + rlen++; addr2.NtoA(&(b2[1]), len - rlen ); rlen = strlen(buf); - } - else + } else b2[0] = '\0'; b3 = buf + rlen; if (!mask.IsNoAddr()) { - b3[0] = '/'; rlen++; + b3[0] = '/'; + rlen++; #if USE_IPV6 snprintf(&(b3[1]), (len-rlen), "%u", mask.GetCIDR() - (addr1.IsIPv4()?96:0) ); #else snprintf(&(b3[1]), (len-rlen), "%u", mask.GetCIDR() ); #endif - } - else + } else b3[0] = '\0'; } @@ -170,7 +170,7 @@ acl_ip_data::NetworkCompare(acl_ip_data * const & a, acl_ip_data * const &b) if (ret == 0) { char buf_n1[3*(MAX_IPSTRLEN+1)]; char buf_n2[3*(MAX_IPSTRLEN+1)]; - if(bina) { + if (bina) { b->toStr(buf_n1, 3*(MAX_IPSTRLEN+1)); a->toStr(buf_n2, 3*(MAX_IPSTRLEN+1)); } else { @@ -199,16 +199,14 @@ acl_ip_data::DecodeMask(const char *asc, IPAddress &mask, int ctype) /* default is a mask that doesn't change any IP */ mask.SetNoAddr(); - if (!asc || !*asc) - { + if (!asc || !*asc) { return true; } /* An int mask 128, 32 */ if ((sscanf(asc, "%d%c", &a1, &junk)==1) && - (a1 <= 128) && (a1 >= 0) - ) - { + (a1 <= 128) && (a1 >= 0) + ) { return mask.ApplyMask(a1, ctype); } @@ -306,7 +304,7 @@ acl_ip_data::FactoryParse(const char *t) memset(&hints, 0, sizeof(struct addrinfo)); - if( iptype != AF_UNSPEC ) { + if ( iptype != AF_UNSPEC ) { hints.ai_flags |= AI_NUMERICHOST; } @@ -317,8 +315,8 @@ acl_ip_data::FactoryParse(const char *t) int errcode = xgetaddrinfo(addr1,NULL,&hints,&hp); if (hp == NULL) { debugs(28, 0, "aclIpParseIpData: Bad host/IP: '" << addr1 << - "' in '" << t << "', flags=" << hints.ai_flags << - " : (" << errcode << ") " << xgai_strerror(errcode) ); + "' in '" << t << "', flags=" << hints.ai_flags << + " : (" << errcode << ") " << xgai_strerror(errcode) ); self_destruct(); return NULL; } @@ -333,13 +331,12 @@ acl_ip_data::FactoryParse(const char *t) /* BUT sorted fortunately, so we can drop most of them easily */ r->addr1 = *x; x = x->ai_next; - if( prev_addr && r->addr1 == *prev_addr) { + if ( prev_addr && r->addr1 == *prev_addr) { debugs(28, 3, "aclIpParseIpData: Duplicate host/IP: '" << r->addr1 << "' dropped."); delete r; *Q = NULL; continue; - } - else + } else prev_addr = &r->addr1; debugs(28, 3, "aclIpParseIpData: Located host/IP: '" << r->addr1 << "'"); @@ -365,7 +362,7 @@ acl_ip_data::FactoryParse(const char *t) #if !USE_IPV6 /* ignore IPv6 addresses when built with IPv4-only */ - if( iptype == AF_INET6 ) { + if ( iptype == AF_INET6 ) { debugs(28, 0, "aclIpParseIpData: IPv6 has not been enabled. build with '--enable-ipv6'"); return NULL; } @@ -381,7 +378,7 @@ acl_ip_data::FactoryParse(const char *t) /* Decode addr2 */ if (!*addr2) - q->addr2.SetAnyAddr(); + q->addr2.SetAnyAddr(); else if (!(q->addr2=addr2) ) { debugs(28, 0, "aclIpParseIpData: unknown second address in '" << t << "'"); delete q; @@ -465,4 +462,4 @@ ACLIP::match(IPAddress &clientip) acl_ip_data::acl_ip_data () :addr1(), addr2(), mask(), next (NULL) {} -acl_ip_data::acl_ip_data (IPAddress const &anAddress1, IPAddress const &anAddress2, IPAddress const &aMask, acl_ip_data *aNext) : addr1(anAddress1), addr2(anAddress2), mask(aMask), next(aNext){} +acl_ip_data::acl_ip_data (IPAddress const &anAddress1, IPAddress const &anAddress2, IPAddress const &aMask, acl_ip_data *aNext) : addr1(anAddress1), addr2(anAddress2), mask(aMask), next(aNext) {} diff --git a/src/ACLIP.h b/src/ACLIP.h index 718ca1bbc5..e5ea68deaf 100644 --- a/src/ACLIP.h +++ b/src/ACLIP.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -76,7 +76,7 @@ public: void *operator new(size_t); void operator delete(void *); - ACLIP() : data(NULL){} + ACLIP() : data(NULL) {} ~ACLIP(); diff --git a/src/ACLIdent.cc b/src/ACLIdent.cc index a7298e2b4f..291563bba5 100644 --- a/src/ACLIdent.cc +++ b/src/ACLIdent.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLIdent.h b/src/ACLIdent.h index 0263781da1..3c563e9b6a 100644 --- a/src/ACLIdent.h +++ b/src/ACLIdent.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLIntRange.cc b/src/ACLIntRange.cc index 21b29641ac..a738a42ffd 100644 --- a/src/ACLIntRange.cc +++ b/src/ACLIntRange.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLIntRange.h b/src/ACLIntRange.h index 72d8b2b058..df8d183703 100644 --- a/src/ACLIntRange.h +++ b/src/ACLIntRange.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLMaxConnection.cc b/src/ACLMaxConnection.cc index a3f2a0b3ff..367eb90f53 100644 --- a/src/ACLMaxConnection.cc +++ b/src/ACLMaxConnection.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLMaxConnection.h b/src/ACLMaxConnection.h index 15559e3d56..a7ab15bab8 100644 --- a/src/ACLMaxConnection.h +++ b/src/ACLMaxConnection.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLMaxUserIP.cc b/src/ACLMaxUserIP.cc index 4d4988b107..9935ea3f5f 100644 --- a/src/ACLMaxUserIP.cc +++ b/src/ACLMaxUserIP.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -110,9 +110,9 @@ ACLMaxUserIP::parse() } /* - * aclMatchUserMaxIP - check for users logging in from multiple IP's + * aclMatchUserMaxIP - check for users logging in from multiple IP's * 0 : No match - * 1 : Match + * 1 : Match */ int ACLMaxUserIP::match(AuthUserRequest * auth_user_request, @@ -131,19 +131,17 @@ ACLMaxUserIP::match(AuthUserRequest * auth_user_request, debugs(28, 1, "aclMatchUserMaxIP: user '" << auth_user_request->username() << "' tries to use too many IP addresses (max " << maximum << " allowed)!"); /* this is a match */ - if (flags.strict) - { + if (flags.strict) { /* * simply deny access - the user name is already associated with - * the request + * the request */ /* remove _this_ ip, as it is the culprit for going over the limit */ authenticateAuthUserRequestRemoveIp(auth_user_request, src_addr); debugs(28, 4, "aclMatchUserMaxIP: Denying access in strict mode"); - } else - { + } else { /* - * non-strict - remove some/all of the cached entries + * non-strict - remove some/all of the cached entries * ie to allow the user to move machines easily */ authenticateAuthUserRequestClearIp(auth_user_request); diff --git a/src/ACLMaxUserIP.h b/src/ACLMaxUserIP.h index d83ec81331..42ce6ca85c 100644 --- a/src/ACLMaxUserIP.h +++ b/src/ACLMaxUserIP.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -71,9 +71,8 @@ private: char const *class_; int maximum; - struct Flags - { - Flags() : strict(0){} + struct Flags { + Flags() : strict(0) {} unsigned int strict:1; } flags; diff --git a/src/ACLMethod.cc b/src/ACLMethod.cc index 7b1e1afc6d..755b90d9b3 100644 --- a/src/ACLMethod.cc +++ b/src/ACLMethod.cc @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLMethod.h b/src/ACLMethod.h index 71bc952431..272cfdd9a6 100644 --- a/src/ACLMethod.h +++ b/src/ACLMethod.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -58,7 +58,7 @@ public: private: static ACLMethodStrategy Instance_; - ACLMethodStrategy(){} + ACLMethodStrategy() {} ACLMethodStrategy&operator=(ACLMethodStrategy const &); }; diff --git a/src/ACLMethodData.cc b/src/ACLMethodData.cc index f00e254120..a3559961a7 100644 --- a/src/ACLMethodData.cc +++ b/src/ACLMethodData.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLMethodData.h b/src/ACLMethodData.h index 5ac338e7c6..cb560a2efc 100644 --- a/src/ACLMethodData.h +++ b/src/ACLMethodData.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLMyIP.cc b/src/ACLMyIP.cc index bd8b449c9d..fedb831315 100644 --- a/src/ACLMyIP.cc +++ b/src/ACLMyIP.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLMyIP.h b/src/ACLMyIP.h index 1d0ca63aae..b8302e71f0 100644 --- a/src/ACLMyIP.h +++ b/src/ACLMyIP.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLMyPort.cc b/src/ACLMyPort.cc index 87c6da0395..4e9b309f30 100644 --- a/src/ACLMyPort.cc +++ b/src/ACLMyPort.cc @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLMyPort.h b/src/ACLMyPort.h index c390afd497..68bf24cee1 100644 --- a/src/ACLMyPort.h +++ b/src/ACLMyPort.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -55,7 +55,7 @@ public: private: static ACLMyPortStrategy Instance_; - ACLMyPortStrategy(){} + ACLMyPortStrategy() {} ACLMyPortStrategy&operator=(ACLMyPortStrategy const &); }; diff --git a/src/ACLMyPortName.cc b/src/ACLMyPortName.cc index 563d53e07e..d1b42dc574 100644 --- a/src/ACLMyPortName.cc +++ b/src/ACLMyPortName.cc @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -51,7 +51,7 @@ int ACLMyPortNameStrategy::match (ACLData * &data, ACLChecklist *checklist) { if (checklist->conn() != NULL) - return data->match (checklist->conn()->port->name); + return data->match (checklist->conn()->port->name); return 0; } diff --git a/src/ACLMyPortName.h b/src/ACLMyPortName.h index ae6b8df313..ee44015c7e 100644 --- a/src/ACLMyPortName.h +++ b/src/ACLMyPortName.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -51,7 +51,7 @@ public: private: static ACLMyPortNameStrategy Instance_; - ACLMyPortNameStrategy(){} + ACLMyPortNameStrategy() {} ACLMyPortNameStrategy&operator=(ACLMyPortNameStrategy const &); }; diff --git a/src/ACLProtocol.cc b/src/ACLProtocol.cc index c5e24f21d0..f12c32b8e9 100644 --- a/src/ACLProtocol.cc +++ b/src/ACLProtocol.cc @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLProtocol.h b/src/ACLProtocol.h index ca09de7ca8..126e47f071 100644 --- a/src/ACLProtocol.h +++ b/src/ACLProtocol.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -53,7 +53,7 @@ public: private: static ACLProtocolStrategy Instance_; - ACLProtocolStrategy(){} + ACLProtocolStrategy() {} ACLProtocolStrategy&operator=(ACLProtocolStrategy const &); }; diff --git a/src/ACLProtocolData.cc b/src/ACLProtocolData.cc index db567b4549..f5a2e37b5b 100644 --- a/src/ACLProtocolData.cc +++ b/src/ACLProtocolData.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLProtocolData.h b/src/ACLProtocolData.h index 2e7b120118..36b84669ce 100644 --- a/src/ACLProtocolData.h +++ b/src/ACLProtocolData.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLProxyAuth.cc b/src/ACLProxyAuth.cc index 354f8dceea..312d908acb 100644 --- a/src/ACLProxyAuth.cc +++ b/src/ACLProxyAuth.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -163,7 +163,7 @@ ProxyAuthLookup::LookupDone(void *data, char *result) AUTHUSERREQUESTUNLOCK(checklist->auth_user_request, "ProxyAuthLookup"); if (checklist->conn() != NULL) { - AUTHUSERREQUESTUNLOCK(checklist->conn()->auth_user_request, "conn via ProxyAuthLookup"); // DPW discomfort + AUTHUSERREQUESTUNLOCK(checklist->conn()->auth_user_request, "conn via ProxyAuthLookup"); // DPW discomfort checklist->conn()->auth_type = AUTH_BROKEN; } } diff --git a/src/ACLProxyAuth.h b/src/ACLProxyAuth.h index dd28ca5cb7..0665abe3ca 100644 --- a/src/ACLProxyAuth.h +++ b/src/ACLProxyAuth.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLReferer.cc b/src/ACLReferer.cc index ad72236495..4947c632b5 100644 --- a/src/ACLReferer.cc +++ b/src/ACLReferer.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLReferer.h b/src/ACLReferer.h index 9f865d99f7..7bf3e2f1e6 100644 --- a/src/ACLReferer.h +++ b/src/ACLReferer.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLRegexData.cc b/src/ACLRegexData.cc index 302c5d8916..568fa40549 100644 --- a/src/ACLRegexData.cc +++ b/src/ACLRegexData.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLRegexData.h b/src/ACLRegexData.h index 9245f6eb93..7694838af9 100644 --- a/src/ACLRegexData.h +++ b/src/ACLRegexData.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLReplyHeaderStrategy.h b/src/ACLReplyHeaderStrategy.h index 79673be716..7ae2a59864 100644 --- a/src/ACLReplyHeaderStrategy.h +++ b/src/ACLReplyHeaderStrategy.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -58,7 +58,7 @@ public: private: static ACLReplyHeaderStrategy *Instance_; - ACLReplyHeaderStrategy(){} + ACLReplyHeaderStrategy() {} ACLReplyHeaderStrategy&operator=(ACLReplyHeaderStrategy const &); }; diff --git a/src/ACLReplyMIMEType.cc b/src/ACLReplyMIMEType.cc index bea60c5582..c5cab024ad 100644 --- a/src/ACLReplyMIMEType.cc +++ b/src/ACLReplyMIMEType.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLReplyMIMEType.h b/src/ACLReplyMIMEType.h index 348e865433..33fb9a09a2 100644 --- a/src/ACLReplyMIMEType.h +++ b/src/ACLReplyMIMEType.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLRequestHeaderStrategy.h b/src/ACLRequestHeaderStrategy.h index 0c1724da2a..bf118c82f1 100644 --- a/src/ACLRequestHeaderStrategy.h +++ b/src/ACLRequestHeaderStrategy.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -58,7 +58,7 @@ public: private: static ACLRequestHeaderStrategy *Instance_; - ACLRequestHeaderStrategy(){} + ACLRequestHeaderStrategy() {} ACLRequestHeaderStrategy&operator=(ACLRequestHeaderStrategy const &); }; diff --git a/src/ACLRequestMIMEType.cc b/src/ACLRequestMIMEType.cc index 77b336f69c..7320001999 100644 --- a/src/ACLRequestMIMEType.cc +++ b/src/ACLRequestMIMEType.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLRequestMIMEType.h b/src/ACLRequestMIMEType.h index 132a173390..af8a80901f 100644 --- a/src/ACLRequestMIMEType.h +++ b/src/ACLRequestMIMEType.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLSourceASN.h b/src/ACLSourceASN.h index 434d390807..e03517cf69 100644 --- a/src/ACLSourceASN.h +++ b/src/ACLSourceASN.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -57,7 +57,7 @@ public: private: static ACLSourceASNStrategy Instance_; - ACLSourceASNStrategy(){} + ACLSourceASNStrategy() {} ACLSourceASNStrategy&operator=(ACLSourceASNStrategy const &); }; diff --git a/src/ACLSourceDomain.cc b/src/ACLSourceDomain.cc index da6b9f86e7..51ca835adc 100644 --- a/src/ACLSourceDomain.cc +++ b/src/ACLSourceDomain.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLSourceDomain.h b/src/ACLSourceDomain.h index ef47de683c..b3c09acae7 100644 --- a/src/ACLSourceDomain.h +++ b/src/ACLSourceDomain.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -53,7 +53,7 @@ public: private: static ACLSourceDomainStrategy Instance_; - ACLSourceDomainStrategy(){} + ACLSourceDomainStrategy() {} ACLSourceDomainStrategy&operator=(ACLSourceDomainStrategy const &); }; diff --git a/src/ACLSourceIP.cc b/src/ACLSourceIP.cc index 1ccf86e815..0b4f939d79 100644 --- a/src/ACLSourceIP.cc +++ b/src/ACLSourceIP.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLSourceIP.h b/src/ACLSourceIP.h index 1aca6eaca9..a3b35dc0c4 100644 --- a/src/ACLSourceIP.h +++ b/src/ACLSourceIP.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLSslError.h b/src/ACLSslError.h index b2d681894f..1068927a61 100644 --- a/src/ACLSslError.h +++ b/src/ACLSslError.h @@ -21,7 +21,7 @@ public: private: static ACLSslErrorStrategy Instance_; - ACLSslErrorStrategy(){} + ACLSslErrorStrategy() {} ACLSslErrorStrategy&operator=(ACLSslErrorStrategy const &); }; diff --git a/src/ACLStrategised.cc b/src/ACLStrategised.cc index b867b7cbfe..8093738f27 100644 --- a/src/ACLStrategised.cc +++ b/src/ACLStrategised.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -41,12 +41,12 @@ #include "ACLRegexData.h" #include "ACLDomainData.h" -/* +/* * moved template instantiation into ACLStrategized.cc from * ACLHTTPRepHeader.cc and ACLHTTPReqHeader.cc to compile on * Mac OSX 10.5 Leopard, this corrects a duplicate symbol error */ - + /* explicit template instantiation required for some systems */ template class ACLStrategised; diff --git a/src/ACLStrategised.h b/src/ACLStrategised.h index e0ef5bb2b4..e09b267606 100644 --- a/src/ACLStrategised.h +++ b/src/ACLStrategised.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLStrategy.h b/src/ACLStrategy.h index 573f7c513b..4f19949554 100644 --- a/src/ACLStrategy.h +++ b/src/ACLStrategy.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -54,7 +54,7 @@ public: virtual bool valid() const {return true;} - virtual ~ACLStrategy(){} + virtual ~ACLStrategy() {} }; #endif /* SQUID_ACLSTRATEGY_H */ diff --git a/src/ACLStringData.cc b/src/ACLStringData.cc index 4fa85ae779..0130885acd 100644 --- a/src/ACLStringData.cc +++ b/src/ACLStringData.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLStringData.h b/src/ACLStringData.h index c8a87f1493..2068e2fd0e 100644 --- a/src/ACLStringData.h +++ b/src/ACLStringData.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLTime.cc b/src/ACLTime.cc index 828109a5c9..d836dbef9b 100644 --- a/src/ACLTime.cc +++ b/src/ACLTime.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLTime.h b/src/ACLTime.h index 518d96dc9b..65e3bf15cf 100644 --- a/src/ACLTime.h +++ b/src/ACLTime.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -53,7 +53,7 @@ public: private: static ACLTimeStrategy Instance_; - ACLTimeStrategy(){} + ACLTimeStrategy() {} ACLTimeStrategy&operator=(ACLTimeStrategy const &); }; diff --git a/src/ACLTimeData.cc b/src/ACLTimeData.cc index d28b6e5ad6..dd0d2a72d7 100644 --- a/src/ACLTimeData.cc +++ b/src/ACLTimeData.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLTimeData.h b/src/ACLTimeData.h index e7f5efa32c..f9cb4f71c1 100644 --- a/src/ACLTimeData.h +++ b/src/ACLTimeData.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLUrl.cc b/src/ACLUrl.cc index c22af11788..97b7f47c26 100644 --- a/src/ACLUrl.cc +++ b/src/ACLUrl.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLUrl.h b/src/ACLUrl.h index 8f28dd02a7..f4e7ce8478 100644 --- a/src/ACLUrl.h +++ b/src/ACLUrl.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -54,7 +54,7 @@ public: private: static ACLUrlStrategy Instance_; - ACLUrlStrategy(){} + ACLUrlStrategy() {} ACLUrlStrategy&operator=(ACLUrlStrategy const &); }; diff --git a/src/ACLUrlPath.cc b/src/ACLUrlPath.cc index 24099bf6bd..bc52026d4f 100644 --- a/src/ACLUrlPath.cc +++ b/src/ACLUrlPath.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLUrlPath.h b/src/ACLUrlPath.h index 6a6f21b27a..f4e371a6d8 100644 --- a/src/ACLUrlPath.h +++ b/src/ACLUrlPath.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -55,7 +55,7 @@ public: private: static ACLUrlPathStrategy Instance_; - ACLUrlPathStrategy(){} + ACLUrlPathStrategy() {} ACLUrlPathStrategy&operator=(ACLUrlPathStrategy const &); }; diff --git a/src/ACLUrlPort.cc b/src/ACLUrlPort.cc index 92193e67eb..3e3c576117 100644 --- a/src/ACLUrlPort.cc +++ b/src/ACLUrlPort.cc @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLUrlPort.h b/src/ACLUrlPort.h index 956682a48e..89d9bfa928 100644 --- a/src/ACLUrlPort.h +++ b/src/ACLUrlPort.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -53,7 +53,7 @@ public: private: static ACLUrlPortStrategy Instance_; - ACLUrlPortStrategy(){} + ACLUrlPortStrategy() {} ACLUrlPortStrategy&operator=(ACLUrlPortStrategy const &); }; diff --git a/src/ACLUserData.cc b/src/ACLUserData.cc index 65f0012154..09da42ddc6 100644 --- a/src/ACLUserData.cc +++ b/src/ACLUserData.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ACLUserData.h b/src/ACLUserData.h index aa9a073aa0..b0bd11d367 100644 --- a/src/ACLUserData.h +++ b/src/ACLUserData.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -54,8 +54,7 @@ public: SplayNode *names; - struct - { + struct { unsigned int case_insensitive:1; unsigned int required:1; } flags; diff --git a/src/AccessLogEntry.h b/src/AccessLogEntry.h index e26facd6e8..6c7905c7a8 100644 --- a/src/AccessLogEntry.h +++ b/src/AccessLogEntry.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/AsyncCall.cc b/src/AsyncCall.cc index b17f5b7dd0..64f1e6dec0 100644 --- a/src/AsyncCall.cc +++ b/src/AsyncCall.cc @@ -13,11 +13,11 @@ unsigned int AsyncCall::TheLastId = 0; /* AsyncCall */ AsyncCall::AsyncCall(int aDebugSection, int aDebugLevel, - const char *aName): name(aName), debugSection(aDebugSection), - debugLevel(aDebugLevel), id(++TheLastId), theNext(0), isCanceled(NULL) + const char *aName): name(aName), debugSection(aDebugSection), + debugLevel(aDebugLevel), id(++TheLastId), theNext(0), isCanceled(NULL) { debugs(debugSection, debugLevel, "The AsyncCall " << name << " constructed, this=" << this << - " [call" << id << ']'); + " [call" << id << ']'); } AsyncCall::~AsyncCall() @@ -29,7 +29,7 @@ void AsyncCall::make() { debugs(debugSection, debugLevel, HERE << "make call " << name << - " [call"<< id << ']'); + " [call"<< id << ']'); if (canFire()) { fire(); return; @@ -39,7 +39,7 @@ AsyncCall::make() isCanceled = "unknown reason"; debugs(debugSection, debugLevel, HERE << "will not call " << name << - " [call"<< id << ']' << " because of " << isCanceled); + " [call"<< id << ']' << " because of " << isCanceled); } bool @@ -47,7 +47,7 @@ AsyncCall::cancel(const char *reason) { if (isCanceled) debugs(debugSection, debugLevel, HERE << "will not call " << name << - " [call"<< id << ']' << " also because " << reason); + " [call"<< id << ']' << " also because " << reason); isCanceled = reason; return false; } @@ -70,10 +70,10 @@ AsyncCall::print(std::ostream &os) } bool -ScheduleCall(const char *fileName, int fileLine, AsyncCall::Pointer &call) +ScheduleCall(const char *fileName, int fileLine, AsyncCall::Pointer &call) { debugs(call->debugSection, call->debugLevel, fileName << "(" << fileLine << - ") will call " << *call << " [call"<< call->id << ']' ); + ") will call " << *call << " [call"<< call->id << ']' ); AsyncCallQueue::Instance().schedule(call); return true; } diff --git a/src/AsyncCall.h b/src/AsyncCall.h index 18a7f6d554..29ade1444c 100644 --- a/src/AsyncCall.h +++ b/src/AsyncCall.h @@ -21,11 +21,11 @@ * event stores the pointer to the callback function and cbdata-protected * callback data. To call a method of an object, the method is wrapped * in a method-specific, static callback function and the pointer to the - * object is passed to the wrapper. For the method call to be safe, the + * object is passed to the wrapper. For the method call to be safe, the * class must be cbdata-enabled. \par * You do not have to use the macros below to make or receive asynchronous - * method calls, but they give you a uniform interface and handy call + * method calls, but they give you a uniform interface and handy call * debugging. */ @@ -45,24 +45,24 @@ public: AsyncCall(int aDebugSection, int aDebugLevel, const char *aName); virtual ~AsyncCall(); - + void make(); // fire if we can; handles general call debugging // can be called from canFire() for debugging; always returns false bool cancel(const char *reason); - + bool canceled() { return isCanceled != NULL; } virtual CallDialer *getDialer() = 0; void print(std::ostream &os); - + void setNext(AsyncCall::Pointer aNext) { - theNext = aNext; + theNext = aNext; } AsyncCall::Pointer &Next() { - return theNext; + return theNext; } public: @@ -116,14 +116,16 @@ class AsyncCallT: public AsyncCall { public: AsyncCallT(int aDebugSection, int aDebugLevel, const char *aName, - const Dialer &aDialer): AsyncCall(aDebugSection, aDebugLevel, aName), - dialer(aDialer) {} + const Dialer &aDialer): AsyncCall(aDebugSection, aDebugLevel, aName), + dialer(aDialer) {} CallDialer *getDialer() { return &dialer; } protected: - virtual bool canFire() { return AsyncCall::canFire() && - dialer.canDial(*this); } + virtual bool canFire() { + return AsyncCall::canFire() && + dialer.canDial(*this); + } virtual void fire() { dialer.dial(*this); } Dialer dialer; @@ -133,7 +135,7 @@ template inline AsyncCall * asyncCall(int aDebugSection, int aDebugLevel, const char *aName, - const Dialer &aDialer) + const Dialer &aDialer) { return new AsyncCallT(aDebugSection, aDebugLevel, aName, aDialer); } diff --git a/src/AsyncCallQueue.cc b/src/AsyncCallQueue.cc index 4d23b69692..a11cd3961b 100644 --- a/src/AsyncCallQueue.cc +++ b/src/AsyncCallQueue.cc @@ -58,7 +58,7 @@ AsyncCallQueue & AsyncCallQueue::Instance() { // TODO: how to remove this frequent check while supporting early calls? - if (!TheInstance) + if (!TheInstance) TheInstance = new AsyncCallQueue(); return *TheInstance; diff --git a/src/AsyncCallQueue.h b/src/AsyncCallQueue.h index 75ff36c5e1..0aa4ca8da7 100644 --- a/src/AsyncCallQueue.h +++ b/src/AsyncCallQueue.h @@ -18,10 +18,10 @@ class AsyncCallQueue { public: // there is only one queue - static AsyncCallQueue &Instance(); + static AsyncCallQueue &Instance(); // make this async call when we get a chance - void schedule(AsyncCall::Pointer &call); + void schedule(AsyncCall::Pointer &call); // fire all scheduled calls; returns true if at least one was fired bool fire(); diff --git a/src/AsyncEngine.cc b/src/AsyncEngine.cc index 9887fd3bf5..56334d8e1f 100644 --- a/src/AsyncEngine.cc +++ b/src/AsyncEngine.cc @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/AsyncEngine.h b/src/AsyncEngine.h index c41fd9ad53..ba7d0197e5 100644 --- a/src/AsyncEngine.h +++ b/src/AsyncEngine.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -64,7 +64,7 @@ public: /* Check the engine for events. If there are events that have completed, * the engine should at this point hand them off to their dispatcher. - * Engines that operate asynchronously - i.e. the DiskThreads engine - + * Engines that operate asynchronously - i.e. the DiskThreads engine - * should hand events off to their dispatcher as they arrive rather than * waiting for checkEvents to be called. Engines like poll and select should * use this call as the time to perform their checks with the OS for new @@ -73,7 +73,7 @@ public: * The return value is the status code of the event checking. If its a * non-negative value then it is used as hint for the minimum requested * time before checkEvents is called again. I.e. the event engine knows - * how long it is until the next event will be scheduled - so it will + * how long it is until the next event will be scheduled - so it will * return that time (in milliseconds). * * The timeout value is a requested timeout for this engine - the engine diff --git a/src/AsyncJobCalls.h b/src/AsyncJobCalls.h index efe3c1b4bd..d40900fab8 100644 --- a/src/AsyncJobCalls.h +++ b/src/AsyncJobCalls.h @@ -30,7 +30,7 @@ class NullaryMemFunT: public JobDialer public: typedef void (C::*Method)(); explicit NullaryMemFunT(C *anObject, Method aMethod): - JobDialer(anObject), object(anObject), method(aMethod) {} + JobDialer(anObject), object(anObject), method(aMethod) {} virtual void print(std::ostream &os) const { os << "()"; } @@ -39,7 +39,7 @@ public: Method method; protected: - virtual void doDial() { (object->*method)(); } + virtual void doDial() { (object->*method)(); } }; template @@ -48,8 +48,8 @@ class UnaryMemFunT: public JobDialer public: typedef void (C::*Method)(Argument1); explicit UnaryMemFunT(C *anObject, Method aMethod, const Argument1 &anArg1): - JobDialer(anObject), - object(anObject), method(aMethod), arg1(anArg1) {} + JobDialer(anObject), + object(anObject), method(aMethod), arg1(anArg1) {} virtual void print(std::ostream &os) const { os << '(' << arg1 << ')'; } @@ -59,7 +59,7 @@ public: Argument1 arg1; protected: - virtual void doDial() { (object->*method)(arg1); } + virtual void doDial() { (object->*method)(arg1); } }; // ... add more as needed @@ -79,7 +79,7 @@ MemFun(C *object, typename NullaryMemFunT::Method method) template UnaryMemFunT MemFun(C *object, typename UnaryMemFunT::Method method, - Argument1 arg1) + Argument1 arg1) { return UnaryMemFunT(object, method, arg1); } diff --git a/src/AuthConfig.cc b/src/AuthConfig.cc index dd250fb027..7dbae08915 100644 --- a/src/AuthConfig.cc +++ b/src/AuthConfig.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/AuthConfig.h b/src/AuthConfig.h index 206a8507f1..bc3feef5de 100644 --- a/src/AuthConfig.h +++ b/src/AuthConfig.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -61,7 +61,7 @@ public: static AuthConfig *Find(const char *proxy_auth); AuthConfig() {} - virtual ~AuthConfig(){} + virtual ~AuthConfig() {} /** * Used by squid to determine whether the auth module has successfully initialised itself with the current configuration. diff --git a/src/AuthScheme.cc b/src/AuthScheme.cc index 4afede9299..1de624c160 100644 --- a/src/AuthScheme.cc +++ b/src/AuthScheme.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/AuthScheme.h b/src/AuthScheme.h index b0bd9c14e8..2d71201231 100644 --- a/src/AuthScheme.h +++ b/src/AuthScheme.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -65,7 +65,7 @@ public: typedef Vector::const_iterator const_iterator; AuthScheme() : initialised (false) {} - virtual ~AuthScheme(){} + virtual ~AuthScheme() {} /* per scheme methods */ virtual char const *type () const = 0; diff --git a/src/AuthUser.cc b/src/AuthUser.cc index e9caf9482e..5c002c5f7a 100644 --- a/src/AuthUser.cc +++ b/src/AuthUser.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -243,8 +243,7 @@ AuthUser::removeIp(IPAddress ipaddr) { auth_user_ip_t *ipdata = (auth_user_ip_t *) ip_list.head; - while (ipdata) - { + while (ipdata) { /* walk the ip list */ if (ipdata->ipaddr == ipaddr) { @@ -275,8 +274,7 @@ AuthUser::addIp(IPAddress ipaddr) * preventing old entries being flushed and locking a user out after * a timeout+reconfigure */ - while (ipdata) - { + while (ipdata) { auth_user_ip_t *tempnode = (auth_user_ip_t *) ipdata->node.next; /* walk the ip list */ diff --git a/src/AuthUser.cci b/src/AuthUser.cci index c1060cab1a..eb1b03924b 100644 --- a/src/AuthUser.cci +++ b/src/AuthUser.cci @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/AuthUser.h b/src/AuthUser.h index 6001e99622..5062912500 100644 --- a/src/AuthUser.h +++ b/src/AuthUser.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/AuthUserRequest.cc b/src/AuthUserRequest.cc index 300eaec50a..aef630dd48 100644 --- a/src/AuthUserRequest.cc +++ b/src/AuthUserRequest.cc @@ -24,12 +24,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -280,7 +280,7 @@ AuthUserRequest::connLastHeader() } /* - * authenticateAuthenticateUser: call the module specific code to + * authenticateAuthenticateUser: call the module specific code to * log this user request in. * Cache hits may change the auth_user pointer in the structure if needed. * This is basically a handle approach. @@ -312,17 +312,17 @@ authTryGetUser (AuthUserRequest **auth_user_request, ConnStateData * conn, HttpR * AUTH_ACL_CANNOT_AUTHENTICATE, * AUTH_AUTHENTICATED * - * How to use: In your proxy-auth dependent acl code, use the following + * How to use: In your proxy-auth dependent acl code, use the following * construct: * int rv; * if ((rv = AuthenticateAuthenticate()) != AUTH_AUTHENTICATED) * return rv; - * + * * when this code is reached, the request/connection is authenticated. * - * if you have non-acl code, but want to force authentication, you need a + * if you have non-acl code, but want to force authentication, you need a * callback mechanism like the acl testing routines that will send a 40[1|7] to - * the client when rv==AUTH_ACL_CHALLENGE, and will communicate with + * the client when rv==AUTH_ACL_CHALLENGE, and will communicate with * the authenticateStart routine for rv==AUTH_ACL_HELPER * * Caller is responsible for locking and unlocking their *auth_user_request! @@ -343,31 +343,29 @@ AuthUserRequest::authenticate(AuthUserRequest ** auth_user_request, http_hdr_typ */ if (((proxy_auth == NULL) && (!authenticateUserAuthenticated(authTryGetUser(auth_user_request,conn,request)))) - || (conn != NULL && conn->auth_type == AUTH_BROKEN)) - { + || (conn != NULL && conn->auth_type == AUTH_BROKEN)) { /* no header or authentication failed/got corrupted - restart */ debugs(29, 4, "authenticateAuthenticate: broken auth or no proxy_auth header. Requesting auth header."); /* something wrong with the AUTH credentials. Force a new attempt */ if (conn != NULL) { conn->auth_type = AUTH_UNKNOWN; - AUTHUSERREQUESTUNLOCK(conn->auth_user_request, "conn"); + AUTHUSERREQUESTUNLOCK(conn->auth_user_request, "conn"); } - *auth_user_request = NULL; + *auth_user_request = NULL; return AUTH_ACL_CHALLENGE; } /* * Is this an already authenticated connection with a new auth header? - * No check for function required in the if: its compulsory for conn based + * No check for function required in the if: its compulsory for conn based * auth modules */ if (proxy_auth && conn != NULL && conn->auth_user_request && authenticateUserAuthenticated(conn->auth_user_request) && conn->auth_user_request->connLastHeader() != NULL && - strcmp(proxy_auth, conn->auth_user_request->connLastHeader())) - { + strcmp(proxy_auth, conn->auth_user_request->connLastHeader())) { debugs(29, 2, "authenticateAuthenticate: DUPLICATE AUTH - authentication header on already authenticated connection!. AU " << conn->auth_user_request << ", Current user '" << conn->auth_user_request->username() << "' proxy_auth " << @@ -378,10 +376,10 @@ AuthUserRequest::authenticate(AuthUserRequest ** auth_user_request, http_hdr_typ */ /* This should _only_ ever occur on the first pass through - * authenticateAuthenticate + * authenticateAuthenticate */ assert(*auth_user_request == NULL); - AUTHUSERREQUESTUNLOCK(conn->auth_user_request, "conn"); + AUTHUSERREQUESTUNLOCK(conn->auth_user_request, "conn"); /* Set the connection auth type */ conn->auth_type = AUTH_UNKNOWN; } @@ -390,8 +388,7 @@ AuthUserRequest::authenticate(AuthUserRequest ** auth_user_request, http_hdr_typ * not had bungled connection oriented authentication happen on it. */ debugs(29, 9, "authenticateAuthenticate: header " << (proxy_auth ? proxy_auth : "-") << "."); - if (*auth_user_request == NULL) - { + if (*auth_user_request == NULL) { debugs(29, 9, "authenticateAuthenticate: This is a new checklist test on FD:" << (conn != NULL ? conn->fd : -1) ); if (proxy_auth && !request->auth_user_request && conn != NULL && conn->auth_user_request) { @@ -403,7 +400,7 @@ AuthUserRequest::authenticate(AuthUserRequest ** auth_user_request, http_hdr_typ "' to '" << proxy_auth << "' (client " << src_addr << ")"); - AUTHUSERREQUESTUNLOCK(conn->auth_user_request, "conn"); + AUTHUSERREQUESTUNLOCK(conn->auth_user_request, "conn"); conn->auth_type = AUTH_UNKNOWN; } } @@ -413,7 +410,7 @@ AuthUserRequest::authenticate(AuthUserRequest ** auth_user_request, http_hdr_typ /* beginning of a new request check */ debugs(29, 4, "authenticateAuthenticate: no connection authentication type"); - *auth_user_request = AuthConfig::CreateAuthUser(proxy_auth); + *auth_user_request = AuthConfig::CreateAuthUser(proxy_auth); if (!authenticateValidateUser(*auth_user_request)) { if (*auth_user_request == NULL) return AUTH_ACL_CHALLENGE; @@ -423,7 +420,7 @@ AuthUserRequest::authenticate(AuthUserRequest ** auth_user_request, http_hdr_typ if ((*auth_user_request)->username()) { request->auth_user_request = *auth_user_request; - AUTHUSERREQUESTLOCK(request->auth_user_request, "request"); + AUTHUSERREQUESTLOCK(request->auth_user_request, "request"); } *auth_user_request = NULL; @@ -450,8 +447,7 @@ AuthUserRequest::authenticate(AuthUserRequest ** auth_user_request, http_hdr_typ } } - if (!authenticateUserAuthenticated(*auth_user_request)) - { + if (!authenticateUserAuthenticated(*auth_user_request)) { /* User not logged in. Log them in */ authenticateAuthenticateUser(*auth_user_request, request, conn, headertype); @@ -462,7 +458,7 @@ AuthUserRequest::authenticate(AuthUserRequest ** auth_user_request, http_hdr_typ if (NULL == request->auth_user_request) { request->auth_user_request = *auth_user_request; - AUTHUSERREQUESTLOCK(request->auth_user_request, "request"); + AUTHUSERREQUESTLOCK(request->auth_user_request, "request"); } /* fallthrough to -2 */ @@ -485,7 +481,7 @@ AuthUserRequest::authenticate(AuthUserRequest ** auth_user_request, http_hdr_typ if ((*auth_user_request)->username()) { if (!request->auth_user_request) { request->auth_user_request = *auth_user_request; - AUTHUSERREQUESTLOCK(request->auth_user_request, "request"); + AUTHUSERREQUESTLOCK(request->auth_user_request, "request"); } } @@ -498,7 +494,7 @@ AuthUserRequest::authenticate(AuthUserRequest ** auth_user_request, http_hdr_typ /* the credentials are correct at this point */ if (NULL == request->auth_user_request) { request->auth_user_request = *auth_user_request; - AUTHUSERREQUESTLOCK(request->auth_user_request, "request"); + AUTHUSERREQUESTLOCK(request->auth_user_request, "request"); authenticateAuthUserRequestSetIp(*auth_user_request, src_addr); } @@ -513,15 +509,14 @@ AuthUserRequest::tryToAuthenticateAndSetAuthUser(AuthUserRequest ** auth_user_re AuthUserRequest *t = authTryGetUser (auth_user_request, conn, request); if (t && t->lastReply != AUTH_ACL_CANNOT_AUTHENTICATE - && t->lastReply != AUTH_ACL_HELPER) - { + && t->lastReply != AUTH_ACL_HELPER) { if (!*auth_user_request) *auth_user_request = t; - if (!request->auth_user_request && t->lastReply == AUTH_AUTHENTICATED) { - request->auth_user_request = t; - AUTHUSERREQUESTLOCK(request->auth_user_request, "request"); - } + if (!request->auth_user_request && t->lastReply == AUTH_AUTHENTICATED) { + request->auth_user_request = t; + AUTHUSERREQUESTLOCK(request->auth_user_request, "request"); + } return t->lastReply; } @@ -558,8 +553,7 @@ AuthUserRequest::addReplyAuthHeader(HttpReply * rep, AuthUserRequest * auth_user { http_hdr_type type; - switch (rep->sline.status) - { + switch (rep->sline.status) { case HTTP_PROXY_AUTHENTICATION_REQUIRED: /* Proxy authorisation needed */ @@ -588,8 +582,7 @@ AuthUserRequest::addReplyAuthHeader(HttpReply * rep, AuthUserRequest * auth_user if ((auth_user_request != NULL) && authenticateDirection(auth_user_request) == 1) /* scheme specific */ auth_user_request->user()->config->fixHeader(auth_user_request, rep, type, request); - else - { + else { /* call each configured & running authscheme */ for (authConfig::iterator i = Config.authConfiguration.begin(); i != Config.authConfiguration.end(); ++i) { @@ -608,11 +601,10 @@ AuthUserRequest::addReplyAuthHeader(HttpReply * rep, AuthUserRequest * auth_user * response - ie digest auth */ - if (auth_user_request != NULL) - { + if (auth_user_request != NULL) { auth_user_request->addHeader(rep, accelerated); - if (auth_user_request->lastReply != AUTH_AUTHENTICATED) - auth_user_request->lastReply = AUTH_ACL_CANNOT_AUTHENTICATE; + if (auth_user_request->lastReply != AUTH_AUTHENTICATED) + auth_user_request->lastReply = AUTH_ACL_CANNOT_AUTHENTICATE; } } diff --git a/src/AuthUserRequest.h b/src/AuthUserRequest.h index f010b754cf..0787703c0d 100644 --- a/src/AuthUserRequest.h +++ b/src/AuthUserRequest.h @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -44,8 +44,7 @@ class ConnStateData; class AuthScheme; -struct AuthUserIP -{ +struct AuthUserIP { dlink_node node; /* IP addr this user authenticated from */ diff --git a/src/BodyPipe.cc b/src/BodyPipe.cc index 909c26e704..66e0563e2c 100644 --- a/src/BodyPipe.cc +++ b/src/BodyPipe.cc @@ -6,24 +6,25 @@ CBDATA_CLASS_INIT(BodyPipe); // BodySink is a BodyConsumer class which just consume and drops -// data from a BodyPipe -class BodySink: public BodyConsumer { +// data from a BodyPipe +class BodySink: public BodyConsumer +{ bool done; public: - BodySink():AsyncJob("BodySink"), done(false){} + BodySink():AsyncJob("BodySink"), done(false) {} virtual ~BodySink() {} - + virtual void noteMoreBodyDataAvailable(BodyPipe::Pointer bp) { - size_t contentSize = bp->buf().contentSize(); - bp->consume(contentSize); + size_t contentSize = bp->buf().contentSize(); + bp->consume(contentSize); } virtual void noteBodyProductionEnded(BodyPipe::Pointer bp) { - stopConsumingFrom(bp); - done = true; + stopConsumingFrom(bp); + done = true; } virtual void noteBodyProducerAborted(BodyPipe::Pointer bp) { - stopConsumingFrom(bp); - done = true; + stopConsumingFrom(bp); + done = true; } bool doneAll() const {return done && AsyncJob::doneAll();} CBDATA_CLASS2(BodySink); @@ -32,63 +33,65 @@ public: CBDATA_CLASS_INIT(BodySink); // The BodyProducerDialer is an AsyncCall class which used to schedule BodyProducer calls. -// In addition to a normal AsyncCall checks if the BodyProducer is still the producer of +// In addition to a normal AsyncCall checks if the BodyProducer is still the producer of // the BodyPipe passed as argument class BodyProducerDialer: public UnaryMemFunT { public: - typedef UnaryMemFunT Parent; + typedef UnaryMemFunT Parent; - BodyProducerDialer(BodyProducer *aProducer, Parent::Method aHandler, - BodyPipe::Pointer bp): Parent(aProducer, aHandler, bp) {} + BodyProducerDialer(BodyProducer *aProducer, Parent::Method aHandler, + BodyPipe::Pointer bp): Parent(aProducer, aHandler, bp) {} - virtual bool canDial(AsyncCall &call); + virtual bool canDial(AsyncCall &call); }; // The BodyConsumerDialer is an AsyncCall class which used to schedule BodyConsumer calls. -// In addition to a normal AsyncCall checks if the BodyConsumer is still the reciptient +// In addition to a normal AsyncCall checks if the BodyConsumer is still the reciptient // of the BodyPipe passed as argument class BodyConsumerDialer: public UnaryMemFunT { public: - typedef UnaryMemFunT Parent; + typedef UnaryMemFunT Parent; - BodyConsumerDialer(BodyConsumer *aConsumer, Parent::Method aHandler, - BodyPipe::Pointer bp): Parent(aConsumer, aHandler, bp) {} + BodyConsumerDialer(BodyConsumer *aConsumer, Parent::Method aHandler, + BodyPipe::Pointer bp): Parent(aConsumer, aHandler, bp) {} - virtual bool canDial(AsyncCall &call); + virtual bool canDial(AsyncCall &call); }; bool -BodyProducerDialer::canDial(AsyncCall &call) { - if (!Parent::canDial(call)) - return false; - - BodyProducer *producer = object; - BodyPipe::Pointer pipe = arg1; - if (!pipe->stillProducing(producer)) { - debugs(call.debugSection, call.debugLevel, HERE << producer << - " no longer producing for " << pipe->status()); - return call.cancel("no longer producing"); - } +BodyProducerDialer::canDial(AsyncCall &call) +{ + if (!Parent::canDial(call)) + return false; + + BodyProducer *producer = object; + BodyPipe::Pointer pipe = arg1; + if (!pipe->stillProducing(producer)) { + debugs(call.debugSection, call.debugLevel, HERE << producer << + " no longer producing for " << pipe->status()); + return call.cancel("no longer producing"); + } - return true; + return true; } bool -BodyConsumerDialer::canDial(AsyncCall &call) { - if (!Parent::canDial(call)) - return false; - - BodyConsumer *consumer = object; - BodyPipe::Pointer pipe = arg1; - if (!pipe->stillConsuming(consumer)) { - debugs(call.debugSection, call.debugLevel, HERE << consumer << - " no longer consuming from " << pipe->status()); - return call.cancel("no longer consuming"); - } +BodyConsumerDialer::canDial(AsyncCall &call) +{ + if (!Parent::canDial(call)) + return false; + + BodyConsumer *consumer = object; + BodyPipe::Pointer pipe = arg1; + if (!pipe->stillConsuming(consumer)) { + debugs(call.debugSection, call.debugLevel, HERE << consumer << + " no longer consuming from " << pipe->status()); + return call.cancel("no longer consuming"); + } - return true; + return true; } @@ -97,11 +100,11 @@ BodyConsumerDialer::canDial(AsyncCall &call) { // inform the pipe that we are done and clear the Pointer void BodyProducer::stopProducingFor(RefCount &pipe, bool atEof) { - debugs(91,7, HERE << this << " will not produce for " << pipe << - "; atEof: " << atEof); - assert(pipe != NULL); // be strict: the caller state may depend on this - pipe->clearProducer(atEof); - pipe = NULL; + debugs(91,7, HERE << this << " will not produce for " << pipe << + "; atEof: " << atEof); + assert(pipe != NULL); // be strict: the caller state may depend on this + pipe->clearProducer(atEof); + pipe = NULL; } @@ -111,294 +114,298 @@ void BodyProducer::stopProducingFor(RefCount &pipe, bool atEof) // inform the pipe that we are done and clear the Pointer void BodyConsumer::stopConsumingFrom(RefCount &pipe) { - debugs(91,7, HERE << this << " will not consume from " << pipe); - assert(pipe != NULL); // be strict: the caller state may depend on this - pipe->clearConsumer(); - pipe = NULL; + debugs(91,7, HERE << this << " will not consume from " << pipe); + assert(pipe != NULL); // be strict: the caller state may depend on this + pipe->clearConsumer(); + pipe = NULL; } /* BodyPipe */ BodyPipe::BodyPipe(Producer *aProducer): theBodySize(-1), - theProducer(aProducer), theConsumer(0), - thePutSize(0), theGetSize(0), - mustAutoConsume(false), isCheckedOut(false) + theProducer(aProducer), theConsumer(0), + thePutSize(0), theGetSize(0), + mustAutoConsume(false), isCheckedOut(false) { - // TODO: teach MemBuf to start with zero minSize - // TODO: limit maxSize by theBodySize, when known? - theBuf.init(2*1024, MaxCapacity); - debugs(91,7, HERE << "created BodyPipe" << status()); + // TODO: teach MemBuf to start with zero minSize + // TODO: limit maxSize by theBodySize, when known? + theBuf.init(2*1024, MaxCapacity); + debugs(91,7, HERE << "created BodyPipe" << status()); } BodyPipe::~BodyPipe() { - debugs(91,7, HERE << "destroying BodyPipe" << status()); - assert(!theProducer); - assert(!theConsumer); - theBuf.clean(); + debugs(91,7, HERE << "destroying BodyPipe" << status()); + assert(!theProducer); + assert(!theConsumer); + theBuf.clean(); } void BodyPipe::setBodySize(uint64_t aBodySize) { - assert(!bodySizeKnown()); - assert(aBodySize >= 0); - assert(thePutSize <= aBodySize); + assert(!bodySizeKnown()); + assert(aBodySize >= 0); + assert(thePutSize <= aBodySize); - // If this assert fails, we need to add code to check for eof and inform - // the consumer about the eof condition via scheduleBodyEndNotification, - // because just setting a body size limit may trigger the eof condition. - assert(!theConsumer); + // If this assert fails, we need to add code to check for eof and inform + // the consumer about the eof condition via scheduleBodyEndNotification, + // because just setting a body size limit may trigger the eof condition. + assert(!theConsumer); - theBodySize = aBodySize; - debugs(91,7, HERE << "set body size" << status()); + theBodySize = aBodySize; + debugs(91,7, HERE << "set body size" << status()); } uint64_t BodyPipe::bodySize() const { - assert(bodySizeKnown()); - return static_cast(theBodySize); + assert(bodySizeKnown()); + return static_cast(theBodySize); } bool BodyPipe::expectMoreAfter(uint64_t offset) const { - assert(theGetSize <= offset); - return offset < thePutSize || // buffer has more now or - (!productionEnded() && mayNeedMoreData()); // buffer will have more + assert(theGetSize <= offset); + return offset < thePutSize || // buffer has more now or + (!productionEnded() && mayNeedMoreData()); // buffer will have more } bool BodyPipe::exhausted() const { - return !expectMoreAfter(theGetSize); + return !expectMoreAfter(theGetSize); } uint64_t BodyPipe::unproducedSize() const { - return bodySize() - thePutSize; // bodySize() asserts that size is known + return bodySize() - thePutSize; // bodySize() asserts that size is known } void BodyPipe::clearProducer(bool atEof) { - if (theProducer) { - debugs(91,7, HERE << "clearing BodyPipe producer" << status()); - theProducer = NULL; - if (atEof) { - if (!bodySizeKnown()) - theBodySize = thePutSize; - else - if (bodySize() != thePutSize) - debugs(91,3, HERE << "aborting on premature eof" << status()); - } else { - // asserta that we can detect the abort if the consumer joins later - assert(!bodySizeKnown() || bodySize() != thePutSize); - } - scheduleBodyEndNotification(); - } + if (theProducer) { + debugs(91,7, HERE << "clearing BodyPipe producer" << status()); + theProducer = NULL; + if (atEof) { + if (!bodySizeKnown()) + theBodySize = thePutSize; + else + if (bodySize() != thePutSize) + debugs(91,3, HERE << "aborting on premature eof" << status()); + } else { + // asserta that we can detect the abort if the consumer joins later + assert(!bodySizeKnown() || bodySize() != thePutSize); + } + scheduleBodyEndNotification(); + } } size_t BodyPipe::putMoreData(const char *buf, size_t size) { - if (bodySizeKnown()) - size = XMIN((uint64_t)size, unproducedSize()); - - const size_t spaceSize = static_cast(theBuf.potentialSpaceSize()); - if ((size = XMIN(size, spaceSize))) { - theBuf.append(buf, size); - postAppend(size); - return size; - } - return 0; + if (bodySizeKnown()) + size = XMIN((uint64_t)size, unproducedSize()); + + const size_t spaceSize = static_cast(theBuf.potentialSpaceSize()); + if ((size = XMIN(size, spaceSize))) { + theBuf.append(buf, size); + postAppend(size); + return size; + } + return 0; } bool BodyPipe::setConsumerIfNotLate(Consumer *aConsumer) { - assert(!theConsumer); - assert(aConsumer); - - // TODO: convert this into an exception and remove IfNotLate suffix - // If there is something consumed already, we are in an auto-consuming mode - // and it is too late to attach a real consumer to the pipe. - if (theGetSize > 0) { - assert(mustAutoConsume); - return false; - } + assert(!theConsumer); + assert(aConsumer); + + // TODO: convert this into an exception and remove IfNotLate suffix + // If there is something consumed already, we are in an auto-consuming mode + // and it is too late to attach a real consumer to the pipe. + if (theGetSize > 0) { + assert(mustAutoConsume); + return false; + } - theConsumer = aConsumer; - debugs(91,7, HERE << "set consumer" << status()); - if (theBuf.hasContent()) - scheduleBodyDataNotification(); - if (!theProducer) - scheduleBodyEndNotification(); + theConsumer = aConsumer; + debugs(91,7, HERE << "set consumer" << status()); + if (theBuf.hasContent()) + scheduleBodyDataNotification(); + if (!theProducer) + scheduleBodyEndNotification(); - return true; + return true; } // When BodyPipe consumer is gone, all events for that consumer must not // reach the new consumer (if any). Otherwise, the calls may go out of order -// (if _some_ calls are dropped due to the ultimate destination being +// (if _some_ calls are dropped due to the ultimate destination being // temporary NULL). The code keeps track of the number of outstanding // events and skips that number if consumer leaves. TODO: when AscyncCall // support is improved, should we just schedule calls directly to consumer? void -BodyPipe::clearConsumer() { - if (theConsumer) { - debugs(91,7, HERE << "clearing consumer" << status()); - theConsumer = NULL; - if (consumedSize() && !exhausted()) { - AsyncCall::Pointer call= asyncCall(91, 7, - "BodyProducer::noteBodyConsumerAborted", - BodyProducerDialer(theProducer, - &BodyProducer::noteBodyConsumerAborted, this)); - ScheduleCallHere(call); - } - } +BodyPipe::clearConsumer() +{ + if (theConsumer) { + debugs(91,7, HERE << "clearing consumer" << status()); + theConsumer = NULL; + if (consumedSize() && !exhausted()) { + AsyncCall::Pointer call= asyncCall(91, 7, + "BodyProducer::noteBodyConsumerAborted", + BodyProducerDialer(theProducer, + &BodyProducer::noteBodyConsumerAborted, this)); + ScheduleCallHere(call); + } + } } size_t BodyPipe::getMoreData(MemBuf &buf) { - if (!theBuf.hasContent()) - return 0; // did not touch the possibly uninitialized buf + if (!theBuf.hasContent()) + return 0; // did not touch the possibly uninitialized buf - if (buf.isNull()) - buf.init(); - const size_t size = XMIN(theBuf.contentSize(), buf.potentialSpaceSize()); - buf.append(theBuf.content(), size); - theBuf.consume(size); - postConsume(size); - return size; // cannot be zero if we called buf.init above + if (buf.isNull()) + buf.init(); + const size_t size = XMIN(theBuf.contentSize(), buf.potentialSpaceSize()); + buf.append(theBuf.content(), size); + theBuf.consume(size); + postConsume(size); + return size; // cannot be zero if we called buf.init above } void BodyPipe::consume(size_t size) { - theBuf.consume(size); - postConsume(size); + theBuf.consume(size); + postConsume(size); } -// In the AutoConsumption mode the consumer has gone but the producer continues +// In the AutoConsumption mode the consumer has gone but the producer continues // producing data. We are using a BodySink BodyConsumer which just discards the produced data. void -BodyPipe::enableAutoConsumption() { - mustAutoConsume = true; - debugs(91,5, HERE << "enabled auto consumption" << status()); - if (!theConsumer && theBuf.hasContent()) - startAutoConsumption(); +BodyPipe::enableAutoConsumption() +{ + mustAutoConsume = true; + debugs(91,5, HERE << "enabled auto consumption" << status()); + if (!theConsumer && theBuf.hasContent()) + startAutoConsumption(); } // start auto consumption by creating body sink void BodyPipe::startAutoConsumption() { - Must(mustAutoConsume); - Must(!theConsumer); - theConsumer = new BodySink; - debugs(91,7, HERE << "starting auto consumption" << status()); - scheduleBodyDataNotification(); + Must(mustAutoConsume); + Must(!theConsumer); + theConsumer = new BodySink; + debugs(91,7, HERE << "starting auto consumption" << status()); + scheduleBodyDataNotification(); } MemBuf & -BodyPipe::checkOut() { - assert(!isCheckedOut); - isCheckedOut = true; - return theBuf; +BodyPipe::checkOut() +{ + assert(!isCheckedOut); + isCheckedOut = true; + return theBuf; } void BodyPipe::checkIn(Checkout &checkout) { - assert(isCheckedOut); - isCheckedOut = false; - const size_t currentSize = theBuf.contentSize(); - if (checkout.checkedOutSize > currentSize) - postConsume(checkout.checkedOutSize - currentSize); - else - if (checkout.checkedOutSize < currentSize) - postAppend(currentSize - checkout.checkedOutSize); + assert(isCheckedOut); + isCheckedOut = false; + const size_t currentSize = theBuf.contentSize(); + if (checkout.checkedOutSize > currentSize) + postConsume(checkout.checkedOutSize - currentSize); + else + if (checkout.checkedOutSize < currentSize) + postAppend(currentSize - checkout.checkedOutSize); } void BodyPipe::undoCheckOut(Checkout &checkout) { - assert(isCheckedOut); - const size_t currentSize = theBuf.contentSize(); - // We can only undo if size did not change, and even that carries - // some risk. If this becomes a problem, the code checking out - // raw buffers should always check them in (possibly unchanged) - // instead of relying on the automated undo mechanism of Checkout. - // The code can always use a temporary buffer to accomplish that. - assert(checkout.checkedOutSize == currentSize); + assert(isCheckedOut); + const size_t currentSize = theBuf.contentSize(); + // We can only undo if size did not change, and even that carries + // some risk. If this becomes a problem, the code checking out + // raw buffers should always check them in (possibly unchanged) + // instead of relying on the automated undo mechanism of Checkout. + // The code can always use a temporary buffer to accomplish that. + assert(checkout.checkedOutSize == currentSize); } // TODO: Optimize: inform consumer/producer about more data/space only if // they used the data/space since we notified them last time. void -BodyPipe::postConsume(size_t size) { - assert(!isCheckedOut); - theGetSize += size; - debugs(91,7, HERE << "consumed " << size << " bytes" << status()); - if (mayNeedMoreData()){ - AsyncCall::Pointer call= asyncCall(91, 7, - "BodyProducer::noteMoreBodySpaceAvailable", - BodyProducerDialer(theProducer, - &BodyProducer::noteMoreBodySpaceAvailable, this)); - ScheduleCallHere(call); - } +BodyPipe::postConsume(size_t size) +{ + assert(!isCheckedOut); + theGetSize += size; + debugs(91,7, HERE << "consumed " << size << " bytes" << status()); + if (mayNeedMoreData()) { + AsyncCall::Pointer call= asyncCall(91, 7, + "BodyProducer::noteMoreBodySpaceAvailable", + BodyProducerDialer(theProducer, + &BodyProducer::noteMoreBodySpaceAvailable, this)); + ScheduleCallHere(call); + } } void -BodyPipe::postAppend(size_t size) { - assert(!isCheckedOut); - thePutSize += size; - debugs(91,7, HERE << "added " << size << " bytes" << status()); +BodyPipe::postAppend(size_t size) +{ + assert(!isCheckedOut); + thePutSize += size; + debugs(91,7, HERE << "added " << size << " bytes" << status()); - if (mustAutoConsume && !theConsumer && size > 0) - startAutoConsumption(); + if (mustAutoConsume && !theConsumer && size > 0) + startAutoConsumption(); - // We should not consume here even if mustAutoConsume because the - // caller may not be ready for the data to be consumed during this call. - scheduleBodyDataNotification(); + // We should not consume here even if mustAutoConsume because the + // caller may not be ready for the data to be consumed during this call. + scheduleBodyDataNotification(); - if (!mayNeedMoreData()) - clearProducer(true); // reached end-of-body + if (!mayNeedMoreData()) + clearProducer(true); // reached end-of-body } void BodyPipe::scheduleBodyDataNotification() { - if (theConsumer) { - AsyncCall::Pointer call = asyncCall(91, 7, - "BodyConsumer::noteMoreBodyDataAvailable", - BodyConsumerDialer(theConsumer, - &BodyConsumer::noteMoreBodyDataAvailable, this)); - ScheduleCallHere(call); - } + if (theConsumer) { + AsyncCall::Pointer call = asyncCall(91, 7, + "BodyConsumer::noteMoreBodyDataAvailable", + BodyConsumerDialer(theConsumer, + &BodyConsumer::noteMoreBodyDataAvailable, this)); + ScheduleCallHere(call); + } } void BodyPipe::scheduleBodyEndNotification() { - if (theConsumer) { - if (bodySizeKnown() && bodySize() == thePutSize) { - AsyncCall::Pointer call = asyncCall(91, 7, - "BodyConsumer::noteBodyProductionEnded", - BodyConsumerDialer(theConsumer, - &BodyConsumer::noteBodyProductionEnded, this)); - ScheduleCallHere(call); - } - else { - AsyncCall::Pointer call = asyncCall(91, 7, - "BodyConsumer::noteBodyProducerAborted", - BodyConsumerDialer(theConsumer, - &BodyConsumer::noteBodyProducerAborted, this)); - ScheduleCallHere(call); - } - } + if (theConsumer) { + if (bodySizeKnown() && bodySize() == thePutSize) { + AsyncCall::Pointer call = asyncCall(91, 7, + "BodyConsumer::noteBodyProductionEnded", + BodyConsumerDialer(theConsumer, + &BodyConsumer::noteBodyProductionEnded, this)); + ScheduleCallHere(call); + } else { + AsyncCall::Pointer call = asyncCall(91, 7, + "BodyConsumer::noteBodyProducerAborted", + BodyConsumerDialer(theConsumer, + &BodyConsumer::noteBodyProducerAborted, this)); + ScheduleCallHere(call); + } + } } // a short temporary string describing buffer status for debugging @@ -409,24 +416,24 @@ const char *BodyPipe::status() const buf.append(" [", 2); - buf.Printf("%"PRIu64"<=%"PRIu64, theGetSize, thePutSize); + buf.Printf("%"PRIu64"<=%"PRIu64, theGetSize, thePutSize); if (theBodySize >= 0) buf.Printf("<=%"PRId64, theBodySize); - else - buf.append("<=?", 3); + else + buf.append("<=?", 3); - buf.Printf(" %d+%d", (int)theBuf.contentSize(), (int)theBuf.spaceSize()); + buf.Printf(" %d+%d", (int)theBuf.contentSize(), (int)theBuf.spaceSize()); - buf.Printf(" pipe%p", this); + buf.Printf(" pipe%p", this); if (theProducer) buf.Printf(" prod%p", theProducer); if (theConsumer) buf.Printf(" cons%p", theConsumer); - if (mustAutoConsume) - buf.append(" A", 2); - if (isCheckedOut) - buf.append(" L", 2); // Locked + if (mustAutoConsume) + buf.append(" A", 2); + if (isCheckedOut) + buf.append(" L", 2); // Locked buf.append("]", 1); @@ -439,36 +446,36 @@ const char *BodyPipe::status() const /* BodyPipeCheckout */ BodyPipeCheckout::BodyPipeCheckout(BodyPipe &aPipe): pipe(aPipe), - buf(aPipe.checkOut()), offset(aPipe.consumedSize()), - checkedOutSize(buf.contentSize()), checkedIn(false) + buf(aPipe.checkOut()), offset(aPipe.consumedSize()), + checkedOutSize(buf.contentSize()), checkedIn(false) { } BodyPipeCheckout::~BodyPipeCheckout() { - if (!checkedIn) - pipe.undoCheckOut(*this); + if (!checkedIn) + pipe.undoCheckOut(*this); } void BodyPipeCheckout::checkIn() { - assert(!checkedIn); - pipe.checkIn(*this); - checkedIn = true; + assert(!checkedIn); + pipe.checkIn(*this); + checkedIn = true; } BodyPipeCheckout::BodyPipeCheckout(const BodyPipeCheckout &c): pipe(c.pipe), - buf(c.buf), offset(c.offset), checkedOutSize(c.checkedOutSize), - checkedIn(c.checkedIn) + buf(c.buf), offset(c.offset), checkedOutSize(c.checkedOutSize), + checkedIn(c.checkedIn) { - assert(false); // prevent copying + assert(false); // prevent copying } BodyPipeCheckout & BodyPipeCheckout::operator =(const BodyPipeCheckout &) { - assert(false); // prevent assignment - return *this; + assert(false); // prevent assignment + return *this; } diff --git a/src/BodyPipe.h b/src/BodyPipe.h index 0db4cc4baa..7ce016ef3a 100644 --- a/src/BodyPipe.h +++ b/src/BodyPipe.h @@ -11,138 +11,142 @@ class BodyPipe; // Interface for those who want to produce body content for others. // BodyProducer is expected to create the BodyPipe. // One pipe cannot have more than one producer. -class BodyProducer: virtual public AsyncJob { - public: - BodyProducer():AsyncJob("BodyProducer"){} - virtual ~BodyProducer() {} +class BodyProducer: virtual public AsyncJob +{ +public: + BodyProducer():AsyncJob("BodyProducer") {} + virtual ~BodyProducer() {} - virtual void noteMoreBodySpaceAvailable(RefCount bp) = 0; - virtual void noteBodyConsumerAborted(RefCount bp) = 0; + virtual void noteMoreBodySpaceAvailable(RefCount bp) = 0; + virtual void noteBodyConsumerAborted(RefCount bp) = 0; - protected: - void stopProducingFor(RefCount &pipe, bool atEof); +protected: + void stopProducingFor(RefCount &pipe, bool atEof); }; // Interface for those who want to consume body content from others. // BodyConsumer is expected to register with an existing BodyPipe // by calling BodyPipe::setConsumer(). // One pipe cannot have more than one consumer. -class BodyConsumer: virtual public AsyncJob { - public: - BodyConsumer():AsyncJob("BodyConsumer"){} - virtual ~BodyConsumer() {} - - virtual void noteMoreBodyDataAvailable(RefCount bp) = 0; - virtual void noteBodyProductionEnded(RefCount bp) = 0; - virtual void noteBodyProducerAborted(RefCount bp) = 0; - - protected: - void stopConsumingFrom(RefCount &pipe); +class BodyConsumer: virtual public AsyncJob +{ +public: + BodyConsumer():AsyncJob("BodyConsumer") {} + virtual ~BodyConsumer() {} + + virtual void noteMoreBodyDataAvailable(RefCount bp) = 0; + virtual void noteBodyProductionEnded(RefCount bp) = 0; + virtual void noteBodyProducerAborted(RefCount bp) = 0; + +protected: + void stopConsumingFrom(RefCount &pipe); }; // Makes raw buffer checkin/checkout interface efficient and exception-safe. // Either append or consume operations can be performed on a checkedout buffer. -class BodyPipeCheckout { - public: - friend class BodyPipe; +class BodyPipeCheckout +{ +public: + friend class BodyPipe; - public: - BodyPipeCheckout(BodyPipe &pipe); // checks out - ~BodyPipeCheckout(); // aborts checkout unless checkedIn +public: + BodyPipeCheckout(BodyPipe &pipe); // checks out + ~BodyPipeCheckout(); // aborts checkout unless checkedIn - void checkIn(); + void checkIn(); - public: - BodyPipe &pipe; - MemBuf &buf; - const uint64_t offset; // of current content, relative to the body start +public: + BodyPipe &pipe; + MemBuf &buf; + const uint64_t offset; // of current content, relative to the body start - protected: - const size_t checkedOutSize; - bool checkedIn; +protected: + const size_t checkedOutSize; + bool checkedIn; - private: - BodyPipeCheckout(const BodyPipeCheckout &); // prevent copying - BodyPipeCheckout &operator =(const BodyPipeCheckout &); // prevent assignment +private: + BodyPipeCheckout(const BodyPipeCheckout &); // prevent copying + BodyPipeCheckout &operator =(const BodyPipeCheckout &); // prevent assignment }; // Connects those who produces message body content with those who // consume it. For example, connects ConnStateData with FtpStateData OR // ICAPModXact with HttpStateData. -class BodyPipe: public RefCountable { - public: - typedef RefCount Pointer; - typedef BodyProducer Producer; - typedef BodyConsumer Consumer; - typedef BodyPipeCheckout Checkout; +class BodyPipe: public RefCountable +{ +public: + typedef RefCount Pointer; + typedef BodyProducer Producer; + typedef BodyConsumer Consumer; + typedef BodyPipeCheckout Checkout; - enum { MaxCapacity = SQUID_TCP_SO_RCVBUF }; + enum { MaxCapacity = SQUID_TCP_SO_RCVBUF }; - friend class BodyPipeCheckout; + friend class BodyPipeCheckout; - public: - BodyPipe(Producer *aProducer); - ~BodyPipe(); // asserts that producer and consumer are cleared +public: + BodyPipe(Producer *aProducer); + ~BodyPipe(); // asserts that producer and consumer are cleared - void setBodySize(uint64_t aSize); // set body size - bool bodySizeKnown() const { return theBodySize >= 0; } - uint64_t bodySize() const; - uint64_t consumedSize() const { return theGetSize; } - bool productionEnded() const { return !theProducer; } + void setBodySize(uint64_t aSize); // set body size + bool bodySizeKnown() const { return theBodySize >= 0; } + uint64_t bodySize() const; + uint64_t consumedSize() const { return theGetSize; } + bool productionEnded() const { return !theProducer; } - // called by producers - void clearProducer(bool atEof); // aborts or sends eof - size_t putMoreData(const char *buf, size_t size); - bool mayNeedMoreData() const { return !bodySizeKnown() || needsMoreData(); } - bool needsMoreData() const { return bodySizeKnown() && unproducedSize() > 0; } - uint64_t unproducedSize() const; // size of still unproduced data - bool stillProducing(const Producer *producer) const { return theProducer == producer; } + // called by producers + void clearProducer(bool atEof); // aborts or sends eof + size_t putMoreData(const char *buf, size_t size); + bool mayNeedMoreData() const { return !bodySizeKnown() || needsMoreData(); } + bool needsMoreData() const { return bodySizeKnown() && unproducedSize() > 0; } + uint64_t unproducedSize() const; // size of still unproduced data + bool stillProducing(const Producer *producer) const { return theProducer == producer; } - // called by consumers - bool setConsumerIfNotLate(Consumer *aConsumer); - void clearConsumer(); // aborts if still piping - size_t getMoreData(MemBuf &buf); - void consume(size_t size); - bool expectMoreAfter(uint64_t offset) const; - bool exhausted() const; // saw eof/abort and all data consumed - bool stillConsuming(const Consumer *consumer) const { return theConsumer == consumer; } + // called by consumers + bool setConsumerIfNotLate(Consumer *aConsumer); + void clearConsumer(); // aborts if still piping + size_t getMoreData(MemBuf &buf); + void consume(size_t size); + bool expectMoreAfter(uint64_t offset) const; + bool exhausted() const; // saw eof/abort and all data consumed + bool stillConsuming(const Consumer *consumer) const { return theConsumer == consumer; } - // start or continue consuming when there is no consumer - void enableAutoConsumption(); + // start or continue consuming when there is no consumer + void enableAutoConsumption(); - const MemBuf &buf() const { return theBuf; } + const MemBuf &buf() const { return theBuf; } - const char *status() const; // for debugging only + const char *status() const; // for debugging only - protected: - // lower-level interface used by Checkout - MemBuf &checkOut(); // obtain raw buffer - void checkIn(Checkout &checkout); // return updated raw buffer - void undoCheckOut(Checkout &checkout); // undo checkout efffect +protected: + // lower-level interface used by Checkout + MemBuf &checkOut(); // obtain raw buffer + void checkIn(Checkout &checkout); // return updated raw buffer + void undoCheckOut(Checkout &checkout); // undo checkout efffect - void scheduleBodyDataNotification(); - void scheduleBodyEndNotification(); + void scheduleBodyDataNotification(); + void scheduleBodyEndNotification(); - // keep counters in sync and notify producer or consumer - void postConsume(size_t size); - void postAppend(size_t size); + // keep counters in sync and notify producer or consumer + void postConsume(size_t size); + void postAppend(size_t size); - void startAutoConsumption(); // delayed start of enabled consumption + void startAutoConsumption(); // delayed start of enabled consumption - private: - int64_t theBodySize; // expected total content length, if known - Producer *theProducer; // content producer, if any - Consumer *theConsumer; // content consumer, if any +private: + int64_t theBodySize; // expected total content length, if known + Producer *theProducer; // content producer, if any + Consumer *theConsumer; // content consumer, if any - uint64_t thePutSize; // ever-increasing total - uint64_t theGetSize; // ever-increasing total + uint64_t thePutSize; // ever-increasing total + uint64_t theGetSize; // ever-increasing total - MemBuf theBuf; // produced but not yet consumed content, if any + MemBuf theBuf; // produced but not yet consumed content, if any - bool mustAutoConsume; // consume when there is no consumer - bool isCheckedOut; // to keep track of checkout violations + bool mustAutoConsume; // consume when there is no consumer + bool isCheckedOut; // to keep track of checkout violations - CBDATA_CLASS2(BodyPipe); + CBDATA_CLASS2(BodyPipe); }; #endif /* SQUID_BODY_PIPE_H */ diff --git a/src/CacheDigest.cc b/src/CacheDigest.cc index a81b663f30..1459afcd82 100644 --- a/src/CacheDigest.cc +++ b/src/CacheDigest.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -40,8 +40,7 @@ /* local types */ -typedef struct -{ +typedef struct { int bit_count; /* total number of bits */ int bit_on_count; /* #bits turned on */ int bseq_len_sum; /* sum of all bit seq length */ @@ -157,26 +156,22 @@ cacheDigestAdd(CacheDigest * cd, const cache_key * key) { int on_xition_cnt = 0; - if (!CBIT_TEST(cd->mask, hashed_keys[0])) - { + if (!CBIT_TEST(cd->mask, hashed_keys[0])) { CBIT_SET(cd->mask, hashed_keys[0]); on_xition_cnt++; } - if (!CBIT_TEST(cd->mask, hashed_keys[1])) - { + if (!CBIT_TEST(cd->mask, hashed_keys[1])) { CBIT_SET(cd->mask, hashed_keys[1]); on_xition_cnt++; } - if (!CBIT_TEST(cd->mask, hashed_keys[2])) - { + if (!CBIT_TEST(cd->mask, hashed_keys[2])) { CBIT_SET(cd->mask, hashed_keys[2]); on_xition_cnt++; } - if (!CBIT_TEST(cd->mask, hashed_keys[3])) - { + if (!CBIT_TEST(cd->mask, hashed_keys[3])) { CBIT_SET(cd->mask, hashed_keys[3]); on_xition_cnt++; } diff --git a/src/CacheManager.h b/src/CacheManager.h index cda9426909..f775eed030 100644 --- a/src/CacheManager.h +++ b/src/CacheManager.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -50,18 +50,18 @@ * The basic action handler. Its virtual method run(StoreEntry *) is invoked * to perform the actual action. */ -class CacheManagerAction { -public: - virtual void run(StoreEntry *sentry) = 0; - char *action; - char *desc; - struct - { - unsigned int pw_req:1; - unsigned int atomic:1; - } flags; - virtual ~CacheManagerAction(); - CacheManagerAction(char const *anAction, char const *aDesc, unsigned int isPwReq, unsigned int isAtomic); +class CacheManagerAction +{ +public: + virtual void run(StoreEntry *sentry) = 0; + char *action; + char *desc; + struct { + unsigned int pw_req:1; + unsigned int atomic:1; + } flags; + virtual ~CacheManagerAction(); + CacheManagerAction(char const *anAction, char const *aDesc, unsigned int isPwReq, unsigned int isAtomic); }; @@ -71,11 +71,12 @@ public: * managed by the caller. * This object is generated by CacheManager::registerAction */ -class CacheManagerActionLegacy : public CacheManagerAction { +class CacheManagerActionLegacy : public CacheManagerAction +{ public: - OBJH *handler; - virtual void run (StoreEntry *sentry); - CacheManagerActionLegacy(char const *anAction, char const *aDesc, unsigned int isPwReq, unsigned int isAtomic, OBJH *aHandler); + OBJH *handler; + virtual void run (StoreEntry *sentry); + CacheManagerActionLegacy(char const *anAction, char const *aDesc, unsigned int isPwReq, unsigned int isAtomic, OBJH *aHandler); }; @@ -112,34 +113,37 @@ protected: // command classes. They are private to the cachemanager, they // may require access to local data, plus we avoid polluting // the namespace more than needed. - class ShutdownAction : public CacheManagerAction { + class ShutdownAction : public CacheManagerAction + { public: - virtual void run (StoreEntry *sentry); - ShutdownAction(); + virtual void run (StoreEntry *sentry); + ShutdownAction(); }; - class ReconfigureAction : public CacheManagerAction { + class ReconfigureAction : public CacheManagerAction + { public: - virtual void run (StoreEntry *sentry); - ReconfigureAction(); + virtual void run (StoreEntry *sentry); + ReconfigureAction(); }; - class OfflineToggleAction : public CacheManagerAction { + class OfflineToggleAction : public CacheManagerAction + { public: - virtual void run (StoreEntry *sentry); - OfflineToggleAction(); + virtual void run (StoreEntry *sentry); + OfflineToggleAction(); }; - class MenuAction : public CacheManagerAction { + class MenuAction : public CacheManagerAction + { private: - //needs to reference the cachemgr in order to get to ActionsList - CacheManager *cmgr; + //needs to reference the cachemgr in order to get to ActionsList + CacheManager *cmgr; public: - virtual void run (StoreEntry *sentry); - MenuAction(CacheManager *); + virtual void run (StoreEntry *sentry); + MenuAction(CacheManager *); }; /// \ingroup CacheManagerInternal - typedef struct - { + typedef struct { StoreEntry *entry; char *action; char *user_name; @@ -147,7 +151,7 @@ protected: } cachemgrStateData; - CacheManager(); + CacheManager(); cachemgrStateData* ParseUrl(const char *url); void ParseHeaders(cachemgrStateData * mgr, const HttpRequest * request); int CheckPassword(cachemgrStateData * mgr); diff --git a/src/ChunkedCodingParser.h b/src/ChunkedCodingParser.h index aea269338b..5fc0c1c808 100644 --- a/src/ChunkedCodingParser.h +++ b/src/ChunkedCodingParser.h @@ -1,6 +1,6 @@ /* * $Id: ChunkedCodingParser.h,v 1.1 2007/12/26 22:33:32 hno Exp $ - * + * * SQUID Web Proxy Cache http://www.squid-cache.org/ * ---------------------------------------------------------- * @@ -17,12 +17,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/CommCalls.cc b/src/CommCalls.cc index 6e5abbd154..8ba22a856a 100644 --- a/src/CommCalls.cc +++ b/src/CommCalls.cc @@ -5,12 +5,12 @@ /* CommCommonCbParams */ CommCommonCbParams::CommCommonCbParams(void *aData): - data(cbdataReference(aData)), fd(-1), xerrno(0), flag(COMM_OK) + data(cbdataReference(aData)), fd(-1), xerrno(0), flag(COMM_OK) { } CommCommonCbParams::CommCommonCbParams(const CommCommonCbParams &p): - data(cbdataReference(p.data)), fd(p.fd), xerrno(p.xerrno), flag(p.flag) + data(cbdataReference(p.data)), fd(p.fd), xerrno(p.xerrno), flag(p.flag) { } @@ -35,7 +35,7 @@ CommCommonCbParams::print(std::ostream &os) const /* CommAcceptCbParams */ CommAcceptCbParams::CommAcceptCbParams(void *aData): CommCommonCbParams(aData), - nfd(-1) + nfd(-1) { } @@ -51,7 +51,7 @@ CommAcceptCbParams::print(std::ostream &os) const /* CommConnectCbParams */ CommConnectCbParams::CommConnectCbParams(void *aData): - CommCommonCbParams(aData) + CommCommonCbParams(aData) { } @@ -61,7 +61,7 @@ CommConnectCbParams::syncWithComm() // drop the call if the call was scheduled before comm_close but // is being fired after comm_close if (fd >= 0 && fd_table[fd].closing()) { - debugs(5, 3, HERE << "droppin late connect call: FD " << fd); + debugs(5, 3, HERE << "droppin late connect call: FD " << fd); return false; } return true; // now we are in sync and can handle the call @@ -70,7 +70,7 @@ CommConnectCbParams::syncWithComm() /* CommIoCbParams */ CommIoCbParams::CommIoCbParams(void *aData): CommCommonCbParams(aData), - buf(NULL), size(0) + buf(NULL), size(0) { } @@ -80,12 +80,12 @@ CommIoCbParams::syncWithComm() // change parameters if the call was scheduled before comm_close but // is being fired after comm_close if (fd >= 0 && fd_table[fd].closing() && flag != COMM_ERR_CLOSING) { - debugs(5, 3, HERE << "converting late call to COMM_ERR_CLOSING: FD " << fd); - flag = COMM_ERR_CLOSING; - size = 0; + debugs(5, 3, HERE << "converting late call to COMM_ERR_CLOSING: FD " << fd); + flag = COMM_ERR_CLOSING; + size = 0; } return true; // now we are in sync and can handle the call -} +} void @@ -95,21 +95,21 @@ CommIoCbParams::print(std::ostream &os) const if (buf) { os << ", size=" << size; os << ", buf=" << (void*)buf; - } + } } /* CommCloseCbParams */ CommCloseCbParams::CommCloseCbParams(void *aData): - CommCommonCbParams(aData) + CommCommonCbParams(aData) { } /* CommTimeoutCbParams */ CommTimeoutCbParams::CommTimeoutCbParams(void *aData): - CommCommonCbParams(aData) + CommCommonCbParams(aData) { } @@ -117,9 +117,9 @@ CommTimeoutCbParams::CommTimeoutCbParams(void *aData): /* CommAcceptCbPtrFun */ CommAcceptCbPtrFun::CommAcceptCbPtrFun(IOACB *aHandler, - const CommAcceptCbParams &aParams): - CommDialerParamsT(aParams), - handler(aHandler) + const CommAcceptCbParams &aParams): + CommDialerParamsT(aParams), + handler(aHandler) { } @@ -141,9 +141,9 @@ CommAcceptCbPtrFun::print(std::ostream &os) const /* CommConnectCbPtrFun */ CommConnectCbPtrFun::CommConnectCbPtrFun(CNCB *aHandler, - const CommConnectCbParams &aParams): - CommDialerParamsT(aParams), - handler(aHandler) + const CommConnectCbParams &aParams): + CommDialerParamsT(aParams), + handler(aHandler) { } @@ -165,8 +165,8 @@ CommConnectCbPtrFun::print(std::ostream &os) const /* CommIoCbPtrFun */ CommIoCbPtrFun::CommIoCbPtrFun(IOCB *aHandler, const CommIoCbParams &aParams): - CommDialerParamsT(aParams), - handler(aHandler) + CommDialerParamsT(aParams), + handler(aHandler) { } @@ -188,9 +188,9 @@ CommIoCbPtrFun::print(std::ostream &os) const /* CommCloseCbPtrFun */ CommCloseCbPtrFun::CommCloseCbPtrFun(PF *aHandler, - const CommCloseCbParams &aParams): - CommDialerParamsT(aParams), - handler(aHandler) + const CommCloseCbParams &aParams): + CommDialerParamsT(aParams), + handler(aHandler) { } @@ -211,9 +211,9 @@ CommCloseCbPtrFun::print(std::ostream &os) const /* CommTimeoutCbPtrFun */ CommTimeoutCbPtrFun::CommTimeoutCbPtrFun(PF *aHandler, - const CommTimeoutCbParams &aParams): - CommDialerParamsT(aParams), - handler(aHandler) + const CommTimeoutCbParams &aParams): + CommDialerParamsT(aParams), + handler(aHandler) { } diff --git a/src/CommCalls.h b/src/CommCalls.h index 0a81507203..6f6a8019a9 100644 --- a/src/CommCalls.h +++ b/src/CommCalls.h @@ -21,21 +21,22 @@ * - I/O (IOCB). */ - /* - * TODO: When there are no function-pointer-based callbacks left, all - * this complexity can be removed. Jobs that need comm services will just - * implement CommReader, CommWriter, etc. interfaces and receive calls - * using general (not comm-specific) AsyncCall code. For now, we have to - * allow the caller to create a callback that comm can modify to set - * parameters, which is not trivial when the caller type/kind is not - * known to comm and there are many kinds of parameters. - */ +/* + * TODO: When there are no function-pointer-based callbacks left, all + * this complexity can be removed. Jobs that need comm services will just + * implement CommReader, CommWriter, etc. interfaces and receive calls + * using general (not comm-specific) AsyncCall code. For now, we have to + * allow the caller to create a callback that comm can modify to set + * parameters, which is not trivial when the caller type/kind is not + * known to comm and there are many kinds of parameters. + */ /* Comm*CbParams classes below handle callback parameters */ // Maintains parameters common to all comm callbacks -class CommCommonCbParams { +class CommCommonCbParams +{ public: CommCommonCbParams(void *aData); CommCommonCbParams(const CommCommonCbParams ¶ms); @@ -43,7 +44,7 @@ public: /// adjust using the current Comm state; returns false to cancel the call // not virtual because callers know dialer type - bool syncWithComm() { return true; } + bool syncWithComm() { return true; } void print(std::ostream &os) const; @@ -55,11 +56,12 @@ public: private: // should not be needed and not yet implemented - CommCommonCbParams &operator =(const CommCommonCbParams ¶ms); + CommCommonCbParams &operator =(const CommCommonCbParams ¶ms); }; // accept parameters -class CommAcceptCbParams: public CommCommonCbParams { +class CommAcceptCbParams: public CommCommonCbParams +{ public: CommAcceptCbParams(void *aData); @@ -71,7 +73,8 @@ public: }; // connect parameters -class CommConnectCbParams: public CommCommonCbParams { +class CommConnectCbParams: public CommCommonCbParams +{ public: CommConnectCbParams(void *aData); @@ -79,7 +82,8 @@ public: }; // read/write (I/O) parameters -class CommIoCbParams: public CommCommonCbParams { +class CommIoCbParams: public CommCommonCbParams +{ public: CommIoCbParams(void *aData); @@ -92,12 +96,14 @@ public: }; // close parameters -class CommCloseCbParams: public CommCommonCbParams { +class CommCloseCbParams: public CommCommonCbParams +{ public: CommCloseCbParams(void *aData); }; -class CommTimeoutCbParams: public CommCommonCbParams { +class CommTimeoutCbParams: public CommCommonCbParams +{ public: CommTimeoutCbParams(void *aData); }; @@ -105,7 +111,8 @@ public: // Interface to expose comm callback parameters of all comm dialers. // GetCommParams() uses this interface to access comm parameters. template -class CommDialerParamsT { +class CommDialerParamsT +{ public: typedef Params_ Params; CommDialerParamsT(const Params &io): params(io) {} @@ -116,8 +123,9 @@ public: // Get comm params of an async comm call template -Params &GetCommParams(AsyncCall::Pointer &call) { - typedef CommDialerParamsT DialerParams; +Params &GetCommParams(AsyncCall::Pointer &call) +{ + typedef CommDialerParamsT DialerParams; DialerParams *dp = dynamic_cast(call->getDialer()); assert(dp); return dp->params; @@ -134,16 +142,21 @@ public: typedef void (C::*Method)(const Params &io); CommCbMemFunT(C *obj, Method meth): JobDialer(obj), - CommDialerParamsT(obj), object(obj), method(meth) {} + CommDialerParamsT(obj), object(obj), method(meth) {} - virtual bool canDial(AsyncCall &c) { return JobDialer::canDial(c) && - this->params.syncWithComm(); } + virtual bool canDial(AsyncCall &c) { + return JobDialer::canDial(c) && + this->params.syncWithComm(); + } virtual void print(std::ostream &os) const { - os << '('; this->params.print(os); os << ')'; } + os << '('; + this->params.print(os); + os << ')'; + } public: - C *object; + C *object; Method method; protected: @@ -153,7 +166,7 @@ protected: // accept (IOACB) dialer class CommAcceptCbPtrFun: public CallDialer, - public CommDialerParamsT + public CommDialerParamsT { public: typedef CommAcceptCbParams Params; @@ -169,7 +182,7 @@ public: // connect (CNCB) dialer class CommConnectCbPtrFun: public CallDialer, - public CommDialerParamsT + public CommDialerParamsT { public: typedef CommConnectCbParams Params; @@ -186,7 +199,7 @@ public: // read/write (IOCB) dialer class CommIoCbPtrFun: public CallDialer, - public CommDialerParamsT + public CommDialerParamsT { public: typedef CommIoCbParams Params; @@ -203,7 +216,7 @@ public: // close (PF) dialer class CommCloseCbPtrFun: public CallDialer, - public CommDialerParamsT + public CommDialerParamsT { public: typedef CommCloseCbParams Params; @@ -218,7 +231,7 @@ public: }; class CommTimeoutCbPtrFun:public CallDialer, - public CommDialerParamsT + public CommDialerParamsT { public: typedef CommTimeoutCbParams Params; @@ -237,12 +250,13 @@ public: // TODO: Get rid of this class by moving canFire() to canDial() method // of dialers. template -class CommCbFunPtrCallT: public AsyncCall { +class CommCbFunPtrCallT: public AsyncCall +{ public: typedef typename Dialer::Params Params; inline CommCbFunPtrCallT(int debugSection, int debugLevel, - const char *callName, const Dialer &aDialer); + const char *callName, const Dialer &aDialer); virtual CallDialer* getDialer() { return &dialer; } @@ -259,10 +273,10 @@ protected: template inline CommCbFunPtrCallT *commCbCall(int debugSection, int debugLevel, - const char *callName, const Dialer &dialer) + const char *callName, const Dialer &dialer) { return new CommCbFunPtrCallT(debugSection, debugLevel, callName, - dialer); + dialer); } /* inlined implementation of templated methods */ @@ -271,7 +285,7 @@ CommCbFunPtrCallT *commCbCall(int debugSection, int debugLevel, template CommCbFunPtrCallT::CommCbFunPtrCallT(int debugSection, int debugLevel, - const char *callName, const Dialer &aDialer): + const char *callName, const Dialer &aDialer): AsyncCall(debugSection, debugLevel, callName), dialer(aDialer) { diff --git a/src/CommRead.h b/src/CommRead.h index b7c078178e..fb18bdaa81 100644 --- a/src/CommRead.h +++ b/src/CommRead.h @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/CommonPool.h b/src/CommonPool.h index 56a0b5e1a3..5c6da52ddc 100644 --- a/src/CommonPool.h +++ b/src/CommonPool.h @@ -22,12 +22,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -49,7 +49,7 @@ \ingroup DelayPoolsAPI * \todo Next steps: make this a composite, and TypeLabel a composite method. - * Then we have a legacy composite which returns class 1/2/3, and new + * Then we have a legacy composite which returns class 1/2/3, and new * composites which return a descriptor of some sort. */ class CommonPool diff --git a/src/CompletionDispatcher.cc b/src/CompletionDispatcher.cc index 2917206c93..1c589a94ad 100644 --- a/src/CompletionDispatcher.cc +++ b/src/CompletionDispatcher.cc @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/CompletionDispatcher.h b/src/CompletionDispatcher.h index afbff9f5d4..a65ea12312 100644 --- a/src/CompletionDispatcher.h +++ b/src/CompletionDispatcher.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/CompositePoolNode.h b/src/CompositePoolNode.h index 71da4ae35f..1694d25e1c 100644 --- a/src/CompositePoolNode.h +++ b/src/CompositePoolNode.h @@ -22,12 +22,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -60,7 +60,7 @@ public: typedef RefCount Pointer; void *operator new(size_t); void operator delete (void *); - virtual ~CompositePoolNode(){} + virtual ~CompositePoolNode() {} virtual void stats(StoreEntry * sentry) =0; virtual void dump(StoreEntry *entry) const =0; diff --git a/src/ConfigOption.cc b/src/ConfigOption.cc index 37634ee2c7..01535ec5e8 100644 --- a/src/ConfigOption.cc +++ b/src/ConfigOption.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -62,7 +62,7 @@ ConfigOptionVector::parse(char const *option, const char *value, int reconfiguri void ConfigOptionVector::dump(StoreEntry * e) const { - for(Vector::const_iterator i = options.begin(); + for (Vector::const_iterator i = options.begin(); i != options.end(); ++i) (*i)->dump(e); } diff --git a/src/ConfigOption.h b/src/ConfigOption.h index 970572d948..63a18a67cb 100644 --- a/src/ConfigOption.h +++ b/src/ConfigOption.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -67,16 +67,14 @@ class ConfigOptionAdapter : public ConfigOption public: ConfigOptionAdapter(C& theObject, bool (C::*parseFP)(char const *option, const char *value, int reconfiguring), void (C::*dumpFP) (StoreEntry * e) const) : object(theObject), parser (parseFP), dumper(dumpFP) {} - bool parse(char const *option, const char *value, int reconfiguring) - { + bool parse(char const *option, const char *value, int reconfiguring) { if (parser) return (object.*parser)(option, value, reconfiguring); return false; } - void dump(StoreEntry * e) const - { + void dump(StoreEntry * e) const { if (dumper) (object.*dumper) (e); } diff --git a/src/ConfigParser.cc b/src/ConfigParser.cc index 2f166fe683..38073289f3 100644 --- a/src/ConfigParser.cc +++ b/src/ConfigParser.cc @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -59,8 +59,8 @@ ConfigParser::strtokFile(void) t = (strtok(NULL, w_space)); if (!t || *t == '#') { - return NULL; - } else if (*t == '\"' || *t == '\'') { + return NULL; + } else if (*t == '\"' || *t == '\'') { /* quote found, start reading from file */ fn = ++t; @@ -110,7 +110,7 @@ ConfigParser::strtokFile(void) /* skip comments */ /* skip blank lines */ - } while( *t == '#' || !*t ); + } while ( *t == '#' || !*t ); return t; } diff --git a/src/ConfigParser.h b/src/ConfigParser.h index 20055bbb4f..d7a46aad81 100644 --- a/src/ConfigParser.h +++ b/src/ConfigParser.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ConnectionDetail.h b/src/ConnectionDetail.h index 637d434e8c..4706b29e47 100644 --- a/src/ConnectionDetail.h +++ b/src/ConnectionDetail.h @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/Debug.h b/src/Debug.h index 9d0aa7f7a5..0409dac2f4 100644 --- a/src/Debug.h +++ b/src/Debug.h @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -73,7 +73,7 @@ public: private: // Hack: replaces global ::xassert() to debug debugging assertions static void xassert(const char *msg, const char *file, int line); - + static std::ostringstream *CurrentDebug; static int TheDepth; // level of nested debugging calls }; @@ -95,7 +95,8 @@ private: #define HERE __FILE__<<"("<<__LINE__<<") "<<__FUNCTION__<<": " /* some uint8_t do not like streaming control-chars (values 0-31, 127+) */ -inline std::ostream& operator <<(std::ostream &os, const uint8_t d) { +inline std::ostream& operator <<(std::ostream &os, const uint8_t d) +{ return (os << (int)d); } diff --git a/src/DelayBucket.cc b/src/DelayBucket.cc index e4778424ab..3604c42bae 100644 --- a/src/DelayBucket.cc +++ b/src/DelayBucket.cc @@ -22,12 +22,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/DelayBucket.h b/src/DelayBucket.h index 3f0564bc4b..cac40bae98 100644 --- a/src/DelayBucket.h +++ b/src/DelayBucket.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/DelayConfig.cc b/src/DelayConfig.cc index b5ebfa46cb..b21c5a859e 100644 --- a/src/DelayConfig.cc +++ b/src/DelayConfig.cc @@ -23,12 +23,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/DelayConfig.h b/src/DelayConfig.h index ca5e23924d..5ad3413ffc 100644 --- a/src/DelayConfig.h +++ b/src/DelayConfig.h @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/DelayId.cc b/src/DelayId.cc index 4e9cb1e66e..990a040119 100644 --- a/src/DelayId.cc +++ b/src/DelayId.cc @@ -23,12 +23,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -81,7 +81,7 @@ bool DelayId::operator == (DelayId const &rhs) const { /* Doesn't compare composites properly.... - * only use to test against default ID's + * only use to test against default ID's */ return pool_ == rhs.pool_ && compositeId == rhs.compositeId; } @@ -105,15 +105,14 @@ DelayId::DelayClient(ClientHttpRequest * http) return DelayId(); } - for (pool = 0; pool < DelayPools::pools(); pool++) - { + for (pool = 0; pool < DelayPools::pools(); pool++) { ACLChecklist ch; #if FOLLOW_X_FORWARDED_FOR - if (Config.onoff.delay_pool_uses_indirect_client) - ch.src_addr = r->indirect_client_addr; - else -#endif /* FOLLOW_X_FORWARDED_FOR */ - ch.src_addr = r->client_addr; + if (Config.onoff.delay_pool_uses_indirect_client) + ch.src_addr = r->indirect_client_addr; + else +#endif /* FOLLOW_X_FORWARDED_FOR */ + ch.src_addr = r->client_addr; ch.my_addr = r->my_addr; if (http->getConn() != NULL) diff --git a/src/DelayId.h b/src/DelayId.h index 8a0a860b41..c58e88b80f 100644 --- a/src/DelayId.h +++ b/src/DelayId.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/DelayIdComposite.h b/src/DelayIdComposite.h index 079757494f..486433a582 100644 --- a/src/DelayIdComposite.h +++ b/src/DelayIdComposite.h @@ -23,12 +23,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -52,7 +52,7 @@ class DelayIdComposite : public RefCountable public: typedef RefCount Pointer; - virtual inline ~DelayIdComposite(){} + virtual inline ~DelayIdComposite() {} virtual int bytesWanted (int min, int max) const =0; virtual void bytesIn(int qty) = 0; diff --git a/src/DelayPool.cc b/src/DelayPool.cc index 9bff7a75d4..d5fa3ef429 100644 --- a/src/DelayPool.cc +++ b/src/DelayPool.cc @@ -22,12 +22,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/DelayPool.h b/src/DelayPool.h index 0420c9db24..d7d01b5209 100644 --- a/src/DelayPool.h +++ b/src/DelayPool.h @@ -23,12 +23,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -66,7 +66,7 @@ public: CommonPool *pool; CompositePoolNode::Pointer theComposite() {return theComposite_;} - CompositePoolNode::Pointer const theComposite() const{return theComposite_;} + CompositePoolNode::Pointer const theComposite() const {return theComposite_;} acl_access *access; diff --git a/src/DelayPools.h b/src/DelayPools.h index 42eb81f7c4..5809db23ab 100644 --- a/src/DelayPools.h +++ b/src/DelayPools.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -44,7 +44,7 @@ class Updateable { public: - virtual ~Updateable(){} + virtual ~Updateable() {} virtual void update(int) = 0; }; diff --git a/src/DelaySpec.cc b/src/DelaySpec.cc index 5fce176117..6302fe1dc7 100644 --- a/src/DelaySpec.cc +++ b/src/DelaySpec.cc @@ -23,12 +23,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/DelaySpec.h b/src/DelaySpec.h index 8b170614e0..ee8f2e9bb6 100644 --- a/src/DelaySpec.h +++ b/src/DelaySpec.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/DelayTagged.cc b/src/DelayTagged.cc index c39cc4ff2c..a1e48288ae 100644 --- a/src/DelayTagged.cc +++ b/src/DelayTagged.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -115,9 +115,8 @@ DelayTagged::dump(StoreEntry *entry) const spec.dump(entry); } -struct DelayTaggedUpdater -{ - DelayTaggedUpdater (DelaySpec &_spec, int _incr):spec(_spec),incr(_incr){}; +struct DelayTaggedUpdater { + DelayTaggedUpdater (DelaySpec &_spec, int _incr):spec(_spec),incr(_incr) {}; DelaySpec spec; int incr; diff --git a/src/DelayTagged.h b/src/DelayTagged.h index 76d629b3db..08c1c1e05d 100644 --- a/src/DelayTagged.h +++ b/src/DelayTagged.h @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/DelayUser.cc b/src/DelayUser.cc index e0840500ce..2a055eac2b 100644 --- a/src/DelayUser.cc +++ b/src/DelayUser.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -116,9 +116,8 @@ DelayUser::dump(StoreEntry *entry) const spec.dump(entry); } -struct DelayUserUpdater -{ - DelayUserUpdater (DelaySpec &_spec, int _incr):spec(_spec),incr(_incr){}; +struct DelayUserUpdater { + DelayUserUpdater (DelaySpec &_spec, int _incr):spec(_spec),incr(_incr) {}; DelaySpec spec; int incr; diff --git a/src/DelayUser.h b/src/DelayUser.h index 781ac66e2c..1341214988 100644 --- a/src/DelayUser.h +++ b/src/DelayUser.h @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/DelayVector.cc b/src/DelayVector.cc index b9b5b61ea9..6780e36ec6 100644 --- a/src/DelayVector.cc +++ b/src/DelayVector.cc @@ -23,12 +23,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/DelayVector.h b/src/DelayVector.h index 8bd7dd418c..445326ceed 100644 --- a/src/DelayVector.h +++ b/src/DelayVector.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/DescriptorSet.cc b/src/DescriptorSet.cc index 3bd2b6a4aa..0243ed72c2 100644 --- a/src/DescriptorSet.cc +++ b/src/DescriptorSet.cc @@ -9,7 +9,7 @@ // pre-allocates descriptor store and index for Squid_MaxFD descriptors DescriptorSet::DescriptorSet(): descriptors_(NULL), index_(NULL), - capacity_(0), size_(0) + capacity_(0), size_(0) { // we allocate once and never realloc, at least for now capacity_ = Squid_MaxFD; diff --git a/src/DescriptorSet.h b/src/DescriptorSet.h index 44846c7c6b..b839a0962a 100644 --- a/src/DescriptorSet.h +++ b/src/DescriptorSet.h @@ -9,7 +9,8 @@ has constant overhead, which is smaller than log(n) of std::set. an unordered collection of unique descriptors with O(1) add/del/has ops */ -class DescriptorSet { +class DescriptorSet +{ public: // for STL compatibility, should we decide to switch to std::set or similar typedef const int *const_iterator; @@ -18,8 +19,10 @@ public: ~DescriptorSet(); /// checks whether fd is in the set - bool has(const int fd) const { return 0 <= fd && fd < capacity_ && - index_[fd] >= 0; } + bool has(const int fd) const { + return 0 <= fd && fd < capacity_ && + index_[fd] >= 0; + } bool add(int fd); ///< adds if unique; returns true if added bool del(int fd); ///< deletes if there; returns true if deleted diff --git a/src/DiskIO/AIO/AIODiskFile.cc b/src/DiskIO/AIO/AIODiskFile.cc index c518acca2f..771767ccf3 100644 --- a/src/DiskIO/AIO/AIODiskFile.cc +++ b/src/DiskIO/AIO/AIODiskFile.cc @@ -17,12 +17,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/DiskIO/AIO/AIODiskFile.h b/src/DiskIO/AIO/AIODiskFile.h index 4f86651fdc..d7c3526603 100644 --- a/src/DiskIO/AIO/AIODiskFile.h +++ b/src/DiskIO/AIO/AIODiskFile.h @@ -17,12 +17,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/DiskIO/AIO/AIODiskIOModule.cc b/src/DiskIO/AIO/AIODiskIOModule.cc index dcb6474192..05262a5bf8 100644 --- a/src/DiskIO/AIO/AIODiskIOModule.cc +++ b/src/DiskIO/AIO/AIODiskIOModule.cc @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/DiskIO/AIO/AIODiskIOModule.h b/src/DiskIO/AIO/AIODiskIOModule.h index 4e0a8de1b0..7b46b2a38f 100644 --- a/src/DiskIO/AIO/AIODiskIOModule.h +++ b/src/DiskIO/AIO/AIODiskIOModule.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/DiskIO/AIO/AIODiskIOStrategy.cc b/src/DiskIO/AIO/AIODiskIOStrategy.cc index e4be536f7c..bcd6b62ae9 100644 --- a/src/DiskIO/AIO/AIODiskIOStrategy.cc +++ b/src/DiskIO/AIO/AIODiskIOStrategy.cc @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -202,7 +202,7 @@ AIODiskIOStrategy::init() void AIODiskIOStrategy::statfs(StoreEntry & sentry)const - {} +{} ConfigOption * AIODiskIOStrategy::getOptionTree() const diff --git a/src/DiskIO/AIO/AIODiskIOStrategy.h b/src/DiskIO/AIO/AIODiskIOStrategy.h index 7546148662..2fc9eeb0cd 100644 --- a/src/DiskIO/AIO/AIODiskIOStrategy.h +++ b/src/DiskIO/AIO/AIODiskIOStrategy.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/DiskIO/AIO/aio_win32.cc b/src/DiskIO/AIO/aio_win32.cc index f1f95d2a2f..20fd7614a2 100644 --- a/src/DiskIO/AIO/aio_win32.cc +++ b/src/DiskIO/AIO/aio_win32.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -59,8 +59,7 @@ int aio_read(struct aiocb *aiocbp) /* Allocate an overlapped structure. */ Overlapped = (LPOVERLAPPED) xcalloc(1, sizeof(OVERLAPPED)); - if (!Overlapped) - { + if (!Overlapped) { errno = ENOMEM; return -1; } @@ -99,15 +98,14 @@ int aio_read(struct aiocb *aiocbp) IoCompletionRoutine); /* Test to see if the I/O was queued successfully. */ - if (!IoOperationStatus) - { + if (!IoOperationStatus) { errno = GetLastError(); debugs(81,1, "aio_read: GetLastError=" << errno ); return -1; } /* The I/O queued successfully. Go back into the - alertable wait for I/O completion or for + alertable wait for I/O completion or for more I/O requests. */ return 0; } @@ -121,8 +119,7 @@ int aio_read64(struct aiocb64 *aiocbp) /* Allocate an overlapped structure. */ Overlapped = (LPOVERLAPPED) xcalloc(1, sizeof(OVERLAPPED)); - if (!Overlapped) - { + if (!Overlapped) { errno = ENOMEM; return -1; } @@ -153,15 +150,14 @@ int aio_read64(struct aiocb64 *aiocbp) IoCompletionRoutine); /* Test to see if the I/O was queued successfully. */ - if (!IoOperationStatus) - { + if (!IoOperationStatus) { errno = GetLastError(); debugs(81, 1, "aio_read: GetLastError=" << errno ); return -1; } /* The I/O queued successfully. Go back into the - alertable wait for I/O completion or for + alertable wait for I/O completion or for more I/O requests. */ return 0; } @@ -175,8 +171,7 @@ int aio_write(struct aiocb *aiocbp) /* Allocate an overlapped structure. */ Overlapped = (LPOVERLAPPED) xcalloc(1, sizeof(OVERLAPPED)); - if (!Overlapped) - { + if (!Overlapped) { errno = ENOMEM; return -1; } @@ -215,15 +210,14 @@ int aio_write(struct aiocb *aiocbp) IoCompletionRoutine); /* Test to see if the I/O was queued successfully. */ - if (!IoOperationStatus) - { + if (!IoOperationStatus) { errno = GetLastError(); debugs(81, 1, "aio_write: GetLastError=" << errno ); return -1; } /* The I/O queued successfully. Go back into the - alertable wait for I/O completion or for + alertable wait for I/O completion or for more I/O requests. */ return 0; } @@ -237,8 +231,7 @@ int aio_write64(struct aiocb64 *aiocbp) /* Allocate an overlapped structure. */ Overlapped = (LPOVERLAPPED) xcalloc(1, sizeof(OVERLAPPED)); - if (!Overlapped) - { + if (!Overlapped) { errno = ENOMEM; return -1; } @@ -269,15 +262,14 @@ int aio_write64(struct aiocb64 *aiocbp) IoCompletionRoutine); /* Test to see if the I/O was queued successfully. */ - if (!IoOperationStatus) - { + if (!IoOperationStatus) { errno = GetLastError(); debugs(81, 1, "aio_write: GetLastError=" << errno ); return -1; } /* The I/O queued successfully. Go back into the - alertable wait for I/O completion or for + alertable wait for I/O completion or for more I/O requests. */ return 0; } diff --git a/src/DiskIO/AIO/aio_win32.h b/src/DiskIO/AIO/aio_win32.h index bd6d2dae8c..b3c14c2937 100644 --- a/src/DiskIO/AIO/aio_win32.h +++ b/src/DiskIO/AIO/aio_win32.h @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -49,8 +49,7 @@ union sigval { void *sival_ptr; /* pointer value */ }; -struct sigevent -{ +struct sigevent { int sigev_notify; /* notification mode */ int sigev_signo; /* signal number */ union sigval sigev_value; /* signal value */ @@ -58,8 +57,7 @@ struct sigevent #endif -struct aiocb64 -{ +struct aiocb64 { int aio_fildes; /* file descriptor */ void *aio_buf; /* buffer location */ size_t aio_nbytes; /* length of transfer */ @@ -70,8 +68,7 @@ struct aiocb64 int aio_lio_opcode; /* listio operation */ }; -struct aiocb -{ +struct aiocb { int aio_fildes; /* file descriptor */ void *aio_buf; /* buffer location */ size_t aio_nbytes; /* length of transfer */ diff --git a/src/DiskIO/AIO/async_io.h b/src/DiskIO/AIO/async_io.h index 9fff102dcd..b238c36021 100644 --- a/src/DiskIO/AIO/async_io.h +++ b/src/DiskIO/AIO/async_io.h @@ -33,8 +33,7 @@ typedef struct _async_queue async_queue_t; class AIODiskFile; -struct _async_queue_entry -{ +struct _async_queue_entry { async_queue_entry_state_t aq_e_state; async_queue_entry_type_t aq_e_type; @@ -48,8 +47,7 @@ struct _async_queue_entry /* An async queue */ -struct _async_queue -{ +struct _async_queue { async_queue_state_t aq_state; async_queue_entry_t aq_queue[MAX_ASYNCOP]; /* queued ops */ int aq_numpending; /* Num of pending ops */ diff --git a/src/DiskIO/Blocking/BlockingDiskIOModule.cc b/src/DiskIO/Blocking/BlockingDiskIOModule.cc index 42e5df2cc0..f2b2075f42 100644 --- a/src/DiskIO/Blocking/BlockingDiskIOModule.cc +++ b/src/DiskIO/Blocking/BlockingDiskIOModule.cc @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/DiskIO/Blocking/BlockingDiskIOModule.h b/src/DiskIO/Blocking/BlockingDiskIOModule.h index e206122e8e..7be1dc5139 100644 --- a/src/DiskIO/Blocking/BlockingDiskIOModule.h +++ b/src/DiskIO/Blocking/BlockingDiskIOModule.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/DiskIO/Blocking/BlockingFile.cc b/src/DiskIO/Blocking/BlockingFile.cc index 0976d88faa..ab8eea05de 100644 --- a/src/DiskIO/Blocking/BlockingFile.cc +++ b/src/DiskIO/Blocking/BlockingFile.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/DiskIO/Blocking/BlockingFile.h b/src/DiskIO/Blocking/BlockingFile.h index 1d6c676cfb..86c6bc2ff4 100644 --- a/src/DiskIO/Blocking/BlockingFile.h +++ b/src/DiskIO/Blocking/BlockingFile.h @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/DiskIO/Blocking/BlockingIOStrategy.cc b/src/DiskIO/Blocking/BlockingIOStrategy.cc index 2b5b2549a8..1a1526d58b 100644 --- a/src/DiskIO/Blocking/BlockingIOStrategy.cc +++ b/src/DiskIO/Blocking/BlockingIOStrategy.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/DiskIO/Blocking/BlockingIOStrategy.h b/src/DiskIO/Blocking/BlockingIOStrategy.h index c417dcf7ab..5c7e49d61b 100644 --- a/src/DiskIO/Blocking/BlockingIOStrategy.h +++ b/src/DiskIO/Blocking/BlockingIOStrategy.h @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/DiskIO/Blocking/DiskIOBlocking.cc b/src/DiskIO/Blocking/DiskIOBlocking.cc index 0da58c37af..9d16faf2b2 100644 --- a/src/DiskIO/Blocking/DiskIOBlocking.cc +++ b/src/DiskIO/Blocking/DiskIOBlocking.cc @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/DiskIO/DiskDaemon/DiskDaemonDiskIOModule.cc b/src/DiskIO/DiskDaemon/DiskDaemonDiskIOModule.cc index 0097fd7921..e7793d1b8e 100644 --- a/src/DiskIO/DiskDaemon/DiskDaemonDiskIOModule.cc +++ b/src/DiskIO/DiskDaemon/DiskDaemonDiskIOModule.cc @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -53,7 +53,7 @@ DiskDaemonDiskIOModule::init() { /* We may be reused - for instance in coss - eventually. * When we do, we either need per-using-module stats ( - * no singleton pattern), or we need to refcount the + * no singleton pattern), or we need to refcount the * initialisation level and handle multiple clients. * RBC - 20030718. */ diff --git a/src/DiskIO/DiskDaemon/DiskDaemonDiskIOModule.h b/src/DiskIO/DiskDaemon/DiskDaemonDiskIOModule.h index 0b7fca389b..81fdaf0d0d 100644 --- a/src/DiskIO/DiskDaemon/DiskDaemonDiskIOModule.h +++ b/src/DiskIO/DiskDaemon/DiskDaemonDiskIOModule.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/DiskIO/DiskDaemon/DiskdFile.cc b/src/DiskIO/DiskDaemon/DiskdFile.cc index e5e11d6cb2..210cd9766d 100644 --- a/src/DiskIO/DiskDaemon/DiskdFile.cc +++ b/src/DiskIO/DiskDaemon/DiskdFile.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/DiskIO/DiskDaemon/DiskdFile.h b/src/DiskIO/DiskDaemon/DiskdFile.h index 91e04dfdb2..b5195d4c11 100644 --- a/src/DiskIO/DiskDaemon/DiskdFile.h +++ b/src/DiskIO/DiskDaemon/DiskdFile.h @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/DiskIO/DiskDaemon/DiskdIOStrategy.cc b/src/DiskIO/DiskDaemon/DiskdIOStrategy.cc index 3c937e6462..a3dd1a33a1 100644 --- a/src/DiskIO/DiskDaemon/DiskdIOStrategy.cc +++ b/src/DiskIO/DiskDaemon/DiskdIOStrategy.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -304,7 +304,7 @@ DiskdIOStrategy::handle(diomsg * M) * - say when we have a error opening after * a read was already queued */ - debugs(79, 3, "storeDiskdHandle: Invalid callback_data " << M->callback_data); + debugs(79, 3, "storeDiskdHandle: Invalid callback_data " << M->callback_data); cbdataReferenceDone (M->callback_data); return; } diff --git a/src/DiskIO/DiskDaemon/DiskdIOStrategy.h b/src/DiskIO/DiskDaemon/DiskdIOStrategy.h index d67f48bc27..ae7b56d2a8 100644 --- a/src/DiskIO/DiskDaemon/DiskdIOStrategy.h +++ b/src/DiskIO/DiskDaemon/DiskdIOStrategy.h @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -125,8 +125,7 @@ private: #define SHMBUF_BLKSZ SM_PAGE_SIZE /// \ingroup diskd -struct diskd_stats_t -{ +struct diskd_stats_t { int open_fail_queue_len; int block_queue_len; int max_away; @@ -136,8 +135,7 @@ struct diskd_stats_t int recv_count; int sio_id; - struct - { + struct { int ops; int success; int fail; diff --git a/src/DiskIO/DiskDaemon/diomsg.h b/src/DiskIO/DiskDaemon/diomsg.h index ebc2d251e1..cd8fa2327f 100644 --- a/src/DiskIO/DiskDaemon/diomsg.h +++ b/src/DiskIO/DiskDaemon/diomsg.h @@ -19,8 +19,7 @@ enum { struct RefCountable_; -struct diomsg -{ +struct diomsg { mtyp_t mtype; int id; int seq_no; diff --git a/src/DiskIO/DiskDaemon/diskd.cc b/src/DiskIO/DiskDaemon/diskd.cc index 863552999b..ae87862d9c 100644 --- a/src/DiskIO/DiskDaemon/diskd.cc +++ b/src/DiskIO/DiskDaemon/diskd.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -54,8 +54,7 @@ const int diomsg::msg_snd_rcv_sz = sizeof(diomsg) - sizeof(mtyp_t); typedef struct _file_state file_state; -struct _file_state -{ +struct _file_state { void *key; file_state *next; int id; @@ -370,8 +369,8 @@ main(int argc, char *argv[]) memset(&rmsg, '\0', sizeof(rmsg)); DEBUG(2) std::cerr << "msgrcv: " << rmsgid << ", " - << &rmsg << ", " << diomsg::msg_snd_rcv_sz - << ", " << 0 << ", " << 0 << std::endl; + << &rmsg << ", " << diomsg::msg_snd_rcv_sz + << ", " << 0 << ", " << 0 << std::endl; rlen = msgrcv(rmsgid, &rmsg, diomsg::msg_snd_rcv_sz, 0, 0); if (rlen < 0) { diff --git a/src/DiskIO/DiskFile.h b/src/DiskIO/DiskFile.h index 9ccb12f4f5..04a4728668 100644 --- a/src/DiskIO/DiskFile.h +++ b/src/DiskIO/DiskFile.h @@ -17,12 +17,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/DiskIO/DiskIOModule.cc b/src/DiskIO/DiskIOModule.cc index a9d77cd1b6..a7636c5b4f 100644 --- a/src/DiskIO/DiskIOModule.cc +++ b/src/DiskIO/DiskIOModule.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/DiskIO/DiskIOModule.h b/src/DiskIO/DiskIOModule.h index 98c2847045..fafb969901 100644 --- a/src/DiskIO/DiskIOModule.h +++ b/src/DiskIO/DiskIOModule.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -51,7 +51,7 @@ public: static void ModuleAdd(DiskIOModule &); static void FreeAllModules(); static DiskIOModule *Find(char const *type); - /* find *any* usable disk module. This will look for the 'best' + /* find *any* usable disk module. This will look for the 'best' * available module for this system. */ static DiskIOModule *FindDefault(); @@ -59,7 +59,7 @@ public: typedef Vector::iterator iterator; typedef Vector::const_iterator const_iterator; DiskIOModule(); - virtual ~DiskIOModule(){} + virtual ~DiskIOModule() {} virtual void init() = 0; //virtual void registerWithCacheManager(void); diff --git a/src/DiskIO/DiskIOStrategy.h b/src/DiskIO/DiskIOStrategy.h index 290cf39cc0..b8c2828802 100644 --- a/src/DiskIO/DiskIOStrategy.h +++ b/src/DiskIO/DiskIOStrategy.h @@ -17,12 +17,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -45,7 +45,7 @@ class DiskIOStrategy { public: - virtual ~DiskIOStrategy(){} + virtual ~DiskIOStrategy() {} /** Can the IO Strategy handle more requests ? */ virtual bool shedLoad() = 0; @@ -82,7 +82,7 @@ class SingletonIOStrategy : public DiskIOStrategy { public: - SingletonIOStrategy(DiskIOStrategy *anIO) : io(anIO){} + SingletonIOStrategy(DiskIOStrategy *anIO) : io(anIO) {} virtual bool shedLoad() { return io->shedLoad(); } diff --git a/src/DiskIO/DiskThreads/DiskThreads.h b/src/DiskIO/DiskThreads/DiskThreads.h index b4dad445f3..9df66ca457 100644 --- a/src/DiskIO/DiskThreads/DiskThreads.h +++ b/src/DiskIO/DiskThreads/DiskThreads.h @@ -39,8 +39,7 @@ typedef enum _squidaio_request_type squidaio_request_type; typedef void AIOCB(int fd, void *cbdata, const char *buf, int aio_return, int aio_errno); -struct squidaio_result_t -{ +struct squidaio_result_t { int aio_return; int aio_errno; enum _squidaio_request_type result_type; @@ -48,8 +47,7 @@ struct squidaio_result_t void *data; /* Available to the caller */ }; -struct squidaio_ctrl_t -{ +struct squidaio_ctrl_t { struct squidaio_ctrl_t *next; int fd; @@ -98,8 +96,7 @@ int aioQueueSize(void); class DiskThreadsIOStrategy; -struct AIOCounts -{ +struct AIOCounts { int open_start; int open_finish; int close_start; diff --git a/src/DiskIO/DiskThreads/DiskThreadsDiskFile.cc b/src/DiskIO/DiskThreads/DiskThreadsDiskFile.cc index ca520c50f6..201395cdb5 100644 --- a/src/DiskIO/DiskThreads/DiskThreadsDiskFile.cc +++ b/src/DiskIO/DiskThreads/DiskThreadsDiskFile.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/DiskIO/DiskThreads/DiskThreadsDiskFile.h b/src/DiskIO/DiskThreads/DiskThreadsDiskFile.h index af1652137b..a06cc8e662 100644 --- a/src/DiskIO/DiskThreads/DiskThreadsDiskFile.h +++ b/src/DiskIO/DiskThreads/DiskThreadsDiskFile.h @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -99,7 +99,7 @@ class IoResult public: void * operator new (size_t); void operator delete (void *); - IoResult(RefCount aFile, RefCount aRequest) : file(aFile), request(aRequest){} + IoResult(RefCount aFile, RefCount aRequest) : file(aFile), request(aRequest) {} RefCount file; RefCount request; diff --git a/src/DiskIO/DiskThreads/DiskThreadsDiskIOModule.cc b/src/DiskIO/DiskThreads/DiskThreadsDiskIOModule.cc index 5a07b426d5..93ec508766 100644 --- a/src/DiskIO/DiskThreads/DiskThreadsDiskIOModule.cc +++ b/src/DiskIO/DiskThreads/DiskThreadsDiskIOModule.cc @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/DiskIO/DiskThreads/DiskThreadsDiskIOModule.h b/src/DiskIO/DiskThreads/DiskThreadsDiskIOModule.h index 6f186191b3..29d362951a 100644 --- a/src/DiskIO/DiskThreads/DiskThreadsDiskIOModule.h +++ b/src/DiskIO/DiskThreads/DiskThreadsDiskIOModule.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/DiskIO/DiskThreads/DiskThreadsIOStrategy.cc b/src/DiskIO/DiskThreads/DiskThreadsIOStrategy.cc index bbc5580cd3..034492881d 100644 --- a/src/DiskIO/DiskThreads/DiskThreadsIOStrategy.cc +++ b/src/DiskIO/DiskThreads/DiskThreadsIOStrategy.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -59,15 +59,15 @@ DiskThreadsIOStrategy::init(void) * there are, which means we don't know how many threads to start. */ - registerWithCacheManager(); + registerWithCacheManager(); } void DiskThreadsIOStrategy::registerWithCacheManager(void) { CacheManager::GetInstance()-> - registerAction("squidaio_counts", "Async IO Function Counters", - aioStats, 0, 1); + registerAction("squidaio_counts", "Async IO Function Counters", + aioStats, 0, 1); } void diff --git a/src/DiskIO/DiskThreads/DiskThreadsIOStrategy.h b/src/DiskIO/DiskThreads/DiskThreadsIOStrategy.h index 73bb580275..dfc92bf7ff 100644 --- a/src/DiskIO/DiskThreads/DiskThreadsIOStrategy.h +++ b/src/DiskIO/DiskThreads/DiskThreadsIOStrategy.h @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/DiskIO/DiskThreads/aiops.cc b/src/DiskIO/DiskThreads/aiops.cc index 582eeb17c3..5b8df2a321 100644 --- a/src/DiskIO/DiskThreads/aiops.cc +++ b/src/DiskIO/DiskThreads/aiops.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -65,8 +65,7 @@ enum _squidaio_thread_status { }; typedef enum _squidaio_thread_status squidaio_thread_status; -typedef struct squidaio_request_t -{ +typedef struct squidaio_request_t { struct squidaio_request_t *next; squidaio_request_type request_type; @@ -88,8 +87,7 @@ typedef struct squidaio_request_t squidaio_result_t *resultp; } squidaio_request_t; -typedef struct squidaio_request_queue_t -{ +typedef struct squidaio_request_queue_t { pthread_mutex_t mutex; pthread_cond_t cond; squidaio_request_t *volatile head; @@ -100,8 +98,7 @@ typedef struct squidaio_request_queue_t typedef struct squidaio_thread_t squidaio_thread_t; -struct squidaio_thread_t -{ +struct squidaio_thread_t { squidaio_thread_t *next; pthread_t thread; squidaio_thread_status status; @@ -146,26 +143,24 @@ static MemAllocator *squidaio_request_pool = NULL; static MemAllocator *squidaio_thread_pool = NULL; static squidaio_request_queue_t request_queue; -static struct -{ +static struct { squidaio_request_t *head, **tailp; } request_queue2 = { - NULL, &request_queue2.head - }; + NULL, &request_queue2.head +}; static squidaio_request_queue_t done_queue; -static struct -{ +static struct { squidaio_request_t *head, **tailp; } done_requests = { - NULL, &done_requests.head - }; + NULL, &done_requests.head +}; static pthread_attr_t globattr; #if HAVE_SCHED_H diff --git a/src/DiskIO/DiskThreads/aiops_win32.cc b/src/DiskIO/DiskThreads/aiops_win32.cc index ec670231f0..4a59524de5 100644 --- a/src/DiskIO/DiskThreads/aiops_win32.cc +++ b/src/DiskIO/DiskThreads/aiops_win32.cc @@ -22,12 +22,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -60,8 +60,7 @@ enum _squidaio_thread_status { }; typedef enum _squidaio_thread_status squidaio_thread_status; -typedef struct squidaio_request_t -{ +typedef struct squidaio_request_t { struct squidaio_request_t *next; squidaio_request_type request_type; @@ -84,8 +83,7 @@ typedef struct squidaio_request_t squidaio_result_t *resultp; } squidaio_request_t; -typedef struct squidaio_request_queue_t -{ +typedef struct squidaio_request_queue_t { HANDLE mutex; HANDLE cond; /* See Event objects */ squidaio_request_t *volatile head; @@ -96,8 +94,7 @@ typedef struct squidaio_request_queue_t typedef struct squidaio_thread_t squidaio_thread_t; -struct squidaio_thread_t -{ +struct squidaio_thread_t { squidaio_thread_t *next; HANDLE thread; DWORD dwThreadId; /* thread ID */ @@ -144,26 +141,24 @@ static MemAllocator *squidaio_request_pool = NULL; static MemAllocator *squidaio_thread_pool = NULL; static squidaio_request_queue_t request_queue; -static struct -{ +static struct { squidaio_request_t *head, **tailp; } request_queue2 = { - NULL, &request_queue2.head - }; + NULL, &request_queue2.head +}; static squidaio_request_queue_t done_queue; -static struct -{ +static struct { squidaio_request_t *head, **tailp; } done_requests = { - NULL, &done_requests.head - }; + NULL, &done_requests.head +}; static HANDLE main_thread; @@ -899,7 +894,7 @@ squidaio_close(int fd, squidaio_result_t * resultp) static void squidaio_do_close(squidaio_request_t * requestp) { - if((requestp->ret = close(requestp->fd)) < 0) { + if ((requestp->ret = close(requestp->fd)) < 0) { debugs(43, 0, "squidaio_do_close: FD " << requestp->fd << ", errno " << errno); close(requestp->fd); } diff --git a/src/DiskIO/DiskThreads/async_io.cc b/src/DiskIO/DiskThreads/async_io.cc index cf182b0afa..a846564ab2 100644 --- a/src/DiskIO/DiskThreads/async_io.cc +++ b/src/DiskIO/DiskThreads/async_io.cc @@ -22,12 +22,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -43,8 +43,7 @@ AIOCounts squidaio_counts; -typedef struct squidaio_unlinkq_t -{ +typedef struct squidaio_unlinkq_t { char *path; struct squidaio_unlinkq_t *next; diff --git a/src/DiskIO/IORequestor.h b/src/DiskIO/IORequestor.h index 1f79dfa0d5..7ad3c248de 100644 --- a/src/DiskIO/IORequestor.h +++ b/src/DiskIO/IORequestor.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/DiskIO/ReadRequest.cc b/src/DiskIO/ReadRequest.cc index c76b24af50..c9380527f8 100644 --- a/src/DiskIO/ReadRequest.cc +++ b/src/DiskIO/ReadRequest.cc @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/DiskIO/ReadRequest.h b/src/DiskIO/ReadRequest.h index 66d2c671f0..d96325825a 100644 --- a/src/DiskIO/ReadRequest.h +++ b/src/DiskIO/ReadRequest.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/DiskIO/WriteRequest.cc b/src/DiskIO/WriteRequest.cc index e2f26595f1..d82d361761 100644 --- a/src/DiskIO/WriteRequest.cc +++ b/src/DiskIO/WriteRequest.cc @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/DiskIO/WriteRequest.h b/src/DiskIO/WriteRequest.h index ce142a010a..689bc6721a 100644 --- a/src/DiskIO/WriteRequest.h +++ b/src/DiskIO/WriteRequest.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ESI.cc b/src/ESI.cc index 084a395b12..13f28bcee8 100644 --- a/src/ESI.cc +++ b/src/ESI.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, ; but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -62,9 +62,9 @@ #include "IPAddress.h" /* quick reference on behaviour here. - * The ESI specification 1.0 requires the ESI processor to be able to - * return an error code at any point in the processing. To that end - * we buffer the incoming esi body until we know we will be able to + * The ESI specification 1.0 requires the ESI processor to be able to + * return an error code at any point in the processing. To that end + * we buffer the incoming esi body until we know we will be able to * satisfy the request. At that point we start streaming the queued * data downstream. * @@ -74,10 +74,10 @@ class ESIStreamContext; /* TODO: split this out into separate files ? */ /* Parsing: quick and dirty. ESI files are not valid XML, so a generic - * XML parser is not much use. Also we need a push parser not a pull + * XML parser is not much use. Also we need a push parser not a pull * parser, so LibXML is out. * - * Interpreter methods: + * Interpreter methods: * Render: May only ever be called after Process returns PROCESS_COMPLETE. * Renders the resulting content into a ESISegment chain. * Process: returns the status of the node. @@ -106,8 +106,7 @@ typedef ESIContext::esiKick_t esiKick_t; /* esiComment */ -struct esiComment : public ESIElement -{ +struct esiComment : public ESIElement { MEMPROXY_CLASS(esiComment); ~esiComment(); esiComment(); @@ -150,8 +149,7 @@ static ESIElement * esiRemoveNew(void); /* esiTry */ -struct esiTry : public ESIElement -{ +struct esiTry : public ESIElement { MEMPROXY_CLASS(esiTry); esiTry(esiTreeParentPtr aParent); @@ -168,8 +166,7 @@ struct esiTry : public ESIElement ESIElement::Pointer attempt; ESIElement::Pointer except; - struct - { + struct { int attemptok:1; /* the attempt branch process correctly */ int exceptok:1; /* likewise */ int attemptfailed:1; /* The attempt branch failed */ @@ -191,8 +188,7 @@ MEMPROXY_CLASS_INLINE(esiTry) /**DOCS_NOSEMI*/ /* esiChoose */ -struct esiChoose : public ESIElement -{ +struct esiChoose : public ESIElement { MEMPROXY_CLASS(esiChoose); esiChoose(esiTreeParentPtr); @@ -226,8 +222,7 @@ MEMPROXY_CLASS_INLINE(esiChoose) /**DOCS_NOSEMI*/ /* esiWhen */ -struct esiWhen : public esiSequence -{ +struct esiWhen : public esiSequence { MEMPROXY_CLASS(esiWhen); esiWhen(esiTreeParentPtr aParent, int attributes, const char **attr, ESIVarState *); ~esiWhen(); @@ -250,8 +245,7 @@ MEMPROXY_CLASS_INLINE(esiWhen) /**DOCS_NOSEMI*/ /* esiOtherwise */ -struct esiOtherwise : public esiSequence -{ +struct esiOtherwise : public esiSequence { // void *operator new (size_t byteCount); // void operator delete (void *address); esiOtherwise(esiTreeParentPtr aParent) : esiSequence (aParent) {} @@ -730,9 +724,9 @@ esiStreamDetach (clientStreamNode *thisNode, ClientHttpRequest *http) * callback to a set of processors like thisNode, to prevent multiple parsing * overhead. More thoughts on thisNode: We have to parse multiple times, because * the output of one processor may create a very different tree. What we could - * do is something like DOM and pass that down to a final renderer. This is + * do is something like DOM and pass that down to a final renderer. This is * getting into web server territory though... - * + * * Preconditions: * This is not the last node in the stream. * ESI processing has been enabled. @@ -744,7 +738,7 @@ esiProcessStream (clientStreamNode *thisNode, ClientHttpRequest *http, HttpReply /* test preconditions */ assert (thisNode != NULL); /* ESI TODO: handle thisNode rather than asserting - it should only ever - * happen if we cause an abort and the callback chain + * happen if we cause an abort and the callback chain * loops back to here, so we can simply return. However, that itself * shouldn't happen, so it stays as an assert for now. */ assert (cbdataReferenceValid (thisNode)); @@ -1358,8 +1352,7 @@ ESIContext::process () status = tree->process(0); processing = false; - switch (status) - { + switch (status) { case ESI_PROCESS_COMPLETE: debugs(86, 5, "esiProcess: tree Processed OK"); @@ -1386,8 +1379,7 @@ ESIContext::process () break; } - if (status != ESI_PROCESS_PENDING_MAYFAIL && (flags.finishedtemplate || cachedASTInUse)) - { + if (status != ESI_PROCESS_PENDING_MAYFAIL && (flags.finishedtemplate || cachedASTInUse)) { /* We've read the entire template, and no nodes will * return failure */ @@ -1396,8 +1388,7 @@ ESIContext::process () } if (status == ESI_PROCESS_COMPLETE - && (flags.finishedtemplate || cachedASTInUse)) - { + && (flags.finishedtemplate || cachedASTInUse)) { /* we've finished all processing. Render and send. */ debugs(86, 5, "esiProcess, processing complete"); flags.finished = 1; @@ -1483,7 +1474,7 @@ ESIContext::fail () send (); /* don't cancel anything. The stream nodes will clean up after - * themselves when the reply is freed - and we don't know what to + * themselves when the reply is freed - and we don't know what to * clean anyway. */ } @@ -2115,9 +2106,9 @@ ElementList::setNULL (int start, int end) if (elements[loopPosition].getRaw()) elements[loopPosition]->finish(); - debugs(86, 5, "esiSequence::NULLElements: Setting index " << - loopPosition << ", pointer " << - elements[loopPosition].getRaw() << " to NULL"); + debugs(86, 5, "esiSequence::NULLElements: Setting index " << + loopPosition << ", pointer " << + elements[loopPosition].getRaw() << " to NULL"); elements[loopPosition] = NULL; } @@ -2338,7 +2329,7 @@ esiWhen::esiWhen (esiTreeParentPtr aParent, int attrcount, const char **attr,ESI /* ignore mistyped attributes. * TODO:? error on these for user feedback - config parameter needed */ - debugs(86, 1, "Found misttyped attribute on ESI When clause"); + debugs(86, 1, "Found misttyped attribute on ESI When clause"); } } @@ -2438,7 +2429,7 @@ esiEnableProcessing (HttpReply *rep) if (!sctusable || sctusable->content.size() == 0) /* Nothing generic or targeted at us, or no - * content processing requested + * content processing requested */ return 0; diff --git a/src/ESI.h b/src/ESI.h index 4835c53e8b..214d52e133 100644 --- a/src/ESI.h +++ b/src/ESI.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ESIAssign.cc b/src/ESIAssign.cc index c9dd09cb25..c7de858c8b 100644 --- a/src/ESIAssign.cc +++ b/src/ESIAssign.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, ; but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ESIAssign.h b/src/ESIAssign.h index 854661fc46..6502d9376e 100644 --- a/src/ESIAssign.h +++ b/src/ESIAssign.h @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ESIAttempt.h b/src/ESIAttempt.h index 82327a36a8..3a609aa5f3 100644 --- a/src/ESIAttempt.h +++ b/src/ESIAttempt.h @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -42,8 +42,7 @@ /* esiAttempt */ -struct esiAttempt : public esiSequence -{ +struct esiAttempt : public esiSequence { // void *operator new (size_t byteCount); // void operator delete (void *address); esiAttempt(esiTreeParentPtr aParent) : esiSequence (aParent) {} diff --git a/src/ESIContext.cc b/src/ESIContext.cc index e0ab92519a..e37e0f18c0 100644 --- a/src/ESIContext.cc +++ b/src/ESIContext.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, ; but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ESIContext.h b/src/ESIContext.h index 596a73177a..35812d78a7 100644 --- a/src/ESIContext.h +++ b/src/ESIContext.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -83,8 +83,7 @@ public: * when it is, so thats ok. */ ClientHttpRequest *http; - struct - { + struct { int passthrough:1; int oktosend:1; int finished:1; @@ -108,13 +107,13 @@ public: ESISegment::Pointer buffered; /* unprocessed data - for whatever reason */ ESISegment::Pointer incoming; /* processed data we are waiting to send, or for - * potential errors to be resolved + * potential errors to be resolved */ ESISegment::Pointer outbound; ESISegment::Pointer outboundtail; /* our write segment */ /* the offset to the next character to send - - * non zero if we haven't sent the entire segment - * for some reason + * non zero if we haven't sent the entire segment + * for some reason */ size_t outbound_offset; int64_t readpos; /* the logical position we are reading from */ diff --git a/src/ESICustomParser.cc b/src/ESICustomParser.cc index de3a0a36af..ff336510ed 100644 --- a/src/ESICustomParser.cc +++ b/src/ESICustomParser.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, ; but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -120,154 +120,154 @@ ESICustomParser::parse(char const *dataToParse, size_t const lengthOfData, bool switch (lastTag) { case ESITAG: { - ++openESITags; - char *tagEnd = strchr(const_cast(tag), '>'); - - if (!tagEnd) { - error = "Could not find end ('>') of tag"; - return false; - } + ++openESITags; + char *tagEnd = strchr(const_cast(tag), '>'); - if (tagEnd - tag > (ssize_t)remainingCount) { - error = "Tag ends beyond the parse buffer."; - return false; - } + if (!tagEnd) { + error = "Could not find end ('>') of tag"; + return false; + } - if (*(tagEnd - 1) == '/') - --openESITags; + if (tagEnd - tag > (ssize_t)remainingCount) { + error = "Tag ends beyond the parse buffer."; + return false; + } - char * endofName = strpbrk(const_cast(tag), w_space); + if (*(tagEnd - 1) == '/') + --openESITags; - if (endofName > tagEnd) - endofName = const_cast(tagEnd); + char * endofName = strpbrk(const_cast(tag), w_space); - *endofName = '\0'; + if (endofName > tagEnd) + endofName = const_cast(tagEnd); - *tagEnd = '\0'; + *endofName = '\0'; - Vectorattributes; + *tagEnd = '\0'; - char *attribute = const_cast(endofName + 1); + Vectorattributes; - while (attribute > tag && attribute < tagEnd) { - /* leading spaces */ + char *attribute = const_cast(endofName + 1); - while (attribute < tagEnd && (xisspace(*attribute) || (*attribute == '/'))) - ++attribute; + while (attribute > tag && attribute < tagEnd) { + /* leading spaces */ - if (! (attribute < tagEnd)) - break; + while (attribute < tagEnd && (xisspace(*attribute) || (*attribute == '/'))) + ++attribute; - /* attribute name */ - attributes.push_back(attribute); + if (! (attribute < tagEnd)) + break; - char *nextSpace = strpbrk(attribute, w_space); + /* attribute name */ + attributes.push_back(attribute); - char *equals = strchr(attribute, '='); + char *nextSpace = strpbrk(attribute, w_space); - if (!equals) { - error = "Missing attribute value."; - return false; - } + char *equals = strchr(attribute, '='); - if (nextSpace && nextSpace < equals) - *nextSpace = '\0'; - else - *equals = '\0'; + if (!equals) { + error = "Missing attribute value."; + return false; + } - ++equals; + if (nextSpace && nextSpace < equals) + *nextSpace = '\0'; + else + *equals = '\0'; - while (equals < tagEnd && xisspace(*equals)) - ++equals; + ++equals; - char sep = *equals; + while (equals < tagEnd && xisspace(*equals)) + ++equals; - if (sep != '\'' && sep != '"') { - error = "Unknown identifier ("; - error.append (sep); - error.append (")"); - return false; - } + char sep = *equals; - char *value = equals + 1; - char *end = strchr (value, sep); - attributes.push_back(value); - *end = '\0'; - attribute = end + 1; + if (sep != '\'' && sep != '"') { + error = "Unknown identifier ("; + error.append (sep); + error.append (")"); + return false; } - theClient->start (tag + 1, (const char **)attributes.items, attributes.size() >> 1); - /* TODO: attributes */ + char *value = equals + 1; + char *end = strchr (value, sep); + attributes.push_back(value); + *end = '\0'; + attribute = end + 1; + } - if (*(tagEnd - 1) == '/') - theClient->end (tag + 1); + theClient->start (tag + 1, (const char **)attributes.items, attributes.size() >> 1); + /* TODO: attributes */ - remainingCount -= tagEnd - currentPos + 1; + if (*(tagEnd - 1) == '/') + theClient->end (tag + 1); - currentPos = tagEnd + 1; - } + remainingCount -= tagEnd - currentPos + 1; - break; + currentPos = tagEnd + 1; + } + + break; case ESIENDTAG: { - if (!openESITags) - return false; + if (!openESITags) + return false; - char const *tagEnd = strchr(tag, '>'); + char const *tagEnd = strchr(tag, '>'); - if (!tagEnd) - return false; + if (!tagEnd) + return false; - if (tagEnd - tag > (ssize_t)remainingCount) - return false; + if (tagEnd - tag > (ssize_t)remainingCount) + return false; - char * endofName = strpbrk(const_cast(tag), w_space); + char * endofName = strpbrk(const_cast(tag), w_space); - if (endofName > tagEnd) - endofName = const_cast(tagEnd); + if (endofName > tagEnd) + endofName = const_cast(tagEnd); - *endofName = '\0'; + *endofName = '\0'; - theClient->end (tag + 2); + theClient->end (tag + 2); - --openESITags; + --openESITags; - remainingCount -= tagEnd - currentPos + 1; + remainingCount -= tagEnd - currentPos + 1; - currentPos = tagEnd + 1; - } + currentPos = tagEnd + 1; + } - break; + break; case ESICOMMENT: { - /* Further optimisation potential: - * 1) recognize end comments for esi and don't callback on - * comments. - * 2) provide the comment length to the caller. - */ - /* Comments must not be nested, without CDATA - * and we don't support CDATA - */ - char *commentEnd = strstr (const_cast(tag), "-->"); - - if (!commentEnd) { - error = "missing end of comment"; - return false; - } - - if (commentEnd - tag > (ssize_t)remainingCount) { - error = "comment ends beyond parse buffer"; - return false; - } + /* Further optimisation potential: + * 1) recognize end comments for esi and don't callback on + * comments. + * 2) provide the comment length to the caller. + */ + /* Comments must not be nested, without CDATA + * and we don't support CDATA + */ + char *commentEnd = strstr (const_cast(tag), "-->"); + + if (!commentEnd) { + error = "missing end of comment"; + return false; + } - *commentEnd = '\0'; - theClient->parserComment (tag + 4); - remainingCount -= commentEnd - currentPos + 3; - currentPos = commentEnd + 3; + if (commentEnd - tag > (ssize_t)remainingCount) { + error = "comment ends beyond parse buffer"; + return false; } - break; - break; + *commentEnd = '\0'; + theClient->parserComment (tag + 4); + remainingCount -= commentEnd - currentPos + 3; + currentPos = commentEnd + 3; + } + + break; + break; default: fatal ("unknown ESI tag type found"); diff --git a/src/ESICustomParser.h b/src/ESICustomParser.h index 3240d8086b..b5bd812336 100644 --- a/src/ESICustomParser.h +++ b/src/ESICustomParser.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ESIElement.h b/src/ESIElement.h index 7924a63c4a..9e026f8ceb 100644 --- a/src/ESIElement.h +++ b/src/ESIElement.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -45,17 +45,15 @@ typedef enum { class ESIElement; -struct esiTreeParent : public RefCountable -{ - virtual void provideData (ESISegment::Pointer data, ESIElement * source) - { +struct esiTreeParent : public RefCountable { + virtual void provideData (ESISegment::Pointer data, ESIElement * source) { /* make abstract when all functionality complete */ assert (0); } virtual void fail(ESIElement * source, char const *reason = NULL) {} - virtual ~esiTreeParent(){} + virtual ~esiTreeParent() {} }; typedef RefCount esiTreeParentPtr; @@ -84,8 +82,7 @@ public: ESI_ELEMENT_ASSIGN }; static ESIElementType_t IdentifyElement (const char *); - virtual bool addElement(ESIElement::Pointer) - { + virtual bool addElement(ESIElement::Pointer) { /* Don't accept children */ debugs(86,5, "ESIElement::addElement: Failed for " << this); return false; @@ -93,14 +90,12 @@ public: virtual void render (ESISegment::Pointer) = 0; /* process this element */ - virtual esiProcessResult_t process (int dovars) - { + virtual esiProcessResult_t process (int dovars) { debugs(86,5, "esiProcessComplete: Processed " << this); return ESI_PROCESS_COMPLETE; } - virtual bool mayFail() const - { + virtual bool mayFail() const { return true; } diff --git a/src/ESIExcept.h b/src/ESIExcept.h index f4272f4529..f24544b560 100644 --- a/src/ESIExcept.h +++ b/src/ESIExcept.h @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ESIExpatParser.cc b/src/ESIExpatParser.cc index f210b0c4d1..ada05ebcd6 100644 --- a/src/ESIExpatParser.cc +++ b/src/ESIExpatParser.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, ; but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ESIExpatParser.h b/src/ESIExpatParser.h index c34e4b3f2d..73999f2d8c 100644 --- a/src/ESIExpatParser.h +++ b/src/ESIExpatParser.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ESIExpression.cc b/src/ESIExpression.cc index beaf2832c7..f4c0dd07e5 100644 --- a/src/ESIExpression.cc +++ b/src/ESIExpression.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, ; but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -37,11 +37,11 @@ #include "ESIExpression.h" /* stack precedence rules: - * before pushing an operator onto the stack, the + * before pushing an operator onto the stack, the * top 2 elements are checked. if either has a higher * or equal precedence than the current operator, they - * are evaluated. - * Start of expression has 5 precedence, + * are evaluated. + * Start of expression has 5 precedence, * end of expression has 0 precedence * literal has 1 as does expression results * | has 2 @@ -57,8 +57,7 @@ typedef struct _stackmember stackmember; typedef int evaluate (stackmember * stack, int *depth, int whereAmI, stackmember * candidate); -typedef enum -{ +typedef enum { ESI_EXPR_INVALID, ESI_EXPR_LITERAL, ESI_EXPR_OR, @@ -75,8 +74,7 @@ typedef enum ESI_EXPR_EXPR /* the result of an expr PRI 1 */ } evaltype; -typedef enum -{ +typedef enum { ESI_LITERAL_STRING, ESI_LITERAL_FLOAT, ESI_LITERAL_INT, @@ -84,11 +82,9 @@ typedef enum ESI_LITERAL_INVALID } literalhint; -struct _stackmember -{ +struct _stackmember { evaluate *eval; - union - { + union { char *string; double floating; int integral; @@ -897,7 +893,7 @@ printliteral (stackmember s) break; case ESI_LITERAL_INT: - debug (86,1) ("%d", s.value.integral); + debug (86,1) ("%d", s.value.integral); break; case ESI_LITERAL_BOOL: diff --git a/src/ESIExpression.h b/src/ESIExpression.h index 90141d5f9e..9e2e10d4fc 100644 --- a/src/ESIExpression.h +++ b/src/ESIExpression.h @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ESIInclude.cc b/src/ESIInclude.cc index 123b8bc018..023cb70080 100644 --- a/src/ESIInclude.cc +++ b/src/ESIInclude.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, ; but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -76,10 +76,10 @@ esiBufferDetach (clientStreamNode *node, ClientHttpRequest *http) * data context is not NULL * There are no more entries in the stream chain. * The caller is responsible for creation and deletion of the Reply headers. - * + * \note * Bug 975, bug 1566 : delete rep; 2006/09/02: TS, #975 - * + * * This was causing double-deletes. Its possible that not deleting * it here will cause memory leaks, but if so, this delete should * not be reinstated or it will trigger bug #975 again - RBC 20060903 @@ -90,10 +90,10 @@ esiBufferRecipient (clientStreamNode *node, ClientHttpRequest *http, HttpReply * /* Test preconditions */ assert (node != NULL); /* ESI TODO: handle thisNode rather than asserting - * - it should only ever happen if we cause an - * abort and the callback chain loops back to - * here, so we can simply return. However, that - * itself shouldn't happen, so it stays as an + * - it should only ever happen if we cause an + * abort and the callback chain loops back to + * here, so we can simply return. However, that + * itself shouldn't happen, so it stays as an * assert for now. */ assert (cbdataReferenceValid (node)); assert (node->node.next == NULL); @@ -191,28 +191,28 @@ esiBufferRecipient (clientStreamNode *node, ClientHttpRequest *http, HttpReply * return; case STREAM_NONE: { - StoreIOBuffer tempBuffer; - - if (!esiStream->buffer.getRaw()) { - esiStream->buffer = esiStream->localbuffer; - } + StoreIOBuffer tempBuffer; - esiStream->buffer = esiStream->buffer->tail(); + if (!esiStream->buffer.getRaw()) { + esiStream->buffer = esiStream->localbuffer; + } - if (esiStream->buffer->len) { - esiStream->buffer->next = new ESISegment; - esiStream->buffer = esiStream->buffer->next; - } + esiStream->buffer = esiStream->buffer->tail(); - tempBuffer.offset = http->out.offset; - tempBuffer.length = sizeof (esiStream->buffer->buf); - tempBuffer.data = esiStream->buffer->buf; - /* now just read into 'buffer' */ - clientStreamRead (node, http, tempBuffer); - debugs(86, 5, HERE << "Requested more data for ESI subrequest"); + if (esiStream->buffer->len) { + esiStream->buffer->next = new ESISegment; + esiStream->buffer = esiStream->buffer->next; } - break; + tempBuffer.offset = http->out.offset; + tempBuffer.length = sizeof (esiStream->buffer->buf); + tempBuffer.data = esiStream->buffer->buf; + /* now just read into 'buffer' */ + clientStreamRead (node, http, tempBuffer); + debugs(86, 5, HERE << "Requested more data for ESI subrequest"); + } + + break; default: fatal ("Hit unreachable code in esiBufferRecipient\n"); @@ -546,12 +546,12 @@ ESIInclude::subRequestDone (ESIStreamContext::Pointer stream, bool success) if (flags.finished || flags.failed) { /* Kick ESI Processor */ - debugs (86, 5, "ESIInclude " << this << - " SubRequest " << stream.getRaw() << + debugs (86, 5, "ESIInclude " << this << + " SubRequest " << stream.getRaw() << " completed, kicking processor , status " << (flags.finished ? "OK" : "FAILED")); /* There is a race condition - and we have no reproducible test case - - * during a subrequest the parent will get set to NULL, which is not + * during a subrequest the parent will get set to NULL, which is not * meant to be possible. Rather than killing squid, we let it leak * memory but complain in the log. * @@ -562,14 +562,14 @@ ESIInclude::subRequestDone (ESIStreamContext::Pointer stream, bool success) */ if (parent.getRaw() == NULL) { debugs (86, 0, "ESIInclude::subRequestDone: Sub request completed " - "after finish() called and parent unlinked. Unable to " - "continue handling the request, and may be memory leaking. " - "See http://www.squid-cache.org/bugs/show_bug.cgi?id=951 - we " - "are looking for a reproducible test case. This will require " - "an ESI template with includes, probably with alt-options, " - "and we're likely to need traffic dumps to allow us to " - "reconstruct the exact tcp handling sequences to trigger this " - "rather elusive bug."); + "after finish() called and parent unlinked. Unable to " + "continue handling the request, and may be memory leaking. " + "See http://www.squid-cache.org/bugs/show_bug.cgi?id=951 - we " + "are looking for a reproducible test case. This will require " + "an ESI template with includes, probably with alt-options, " + "and we're likely to need traffic dumps to allow us to " + "reconstruct the exact tcp handling sequences to trigger this " + "rather elusive bug."); return; } assert (parent.getRaw()); diff --git a/src/ESIInclude.h b/src/ESIInclude.h index 75b0666520..15558ad92f 100644 --- a/src/ESIInclude.h +++ b/src/ESIInclude.h @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -79,8 +79,7 @@ public: Pointer makeUsable(esiTreeParentPtr, ESIVarState &) const; void subRequestDone (ESIStreamContext::Pointer, bool); - struct - { + struct { int onerrorcontinue:1; /* on error return zero data */ int failed:1; /* Failed to process completely */ int finished:1; /* Finished getting subrequest data */ diff --git a/src/ESILibxml2Parser.cc b/src/ESILibxml2Parser.cc index 3373e5c9c6..989b75be13 100644 --- a/src/ESILibxml2Parser.cc +++ b/src/ESILibxml2Parser.cc @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, ; but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ESILibxml2Parser.h b/src/ESILibxml2Parser.h index 5c6f97c794..58759b07dc 100644 --- a/src/ESILibxml2Parser.h +++ b/src/ESILibxml2Parser.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ESILiteral.h b/src/ESILiteral.h index 1f493e153f..2e723aab46 100644 --- a/src/ESILiteral.h +++ b/src/ESILiteral.h @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -42,8 +42,7 @@ class ESIContext; /* esiLiteral */ -struct esiLiteral : public ESIElement -{ +struct esiLiteral : public ESIElement { MEMPROXY_CLASS(esiLiteral); esiLiteral(ESISegment::Pointer); @@ -57,8 +56,7 @@ struct esiLiteral : public ESIElement /* optimise copies away later */ ESISegment::Pointer buffer; - struct - { + struct { int donevars:1; } flags; diff --git a/src/ESIParser.cc b/src/ESIParser.cc index 492a43dc4c..30fcf33c4c 100644 --- a/src/ESIParser.cc +++ b/src/ESIParser.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, ; but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ESIParser.h b/src/ESIParser.h index 9f778d413a..e1a208a530 100644 --- a/src/ESIParser.h +++ b/src/ESIParser.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -68,7 +68,7 @@ public: virtual char const * errorString() const =0; protected: - ESIParser(){}; + ESIParser() {}; class Register; @@ -83,8 +83,7 @@ class ESIParser::Register { public: - Register(const char *_name, ESIParser::Pointer (*_newParser)(ESIParserClient *aClient)) : name(_name), newParser(_newParser) - { + Register(const char *_name, ESIParser::Pointer (*_newParser)(ESIParserClient *aClient)) : name(_name), newParser(_newParser) { this->next = ESIParser::Parsers; ESIParser::Parsers = this; } diff --git a/src/ESISegment.cc b/src/ESISegment.cc index 206e1595b6..377b58a73f 100644 --- a/src/ESISegment.cc +++ b/src/ESISegment.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, ; but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ESISegment.h b/src/ESISegment.h index b1c48e45e4..89d4901367 100644 --- a/src/ESISegment.h +++ b/src/ESISegment.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ESISequence.cc b/src/ESISequence.cc index df7bfb4308..f234df156e 100644 --- a/src/ESISequence.cc +++ b/src/ESISequence.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -93,7 +93,7 @@ void esiSequence::render(ESISegment::Pointer output) { /* append all processed elements, and trim processed - * and rendered elements + * and rendered elements */ assert (output->next == NULL); debugs (86,5, "esiSequenceRender: rendering " << processedcount << " elements"); @@ -126,12 +126,12 @@ esiSequence::provideData (ESISegment::Pointer data, ESIElement *source) if (processing) debugs(86, 5, "esiSequence::provideData: " << this << " data provided during processing"); - debugs(86, 5, "esiSequence::provideData " << this << " " << data.getRaw() << " " << source); + debugs(86, 5, "esiSequence::provideData " << this << " " << data.getRaw() << " " << source); /* when data is provided, the element *must* be completed */ /* XXX: when the callback model is complete, - * we can introduce 'finished'. And then this rule can be + * we can introduce 'finished'. And then this rule can be * relaxed */ /* find the index */ diff --git a/src/ESISequence.h b/src/ESISequence.h index e3150148a6..807eb77afd 100644 --- a/src/ESISequence.h +++ b/src/ESISequence.h @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -66,8 +66,7 @@ public: ElementList elements; /* unprocessed or rendered nodes */ size_t processedcount; - struct - { + struct { int dovars:1; /* for esiVar */ } flags; void finish(); diff --git a/src/ESIVar.h b/src/ESIVar.h index 95434b85dd..1f6e870dca 100644 --- a/src/ESIVar.h +++ b/src/ESIVar.h @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -48,8 +48,7 @@ class ESIVar:public esiSequence public: // void *operator new (size_t byteCount); // void operator delete (void *address); - ESIVar(esiTreeParentPtr aParent) : esiSequence (aParent) - { + ESIVar(esiTreeParentPtr aParent) : esiSequence (aParent) { flags.dovars = 1; } }; diff --git a/src/ESIVarState.cc b/src/ESIVarState.cc index eb11470a21..dafa49e64d 100644 --- a/src/ESIVarState.cc +++ b/src/ESIVarState.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, ; but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -41,19 +41,17 @@ CBDATA_TYPE (ESIVarState); FREE ESIVarStateFree; -char const *ESIVariableUserAgent::esiUserOs[]= - { - "WIN", - "MAC", - "UNIX", - "OTHER" - }; +char const *ESIVariableUserAgent::esiUserOs[]= { + "WIN", + "MAC", + "UNIX", + "OTHER" +}; -char const * esiBrowsers[]= - {"MSIE", - "MOZILLA", - "OTHER" - }; +char const * esiBrowsers[]= {"MSIE", + "MOZILLA", + "OTHER" + }; void @@ -114,8 +112,7 @@ ESIVariableQuery::queryString() const } struct _query_elem const * - ESIVariableQuery::queryVector() const - { + ESIVariableQuery::queryVector() const { return query; } @@ -354,20 +351,20 @@ ESIVariableUserAgent::ESIVariableUserAgent(ESIVarState &state) /* Grr this Node is painful - RFC 2616 specifies that 'by convention' the tokens are in order of importance * in identifying the product. According to the RFC the above should be interpreted as: * Product - Mozilla version 4.0 - * in comments - compatible; .... 3705 + * in comments - compatible; .... 3705 * * Useing the RFC a more appropriate header would be * User-Agent: MSIE/6.0 Mozilla/4.0 Windows-NT/5.1 .NET-CLR/1.0.3705 * or something similar. * - * Because we can't parse under those rules and get real-world useful answers, we follow the following + * Because we can't parse under those rules and get real-world useful answers, we follow the following * algorithm: * if the string Windows appears in the header, the OS is WIN. * If the string Mac appears in the header, the OS is MAC. * If the string nix, or BSD appears in the header, the OS is UNIX. - * If the string MSIE appears in the header, the BROWSER is MSIE, and the version is the string from + * If the string MSIE appears in the header, the BROWSER is MSIE, and the version is the string from * MSIE to the first ;, or end of string. - * If the String MSIE does not appear in the header, and MOZILLA does, we use the version from the + * If the String MSIE does not appear in the header, and MOZILLA does, we use the version from the * /version field. * if MOZILLA doesn't appear, the browser is set to OTHER. * In future, this may be better implemented as a regexp. diff --git a/src/ESIVarState.h b/src/ESIVarState.h index 00685f8ca3..36f8aa53cd 100644 --- a/src/ESIVarState.h +++ b/src/ESIVarState.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -51,7 +51,7 @@ extern char const * esiBrowsers[]; /* Recursive uses are not supported by design */ -struct _query_elem{char *var, *val;}; +struct _query_elem {char *var, *val;}; class ESIVarState { @@ -86,8 +86,7 @@ private: ESISegment::Pointer output; HttpHeader hdr; - struct - { + struct { int language:1; int cookie:1; int host:1; @@ -103,7 +102,7 @@ public: public: Variable () {} - virtual ~Variable(){} + virtual ~Variable() {} /* prevent synthetics */ Variable (Variable const &) {} @@ -178,7 +177,7 @@ public: private: static char const * esiUserOs[]; - enum esiUserOs_t{ + enum esiUserOs_t { ESI_OS_WIN, ESI_OS_MAC, ESI_OS_UNIX, diff --git a/src/ETag.cc b/src/ETag.cc index 4c8ae357b0..9e9a4fbce7 100644 --- a/src/ETag.cc +++ b/src/ETag.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ElementList.h b/src/ElementList.h index 9cdef272b1..df7637f63e 100644 --- a/src/ElementList.h +++ b/src/ElementList.h @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/EventLoop.cc b/src/EventLoop.cc index 25a845e748..b2944b8aa1 100644 --- a/src/EventLoop.cc +++ b/src/EventLoop.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -119,7 +119,7 @@ EventLoop::runOnce() sawActivity = dispatchCalls(); if (sawActivity) runOnceResult = false; - } while (sawActivity); + } while (sawActivity); if (waitingEngine != NULL) checkEngine(waitingEngine, true); diff --git a/src/EventLoop.h b/src/EventLoop.h index 5b3adc99c7..e2835c1e74 100644 --- a/src/EventLoop.h +++ b/src/EventLoop.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -58,7 +58,7 @@ public: void registerEngine(AsyncEngine *engine); /** start the event loop running. The loop will run until it is stopped by - * calling stop(), or when the loop is completely idle - nothing + * calling stop(), or when the loop is completely idle - nothing * dispatched in a loop, and all engines idle. */ void run(); @@ -74,13 +74,13 @@ public: * lowest requested timeout gathered from the other engines each loop. * (There is a default of 10ms if all engines are idle or request higher * delays). - * If no primary has been nominated, the last async engine added is + * If no primary has been nominated, the last async engine added is * implicitly the default. */ void setPrimaryEngine(AsyncEngine * engine); /** set the time service. There can be only one time service set at any - * time. The time service is invoked on each loop + * time. The time service is invoked on each loop */ void setTimeService(TimeEngine *engine); diff --git a/src/ExternalACL.h b/src/ExternalACL.h index 8b15be8bea..f9345ad69a 100644 --- a/src/ExternalACL.h +++ b/src/ExternalACL.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ExternalACLEntry.cc b/src/ExternalACLEntry.cc index c6b5c31c82..8f22e75c1f 100644 --- a/src/ExternalACLEntry.cc +++ b/src/ExternalACLEntry.cc @@ -28,12 +28,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ExternalACLEntry.h b/src/ExternalACLEntry.h index f54a017c0a..dce803e368 100644 --- a/src/ExternalACLEntry.h +++ b/src/ExternalACLEntry.h @@ -28,12 +28,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/Generic.h b/src/Generic.h index 14aff37200..ba6f857303 100644 --- a/src/Generic.h +++ b/src/Generic.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -38,8 +38,7 @@ #include "dlink.h" template -struct unary_function -{ +struct unary_function { typedef _Arg argument_type; typedef _Result result_type; }; @@ -119,12 +118,10 @@ Visitor& for_each(InputIterator from, InputIterator to, Visitor& visitor) /* generic ostream printer */ template -struct PointerPrinter -{ +struct PointerPrinter { PointerPrinter(std::ostream &astream, std::string aDelimiter) : os(astream), delimiter (aDelimiter) {} - void operator () (Pointer aNode) - { + void operator () (Pointer aNode) { os << *aNode << delimiter; } diff --git a/src/HierarchyLogEntry.h b/src/HierarchyLogEntry.h index 59b7735791..a5fd7ffb31 100644 --- a/src/HierarchyLogEntry.h +++ b/src/HierarchyLogEntry.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/HttpBody.cc b/src/HttpBody.cc index 51a3e0b939..f40e71e009 100644 --- a/src/HttpBody.cc +++ b/src/HttpBody.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/HttpHdrCc.cc b/src/HttpHdrCc.cc index 87a180762f..579e0dfd08 100644 --- a/src/HttpHdrCc.cc +++ b/src/HttpHdrCc.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -38,22 +38,21 @@ #include "HttpHeader.h" /* this table is used for parsing cache control header */ -static const HttpHeaderFieldAttrs CcAttrs[CC_ENUM_END] = - { - {"public", (http_hdr_type)CC_PUBLIC}, - - {"private", (http_hdr_type)CC_PRIVATE}, - {"no-cache", (http_hdr_type)CC_NO_CACHE}, - {"no-store", (http_hdr_type)CC_NO_STORE}, - {"no-transform", (http_hdr_type)CC_NO_TRANSFORM}, - {"must-revalidate", (http_hdr_type)CC_MUST_REVALIDATE}, - {"proxy-revalidate", (http_hdr_type)CC_PROXY_REVALIDATE}, - {"only-if-cached", (http_hdr_type)CC_ONLY_IF_CACHED}, - {"max-age", (http_hdr_type)CC_MAX_AGE}, - {"s-maxage", (http_hdr_type)CC_S_MAXAGE}, - {"max-stale", (http_hdr_type)CC_MAX_STALE}, - {"Other,", (http_hdr_type)CC_OTHER} /* ',' will protect from matches */ - }; +static const HttpHeaderFieldAttrs CcAttrs[CC_ENUM_END] = { + {"public", (http_hdr_type)CC_PUBLIC}, + + {"private", (http_hdr_type)CC_PRIVATE}, + {"no-cache", (http_hdr_type)CC_NO_CACHE}, + {"no-store", (http_hdr_type)CC_NO_STORE}, + {"no-transform", (http_hdr_type)CC_NO_TRANSFORM}, + {"must-revalidate", (http_hdr_type)CC_MUST_REVALIDATE}, + {"proxy-revalidate", (http_hdr_type)CC_PROXY_REVALIDATE}, + {"only-if-cached", (http_hdr_type)CC_ONLY_IF_CACHED}, + {"max-age", (http_hdr_type)CC_MAX_AGE}, + {"s-maxage", (http_hdr_type)CC_S_MAXAGE}, + {"max-stale", (http_hdr_type)CC_MAX_STALE}, + {"Other,", (http_hdr_type)CC_OTHER} /* ',' will protect from matches */ +}; HttpHeaderFieldInfo *CcFieldsInfo = NULL; diff --git a/src/HttpHdrContRange.cc b/src/HttpHdrContRange.cc index cb6e9c70f2..e1a7344082 100644 --- a/src/HttpHdrContRange.cc +++ b/src/HttpHdrContRange.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -177,10 +177,10 @@ httpHdrContRangeParseInit(HttpHdrContRange * range, const char *str) else if (!httpHeaderParseOffset(p, &range->elength)) return 0; - debugs(68, 8, "parsed content-range field: " << - (long int) range->spec.offset << "-" << - (long int) range->spec.offset + range->spec.length - 1 << " / " << - (long int) range->elength); + debugs(68, 8, "parsed content-range field: " << + (long int) range->spec.offset << "-" << + (long int) range->spec.offset + range->spec.length - 1 << " / " << + (long int) range->elength); return 1; } diff --git a/src/HttpHdrContRange.h b/src/HttpHdrContRange.h index 82032c4733..d20ad2676e 100644 --- a/src/HttpHdrContRange.h +++ b/src/HttpHdrContRange.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/HttpHdrExtField.cc b/src/HttpHdrExtField.cc index b4fbd38382..1c765decc4 100644 --- a/src/HttpHdrExtField.cc +++ b/src/HttpHdrExtField.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/HttpHdrRange.cc b/src/HttpHdrRange.cc index a122651773..15adc4c99f 100644 --- a/src/HttpHdrRange.cc +++ b/src/HttpHdrRange.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -69,7 +69,7 @@ int64_t const HttpHdrRangeSpec::UnknownPosition = -1; * Range-Spec */ -HttpHdrRangeSpec::HttpHdrRangeSpec() : offset(UnknownPosition), length(UnknownPosition){} +HttpHdrRangeSpec::HttpHdrRangeSpec() : offset(UnknownPosition), length(UnknownPosition) {} /* parses range-spec and returns new object on success */ HttpHdrRangeSpec * @@ -158,12 +158,10 @@ HttpHdrRangeSpec::canonize(int64_t clen) outputInfo ("have"); HttpRange object(0, clen); - if (!known_spec(offset)) /* suffix */ - { + if (!known_spec(offset)) { /* suffix */ assert(known_spec(length)); offset = object.intersection(HttpRange (clen - length, clen)).start; - } else if (!known_spec(length)) /* trailer */ - { + } else if (!known_spec(length)) { /* trailer */ assert(known_spec(offset)); HttpRange newRange = object.intersection(HttpRange (offset, clen)); length = newRange.size(); @@ -343,7 +341,7 @@ HttpHdrRange::merge (Vector &basis) /* reset old array */ specs.clean(); /* merge specs: - * take one spec from "goods" and merge it with specs from + * take one spec from "goods" and merge it with specs from * "specs" (if any) until there is no overlap */ iterator i = basis.begin(); @@ -383,9 +381,9 @@ HttpHdrRange::getCanonizedSpecs (Vector ©) /* * canonizes all range specs within a set preserving the order - * returns true if the set is valid after canonization; - * the set is valid if - * - all range specs are valid and + * returns true if the set is valid after canonization; + * the set is valid if + * - all range specs are valid and * - there is at least one range spec */ int @@ -528,7 +526,7 @@ HttpHdrRange::lowestOffset(int64_t size) const /* * Return true if the first range offset is larger than the configured * limit. - * Note that exceeding the limit (returning true) results in only + * Note that exceeding the limit (returning true) results in only * grabbing the needed range elements from the origin. */ bool @@ -539,8 +537,8 @@ HttpHdrRange::offsetLimitExceeded() const return false; if (Config.rangeOffsetLimit == 0) - /* disabled */ - return true; + /* disabled */ + return true; if (-1 == Config.rangeOffsetLimit) /* forced */ diff --git a/src/HttpHdrSc.cc b/src/HttpHdrSc.cc index 2091304050..59af4d210f 100644 --- a/src/HttpHdrSc.cc +++ b/src/HttpHdrSc.cc @@ -23,12 +23,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -41,15 +41,14 @@ #include "HttpHdrSc.h" /* this table is used for parsing surrogate control header */ -static const HttpHeaderFieldAttrs ScAttrs[SC_ENUM_END] = - { - {"no-store", (http_hdr_type)SC_NO_STORE}, - - {"no-store-remote", (http_hdr_type)SC_NO_STORE_REMOTE}, - {"max-age", (http_hdr_type)SC_MAX_AGE}, - {"content", (http_hdr_type)SC_CONTENT}, - {"Other,", (http_hdr_type)SC_OTHER} /* ',' will protect from matches */ - }; +static const HttpHeaderFieldAttrs ScAttrs[SC_ENUM_END] = { + {"no-store", (http_hdr_type)SC_NO_STORE}, + + {"no-store-remote", (http_hdr_type)SC_NO_STORE_REMOTE}, + {"max-age", (http_hdr_type)SC_MAX_AGE}, + {"content", (http_hdr_type)SC_CONTENT}, + {"Other,", (http_hdr_type)SC_OTHER} /* ',' will protect from matches */ +}; HttpHeaderFieldInfo *ScFieldsInfo = NULL; diff --git a/src/HttpHdrSc.h b/src/HttpHdrSc.h index c6f008edb8..4240f9cffb 100644 --- a/src/HttpHdrSc.h +++ b/src/HttpHdrSc.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/HttpHdrScTarget.cc b/src/HttpHdrScTarget.cc index f79e176f67..0791619102 100644 --- a/src/HttpHdrScTarget.cc +++ b/src/HttpHdrScTarget.cc @@ -23,12 +23,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/HttpHdrScTarget.h b/src/HttpHdrScTarget.h index 7faac23c71..4157ec575f 100644 --- a/src/HttpHdrScTarget.h +++ b/src/HttpHdrScTarget.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/HttpHeader.cc b/src/HttpHeader.cc index c77ebdcbb8..336bda4a35 100644 --- a/src/HttpHeader.cc +++ b/src/HttpHeader.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -43,19 +43,19 @@ /* * On naming conventions: - * - * HTTP/1.1 defines message-header as - * + * + * HTTP/1.1 defines message-header as + * * message-header = field-name ":" [ field-value ] CRLF * field-name = token * field-value = *( field-content | LWS ) - * + * * HTTP/1.1 does not give a name name a group of all message-headers in a message. * Squid 1.1 seems to refer to that group _plus_ start-line as "headers". - * + * * HttpHeader is an object that represents all message-headers in a message. * HttpHeader does not manage start-line. - * + * * HttpHeader is implemented as a collection of header "entries". * An entry is a (field_id, field_name, field_value) triplet. */ @@ -66,85 +66,84 @@ */ /* - * A table with major attributes for every known field. - * We calculate name lengths and reorganize this array on start up. + * A table with major attributes for every known field. + * We calculate name lengths and reorganize this array on start up. * After reorganization, field id can be used as an index to the table. */ -static const HttpHeaderFieldAttrs HeadersAttrs[] = - { - {"Accept", HDR_ACCEPT, ftStr}, - - {"Accept-Charset", HDR_ACCEPT_CHARSET, ftStr}, - {"Accept-Encoding", HDR_ACCEPT_ENCODING, ftStr}, - {"Accept-Language", HDR_ACCEPT_LANGUAGE, ftStr}, - {"Accept-Ranges", HDR_ACCEPT_RANGES, ftStr}, - {"Age", HDR_AGE, ftInt}, - {"Allow", HDR_ALLOW, ftStr}, - {"Authorization", HDR_AUTHORIZATION, ftStr}, /* for now */ - {"Cache-Control", HDR_CACHE_CONTROL, ftPCc}, - {"Connection", HDR_CONNECTION, ftStr}, - {"Content-Base", HDR_CONTENT_BASE, ftStr}, - {"Content-Encoding", HDR_CONTENT_ENCODING, ftStr}, - {"Content-Language", HDR_CONTENT_LANGUAGE, ftStr}, - {"Content-Length", HDR_CONTENT_LENGTH, ftInt64}, - {"Content-Location", HDR_CONTENT_LOCATION, ftStr}, - {"Content-MD5", HDR_CONTENT_MD5, ftStr}, /* for now */ - {"Content-Range", HDR_CONTENT_RANGE, ftPContRange}, - {"Content-Type", HDR_CONTENT_TYPE, ftStr}, - {"Cookie", HDR_COOKIE, ftStr}, - {"Date", HDR_DATE, ftDate_1123}, - {"ETag", HDR_ETAG, ftETag}, - {"Expires", HDR_EXPIRES, ftDate_1123}, - {"From", HDR_FROM, ftStr}, - {"Host", HDR_HOST, ftStr}, - {"If-Match", HDR_IF_MATCH, ftStr}, /* for now */ - {"If-Modified-Since", HDR_IF_MODIFIED_SINCE, ftDate_1123}, - {"If-None-Match", HDR_IF_NONE_MATCH, ftStr}, /* for now */ - {"If-Range", HDR_IF_RANGE, ftDate_1123_or_ETag}, - {"Keep-Alive", HDR_KEEP_ALIVE, ftStr}, - {"Last-Modified", HDR_LAST_MODIFIED, ftDate_1123}, - {"Link", HDR_LINK, ftStr}, - {"Location", HDR_LOCATION, ftStr}, - {"Max-Forwards", HDR_MAX_FORWARDS, ftInt}, - {"Mime-Version", HDR_MIME_VERSION, ftStr}, /* for now */ - {"Pragma", HDR_PRAGMA, ftStr}, - {"Proxy-Authenticate", HDR_PROXY_AUTHENTICATE, ftStr}, - {"Proxy-Authentication-Info", HDR_PROXY_AUTHENTICATION_INFO, ftStr}, - {"Proxy-Authorization", HDR_PROXY_AUTHORIZATION, ftStr}, - {"Proxy-Connection", HDR_PROXY_CONNECTION, ftStr}, - {"Proxy-support", HDR_PROXY_SUPPORT, ftStr}, - {"Public", HDR_PUBLIC, ftStr}, - {"Range", HDR_RANGE, ftPRange}, - {"Referer", HDR_REFERER, ftStr}, - {"Request-Range", HDR_REQUEST_RANGE, ftPRange}, /* usually matches HDR_RANGE */ - {"Retry-After", HDR_RETRY_AFTER, ftStr}, /* for now (ftDate_1123 or ftInt!) */ - {"Server", HDR_SERVER, ftStr}, - {"Set-Cookie", HDR_SET_COOKIE, ftStr}, - {"TE", HDR_TE, ftStr}, - {"Title", HDR_TITLE, ftStr}, - {"Trailers", HDR_TRAILERS, ftStr}, - {"Transfer-Encoding", HDR_TRANSFER_ENCODING, ftStr}, - {"Upgrade", HDR_UPGRADE, ftStr}, /* for now */ - {"User-Agent", HDR_USER_AGENT, ftStr}, - {"Vary", HDR_VARY, ftStr}, /* for now */ - {"Via", HDR_VIA, ftStr}, /* for now */ - {"Warning", HDR_WARNING, ftStr}, /* for now */ - {"WWW-Authenticate", HDR_WWW_AUTHENTICATE, ftStr}, - {"Authentication-Info", HDR_AUTHENTICATION_INFO, ftStr}, - {"X-Cache", HDR_X_CACHE, ftStr}, - {"X-Cache-Lookup", HDR_X_CACHE_LOOKUP, ftStr}, - {"X-Forwarded-For", HDR_X_FORWARDED_FOR, ftStr}, - {"X-Request-URI", HDR_X_REQUEST_URI, ftStr}, - {"X-Squid-Error", HDR_X_SQUID_ERROR, ftStr}, - {"Negotiate", HDR_NEGOTIATE, ftStr}, +static const HttpHeaderFieldAttrs HeadersAttrs[] = { + {"Accept", HDR_ACCEPT, ftStr}, + + {"Accept-Charset", HDR_ACCEPT_CHARSET, ftStr}, + {"Accept-Encoding", HDR_ACCEPT_ENCODING, ftStr}, + {"Accept-Language", HDR_ACCEPT_LANGUAGE, ftStr}, + {"Accept-Ranges", HDR_ACCEPT_RANGES, ftStr}, + {"Age", HDR_AGE, ftInt}, + {"Allow", HDR_ALLOW, ftStr}, + {"Authorization", HDR_AUTHORIZATION, ftStr}, /* for now */ + {"Cache-Control", HDR_CACHE_CONTROL, ftPCc}, + {"Connection", HDR_CONNECTION, ftStr}, + {"Content-Base", HDR_CONTENT_BASE, ftStr}, + {"Content-Encoding", HDR_CONTENT_ENCODING, ftStr}, + {"Content-Language", HDR_CONTENT_LANGUAGE, ftStr}, + {"Content-Length", HDR_CONTENT_LENGTH, ftInt64}, + {"Content-Location", HDR_CONTENT_LOCATION, ftStr}, + {"Content-MD5", HDR_CONTENT_MD5, ftStr}, /* for now */ + {"Content-Range", HDR_CONTENT_RANGE, ftPContRange}, + {"Content-Type", HDR_CONTENT_TYPE, ftStr}, + {"Cookie", HDR_COOKIE, ftStr}, + {"Date", HDR_DATE, ftDate_1123}, + {"ETag", HDR_ETAG, ftETag}, + {"Expires", HDR_EXPIRES, ftDate_1123}, + {"From", HDR_FROM, ftStr}, + {"Host", HDR_HOST, ftStr}, + {"If-Match", HDR_IF_MATCH, ftStr}, /* for now */ + {"If-Modified-Since", HDR_IF_MODIFIED_SINCE, ftDate_1123}, + {"If-None-Match", HDR_IF_NONE_MATCH, ftStr}, /* for now */ + {"If-Range", HDR_IF_RANGE, ftDate_1123_or_ETag}, + {"Keep-Alive", HDR_KEEP_ALIVE, ftStr}, + {"Last-Modified", HDR_LAST_MODIFIED, ftDate_1123}, + {"Link", HDR_LINK, ftStr}, + {"Location", HDR_LOCATION, ftStr}, + {"Max-Forwards", HDR_MAX_FORWARDS, ftInt}, + {"Mime-Version", HDR_MIME_VERSION, ftStr}, /* for now */ + {"Pragma", HDR_PRAGMA, ftStr}, + {"Proxy-Authenticate", HDR_PROXY_AUTHENTICATE, ftStr}, + {"Proxy-Authentication-Info", HDR_PROXY_AUTHENTICATION_INFO, ftStr}, + {"Proxy-Authorization", HDR_PROXY_AUTHORIZATION, ftStr}, + {"Proxy-Connection", HDR_PROXY_CONNECTION, ftStr}, + {"Proxy-support", HDR_PROXY_SUPPORT, ftStr}, + {"Public", HDR_PUBLIC, ftStr}, + {"Range", HDR_RANGE, ftPRange}, + {"Referer", HDR_REFERER, ftStr}, + {"Request-Range", HDR_REQUEST_RANGE, ftPRange}, /* usually matches HDR_RANGE */ + {"Retry-After", HDR_RETRY_AFTER, ftStr}, /* for now (ftDate_1123 or ftInt!) */ + {"Server", HDR_SERVER, ftStr}, + {"Set-Cookie", HDR_SET_COOKIE, ftStr}, + {"TE", HDR_TE, ftStr}, + {"Title", HDR_TITLE, ftStr}, + {"Trailers", HDR_TRAILERS, ftStr}, + {"Transfer-Encoding", HDR_TRANSFER_ENCODING, ftStr}, + {"Upgrade", HDR_UPGRADE, ftStr}, /* for now */ + {"User-Agent", HDR_USER_AGENT, ftStr}, + {"Vary", HDR_VARY, ftStr}, /* for now */ + {"Via", HDR_VIA, ftStr}, /* for now */ + {"Warning", HDR_WARNING, ftStr}, /* for now */ + {"WWW-Authenticate", HDR_WWW_AUTHENTICATE, ftStr}, + {"Authentication-Info", HDR_AUTHENTICATION_INFO, ftStr}, + {"X-Cache", HDR_X_CACHE, ftStr}, + {"X-Cache-Lookup", HDR_X_CACHE_LOOKUP, ftStr}, + {"X-Forwarded-For", HDR_X_FORWARDED_FOR, ftStr}, + {"X-Request-URI", HDR_X_REQUEST_URI, ftStr}, + {"X-Squid-Error", HDR_X_SQUID_ERROR, ftStr}, + {"Negotiate", HDR_NEGOTIATE, ftStr}, #if X_ACCELERATOR_VARY - {"X-Accelerator-Vary", HDR_X_ACCELERATOR_VARY, ftStr}, + {"X-Accelerator-Vary", HDR_X_ACCELERATOR_VARY, ftStr}, #endif - {"Surrogate-Capability", HDR_SURROGATE_CAPABILITY, ftStr}, - {"Surrogate-Control", HDR_SURROGATE_CONTROL, ftPSc}, - {"Front-End-Https", HDR_FRONT_END_HTTPS, ftStr}, - {"Other:", HDR_OTHER, ftStr} /* ':' will not allow matches */ - }; + {"Surrogate-Capability", HDR_SURROGATE_CAPABILITY, ftStr}, + {"Surrogate-Control", HDR_SURROGATE_CONTROL, ftPSc}, + {"Front-End-Https", HDR_FRONT_END_HTTPS, ftStr}, + {"Other:", HDR_OTHER, ftStr} /* ':' will not allow matches */ +}; static HttpHeaderFieldInfo *Headers = NULL; @@ -161,100 +160,93 @@ http_hdr_type &operator++ (http_hdr_type &aHeader) * Headers that are currently not recognized, are commented out. */ static HttpHeaderMask ListHeadersMask; /* set run-time using ListHeadersArr */ -static http_hdr_type ListHeadersArr[] = - { - HDR_ACCEPT, - HDR_ACCEPT_CHARSET, HDR_ACCEPT_ENCODING, HDR_ACCEPT_LANGUAGE, - HDR_ACCEPT_RANGES, HDR_ALLOW, - HDR_CACHE_CONTROL, - HDR_CONTENT_ENCODING, - HDR_CONTENT_LANGUAGE, - HDR_CONNECTION, - HDR_IF_MATCH, HDR_IF_NONE_MATCH, - HDR_LINK, HDR_PRAGMA, - HDR_PROXY_CONNECTION, - HDR_PROXY_SUPPORT, - HDR_TRANSFER_ENCODING, - HDR_UPGRADE, - HDR_VARY, - HDR_VIA, - /* HDR_WARNING, */ - HDR_WWW_AUTHENTICATE, - HDR_AUTHENTICATION_INFO, - HDR_PROXY_AUTHENTICATION_INFO, - /* HDR_EXPECT, HDR_TE, HDR_TRAILER */ +static http_hdr_type ListHeadersArr[] = { + HDR_ACCEPT, + HDR_ACCEPT_CHARSET, HDR_ACCEPT_ENCODING, HDR_ACCEPT_LANGUAGE, + HDR_ACCEPT_RANGES, HDR_ALLOW, + HDR_CACHE_CONTROL, + HDR_CONTENT_ENCODING, + HDR_CONTENT_LANGUAGE, + HDR_CONNECTION, + HDR_IF_MATCH, HDR_IF_NONE_MATCH, + HDR_LINK, HDR_PRAGMA, + HDR_PROXY_CONNECTION, + HDR_PROXY_SUPPORT, + HDR_TRANSFER_ENCODING, + HDR_UPGRADE, + HDR_VARY, + HDR_VIA, + /* HDR_WARNING, */ + HDR_WWW_AUTHENTICATE, + HDR_AUTHENTICATION_INFO, + HDR_PROXY_AUTHENTICATION_INFO, + /* HDR_EXPECT, HDR_TE, HDR_TRAILER */ #if X_ACCELERATOR_VARY - HDR_X_ACCELERATOR_VARY, + HDR_X_ACCELERATOR_VARY, #endif - HDR_SURROGATE_CAPABILITY, - HDR_SURROGATE_CONTROL, - HDR_X_FORWARDED_FOR - }; + HDR_SURROGATE_CAPABILITY, + HDR_SURROGATE_CONTROL, + HDR_X_FORWARDED_FOR +}; /* general-headers */ -static http_hdr_type GeneralHeadersArr[] = - { - HDR_CACHE_CONTROL, HDR_CONNECTION, HDR_DATE, HDR_PRAGMA, - HDR_TRANSFER_ENCODING, - HDR_UPGRADE, - /* HDR_TRAILER, */ - HDR_VIA, - }; +static http_hdr_type GeneralHeadersArr[] = { + HDR_CACHE_CONTROL, HDR_CONNECTION, HDR_DATE, HDR_PRAGMA, + HDR_TRANSFER_ENCODING, + HDR_UPGRADE, + /* HDR_TRAILER, */ + HDR_VIA, +}; /* entity-headers */ -static http_hdr_type EntityHeadersArr[] = - { - HDR_ALLOW, HDR_CONTENT_BASE, HDR_CONTENT_ENCODING, HDR_CONTENT_LANGUAGE, - HDR_CONTENT_LENGTH, HDR_CONTENT_LOCATION, HDR_CONTENT_MD5, - HDR_CONTENT_RANGE, HDR_CONTENT_TYPE, HDR_ETAG, HDR_EXPIRES, HDR_LAST_MODIFIED, HDR_LINK, - HDR_OTHER - }; +static http_hdr_type EntityHeadersArr[] = { + HDR_ALLOW, HDR_CONTENT_BASE, HDR_CONTENT_ENCODING, HDR_CONTENT_LANGUAGE, + HDR_CONTENT_LENGTH, HDR_CONTENT_LOCATION, HDR_CONTENT_MD5, + HDR_CONTENT_RANGE, HDR_CONTENT_TYPE, HDR_ETAG, HDR_EXPIRES, HDR_LAST_MODIFIED, HDR_LINK, + HDR_OTHER +}; static HttpHeaderMask ReplyHeadersMask; /* set run-time using ReplyHeaders */ -static http_hdr_type ReplyHeadersArr[] = - { - HDR_ACCEPT, HDR_ACCEPT_CHARSET, HDR_ACCEPT_ENCODING, HDR_ACCEPT_LANGUAGE, - HDR_ACCEPT_RANGES, HDR_AGE, - HDR_LOCATION, HDR_MAX_FORWARDS, - HDR_MIME_VERSION, HDR_PUBLIC, HDR_RETRY_AFTER, HDR_SERVER, HDR_SET_COOKIE, - HDR_VARY, - HDR_WARNING, HDR_PROXY_CONNECTION, HDR_X_CACHE, - HDR_X_CACHE_LOOKUP, - HDR_X_REQUEST_URI, +static http_hdr_type ReplyHeadersArr[] = { + HDR_ACCEPT, HDR_ACCEPT_CHARSET, HDR_ACCEPT_ENCODING, HDR_ACCEPT_LANGUAGE, + HDR_ACCEPT_RANGES, HDR_AGE, + HDR_LOCATION, HDR_MAX_FORWARDS, + HDR_MIME_VERSION, HDR_PUBLIC, HDR_RETRY_AFTER, HDR_SERVER, HDR_SET_COOKIE, + HDR_VARY, + HDR_WARNING, HDR_PROXY_CONNECTION, HDR_X_CACHE, + HDR_X_CACHE_LOOKUP, + HDR_X_REQUEST_URI, #if X_ACCELERATOR_VARY - HDR_X_ACCELERATOR_VARY, + HDR_X_ACCELERATOR_VARY, #endif - HDR_X_SQUID_ERROR, - HDR_SURROGATE_CONTROL - }; + HDR_X_SQUID_ERROR, + HDR_SURROGATE_CONTROL +}; static HttpHeaderMask RequestHeadersMask; /* set run-time using RequestHeaders */ -static http_hdr_type RequestHeadersArr[] = - { - HDR_AUTHORIZATION, HDR_FROM, HDR_HOST, - HDR_IF_MATCH, HDR_IF_MODIFIED_SINCE, HDR_IF_NONE_MATCH, - HDR_IF_RANGE, HDR_MAX_FORWARDS, HDR_PROXY_CONNECTION, - HDR_PROXY_AUTHORIZATION, HDR_RANGE, HDR_REFERER, HDR_REQUEST_RANGE, - HDR_USER_AGENT, HDR_X_FORWARDED_FOR, HDR_SURROGATE_CAPABILITY - }; +static http_hdr_type RequestHeadersArr[] = { + HDR_AUTHORIZATION, HDR_FROM, HDR_HOST, + HDR_IF_MATCH, HDR_IF_MODIFIED_SINCE, HDR_IF_NONE_MATCH, + HDR_IF_RANGE, HDR_MAX_FORWARDS, HDR_PROXY_CONNECTION, + HDR_PROXY_AUTHORIZATION, HDR_RANGE, HDR_REFERER, HDR_REQUEST_RANGE, + HDR_USER_AGENT, HDR_X_FORWARDED_FOR, HDR_SURROGATE_CAPABILITY +}; static HttpHeaderMask HopByHopHeadersMask; -static http_hdr_type HopByHopHeadersArr[] = - { - HDR_CONNECTION, HDR_KEEP_ALIVE, /*HDR_PROXY_AUTHENTICATE,*/ HDR_PROXY_AUTHORIZATION, - HDR_TE, HDR_TRAILERS, HDR_TRANSFER_ENCODING, HDR_UPGRADE, HDR_PROXY_CONNECTION - }; +static http_hdr_type HopByHopHeadersArr[] = { + HDR_CONNECTION, HDR_KEEP_ALIVE, /*HDR_PROXY_AUTHENTICATE,*/ HDR_PROXY_AUTHORIZATION, + HDR_TE, HDR_TRAILERS, HDR_TRANSFER_ENCODING, HDR_UPGRADE, HDR_PROXY_CONNECTION +}; /* header accounting */ -static HttpHeaderStat HttpHeaderStats[] = - { - {"all"}, +static HttpHeaderStat HttpHeaderStats[] = { + {"all"}, #if USE_HTCP - {"HTCP reply"}, + {"HTCP reply"}, #endif - {"request"}, - {"reply"} - }; + {"request"}, + {"reply"} +}; static int HttpHeaderStatCount = countof(HttpHeaderStats); static int HeaderEntryParsedCount = 0; @@ -278,9 +270,9 @@ static void httpHeaderRegisterWithCacheManager(void) { CacheManager::GetInstance()-> - registerAction("http_headers", - "HTTP Header Statistics", - httpHeaderStoreReport, 0, 1); + registerAction("http_headers", + "HTTP Header Statistics", + httpHeaderStoreReport, 0, 1); } void @@ -509,8 +501,8 @@ HttpHeader::parse(const char *header_start, const char *header_end) HttpHeaderStats[owner].parsedCount++; if (memchr(header_start, '\0', header_end - header_start)) { - debugs(55, 1, "WARNING: HTTP header contains NULL characters {" << - getStringPrefix(header_start, header_end) << "}"); + debugs(55, 1, "WARNING: HTTP header contains NULL characters {" << + getStringPrefix(header_start, header_end) << "}"); goto reset; } @@ -537,7 +529,7 @@ HttpHeader::parse(const char *header_start, const char *header_end) if (Config.onoff.relaxed_header_parser && field_end > this_line + 1 && field_end[-1] == '\r') { debugs(55, Config.onoff.relaxed_header_parser <= 0 ? 1 : 2, - "WARNING: Double CR characters in HTTP header {" << getStringPrefix(field_start, field_end) << "}"); + "WARNING: Double CR characters in HTTP header {" << getStringPrefix(field_start, field_end) << "}"); field_end--; } } @@ -545,7 +537,7 @@ HttpHeader::parse(const char *header_start, const char *header_end) /* Barf on stray CR characters */ if (memchr(this_line, '\r', field_end - this_line)) { debugs(55, 1, "WARNING: suspicious CR characters in HTTP header {" << - getStringPrefix(field_start, field_end) << "}"); + getStringPrefix(field_start, field_end) << "}"); if (Config.onoff.relaxed_header_parser) { char *p = (char *) this_line; /* XXX Warning! This destroys original header content and violates specifications somewhat */ @@ -558,7 +550,7 @@ HttpHeader::parse(const char *header_start, const char *header_end) if (this_line + 1 == field_end && this_line > field_start) { debugs(55, 1, "WARNING: Blank continuation line in HTTP header {" << - getStringPrefix(header_start, header_end) << "}"); + getStringPrefix(header_start, header_end) << "}"); goto reset; } } while (field_ptr < header_end && (*field_ptr == ' ' || *field_ptr == '\t')); @@ -566,7 +558,7 @@ HttpHeader::parse(const char *header_start, const char *header_end) if (field_start == field_end) { if (field_ptr < header_end) { debugs(55, 1, "WARNING: unparseable HTTP header field near {" << - getStringPrefix(field_start, header_end) << "}"); + getStringPrefix(field_start, header_end) << "}"); goto reset; } @@ -574,10 +566,10 @@ HttpHeader::parse(const char *header_start, const char *header_end) } if ((e = HttpHeaderEntry::parse(field_start, field_end)) == NULL) { - debugs(55, 1, "WARNING: unparseable HTTP header field {" << - getStringPrefix(field_start, field_end) << "}"); + debugs(55, 1, "WARNING: unparseable HTTP header field {" << + getStringPrefix(field_start, field_end) << "}"); debugs(55, Config.onoff.relaxed_header_parser <= 0 ? 1 : 2, - " in {" << getStringPrefix(header_start, header_end) << "}"); + " in {" << getStringPrefix(header_start, header_end) << "}"); if (Config.onoff.relaxed_header_parser) continue; @@ -589,7 +581,7 @@ HttpHeader::parse(const char *header_start, const char *header_end) if (e->value.cmp(e2->value.buf()) != 0) { int64_t l1, l2; debugs(55, Config.onoff.relaxed_header_parser <= 0 ? 1 : 2, - "WARNING: found two conflicting content-length headers in {" << getStringPrefix(header_start, header_end) << "}"); + "WARNING: found two conflicting content-length headers in {" << getStringPrefix(header_start, header_end) << "}"); if (!Config.onoff.relaxed_header_parser) { delete e; @@ -611,7 +603,7 @@ HttpHeader::parse(const char *header_start, const char *header_end) } } else { debugs(55, Config.onoff.relaxed_header_parser <= 0 ? 1 : 2, - "NOTICE: found double content-length header"); + "NOTICE: found double content-length header"); if (Config.onoff.relaxed_header_parser) { delete e; @@ -625,7 +617,7 @@ HttpHeader::parse(const char *header_start, const char *header_end) if (e->id == HDR_OTHER && stringHasWhitespace(e->name.buf())) { debugs(55, Config.onoff.relaxed_header_parser <= 0 ? 1 : 2, - "WARNING: found whitespace in HTTP header name {" << + "WARNING: found whitespace in HTTP header name {" << getStringPrefix(field_start, field_end) << "}"); if (!Config.onoff.relaxed_header_parser) { @@ -677,7 +669,7 @@ HttpHeader::getEntry(HttpHeaderPos * pos) const } /* - * returns a pointer to a specified entry if any + * returns a pointer to a specified entry if any * note that we return one entry so it does not make much sense to ask for * "list" headers */ @@ -734,7 +726,7 @@ HttpHeader::findLastEntry(http_hdr_type id) const } /* - * deletes all fields with a given name if any, returns #fields deleted; + * deletes all fields with a given name if any, returns #fields deleted; */ int HttpHeader::delByName(const char *name) @@ -818,7 +810,7 @@ HttpHeader::refreshMask() debugs(55, 7, "refreshing the mask in hdr " << this); HttpHeaderPos pos = HttpHeaderInitPos; while (HttpHeaderEntry *e = getEntry(&pos)) { - CBIT_SET(mask, e->id); + CBIT_SET(mask, e->id); } } @@ -1308,7 +1300,7 @@ HttpHeader::getSc() const return NULL; String s; - + (void) getList(HDR_SURROGATE_CONTROL, &s); HttpHdrSc *sc = httpHdrScParseCreate(&s); @@ -1370,8 +1362,7 @@ HttpHeader::getAuth(http_hdr_type id, const char *auth_scheme) const ETag HttpHeader::getETag(http_hdr_type id) const { - ETag etag = - {NULL, -1}; + ETag etag = {NULL, -1}; HttpHeaderEntry *e; assert(Headers[id].type == ftETag); /* must be of an appropriate type */ @@ -1453,7 +1444,7 @@ HttpHeaderEntry::parse(const char *field_start, const char *field_end) { /* note: name_start == field_start */ const char *name_end = (const char *)memchr(field_start, ':', field_end - field_start); - int name_len = name_end ? name_end - field_start : 0; + int name_len = name_end ? name_end - field_start :0; const char *value_start = field_start + name_len + 1; /* skip ':' */ /* note: value_end == field_end */ @@ -1779,16 +1770,16 @@ void HttpHeader::removeHopByHopEntries() { removeConnectionHeaderEntries(); - + const HttpHeaderEntry *e; HttpHeaderPos pos = HttpHeaderInitPos; int headers_deleted = 0; while ((e = getEntry(&pos))) { - int id = e->id; - if(CBIT_TEST(HopByHopHeadersMask, id)){ - delAt(pos, headers_deleted); - CBIT_CLR(mask, id); - } + int id = e->id; + if (CBIT_TEST(HopByHopHeadersMask, id)) { + delAt(pos, headers_deleted); + CBIT_CLR(mask, id); + } } } @@ -1798,8 +1789,8 @@ HttpHeader::removeConnectionHeaderEntries() if (has(HDR_CONNECTION)) { /* anything that matches Connection list member will be deleted */ String strConnection; - - (void) getList(HDR_CONNECTION, &strConnection); + + (void) getList(HDR_CONNECTION, &strConnection); const HttpHeaderEntry *e; HttpHeaderPos pos = HttpHeaderInitPos; /* diff --git a/src/HttpHeader.h b/src/HttpHeader.h index 4eba065dba..bbc771215f 100644 --- a/src/HttpHeader.h +++ b/src/HttpHeader.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -143,8 +143,7 @@ typedef enum { hoReply } http_hdr_owner_type; -struct _HttpHeaderFieldAttrs -{ +struct _HttpHeaderFieldAttrs { const char *name; http_hdr_type id; field_type type; diff --git a/src/HttpHeaderMask.h b/src/HttpHeaderMask.h index dbd3fd03b4..4940d2a0d1 100644 --- a/src/HttpHeaderMask.h +++ b/src/HttpHeaderMask.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/HttpHeaderRange.h b/src/HttpHeaderRange.h index cbe30c22bf..6777e810a1 100644 --- a/src/HttpHeaderRange.h +++ b/src/HttpHeaderRange.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/HttpHeaderTools.cc b/src/HttpHeaderTools.cc index 17ac532294..fba64bfe5a 100644 --- a/src/HttpHeaderTools.cc +++ b/src/HttpHeaderTools.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -247,9 +247,9 @@ strListGetItem(const String * str, char del, const char **item, int *ilen, const { size_t len; static char delim[3][8] = { - "\"?,", - "\"\\", - " ?,\t\r\n" + "\"?,", + "\"\\", + " ?,\t\r\n" }; int quoted = 0; assert(str && item && pos); @@ -336,7 +336,7 @@ httpHeaderParseOffset(const char *start, int64_t * value) errno = 0; int64_t res = strtoll(start, NULL, 10); if (!res && EINVAL == errno) /* maybe not portable? */ - return 0; + return 0; *value = res; return 1; } diff --git a/src/HttpMsg.cc b/src/HttpMsg.cc index 4126ef19c7..5801b887a4 100644 --- a/src/HttpMsg.cc +++ b/src/HttpMsg.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -253,18 +253,18 @@ HttpMsg::httpMsgParseStep(const char *buf, int len, int atEnd) if (pstate == psReadyToParseStartLine) { if (!httpMsgIsolateStart(&parse_start, &blk_start, &blk_end)) { retval = 0; - goto finish; - } + goto finish; + } if (!parseFirstLine(blk_start, blk_end)) { retval = httpMsgParseError(); - goto finish; - } + goto finish; + } *parse_end_ptr = parse_start; hdr_sz = *parse_end_ptr - buf; - parse_len = parse_len - hdr_sz; + parse_len = parse_len - hdr_sz; ++pstate; } @@ -278,9 +278,9 @@ HttpMsg::httpMsgParseStep(const char *buf, int len, int atEnd) if (!httpMsgIsolateHeaders(&parse_start, parse_len, &blk_start, &blk_end)) { if (atEnd) { blk_start = parse_start, blk_end = blk_start + strlen(blk_start); - } else { - retval = 0; - goto finish; + } else { + retval = 0; + goto finish; } } @@ -395,12 +395,12 @@ HttpMsg::_unlock() void HttpParserInit(HttpParser *hdr, const char *buf, int bufsiz) { - hdr->state = 1; - hdr->buf = buf; - hdr->bufsiz = bufsiz; - hdr->req_start = hdr->req_end = -1; - hdr->hdr_start = hdr->hdr_end = -1; - debugs(74, 5, "httpParseInit: Request buffer is " << buf); + hdr->state = 1; + hdr->buf = buf; + hdr->bufsiz = bufsiz; + hdr->req_start = hdr->req_end = -1; + hdr->hdr_start = hdr->hdr_end = -1; + debugs(74, 5, "httpParseInit: Request buffer is " << buf); } #if MSGDODEBUG @@ -408,14 +408,14 @@ HttpParserInit(HttpParser *hdr, const char *buf, int bufsiz) int HttpParserReqSz(HttpParser *hp) { - assert(hp->state == 1); - assert(hp->req_start != -1); - assert(hp->req_end != -1); - return hp->req_end - hp->req_start + 1; + assert(hp->state == 1); + assert(hp->req_start != -1); + assert(hp->req_end != -1); + return hp->req_end - hp->req_start + 1; } -/* +/* * This +1 makes it 'right' but won't make any sense if * there's a 0 byte header? This won't happen normally - a valid header * is at -least- a blank line (\n, or \r\n.) @@ -423,32 +423,32 @@ HttpParserReqSz(HttpParser *hp) int HttpParserHdrSz(HttpParser *hp) { - assert(hp->state == 1); - assert(hp->hdr_start != -1); - assert(hp->hdr_end != -1); - return hp->hdr_end - hp->hdr_start + 1; + assert(hp->state == 1); + assert(hp->hdr_start != -1); + assert(hp->hdr_end != -1); + return hp->hdr_end - hp->hdr_start + 1; } const char * HttpParserHdrBuf(HttpParser *hp) { - assert(hp->state == 1); - assert(hp->hdr_start != -1); - assert(hp->hdr_end != -1); - return hp->buf + hp->hdr_start; + assert(hp->state == 1); + assert(hp->hdr_start != -1); + assert(hp->hdr_end != -1); + return hp->buf + hp->hdr_start; } int HttpParserRequestLen(HttpParser *hp) { - return hp->hdr_end - hp->req_start + 1; + return hp->hdr_end - hp->req_start + 1; } #endif /* * Attempt to parse the request line. * - * This will set the values in hmsg that it determines. One may end up + * This will set the values in hmsg that it determines. One may end up * with a partially-parsed buffer; the return value tells you whether * the values are valid or not. * @@ -461,163 +461,165 @@ HttpParserRequestLen(HttpParser *hp) int HttpParserParseReqLine(HttpParser *hmsg) { - int i = 0; - int retcode = 0; - int maj = -1, min = -1; - int last_whitespace = -1, line_end = -1; - - debugs(74, 5, "httpParserParseReqLine: parsing " << hmsg->buf); - - PROF_start(HttpParserParseReqLine); - /* Find \r\n - end of URL+Version (and the request) */ - hmsg->req_end = -1; - for (i = 0; i < hmsg->bufsiz; i++) { - if (hmsg->buf[i] == '\n') { - hmsg->req_end = i; - break; - } - if (i < hmsg->bufsiz - 1 && hmsg->buf[i] == '\r' && hmsg->buf[i + 1] == '\n') { - hmsg->req_end = i + 1; - break; - } - } - if (hmsg->req_end == -1) { - retcode = 0; - goto finish; - } - assert(hmsg->buf[hmsg->req_end] == '\n'); - /* Start at the beginning again */ - i = 0; - - /* Find first non-whitespace - beginning of method */ - for (; i < hmsg->req_end && (xisspace(hmsg->buf[i])); i++); - if (i >= hmsg->req_end) { - retcode = 0; - goto finish; - } - hmsg->m_start = i; - hmsg->req_start = i; - - /* Find first whitespace - end of method */ - for (; i < hmsg->req_end && (! xisspace(hmsg->buf[i])); i++); - if (i >= hmsg->req_end) { - retcode = 0; - goto finish; - } - hmsg->m_end = i - 1; - - /* Find first non-whitespace - beginning of URL+Version */ - for (; i < hmsg->req_end && (xisspace(hmsg->buf[i])); i++); - if (i >= hmsg->req_end) { - retcode = 0; - goto finish; - } - hmsg->u_start = i; - - /* Find \r\n or \n - thats the end of the line. Keep track of the last whitespace! */ - for (; i <= hmsg->req_end; i++) { - /* If \n - its end of line */ - if (hmsg->buf[i] == '\n') { - line_end = i; - break; - } - /* XXX could be off-by-one wrong! */ - if (hmsg->buf[i] == '\r' && (i + 1) <= hmsg->req_end && hmsg->buf[i+1] == '\n') { - line_end = i; - break; - } - /* If its a whitespace, note it as it'll delimit our version */ - if (hmsg->buf[i] == ' ' || hmsg->buf[i] == '\t') { - last_whitespace = i; - } - } - if (i > hmsg->req_end) { - retcode = 0; - goto finish; - } - - /* At this point we don't need the 'i' value; so we'll recycle it for version parsing */ - - /* - * At this point: line_end points to the first eol char (\r or \n); - * last_whitespace points to the last whitespace char in the URL. - * We know we have a full buffer here! - */ - if (last_whitespace == -1) { - maj = 0; min = 9; - hmsg->u_end = line_end - 1; - assert(hmsg->u_end >= hmsg->u_start); - } else { - /* Find the first non-whitespace after last_whitespace */ - /* XXX why <= vs < ? I do need to really re-audit all of this ..*/ - for (i = last_whitespace; i <= hmsg->req_end && xisspace(hmsg->buf[i]); i++); - if (i > hmsg->req_end) { - retcode = 0; - goto finish; - } - - /* is it http/ ? if so, we try parsing. If not, the URL is the whole line; version is 0.9 */ - if (i + 5 >= hmsg->req_end || (strncasecmp(&hmsg->buf[i], "HTTP/", 5) != 0)) { - maj = 0; min = 9; - hmsg->u_end = line_end - 1; - assert(hmsg->u_end >= hmsg->u_start); - } else { - /* Ok, lets try parsing! Yes, this needs refactoring! */ - hmsg->v_start = i; - i += 5; - - /* next should be 1 or more digits */ - maj = 0; - for (; i < hmsg->req_end && (isdigit(hmsg->buf[i])); i++) { - maj = maj * 10; - maj = maj + (hmsg->buf[i]) - '0'; - } - if (i >= hmsg->req_end) { - retcode = 0; - goto finish; - } - - /* next should be .; we -have- to have this as we have a whole line.. */ - if (hmsg->buf[i] != '.') { - retcode = 0; - goto finish; - } - if (i + 1 >= hmsg->req_end) { - retcode = 0; - goto finish; - } - - /* next should be one or more digits */ - i++; - min = 0; - for (; i < hmsg->req_end && (isdigit(hmsg->buf[i])); i++) { - min = min * 10; - min = min + (hmsg->buf[i]) - '0'; - } - - /* Find whitespace, end of version */ - hmsg->v_end = i; - hmsg->u_end = last_whitespace - 1; - } - } - - /* - * Rightio - we have all the schtuff. Return true; we've got enough. - */ - retcode = 1; - assert(maj != -1); - assert(min != -1); + int i = 0; + int retcode = 0; + int maj = -1, min = -1; + int last_whitespace = -1, line_end = -1; + + debugs(74, 5, "httpParserParseReqLine: parsing " << hmsg->buf); + + PROF_start(HttpParserParseReqLine); + /* Find \r\n - end of URL+Version (and the request) */ + hmsg->req_end = -1; + for (i = 0; i < hmsg->bufsiz; i++) { + if (hmsg->buf[i] == '\n') { + hmsg->req_end = i; + break; + } + if (i < hmsg->bufsiz - 1 && hmsg->buf[i] == '\r' && hmsg->buf[i + 1] == '\n') { + hmsg->req_end = i + 1; + break; + } + } + if (hmsg->req_end == -1) { + retcode = 0; + goto finish; + } + assert(hmsg->buf[hmsg->req_end] == '\n'); + /* Start at the beginning again */ + i = 0; + + /* Find first non-whitespace - beginning of method */ + for (; i < hmsg->req_end && (xisspace(hmsg->buf[i])); i++); + if (i >= hmsg->req_end) { + retcode = 0; + goto finish; + } + hmsg->m_start = i; + hmsg->req_start = i; + + /* Find first whitespace - end of method */ + for (; i < hmsg->req_end && (! xisspace(hmsg->buf[i])); i++); + if (i >= hmsg->req_end) { + retcode = 0; + goto finish; + } + hmsg->m_end = i - 1; + + /* Find first non-whitespace - beginning of URL+Version */ + for (; i < hmsg->req_end && (xisspace(hmsg->buf[i])); i++); + if (i >= hmsg->req_end) { + retcode = 0; + goto finish; + } + hmsg->u_start = i; + + /* Find \r\n or \n - thats the end of the line. Keep track of the last whitespace! */ + for (; i <= hmsg->req_end; i++) { + /* If \n - its end of line */ + if (hmsg->buf[i] == '\n') { + line_end = i; + break; + } + /* XXX could be off-by-one wrong! */ + if (hmsg->buf[i] == '\r' && (i + 1) <= hmsg->req_end && hmsg->buf[i+1] == '\n') { + line_end = i; + break; + } + /* If its a whitespace, note it as it'll delimit our version */ + if (hmsg->buf[i] == ' ' || hmsg->buf[i] == '\t') { + last_whitespace = i; + } + } + if (i > hmsg->req_end) { + retcode = 0; + goto finish; + } + + /* At this point we don't need the 'i' value; so we'll recycle it for version parsing */ + + /* + * At this point: line_end points to the first eol char (\r or \n); + * last_whitespace points to the last whitespace char in the URL. + * We know we have a full buffer here! + */ + if (last_whitespace == -1) { + maj = 0; + min = 9; + hmsg->u_end = line_end - 1; + assert(hmsg->u_end >= hmsg->u_start); + } else { + /* Find the first non-whitespace after last_whitespace */ + /* XXX why <= vs < ? I do need to really re-audit all of this ..*/ + for (i = last_whitespace; i <= hmsg->req_end && xisspace(hmsg->buf[i]); i++); + if (i > hmsg->req_end) { + retcode = 0; + goto finish; + } + + /* is it http/ ? if so, we try parsing. If not, the URL is the whole line; version is 0.9 */ + if (i + 5 >= hmsg->req_end || (strncasecmp(&hmsg->buf[i], "HTTP/", 5) != 0)) { + maj = 0; + min = 9; + hmsg->u_end = line_end - 1; + assert(hmsg->u_end >= hmsg->u_start); + } else { + /* Ok, lets try parsing! Yes, this needs refactoring! */ + hmsg->v_start = i; + i += 5; + + /* next should be 1 or more digits */ + maj = 0; + for (; i < hmsg->req_end && (isdigit(hmsg->buf[i])); i++) { + maj = maj * 10; + maj = maj + (hmsg->buf[i]) - '0'; + } + if (i >= hmsg->req_end) { + retcode = 0; + goto finish; + } + + /* next should be .; we -have- to have this as we have a whole line.. */ + if (hmsg->buf[i] != '.') { + retcode = 0; + goto finish; + } + if (i + 1 >= hmsg->req_end) { + retcode = 0; + goto finish; + } + + /* next should be one or more digits */ + i++; + min = 0; + for (; i < hmsg->req_end && (isdigit(hmsg->buf[i])); i++) { + min = min * 10; + min = min + (hmsg->buf[i]) - '0'; + } + + /* Find whitespace, end of version */ + hmsg->v_end = i; + hmsg->u_end = last_whitespace - 1; + } + } + + /* + * Rightio - we have all the schtuff. Return true; we've got enough. + */ + retcode = 1; + assert(maj != -1); + assert(min != -1); finish: - hmsg->v_maj = maj; - hmsg->v_min = min; - PROF_stop(HttpParserParseReqLine); - debugs(74, 5, "Parser: retval " << retcode << ": from " << hmsg->req_start << - "->" << hmsg->req_end << ": method " << hmsg->m_start << "->" << - hmsg->m_end << "; url " << hmsg->u_start << "->" << hmsg->u_end << - "; version " << hmsg->v_start << "->" << hmsg->v_end << " (" << maj << - "/" << min << ")"); - - return retcode; + hmsg->v_maj = maj; + hmsg->v_min = min; + PROF_stop(HttpParserParseReqLine); + debugs(74, 5, "Parser: retval " << retcode << ": from " << hmsg->req_start << + "->" << hmsg->req_end << ": method " << hmsg->m_start << "->" << + hmsg->m_end << "; url " << hmsg->u_start << "->" << hmsg->u_end << + "; version " << hmsg->v_start << "->" << hmsg->v_end << " (" << maj << + "/" << min << ")"); + + return retcode; } diff --git a/src/HttpMsg.h b/src/HttpMsg.h index 184850a8f2..b89ff609d7 100644 --- a/src/HttpMsg.h +++ b/src/HttpMsg.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -55,8 +55,8 @@ public: virtual HttpMsg *_lock(); // please use HTTPMSGLOCK() virtual void _unlock(); // please use HTTPMSGUNLOCK() - ///< produce a message copy, except for a few connection-specific settings - virtual HttpMsg *clone() const = 0; ///< \todo rename: not a true copy? + ///< produce a message copy, except for a few connection-specific settings + virtual HttpMsg *clone() const = 0; ///< \todo rename: not a true copy? public: HttpVersion http_ver; @@ -92,7 +92,7 @@ public: virtual bool expectingBody(const HttpRequestMethod&, int64_t&) const = 0; void firstLineBuf(MemBuf&); - + virtual bool inheritProperties(const HttpMsg *aMsg) = 0; protected: @@ -110,15 +110,15 @@ protected: /* Temporary parsing state; might turn into the replacement parser later on */ struct _HttpParser { - char state; - const char *buf; - int bufsiz; - int req_start, req_end; - int hdr_start, hdr_end; - int m_start, m_end; - int u_start, u_end; - int v_start, v_end; - int v_maj, v_min; + char state; + const char *buf; + int bufsiz; + int req_start, req_end; + int hdr_start, hdr_end; + int m_start, m_end; + int u_start, u_end; + int v_start, v_end; + int v_maj, v_min; }; typedef struct _HttpParser HttpParser; diff --git a/src/HttpReply.cc b/src/HttpReply.cc index 6326350e1d..3a5a51c08f 100644 --- a/src/HttpReply.cc +++ b/src/HttpReply.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -53,21 +53,20 @@ * origin server to set headers it should not in a 304, we must explicitly ignore * these too. Specifically all entity-headers except those permitted in a 304 * (rfc2616 10.3.5) must be ignored. - * + * * The list of headers we don't update is made up of: * all hop-by-hop headers * all entity-headers except Expires and Content-Location */ static HttpHeaderMask Denied304HeadersMask; -static http_hdr_type Denied304HeadersArr[] = - { - // hop-by-hop headers - HDR_CONNECTION, HDR_KEEP_ALIVE, HDR_PROXY_AUTHENTICATE, HDR_PROXY_AUTHORIZATION, - HDR_TE, HDR_TRAILERS, HDR_TRANSFER_ENCODING, HDR_UPGRADE, - // entity headers - HDR_ALLOW, HDR_CONTENT_ENCODING, HDR_CONTENT_LANGUAGE, HDR_CONTENT_LENGTH, - HDR_CONTENT_MD5, HDR_CONTENT_RANGE, HDR_CONTENT_TYPE, HDR_LAST_MODIFIED - }; +static http_hdr_type Denied304HeadersArr[] = { + // hop-by-hop headers + HDR_CONNECTION, HDR_KEEP_ALIVE, HDR_PROXY_AUTHENTICATE, HDR_PROXY_AUTHORIZATION, + HDR_TE, HDR_TRAILERS, HDR_TRANSFER_ENCODING, HDR_UPGRADE, + // entity headers + HDR_ALLOW, HDR_CONTENT_ENCODING, HDR_CONTENT_LANGUAGE, HDR_CONTENT_LENGTH, + HDR_CONTENT_MD5, HDR_CONTENT_RANGE, HDR_CONTENT_TYPE, HDR_LAST_MODIFIED +}; /* module initialization */ void @@ -78,9 +77,9 @@ httpReplyInitModule(void) httpHeaderCalcMask(&Denied304HeadersMask, Denied304HeadersArr, countof(Denied304HeadersArr)); } -HttpReply::HttpReply() : HttpMsg(hoReply), date (0), last_modified (0), - expires (0), surrogate_control (NULL), content_range (NULL), keep_alive (0), - protoPrefix("HTTP/"), bodySizeMax(-2) +HttpReply::HttpReply() : HttpMsg(hoReply), date (0), last_modified (0), + expires (0), surrogate_control (NULL), content_range (NULL), keep_alive (0), + protoPrefix("HTTP/"), bodySizeMax(-2) { init(); } @@ -117,7 +116,7 @@ void HttpReply::reset() void HttpReply::clean() { - // we used to assert that the pipe is NULL, but now the message only + // we used to assert that the pipe is NULL, but now the message only // points to a pipe that is owned and initiated by another object. body_pipe = NULL; @@ -521,7 +520,7 @@ HttpReply::expectedBodyTooLarge(HttpRequest& request) int64_t expectedSize = -1; if (!expectingBody(request.method, expectedSize)) return false; - + debugs(58, 6, HERE << expectedSize << " >? " << bodySizeMax); if (expectedSize < 0) // expecting body of an unknown length @@ -574,8 +573,8 @@ HttpReply::clone() const bool HttpReply::inheritProperties(const HttpMsg *aMsg) { const HttpReply *aRep = dynamic_cast(aMsg); - if(!aRep) - return false; + if (!aRep) + return false; keep_alive = aRep->keep_alive; return true; } diff --git a/src/HttpReply.h b/src/HttpReply.h index baf595fc2a..790683d7d9 100644 --- a/src/HttpReply.h +++ b/src/HttpReply.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/HttpRequest.h b/src/HttpRequest.h index 4d71f0e123..a8a7e0f4ef 100644 --- a/src/HttpRequest.h +++ b/src/HttpRequest.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -58,8 +58,7 @@ public: virtual void reset(); // use HTTPMSGLOCK() instead of calling this directly - virtual HttpRequest *_lock() - { + virtual HttpRequest *_lock() { return static_cast(HttpMsg::_lock()); }; @@ -74,14 +73,12 @@ public: /* HACK: These two methods are only inline to get around Makefile dependancies */ /* caused by HttpRequest being used in places it really shouldn't. */ /* ideally they would be methods of URL instead. */ - inline void SetHost(const char *src) - { + inline void SetHost(const char *src) { host_addr.SetEmpty(); host_addr = src; - if( host_addr.IsAnyAddr() ) { + if ( host_addr.IsAnyAddr() ) { xstrncpy(host, src, SQUIDHOSTNAMELEN); - } - else { + } else { host_addr.ToHostname(host, SQUIDHOSTNAMELEN); debugs(23, 3, "HttpRequest::SetHost() given IP: " << host_addr); } @@ -100,10 +97,10 @@ public: private: char host[SQUIDHOSTNAMELEN]; - + /*** - * The client side connection data of pinned connections for the client side - * request related objects + * The client side connection data of pinned connections for the client side + * request related objects */ ConnStateData *pinned_connection; @@ -182,17 +179,17 @@ public: static HttpRequest * CreateFromUrlAndMethod(char * url, const HttpRequestMethod& method); static HttpRequest * CreateFromUrl(char * url); - + void setPinnedConnection(ConnStateData *conn) { - pinned_connection = cbdataReference(conn); + pinned_connection = cbdataReference(conn); } ConnStateData *pinnedConnection() { - return pinned_connection; + return pinned_connection; } void releasePinnedConnection() { - cbdataReferenceDone(pinned_connection); + cbdataReferenceDone(pinned_connection); } private: @@ -204,7 +201,7 @@ protected: virtual bool sanityCheckStartLine(MemBuf *buf, http_status *error); virtual void hdrCacheInit(); - + virtual bool inheritProperties(const HttpMsg *aMsg); }; diff --git a/src/HttpRequestMethod.cc b/src/HttpRequestMethod.cc index 710b44273f..f6df1cf669 100644 --- a/src/HttpRequestMethod.cc +++ b/src/HttpRequestMethod.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -38,40 +38,39 @@ #include "HttpRequestMethod.h" #include "wordlist.h" -const char* HttpRequestMethod::RequestMethodStr[] = - { - "NONE", - "GET", - "POST", - "PUT", - "HEAD", - "CONNECT", - "TRACE", - "PURGE", - "OPTIONS", - "DELETE", - "PROPFIND", - "PROPPATCH", - "MKCOL", - "COPY", - "MOVE", - "LOCK", - "UNLOCK", - "BMOVE", - "BDELETE", - "BPROPFIND", - "BPROPPATCH", - "BCOPY", - "SEARCH", - "SUBSCRIBE", - "UNSUBSCRIBE", - "POLL", - "REPORT", - "MKACTIVITY", - "CHECKOUT", - "MERGE", - "ERROR" - }; +const char* HttpRequestMethod::RequestMethodStr[] = { + "NONE", + "GET", + "POST", + "PUT", + "HEAD", + "CONNECT", + "TRACE", + "PURGE", + "OPTIONS", + "DELETE", + "PROPFIND", + "PROPPATCH", + "MKCOL", + "COPY", + "MOVE", + "LOCK", + "UNLOCK", + "BMOVE", + "BDELETE", + "BPROPFIND", + "BPROPPATCH", + "BCOPY", + "SEARCH", + "SUBSCRIBE", + "UNSUBSCRIBE", + "POLL", + "REPORT", + "MKACTIVITY", + "CHECKOUT", + "MERGE", + "ERROR" +}; static _method_t &operator++ (_method_t &aMethod) @@ -83,7 +82,7 @@ _method_t &operator++ (_method_t &aMethod) /* * Construct a HttpRequestMethod from a NULL terminated string such as "GET" - * or from a range of chars, * such as "GET" from "GETFOOBARBAZ" + * or from a range of chars, * such as "GET" from "GETFOOBARBAZ" * (pass in pointer to G and pointer to F.) */ HttpRequestMethod::HttpRequestMethod(char const *begin, char const *end) : theMethod (METHOD_NONE) @@ -107,12 +106,12 @@ HttpRequestMethod::HttpRequestMethod(char const *begin, char const *end) : theMe */ if (NULL == end) end = begin + strcspn(begin, w_space); - + if (end == begin) { - theMethod = METHOD_NONE; - return; + theMethod = METHOD_NONE; + return; } - + for (++theMethod; theMethod < METHOD_ENUM_END; ++theMethod) { if (0 == strncasecmp(begin, RequestMethodStr[theMethod], end-begin)) { return; @@ -171,13 +170,12 @@ HttpRequestMethod::Configure(SquidConfig &Config) #endif } -char const* +char const* HttpRequestMethod::image() const { if (METHOD_OTHER != theMethod) { return RequestMethodStr[theMethod]; - } - else { + } else { if (theImage.size()>0) { return theImage.buf(); } else { @@ -186,7 +184,7 @@ HttpRequestMethod::image() const } } -bool +bool HttpRequestMethod::isCacheble() const { // TODO: optimize the lookup with a precomputed flags array @@ -204,44 +202,44 @@ HttpRequestMethod::isCacheble() const if (theMethod == METHOD_POST) return false; - + if (theMethod == METHOD_OTHER) return false; - + return true; } -bool +bool HttpRequestMethod::purgesOthers() const { // TODO: optimize the lookup with a precomputed flags array switch (theMethod) { /* common sense suggests purging is not required? */ - case METHOD_GET: // XXX: but we do purge HEAD on successful GET - case METHOD_HEAD: - case METHOD_NONE: - case METHOD_CONNECT: - case METHOD_TRACE: - case METHOD_OPTIONS: - case METHOD_PROPFIND: - case METHOD_BPROPFIND: - case METHOD_COPY: - case METHOD_BCOPY: - case METHOD_LOCK: - case METHOD_UNLOCK: - case METHOD_SEARCH: - return false; + case METHOD_GET: // XXX: but we do purge HEAD on successful GET + case METHOD_HEAD: + case METHOD_NONE: + case METHOD_CONNECT: + case METHOD_TRACE: + case METHOD_OPTIONS: + case METHOD_PROPFIND: + case METHOD_BPROPFIND: + case METHOD_COPY: + case METHOD_BCOPY: + case METHOD_LOCK: + case METHOD_UNLOCK: + case METHOD_SEARCH: + return false; /* purging mandated by RFC 2616 */ - case METHOD_POST: - case METHOD_PUT: - case METHOD_DELETE: - return true; + case METHOD_POST: + case METHOD_PUT: + case METHOD_DELETE: + return true; /* purging suggested by common sense */ - case METHOD_PURGE: - return true; + case METHOD_PURGE: + return true; /* * RFC 2616 sayeth, in section 13.10, final paragraph: @@ -249,10 +247,10 @@ HttpRequestMethod::purgesOthers() const * understand SHOULD invalidate any entities referred to by the * Request-URI. */ - case METHOD_OTHER: - default: - return true; - } + case METHOD_OTHER: + default: + return true; + } return true; // not reached, but just in case } diff --git a/src/HttpRequestMethod.h b/src/HttpRequestMethod.h index 33c9fd23a4..f474d4d935 100644 --- a/src/HttpRequestMethod.h +++ b/src/HttpRequestMethod.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -99,36 +99,31 @@ public: */ HttpRequestMethod(char const * begin, char const * end); - HttpRequestMethod & operator = (const HttpRequestMethod& aMethod) - { + HttpRequestMethod & operator = (const HttpRequestMethod& aMethod) { theMethod = aMethod.theMethod; theImage = aMethod.theImage; return *this; } - HttpRequestMethod & operator = (_method_t const aMethod) - { + HttpRequestMethod & operator = (_method_t const aMethod) { theMethod = aMethod; theImage.clean(); return *this; } bool operator == (_method_t const & aMethod) const { return theMethod == aMethod; } - bool operator == (HttpRequestMethod const & aMethod) const - { + bool operator == (HttpRequestMethod const & aMethod) const { return theMethod == aMethod.theMethod && - (theMethod != METHOD_OTHER || theImage == aMethod.theImage); + (theMethod != METHOD_OTHER || theImage == aMethod.theImage); } bool operator != (_method_t const & aMethod) const { return theMethod != aMethod; } - bool operator != (HttpRequestMethod const & aMethod) const - { + bool operator != (HttpRequestMethod const & aMethod) const { return !operator==(aMethod); } /** Iterate through all HTTP method IDs. */ - HttpRequestMethod& operator++() - { + HttpRequestMethod& operator++() { // TODO: when this operator is used in more than one place, // replace it with HttpRequestMethods::Iterator API // XXX: this interface can create METHOD_OTHER without an image @@ -165,15 +160,15 @@ operator << (std::ostream &os, HttpRequestMethod const &method) } inline const char* -RequestMethodStr(const _method_t m) +RequestMethodStr(const _method_t m) { - return HttpRequestMethod(m).image(); + return HttpRequestMethod(m).image(); } inline const char* -RequestMethodStr(const HttpRequestMethod& m) +RequestMethodStr(const HttpRequestMethod& m) { - return m.image(); + return m.image(); } #endif /* SQUID_HTTPREQUESTMETHOD_H */ diff --git a/src/HttpStatusLine.cc b/src/HttpStatusLine.cc index a4ed0f455b..b1b0a07236 100644 --- a/src/HttpStatusLine.cc +++ b/src/HttpStatusLine.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/HttpStatusLine.h b/src/HttpStatusLine.h index e445b4c267..acb26ae0b7 100644 --- a/src/HttpStatusLine.h +++ b/src/HttpStatusLine.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/HttpVersion.h b/src/HttpVersion.h index 5df8d748ad..2cb1237346 100644 --- a/src/HttpVersion.h +++ b/src/HttpVersion.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -39,14 +39,12 @@ class HttpVersion { public: - HttpVersion() - { + HttpVersion() { major = 0; minor = 0; } - HttpVersion(unsigned int aMajor, unsigned int aMinor) - { + HttpVersion(unsigned int aMajor, unsigned int aMinor) { major = aMajor; minor = aMinor; } @@ -54,8 +52,7 @@ public: unsigned int major; unsigned int minor; - bool operator==(const HttpVersion& that) const - { + bool operator==(const HttpVersion& that) const { if (this->major != that.major) return false; @@ -65,8 +62,7 @@ public: return true; } - bool operator!=(const HttpVersion& that) const - { + bool operator!=(const HttpVersion& that) const { return ((this->major != that.major) || (this->minor != that.minor)); } diff --git a/src/ICAP/AsyncJob.cc b/src/ICAP/AsyncJob.cc index f97454b98f..158ddc3a50 100644 --- a/src/ICAP/AsyncJob.cc +++ b/src/ICAP/AsyncJob.cc @@ -12,7 +12,8 @@ unsigned int AsyncJob::TheLastId = 0; -AsyncJob *AsyncJob::AsyncStart(AsyncJob *job) { +AsyncJob *AsyncJob::AsyncStart(AsyncJob *job) +{ assert(job); CallJobHere(93, 5, job, AsyncJob::noteStart); return job; @@ -21,7 +22,7 @@ AsyncJob *AsyncJob::AsyncStart(AsyncJob *job) { AsyncJob::AsyncJob(const char *aTypeName): typeName(aTypeName), inCall(NULL), id(++TheLastId) { debugs(93,3, "AsyncJob of type " << typeName << " constructed, this=" << this << - " [async" << id << ']'); + " [async" << id << ']'); } AsyncJob::~AsyncJob() @@ -47,12 +48,12 @@ void AsyncJob::deleteThis(const char *aReason) // if we are in-call, then the call wrapper will delete us debugs(93, 4, typeName << " will NOT delete in-call job, reason: " << stopReason); return; - } - + } + // there is no call wrapper waiting for our return, so we fake it debugs(93, 5, typeName << " will delete this, reason: " << stopReason); AsyncCall::Pointer fakeCall = asyncCall(93,4, "FAKE-deleteThis", - MemFun(this, &AsyncJob::deleteThis, aReason)); + MemFun(this, &AsyncJob::deleteThis, aReason)); inCall = fakeCall; callEnd(); // delete fakeCall; @@ -63,11 +64,11 @@ void AsyncJob::mustStop(const char *aReason) // XXX: temporary code to catch cases where mustStop is called outside // of an async call context. Will be removed when that becomes impossible. // Until then, this will cause memory leaks and possibly other problems. - if (!inCall) { + if (!inCall) { stopReason = aReason; debugs(93, 5, typeName << " will STALL, reason: " << stopReason); return; - } + } Must(inCall != NULL); // otherwise nobody will delete us if we are done() Must(aReason); @@ -95,8 +96,8 @@ bool AsyncJob::canBeCalled(AsyncCall &call) const if (inCall != NULL) { // This may happen when we have bugs or some module is not calling // us asynchronously (comm used to do that). - debugs(93, 5, HERE << inCall << " is in progress; " << - call << " canot reenter the job."); + debugs(93, 5, HERE << inCall << " is in progress; " << + call << " canot reenter the job."); return call.cancel("reentrant job call"); } @@ -112,7 +113,7 @@ void AsyncJob::callStart(AsyncCall &call) inCall = &call; // XXX: ugly, but safe if callStart/callEnd,Ex are paired debugs(inCall->debugSection, inCall->debugLevel, - typeName << " status in:" << status()); + typeName << " status in:" << status()); } void AsyncJob::callException(const std::exception &e) @@ -141,7 +142,7 @@ void AsyncJob::callEnd() } debugs(inCall->debugSection, inCall->debugLevel, - typeName << " status out:" << status()); + typeName << " status out:" << status()); inCall = NULL; } @@ -152,9 +153,9 @@ const char *AsyncJob::status() const buf.reset(); buf.append(" [", 2); - if (stopReason != NULL){ + if (stopReason != NULL) { buf.Printf("Stopped, reason:"); - buf.Printf(stopReason); + buf.Printf(stopReason); } buf.Printf(" job%d]", id); buf.terminate(); @@ -174,7 +175,7 @@ JobDialer::JobDialer(AsyncJob *aJob): job(NULL), lock(NULL) } JobDialer::JobDialer(const JobDialer &d): CallDialer(d), - job(NULL), lock(NULL) + job(NULL), lock(NULL) { if (d.lock && cbdataReferenceValid(d.lock)) { lock = cbdataReference(d.lock); @@ -183,7 +184,8 @@ JobDialer::JobDialer(const JobDialer &d): CallDialer(d), } } -JobDialer::~JobDialer(){ +JobDialer::~JobDialer() +{ cbdataReferenceDone(lock); // lock may be NULL } @@ -202,7 +204,7 @@ JobDialer::canDial(AsyncCall &call) } void -JobDialer::dial(AsyncCall &call) +JobDialer::dial(AsyncCall &call) { Must(lock && cbdataReferenceValid(lock)); // canDial() checks for this Must(job); @@ -211,10 +213,9 @@ JobDialer::dial(AsyncCall &call) try { doDial(); - } - catch (const std::exception &e) { + } catch (const std::exception &e) { debugs(call.debugSection, 3, - HERE << call.name << " threw exception: " << e.what()); + HERE << call.name << " threw exception: " << e.what()); job->callException(e); } diff --git a/src/ICAP/AsyncJob.h b/src/ICAP/AsyncJob.h index c1663a294a..2796462637 100644 --- a/src/ICAP/AsyncJob.h +++ b/src/ICAP/AsyncJob.h @@ -1,6 +1,6 @@ - /* - * $Id: AsyncJob.h,v 1.4 2008/02/26 21:49:41 amosjeffries Exp $ - */ +/* + * $Id: AsyncJob.h,v 1.4 2008/02/26 21:49:41 amosjeffries Exp $ + */ #ifndef SQUID_ASYNC_JOB_H #define SQUID_ASYNC_JOB_H @@ -18,7 +18,7 @@ * "job", "task", or "logical processing thread" which receives asynchronous * calls. * - * Implementations should wrap each method receiving an asynchronous call in + * Implementations should wrap each method receiving an asynchronous call in * a pair of macros: AsyncCallEnter and AsyncCallExit. These macros: * - provide call debugging * - trap exceptions and terminate the task if an exception occurs @@ -103,7 +103,7 @@ protected: private: // not implemented and should not be needed - JobDialer &operator =(const JobDialer &); + JobDialer &operator =(const JobDialer &); }; #include "AsyncJobCalls.h" @@ -111,7 +111,7 @@ private: template bool CallJob(int debugSection, int debugLevel, const char *fileName, int fileLine, - const char *callName, const Dialer &dialer) + const char *callName, const Dialer &dialer) { AsyncCall::Pointer call = asyncCall(debugSection, debugLevel, callName, dialer); return ScheduleCall(fileName, fileLine, call); diff --git a/src/ICAP/ICAPClient.h b/src/ICAP/ICAPClient.h index daed777c86..8e6c66889c 100644 --- a/src/ICAP/ICAPClient.h +++ b/src/ICAP/ICAPClient.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ICAP/ICAPConfig.cc b/src/ICAP/ICAPConfig.cc index 36118ff94f..50be965fee 100644 --- a/src/ICAP/ICAPConfig.cc +++ b/src/ICAP/ICAPConfig.cc @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -48,8 +48,8 @@ ICAPConfig TheICAPConfig; ICAPConfig::ICAPConfig(): preview_enable(0), preview_size(0), - connect_timeout_raw(0), io_timeout_raw(0), reuse_connections(0), - client_username_header(NULL), client_username_encode(0) + connect_timeout_raw(0), io_timeout_raw(0), reuse_connections(0), + client_username_header(NULL), client_username_encode(0) { } @@ -78,7 +78,7 @@ time_t ICAPConfig::io_timeout(bool) const { if (io_timeout_raw > 0) return io_timeout_raw; // explicitly configured - // TODO: provide a different default for an ICAP transaction that + // TODO: provide a different default for an ICAP transaction that // can still be bypassed - return ::Config.Timeout.read; + return ::Config.Timeout.read; } diff --git a/src/ICAP/ICAPConfig.h b/src/ICAP/ICAPConfig.h index 1bdd995364..adb27dbcc8 100644 --- a/src/ICAP/ICAPConfig.h +++ b/src/ICAP/ICAPConfig.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ICAP/ICAPElements.h b/src/ICAP/ICAPElements.h index 9cdfca1769..33bc5f6a9b 100644 --- a/src/ICAP/ICAPElements.h +++ b/src/ICAP/ICAPElements.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -40,19 +40,19 @@ namespace ICAP { - using Adaptation::Method; - using Adaptation::methodNone; - using Adaptation::methodRespmod; - using Adaptation::methodReqmod; - - using Adaptation::VectPoint; - using Adaptation::pointNone; - using Adaptation::pointPreCache; - using Adaptation::pointPostCache; - - using Adaptation::crlf; - using Adaptation::methodStr; - using Adaptation::vectPointStr; +using Adaptation::Method; +using Adaptation::methodNone; +using Adaptation::methodRespmod; +using Adaptation::methodReqmod; + +using Adaptation::VectPoint; +using Adaptation::pointNone; +using Adaptation::pointPreCache; +using Adaptation::pointPostCache; + +using Adaptation::crlf; +using Adaptation::methodStr; +using Adaptation::vectPointStr; } #endif /* SQUID_ICAPCLIENT_H */ diff --git a/src/ICAP/ICAPInOut.h b/src/ICAP/ICAPInOut.h index f3fe51444f..df457321ae 100644 --- a/src/ICAP/ICAPInOut.h +++ b/src/ICAP/ICAPInOut.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -39,8 +39,8 @@ #include "HttpReply.h" // IcapInOut manages a pointer to the HTTP message being worked on. -// For HTTP responses, request header information is also available -// as the "cause". ICAP transactions use this class to store virgin +// For HTTP responses, request header information is also available +// as the "cause". ICAP transactions use this class to store virgin // and adapted HTTP messages. class ICAPInOut @@ -51,14 +51,12 @@ public: ICAPInOut(): header(0), cause(0) {} - ~ICAPInOut() - { + ~ICAPInOut() { HTTPMSGUNLOCK(cause); HTTPMSGUNLOCK(header); } - void setCause(HttpRequest *r) - { + void setCause(HttpRequest *r) { if (r) { HTTPMSGUNLOCK(cause); cause = HTTPMSGLOCK(r); @@ -67,11 +65,10 @@ public: } } - void setHeader(Header *h) - { + void setHeader(Header *h) { HTTPMSGUNLOCK(header); header = HTTPMSGLOCK(h); - body_pipe = header->body_pipe; + body_pipe = header->body_pipe; } public: @@ -81,8 +78,8 @@ public: // HTTP request header for HTTP responses (the cause of the response) HttpRequest *cause; - // Copy of header->body_pipe, in case somebody moves the original. - BodyPipe::Pointer body_pipe; + // Copy of header->body_pipe, in case somebody moves the original. + BodyPipe::Pointer body_pipe; }; // TODO: s/Header/Message/i ? diff --git a/src/ICAP/ICAPLauncher.cc b/src/ICAP/ICAPLauncher.cc index 7e738605ac..575066e484 100644 --- a/src/ICAP/ICAPLauncher.cc +++ b/src/ICAP/ICAPLauncher.cc @@ -11,10 +11,10 @@ ICAPLauncher::ICAPLauncher(const char *aTypeName, - Adaptation::Initiator *anInitiator, Adaptation::ServicePointer &aService): - AsyncJob(aTypeName), - Adaptation::Initiate(aTypeName, anInitiator, aService), - theXaction(0), theLaunches(0) + Adaptation::Initiator *anInitiator, Adaptation::ServicePointer &aService): + AsyncJob(aTypeName), + Adaptation::Initiate(aTypeName, anInitiator, aService), + theXaction(0), theLaunches(0) { } @@ -48,7 +48,7 @@ void ICAPLauncher::noteAdaptationAnswer(HttpMsg *message) sendAnswer(message); clearAdaptation(theXaction); Must(done()); - debugs(93,3, HERE << "ICAPLauncher::noteAdaptationAnswer exiting "); + debugs(93,3, HERE << "ICAPLauncher::noteAdaptationAnswer exiting "); } void ICAPLauncher::noteInitiatorAborted() @@ -69,13 +69,14 @@ void ICAPLauncher::noteAdaptationQueryAbort(bool final) launchXaction(true); } else { debugs(93,3, HERE << "cannot retry the failed ICAP xaction; tries: " << - theLaunches << "; final: " << final); + theLaunches << "; final: " << final); Must(done()); // swanSong will notify the initiator } } -bool ICAPLauncher::doneAll() const { +bool ICAPLauncher::doneAll() const +{ return (!theInitiator || !theXaction) && Adaptation::Initiate::doneAll(); } diff --git a/src/ICAP/ICAPLauncher.h b/src/ICAP/ICAPLauncher.h index ef11ec746a..ff62f0390e 100644 --- a/src/ICAP/ICAPLauncher.h +++ b/src/ICAP/ICAPLauncher.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -53,8 +53,8 @@ * Specific ICAP launchers implement the createXaction() method to create * REQMOD, RESPMOD, or OPTIONS transaction from initiator-supplied data. * - * TODO: This class might be the right place to initiate ICAP ACL checks or - * implement more sophisticated ICAP transaction handling like chaining of + * TODO: This class might be the right place to initiate ICAP ACL checks or + * implement more sophisticated ICAP transaction handling like chaining of * ICAP transactions. */ diff --git a/src/ICAP/ICAPOptXact.cc b/src/ICAP/ICAPOptXact.cc index e6e415f22d..a462f99792 100644 --- a/src/ICAP/ICAPOptXact.cc +++ b/src/ICAP/ICAPOptXact.cc @@ -15,8 +15,8 @@ CBDATA_CLASS_INIT(ICAPOptXactLauncher); ICAPOptXact::ICAPOptXact(Adaptation::Initiator *anInitiator, ICAPServiceRep::Pointer &aService): - AsyncJob("ICAPOptXact"), - ICAPXaction("ICAPOptXact", anInitiator, aService) + AsyncJob("ICAPOptXact"), + ICAPXaction("ICAPOptXact", anInitiator, aService) { } @@ -89,8 +89,8 @@ HttpMsg *ICAPOptXact::parseResponse() /* ICAPOptXactLauncher */ ICAPOptXactLauncher::ICAPOptXactLauncher(Adaptation::Initiator *anInitiator, Adaptation::ServicePointer aService): - AsyncJob("ICAPOptXactLauncher"), - ICAPLauncher("ICAPOptXactLauncher", anInitiator, aService) + AsyncJob("ICAPOptXactLauncher"), + ICAPLauncher("ICAPOptXactLauncher", anInitiator, aService) { } diff --git a/src/ICAP/ICAPOptXact.h b/src/ICAP/ICAPOptXact.h index 20ef83ee6d..1293e289a9 100644 --- a/src/ICAP/ICAPOptXact.h +++ b/src/ICAP/ICAPOptXact.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -65,7 +65,7 @@ private: CBDATA_CLASS2(ICAPOptXact); }; -// An ICAPLauncher that stores ICAPOptXact construction info and +// An ICAPLauncher that stores ICAPOptXact construction info and // creates ICAPOptXact when needed class ICAPOptXactLauncher: public ICAPLauncher { diff --git a/src/ICAP/ICAPOptions.h b/src/ICAP/ICAPOptions.h index 0187cc0234..1d7903d325 100644 --- a/src/ICAP/ICAPOptions.h +++ b/src/ICAP/ICAPOptions.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -81,26 +81,26 @@ public: protected: // Transfer-* extension list representation // maintains wordlist and does parsing/matching - class TransferList { - public: - TransferList(); - ~TransferList(); + class TransferList + { + public: + TransferList(); + ~TransferList(); - bool matches(const String &urlPath) const; + bool matches(const String &urlPath) const; - void parse(const String &buf, bool &foundStar); - void add(const char *extension); - void report(int level, const char *prefix) const; + void parse(const String &buf, bool &foundStar); + void add(const char *extension); + void report(int level, const char *prefix) const; - public: - wordlist *extensions; // TODO: optimize with a hash of some sort - const char *name; // header name, mostly for debugging - TransferKind kind; // to simplify caller's life + public: + wordlist *extensions; // TODO: optimize with a hash of some sort + const char *name; // header name, mostly for debugging + TransferKind kind; // to simplify caller's life }; // varios Transfer-* lists - struct Transfers - { + struct Transfers { TransferList preview; TransferList ignore; TransferList complete; diff --git a/src/ICMP.h b/src/ICMP.h index deb9951d48..31682f0f09 100644 --- a/src/ICMP.h +++ b/src/ICMP.h @@ -48,8 +48,7 @@ #if USE_ICMP /* This is a line-data format struct. DO NOT alter. */ -struct pingerEchoData -{ +struct pingerEchoData { IPAddress to; unsigned char opcode; int psize; @@ -57,8 +56,7 @@ struct pingerEchoData }; /* This is a line-data format struct. DO NOT alter. */ -struct pingerReplyData -{ +struct pingerReplyData { IPAddress from; unsigned char opcode; int rtt; @@ -67,8 +65,7 @@ struct pingerReplyData char payload[PINGER_PAYLOAD_SZ]; }; -struct icmpEchoData -{ +struct icmpEchoData { struct timeval tv; unsigned char opcode; char payload[MAX_PAYLOAD]; @@ -127,7 +124,7 @@ protected: /** * Translate TTL to a hop distance - * + * \param ttl negative : n > 33 \param ttl n(0...32) : 32 >= n >= 1 \param ttl n(33...62) : 32 >= n >= 1 diff --git a/src/ICMPConfig.h b/src/ICMPConfig.h index 60be4bc68b..a1a1b3b9b0 100644 --- a/src/ICMPConfig.h +++ b/src/ICMPConfig.h @@ -50,7 +50,8 @@ * This structure is included as a child field of the global Config * such that if ICMP is built it can be accessed as Config.pinger.* */ -class ICMPConfig { +class ICMPConfig +{ public: @@ -58,9 +59,9 @@ public: * alongside any custom parsing routines needed for this component. * First though, the whole global Config dependancy tree needs fixing */ ICMPConfig() : program(NULL), enable(0) {}; - ~ICMPConfig() { if(program) delete program; program = NULL; }; + ~ICMPConfig() { if (program) delete program; program = NULL; }; -/* variables */ + /* variables */ /** pinger helper application path */ char *program; diff --git a/src/ICMPPinger.cc b/src/ICMPPinger.cc index 2daf56286f..5e07f4f238 100644 --- a/src/ICMPPinger.cc +++ b/src/ICMPPinger.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -210,7 +210,7 @@ ICMPPinger::Recv(void) #if USE_IPV6 /* pass request for ICMPv6 handing */ - if(pecho.to.IsIPv6()) { + if (pecho.to.IsIPv6()) { debugs(42, 2, HERE << " Pass " << pecho.to << " off to ICMPv6 module."); icmp6.SendEcho(pecho.to, pecho.opcode, @@ -220,14 +220,13 @@ ICMPPinger::Recv(void) #endif /* pass the packet for ICMP handling */ - else if(pecho.to.IsIPv4()) { + else if (pecho.to.IsIPv4()) { debugs(42, 2, HERE << " Pass " << pecho.to << " off to ICMPv4 module."); icmp4.SendEcho(pecho.to, pecho.opcode, pecho.payload, pecho.psize); - } - else { + } else { debugs(42, 1, HERE << " IP has unknown Type. " << pecho.to ); } } diff --git a/src/ICMPSquid.cc b/src/ICMPSquid.cc index bc9c89354d..0132f2c0ca 100644 --- a/src/ICMPSquid.cc +++ b/src/ICMPSquid.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -74,15 +74,15 @@ ICMPSquid::SendEcho(IPAddress &to, int opcode, const char *payload, int len) int x, slen; /** \li Does nothing if the pinger socket is not available. */ - if(icmp_sock < 0) { + if (icmp_sock < 0) { debugs(37, 2, HERE << " Socket Closed. Aborted send to " << pecho.to << ", opcode " << opcode << ", len " << pecho.psize); return; } /** \li If no payload is given or is set as NULL it will ignore payload and len */ - if(!payload) + if (!payload) len = 0; - + /** \li Otherwise if len is 0, uses strlen() to detect length of payload. \bug This will result in part of the payload being truncated if it contains a NULL character. \bug Or it may result in a buffer over-run if the payload is not nul-terminated properly. @@ -102,7 +102,7 @@ ICMPSquid::SendEcho(IPAddress &to, int opcode, const char *payload, int len) pecho.psize = len; - if(len > 0) + if (len > 0) xmemcpy(pecho.payload, payload, len); slen = sizeof(pingerEchoData) - PINGER_PAYLOAD_SZ + pecho.psize; @@ -213,7 +213,7 @@ ICMPSquid::Open(void) IPAddress localhost; /* User configured disabled. */ - if(!Config.pinger.enable) { + if (!Config.pinger.enable) { Close(); return -1; } @@ -255,7 +255,7 @@ ICMPSquid::Open(void) #if USE_IPV6 SendEcho(localhost, S_ICMP_ECHO, "ip6-localhost"); #endif - if(localhost.SetIPv4()) + if (localhost.SetIPv4()) SendEcho(localhost, S_ICMP_ECHO, "localhost"); #ifdef _SQUID_MSWIN_ diff --git a/src/ICMPv4.cc b/src/ICMPv4.cc index 221d32def1..67b789476d 100644 --- a/src/ICMPv4.cc +++ b/src/ICMPv4.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -42,30 +42,30 @@ #include "ICMPPinger.h" #include "Debug.h" -const char *icmpPktStr[] = - { - "Echo Reply", - "ICMP 1", - "ICMP 2", - "Destination Unreachable", - "Source Quench", - "Redirect", - "ICMP 6", - "ICMP 7", - "Echo", - "ICMP 9", - "ICMP 10", - "Time Exceeded", - "Parameter Problem", - "Timestamp", - "Timestamp Reply", - "Info Request", - "Info Reply", - "Out of Range Type" - }; +const char *icmpPktStr[] = { + "Echo Reply", + "ICMP 1", + "ICMP 2", + "Destination Unreachable", + "Source Quench", + "Redirect", + "ICMP 6", + "ICMP 7", + "Echo", + "ICMP 9", + "ICMP 10", + "Time Exceeded", + "Parameter Problem", + "Timestamp", + "Timestamp Reply", + "Info Request", + "Info Reply", + "Out of Range Type" +}; ICMPv4::ICMPv4() : ICMP() -{; +{ + ; } ICMPv4::~ICMPv4() @@ -108,8 +108,7 @@ ICMPv4::SendEcho(IPAddress &to, int opcode, const char *payload, int len) * cevans - beware signed/unsigned issues in untrusted data from * the network!! */ - if (len < 0) - { + if (len < 0) { len = 0; } @@ -127,8 +126,7 @@ ICMPv4::SendEcho(IPAddress &to, int opcode, const char *payload, int len) icmp_pktsize += sizeof(struct timeval) + sizeof(char); - if (payload) - { + if (payload) { if (len > MAX_PAYLOAD) len = MAX_PAYLOAD; @@ -146,13 +144,13 @@ ICMPv4::SendEcho(IPAddress &to, int opcode, const char *payload, int len) debugs(42, 2, HERE << "Send ICMP packet to " << to << "."); x = sendto(icmp_sock, - (const void *) pkt, - icmp_pktsize, - 0, - S->ai_addr, - S->ai_addrlen); + (const void *) pkt, + icmp_pktsize, + 0, + S->ai_addr, + S->ai_addrlen); - if(x < 0) { + if (x < 0) { debugs(42, 1, HERE << "Error sending to ICMP packet to " << to << ". ERR: " << xstrerror()); } @@ -172,7 +170,7 @@ ICMPv4::Recv(void) icmpEchoData *echo; static pingerReplyData preply; - if(icmp_sock < 0) { + if (icmp_sock < 0) { debugs(42, 0, HERE << "No socket! Recv() should not be called."); return; } diff --git a/src/ICMPv4.h b/src/ICMPv4.h index d26739fc53..59a31315cc 100644 --- a/src/ICMPv4.h +++ b/src/ICMPv4.h @@ -106,8 +106,7 @@ #endif /* IP Header */ -typedef struct iphdr -{ +typedef struct iphdr { u_int8_t ip_vhl: 4; /* Length of the header in dwords */ @@ -126,8 +125,7 @@ u_int8_t version: } iphdr; /* ICMP header */ -typedef struct icmphdr -{ +typedef struct icmphdr { u_int8_t icmp_type; /* ICMP packet type */ u_int8_t icmp_code; /* Type sub code */ u_int16_t icmp_cksum; diff --git a/src/ICMPv6.cc b/src/ICMPv6.cc index c8d5bb0a2d..f05ff7a2df 100644 --- a/src/ICMPv6.cc +++ b/src/ICMPv6.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -52,58 +52,56 @@ // ICMPv6 OP-Codes // see http://www.iana.org/assignments/icmpv6-parameters // NP: LowPktStr is for codes 0-127 -static const char *icmp6LowPktStr[] = - { - "ICMP 0", // 0 - "Destination Unreachable", // 1 - RFC2463 - "Packet Too Big", // 2 - RFC2463 - "Time Exceeded", // 3 - RFC2463 - "Parameter Problem", // 4 - RFC2463 - "ICMP 5", // 5 - "ICMP 6", // 6 - "ICMP 7", // 7 - "ICMP 8", // 8 - "ICMP 9", // 9 - "ICMP 10" // 10 - }; +static const char *icmp6LowPktStr[] = { + "ICMP 0", // 0 + "Destination Unreachable", // 1 - RFC2463 + "Packet Too Big", // 2 - RFC2463 + "Time Exceeded", // 3 - RFC2463 + "Parameter Problem", // 4 - RFC2463 + "ICMP 5", // 5 + "ICMP 6", // 6 + "ICMP 7", // 7 + "ICMP 8", // 8 + "ICMP 9", // 9 + "ICMP 10" // 10 +}; // NP: HighPktStr is for codes 128-255 -static const char *icmp6HighPktStr[] = - { - "Echo Request", // 128 - RFC2463 - "Echo Reply", // 129 - RFC2463 - "Multicast Listener Query", // 130 - RFC2710 - "Multicast Listener Report", // 131 - RFC2710 - "Multicast Listener Done", // 132 - RFC2710 - "Router Solicitation", // 133 - RFC4861 - "Router Advertisement", // 134 - RFC4861 - "Neighbor Solicitation", // 135 - RFC4861 - "Neighbor Advertisement", // 136 - RFC4861 - "Redirect Message", // 137 - RFC4861 - "Router Renumbering", // 138 - Crawford - "ICMP Node Information Query", // 139 - RFC4620 - "ICMP Node Information Response", // 140 - RFC4620 - "Inverse Neighbor Discovery Solicitation", // 141 - RFC3122 - "Inverse Neighbor Discovery Advertisement", // 142 - RFC3122 - "Version 2 Multicast Listener Report", // 143 - RFC3810 - "Home Agent Address Discovery Request", // 144 - RFC3775 - "Home Agent Address Discovery Reply", // 145 - RFC3775 - "Mobile Prefix Solicitation", // 146 - RFC3775 - "Mobile Prefix Advertisement", // 147 - RFC3775 - "Certification Path Solicitation", // 148 - RFC3971 - "Certification Path Advertisement", // 149 - RFC3971 - "ICMP Experimental (150)", // 150 - RFC4065 - "Multicast Router Advertisement", // 151 - RFC4286 - "Multicast Router Solicitation", // 152 - RFC4286 - "Multicast Router Termination", // 153 - [RFC4286] - "ICMP 154", - "ICMP 155", - "ICMP 156", - "ICMP 157", - "ICMP 158", - "ICMP 159", - "ICMP 160" - }; +static const char *icmp6HighPktStr[] = { + "Echo Request", // 128 - RFC2463 + "Echo Reply", // 129 - RFC2463 + "Multicast Listener Query", // 130 - RFC2710 + "Multicast Listener Report", // 131 - RFC2710 + "Multicast Listener Done", // 132 - RFC2710 + "Router Solicitation", // 133 - RFC4861 + "Router Advertisement", // 134 - RFC4861 + "Neighbor Solicitation", // 135 - RFC4861 + "Neighbor Advertisement", // 136 - RFC4861 + "Redirect Message", // 137 - RFC4861 + "Router Renumbering", // 138 - Crawford + "ICMP Node Information Query", // 139 - RFC4620 + "ICMP Node Information Response", // 140 - RFC4620 + "Inverse Neighbor Discovery Solicitation", // 141 - RFC3122 + "Inverse Neighbor Discovery Advertisement", // 142 - RFC3122 + "Version 2 Multicast Listener Report", // 143 - RFC3810 + "Home Agent Address Discovery Request", // 144 - RFC3775 + "Home Agent Address Discovery Reply", // 145 - RFC3775 + "Mobile Prefix Solicitation", // 146 - RFC3775 + "Mobile Prefix Advertisement", // 147 - RFC3775 + "Certification Path Solicitation", // 148 - RFC3971 + "Certification Path Advertisement", // 149 - RFC3971 + "ICMP Experimental (150)", // 150 - RFC4065 + "Multicast Router Advertisement", // 151 - RFC4286 + "Multicast Router Solicitation", // 152 - RFC4286 + "Multicast Router Termination", // 153 - [RFC4286] + "ICMP 154", + "ICMP 155", + "ICMP 156", + "ICMP 157", + "ICMP 158", + "ICMP 159", + "ICMP 160" +}; ICMPv6::ICMPv6() : ICMP() { @@ -172,8 +170,7 @@ ICMPv6::SendEcho(IPAddress &to, int opcode, const char *payload, int len) icmp6_pktsize += sizeof(struct timeval) + sizeof(char); - if (payload) - { + if (payload) { if (len > MAX_PAYLOAD) len = MAX_PAYLOAD; @@ -192,13 +189,13 @@ ICMPv6::SendEcho(IPAddress &to, int opcode, const char *payload, int len) debugs(42, 5, HERE << "Send ICMPv6 packet to " << to << "."); x = sendto(icmp_sock, - (const void *) pkt, - icmp6_pktsize, - 0, - S->ai_addr, - S->ai_addrlen); + (const void *) pkt, + icmp6_pktsize, + 0, + S->ai_addr, + S->ai_addrlen); - if(x < 0) { + if (x < 0) { debugs(42, 1, HERE << "Error sending to ICMPv6 packet to " << to << ". ERR: " << xstrerror()); } debugs(42,9, HERE << "x=" << x); @@ -221,7 +218,7 @@ ICMPv6::Recv(void) struct timeval now; static pingerReplyData preply; - if(icmp_sock < 0) { + if (icmp_sock < 0) { debugs(42,0, HERE << "dropping ICMPv6 read. No socket!?"); return; } @@ -258,44 +255,44 @@ ICMPv6::Recv(void) // TTL still has to come from the IP header somewhere. // still need to strip and process it properly. // probably have to rely on RTT as given by timestamp in data sent and current. -/* IPv6 Header Structures (linux) -struct ip6_hdr + /* IPv6 Header Structures (linux) + struct ip6_hdr -// fields (via simple define) -#define ip6_vfc // N.A -#define ip6_flow // N/A -#define ip6_plen // payload length. -#define ip6_nxt // expect to be type 0x3a - ICMPv6 -#define ip6_hlim // MAX hops (always 64, but no guarantee) -#define ip6_hops // HOPS!!! (can it be true??) + // fields (via simple define) + #define ip6_vfc // N.A + #define ip6_flow // N/A + #define ip6_plen // payload length. + #define ip6_nxt // expect to be type 0x3a - ICMPv6 + #define ip6_hlim // MAX hops (always 64, but no guarantee) + #define ip6_hops // HOPS!!! (can it be true??) - ip = (struct ip6_hdr *) pkt; - pkt += sizeof(ip6_hdr); + ip = (struct ip6_hdr *) pkt; + pkt += sizeof(ip6_hdr); -debugs(42,0, HERE << "ip6_nxt=" << ip->ip6_nxt << - ", ip6_plen=" << ip->ip6_plen << - ", ip6_hlim=" << ip->ip6_hlim << - ", ip6_hops=" << ip->ip6_hops << - " ::: 40 == sizef(ip6_hdr) == " << sizeof(ip6_hdr) -); -*/ + debugs(42,0, HERE << "ip6_nxt=" << ip->ip6_nxt << + ", ip6_plen=" << ip->ip6_plen << + ", ip6_hlim=" << ip->ip6_hlim << + ", ip6_hops=" << ip->ip6_hops << + " ::: 40 == sizef(ip6_hdr) == " << sizeof(ip6_hdr) + ); + */ icmp6 = (struct icmp6_hdr *) pkt; pkt += sizeof(icmp6_hdr); if (icmp6->icmp6_type != ICMP6_ECHO_REPLY) { - switch(icmp6->icmp6_type) { - case 134: - case 135: - case 136: - /* ignore Router/Neighbour Advertisements */ + switch (icmp6->icmp6_type) { + case 134: + case 135: + case 136: + /* ignore Router/Neighbour Advertisements */ break; - default: - debugs(42, 8, HERE << preply.from << " said: " << icmp6->icmp6_type << "/" << (int)icmp6->icmp6_code << " " << - ( icmp6->icmp6_type&0x80 ? icmp6HighPktStr[(int)(icmp6->icmp6_type&0x7f)] : icmp6LowPktStr[(int)(icmp6->icmp6_type&0x7f)] ) + default: + debugs(42, 8, HERE << preply.from << " said: " << icmp6->icmp6_type << "/" << (int)icmp6->icmp6_code << " " << + ( icmp6->icmp6_type&0x80 ? icmp6HighPktStr[(int)(icmp6->icmp6_type&0x7f)] : icmp6LowPktStr[(int)(icmp6->icmp6_type&0x7f)] ) ); } return; @@ -314,21 +311,20 @@ debugs(42,0, HERE << "ip6_nxt=" << ip->ip6_nxt << memcpy(&tv, &echo->tv, sizeof(struct timeval)); preply.rtt = tvSubMsec(tv, now); -/* - * FIXME INET6: Without access to the IPv6-Hops header we must rely on the total RTT - * and could caculate the hops from that, but it produces some weird value mappings using ipHops - * for now everything is 1 v6 hop away with variant RTT - * WANT: preply.hops = ip->ip6_hops; // ipHops(ip->ip_hops); - */ + /* + * FIXME INET6: Without access to the IPv6-Hops header we must rely on the total RTT + * and could caculate the hops from that, but it produces some weird value mappings using ipHops + * for now everything is 1 v6 hop away with variant RTT + * WANT: preply.hops = ip->ip6_hops; // ipHops(ip->ip_hops); + */ preply.hops = 1; preply.psize = n - /* sizeof(ip6_hdr) - */ sizeof(icmp6_hdr) - (sizeof(icmpEchoData) - MAX_PKT6_SZ); /* Ensure the response packet has safe payload size */ - if( preply.psize > (unsigned short) MAX_PKT6_SZ) { + if ( preply.psize > (unsigned short) MAX_PKT6_SZ) { preply.psize = MAX_PKT6_SZ; - } - else if( preply.psize < (unsigned short)0) { + } else if ( preply.psize < (unsigned short)0) { preply.psize = 0; } diff --git a/src/ICP.h b/src/ICP.h index 0973f4784b..058da11df6 100644 --- a/src/ICP.h +++ b/src/ICP.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -47,8 +47,7 @@ * DO NOT add more move fields on pain of breakage. * DO NOT add virtual methods. */ -struct _icp_common_t -{ +struct _icp_common_t { /** opcode */ unsigned char opcode; /** version number */ @@ -107,8 +106,7 @@ public: #endif /// \ingroup ServerProtocolICPAPI -struct icpUdpData -{ +struct icpUdpData { IPAddress address; void *msg; size_t len; diff --git a/src/IPInterception.cc b/src/IPInterception.cc index e5be35368a..a307aa77a7 100644 --- a/src/IPInterception.cc +++ b/src/IPInterception.cc @@ -1,7 +1,7 @@ /* * $Id: IPInterception.cc,v 1.20 2008/02/05 22:38:24 amosjeffries Exp $ * - * DEBUG: section 89 NAT / IP Interception + * DEBUG: section 89 NAT / IP Interception * AUTHOR: Robert Collins * AUTHOR: Amos Jeffries * @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -107,16 +107,18 @@ IPIntercept IPInterceptor; void -IPIntercept::StopTransparency(const char *str) { - if(transparent_active) { +IPIntercept::StopTransparency(const char *str) +{ + if (transparent_active) { debugs(89, DBG_IMPORTANT, "Stopping full transparency: " << str); transparent_active = 0; } } void -IPIntercept::StopInterception(const char *str) { - if(intercept_active) { +IPIntercept::StopInterception(const char *str) +{ + if (intercept_active) { debugs(89, DBG_IMPORTANT, "Stopping IP interception: " << str); intercept_active = 0; } @@ -132,19 +134,18 @@ IPIntercept::NetfilterInterception(int fd, const IPAddress &me, IPAddress &dst, /** \par * Try NAT lookup for REDIRECT or DNAT targets. */ - if( getsockopt(fd, SOL_IP, SO_ORIGINAL_DST, lookup->ai_addr, &lookup->ai_addrlen) == 0) { - if(!silent) { + if ( getsockopt(fd, SOL_IP, SO_ORIGINAL_DST, lookup->ai_addr, &lookup->ai_addrlen) == 0) { + if (!silent) { debugs(89, DBG_IMPORTANT, HERE << " NF getsockopt(SO_ORIGINAL_DST) failed on FD " << fd << ": " << xstrerror()); last_reported = squid_curtime; } - } - else { + } else { dst = *lookup; } dst.FreeAddrInfo(lookup); - if(me != dst) { + if (me != dst) { debugs(89, 5, HERE << "address: " << dst); return 0; } @@ -162,7 +163,7 @@ IPIntercept::NetfilterTransparent(int fd, const IPAddress &me, IPAddress &client /* Trust the user configured properly. If not no harm done. * We will simply attempt a bind outgoing on our own IP. */ - if(fd_table[fd].flags.transparent) { + if (fd_table[fd].flags.transparent) { client.SetPort(0); // allow random outgoing port to prevent address clashes return 0; } @@ -180,19 +181,18 @@ IPIntercept::IPFWInterception(int fd, const IPAddress &me, IPAddress &dst, int s /** \par * Try lookup for IPFW interception. */ - if( getsockname(fd, lookup->ai_addr, &lookup->ai_addrlen) != 0 ) { - if( !silent ) { + if ( getsockname(fd, lookup->ai_addr, &lookup->ai_addrlen) != 0 ) { + if ( !silent ) { debugs(89, DBG_IMPORTANT, HERE << " IPFW getsockname(...) failed: " << xstrerror()); last_reported = squid_curtime; } - } - else { + } else { dst = *lookup; } dst.FreeAddrInfo(lookup); - if(me != dst) { + if (me != dst) { debugs(89, 5, HERE << "address: " << dst); return 0; } @@ -207,8 +207,8 @@ IPIntercept::NatLookup(int fd, const IPAddress &me, const IPAddress &peer, IPAdd { #if IPF_TRANSPARENT /* --enable-ipf-transparent */ client = me; - if( !me.IsIPv4() ) return -1; - if( !peer.IsIPv4() ) return -1; + if ( !me.IsIPv4() ) return -1; + if ( !peer.IsIPv4() ) return -1; #if defined(IPFILTER_VERSION) && (IPFILTER_VERSION >= 4000027) @@ -238,8 +238,7 @@ IPIntercept::NatLookup(int fd, const IPAddress &me, const IPAddress &peer, IPAdd peer.GetInAddr(natLookup.nl_outip); natLookup.nl_flags = IPN_TCP; - if (natfd < 0) - { + if (natfd < 0) { int save_errno; enter_suid(); #ifdef IPNAT_NAME @@ -255,8 +254,7 @@ IPIntercept::NatLookup(int fd, const IPAddress &me, const IPAddress &peer, IPAdd errno = save_errno; } - if (natfd < 0) - { + if (natfd < 0) { if (squid_curtime - last_reported > 60) { debugs(89, 1, "clientNatLookup: NAT open failed: " << xstrerror()); last_reported = squid_curtime; @@ -275,19 +273,16 @@ IPIntercept::NatLookup(int fd, const IPAddress &me, const IPAddress &peer, IPAdd * put something in configure and use ifdefs here, but * this seems simpler. */ - if (63 == siocgnatl_cmd) - { + if (63 == siocgnatl_cmd) { struct natlookup *nlp = &natLookup; x = ioctl(natfd, SIOCGNATL, &nlp); - } else - { + } else { x = ioctl(natfd, SIOCGNATL, &natLookup); } #endif - if (x < 0) - { + if (x < 0) { if (errno != ESRCH) { if (squid_curtime - last_reported > 60) { debugs(89, 1, "clientNatLookup: NAT lookup failed: ioctl(SIOCGNATL)"); @@ -299,8 +294,7 @@ IPIntercept::NatLookup(int fd, const IPAddress &me, const IPAddress &peer, IPAdd } return -1; - } else - { + } else { if (me != natLookup.nl_realip) { client = natLookup.nl_realip; @@ -322,8 +316,8 @@ IPIntercept::NatLookup(int fd, const IPAddress &me, const IPAddress &peer, IPAdd client = me; dst = peer; - if( !me.IsIPv4() ) return -1; - if( !peer.IsIPv4() ) return -1; + if ( !me.IsIPv4() ) return -1; + if ( !peer.IsIPv4() ) return -1; #if 0 // Crop interception errors down to one per minute. @@ -333,12 +327,12 @@ IPIntercept::NatLookup(int fd, const IPAddress &me, const IPAddress &peer, IPAdd int silent = 0; #endif - if(intercept_active) { - if( NetfilterInterception(fd, me, client, silent) == 0) return 0; - if( IPFWInterception(fd, me, client, silent) == 0) return 0; + if (intercept_active) { + if ( NetfilterInterception(fd, me, client, silent) == 0) return 0; + if ( IPFWInterception(fd, me, client, silent) == 0) return 0; } - if(transparent_active) { - if( NetfilterTransparent(fd, me, dst, silent) == 0) return 0; + if (transparent_active) { + if ( NetfilterTransparent(fd, me, dst, silent) == 0) return 0; } return -1; @@ -348,14 +342,13 @@ IPIntercept::NatLookup(int fd, const IPAddress &me, const IPAddress &peer, IPAdd struct pfioc_natlook nl; static int pffd = -1; - if( !me.IsIPv4() ) return -1; - if( !peer.IsIPv4() ) return -1; + if ( !me.IsIPv4() ) return -1; + if ( !peer.IsIPv4() ) return -1; if (pffd < 0) pffd = open("/dev/pf", O_RDONLY); - if (pffd < 0) - { + if (pffd < 0) { if (squid_curtime - last_reported > 60) { debugs(89, 1, "clientNatLookup: PF open failed: " << xstrerror()); last_reported = squid_curtime; @@ -378,8 +371,7 @@ IPIntercept::NatLookup(int fd, const IPAddress &me, const IPAddress &peer, IPAdd nl.proto = IPPROTO_TCP; nl.direction = PF_OUT; - if (ioctl(pffd, DIOCNATLOOK, &nl)) - { + if (ioctl(pffd, DIOCNATLOOK, &nl)) { if (errno != ENOENT) { if (squid_curtime - last_reported > 60) { debugs(89, 1, "clientNatLookup: PF lookup failed: ioctl(DIOCNATLOOK)"); @@ -391,8 +383,7 @@ IPIntercept::NatLookup(int fd, const IPAddress &me, const IPAddress &peer, IPAdd } return -1; - } else - { + } else { int natted = (me != nl.rdaddr.v4); client = nl.rdaddr.v4; client.SetPort(ntohs(nl.rdport)); diff --git a/src/LeakFinder.cc b/src/LeakFinder.cc index 235539475f..e8a86a749f 100644 --- a/src/LeakFinder.cc +++ b/src/LeakFinder.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -71,7 +71,7 @@ LeakFinder::LeakFinder() void * LeakFinder::add - (void *p, const char *file, int line) +(void *p, const char *file, int line) { assert(hash_lookup(table, p) == NULL); LeakFinderPtr *c = new LeakFinderPtr(p, file, line); @@ -138,8 +138,8 @@ LeakFinder::dump() LeakFinderPtr *c; while ((c = (LeakFinderPtr *)hash_next(table))) { - debugs(45, 1, std::setw(20) << c->key << " last used " << std::setw(9) << (squid_curtime - c->when) << - " seconds ago by " << c->file << ":" << c->line); + debugs(45, 1, std::setw(20) << c->key << " last used " << std::setw(9) << (squid_curtime - c->when) << + " seconds ago by " << c->file << ":" << c->line); } } diff --git a/src/LoadableModule.cc b/src/LoadableModule.cc index e35e1702d1..fe18d8a820 100644 --- a/src/LoadableModule.cc +++ b/src/LoadableModule.cc @@ -2,14 +2,14 @@ /* The original code has this constant ./configure-able. * The "#else" branches use raw dlopen interface and have not been tested. - * We can remove that code if we are going to rely on libtool's ltdl in + * We can remove that code if we are going to rely on libtool's ltdl in * all environments. */ #define XSTD_USE_LIBLTDL 1 #if XSTD_USE_LIBLTDL - #include "libLtdl/ltdl.h" /* generated file */ +#include "libLtdl/ltdl.h" /* generated file */ #else - #include +#include #endif #include "TextException.h" @@ -18,69 +18,77 @@ // Note: We must use preprocessor instead of C ifs because if dlopen() // is seen by the static linker, the linker will complain. -LoadableModule::LoadableModule(const String &aName): theName(aName), theHandle(0) { +LoadableModule::LoadableModule(const String &aName): theName(aName), theHandle(0) +{ # if XSTD_USE_LIBLTDL - // Initialise preloaded symbol lookup table. - LTDL_SET_PRELOADED_SYMBOLS(); - if (lt_dlinit() != 0) - throw TexcHere("internal error: cannot initialize libtool module loader"); + // Initialise preloaded symbol lookup table. + LTDL_SET_PRELOADED_SYMBOLS(); + if (lt_dlinit() != 0) + throw TexcHere("internal error: cannot initialize libtool module loader"); # endif } -LoadableModule::~LoadableModule() { - if (loaded()) - unload(); +LoadableModule::~LoadableModule() +{ + if (loaded()) + unload(); # if XSTD_USE_LIBLTDL - assert(lt_dlexit() == 0); // XXX: replace with a warning + assert(lt_dlexit() == 0); // XXX: replace with a warning # endif } -bool LoadableModule::loaded() const { - return theHandle != 0; +bool LoadableModule::loaded() const +{ + return theHandle != 0; } -void LoadableModule::load(int mode) { - if (loaded()) - throw TexcHere("internal error: reusing LoadableModule object"); +void LoadableModule::load(int mode) +{ + if (loaded()) + throw TexcHere("internal error: reusing LoadableModule object"); - theHandle = openModule(mode); + theHandle = openModule(mode); - if (!loaded()) - throw TexcHere(errorMsg()); + if (!loaded()) + throw TexcHere(errorMsg()); } -void LoadableModule::unload() { - if (!loaded()) - throw TexcHere("internal error: unloading not loaded module"); +void LoadableModule::unload() +{ + if (!loaded()) + throw TexcHere("internal error: unloading not loaded module"); - if (!closeModule()) - throw TexcHere(errorMsg()); + if (!closeModule()) + throw TexcHere(errorMsg()); - theHandle = 0; + theHandle = 0; } -void *LoadableModule::openModule(int mode) { +void *LoadableModule::openModule(int mode) +{ # if XSTD_USE_LIBLTDL - return lt_dlopen(theName.buf()); + return lt_dlopen(theName.buf()); # else - return dlopen(theName.c_str(), - mode == lmNow ? RTLD_NOW : RTLD_LAZY); + return dlopen(theName.c_str(), + mode == lmNow ? RTLD_NOW : RTLD_LAZY); # endif } -bool LoadableModule::closeModule() { +bool LoadableModule::closeModule() +{ # if XSTD_USE_LIBLTDL - // we cast to avoid including ltdl.h in LoadableModule.h - return lt_dlclose(static_cast(theHandle)) == 0; + // we cast to avoid including ltdl.h in LoadableModule.h + return lt_dlclose(static_cast(theHandle)) == 0; # else - return dlclose(theHandle) == 0; + return dlclose(theHandle) == 0; # endif } -const char *LoadableModule::errorMsg() { +const char *LoadableModule::errorMsg() +{ # if XSTD_USE_LIBLTDL - return lt_dlerror(); + return lt_dlerror(); # else - return dlerror(); + return dlerror(); # endif } diff --git a/src/LoadableModule.h b/src/LoadableModule.h index 5d9f17f99c..88f239a425 100644 --- a/src/LoadableModule.h +++ b/src/LoadableModule.h @@ -4,7 +4,8 @@ #include "SquidString.h" // wrapper for dlopen(3), libltdl, and friends -class LoadableModule { +class LoadableModule +{ public: enum LoadMode { lmNow, lmLazy }; diff --git a/src/Mem.h b/src/Mem.h index f188cc5106..f90e624371 100644 --- a/src/Mem.h +++ b/src/Mem.h @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/MemBuf.cc b/src/MemBuf.cc index d5b253c503..d754d4e9b3 100644 --- a/src/MemBuf.cc +++ b/src/MemBuf.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -40,56 +40,56 @@ \verbatim * Rationale: * ---------- - * + * * Here is how one would comm_write an object without MemBuffer: - * + * * { * -- allocate: * buf = malloc(big_enough); - * + * * -- "pack": * snprintf object(s) piece-by-piece constantly checking for overflows * and maintaining (buf+offset); * ... - * + * * -- write * comm_write(buf, free, ...); * } - * + * * The whole "packing" idea is quite messy: We are given a buffer of fixed * size and we have to check all the time that we still fit. Sounds logical. * * However, what happens if we have more data? If we are lucky to stop before * we overrun any buffers, we still may have garbage (e.g. half of ETag) in * the buffer. - * + * * MemBuffer: * ---------- - * + * * MemBuffer is a memory-resident buffer with printf()-like interface. It * hides all offest handling and overflow checking. Moreover, it has a * build-in control that no partial data has been written. - * + * * MemBuffer is designed to handle relatively small data. It starts with a * small buffer of configurable size to avoid allocating huge buffers all the * time. MemBuffer doubles the buffer when needed. It assert()s that it will * not grow larger than a configurable limit. MemBuffer has virtually no * overhead (and can even reduce memory consumption) compared to old * "packing" approach. - * + * * MemBuffer eliminates both "packing" mess and truncated data: - * + * * { * -- setup * MemBuf buf; - * + * * -- required init with optional size tuning (see #defines for defaults) * buf.init(initial-size, absolute-maximum); - * + * * -- "pack" (no need to handle offsets or check for overflows) * buf.Printf(...); * ... - * + * * -- write * comm_write_mbuf(fd, buf, handler, data); * @@ -282,8 +282,7 @@ MemBuf::Printf(const char *fmt,...) #else void MemBuf::Printf(va_alist) -va_dcl -{ +va_dcl { va_list args; mb_size_t sz = 0; va_start(args); diff --git a/src/MemBuf.cci b/src/MemBuf.cci index 30a38f6514..d0874dab71 100644 --- a/src/MemBuf.cci +++ b/src/MemBuf.cci @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/MemBuf.h b/src/MemBuf.h index 10ab7e0dba..4da921b3a8 100644 --- a/src/MemBuf.h +++ b/src/MemBuf.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -150,7 +150,7 @@ public: /** \deprecated use space*() and content*() methods to access safely instead. * public, read-only. - * + * \todo XXX: hide these members completely and remove 0-termination * so that consume() does not need to memmove all the time */ @@ -169,7 +169,7 @@ public: \deprecated Use interface function instead \todo XXX: make these private after converting memBuf*() functions to methods */ - mb_size_t capacity; + mb_size_t capacity; unsigned stolen:1; /* the buffer has been stolen for use by someone else */ diff --git a/src/MemObject.cc b/src/MemObject.cc index 2966c1a10a..7c913a5651 100644 --- a/src/MemObject.cc +++ b/src/MemObject.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -144,7 +144,7 @@ MemObject::write ( StoreIOBuffer writeBuffer, STMCB *callback, void *callbackDat writeBuffer.offset += (_reply ? _reply->hdr_sz : 0); /* We don't separate out mime headers yet, so ensure that the first - * write is at offset 0 - where they start + * write is at offset 0 - where they start */ assert (data_hdr.endOffset() || writeBuffer.offset == 0); @@ -184,12 +184,10 @@ MemObject::replaceHttpReply(HttpReply *newrep) _reply = HTTPMSGLOCK(newrep); } -struct LowestMemReader : public unary_function -{ - LowestMemReader(int64_t seed):current(seed){} +struct LowestMemReader : public unary_function { + LowestMemReader(int64_t seed):current(seed) {} - void operator() (store_client const &x) - { + void operator() (store_client const &x) { if (x.memReaderHasLowerOffset(current)) current = x.copyInto.offset; } @@ -197,12 +195,10 @@ struct LowestMemReader : public unary_function int64_t current; }; -struct StoreClientStats : public unary_function -{ - StoreClientStats(MemBuf *anEntry):where(anEntry),index(0){} +struct StoreClientStats : public unary_function { + StoreClientStats(MemBuf *anEntry):where(anEntry),index(0) {} - void operator()(store_client const &x) - { + void operator()(store_client const &x) { x.dumpStats(where, index++); } @@ -296,7 +292,7 @@ MemObject::objectBytesOnDisk() const /* * NOTE: storeOffset() represents the disk file size, * not the amount of object data on disk. - * + * * If we don't have at least 'swap_hdr_sz' bytes * then none of the object data is on disk. * diff --git a/src/MemObject.h b/src/MemObject.h index 48b48fd5c5..efaec4ed97 100644 --- a/src/MemObject.h +++ b/src/MemObject.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -122,8 +122,7 @@ public: IRCB *ping_reply_callback; void *ircb_data; - struct - { + struct { STABH *callback; void *data; } abort; diff --git a/src/NullDelayId.cc b/src/NullDelayId.cc index e333bf3e54..18c5883de4 100644 --- a/src/NullDelayId.cc +++ b/src/NullDelayId.cc @@ -23,12 +23,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/NullDelayId.h b/src/NullDelayId.h index c32114bb72..cd4dc74996 100644 --- a/src/NullDelayId.h +++ b/src/NullDelayId.h @@ -23,12 +23,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/Packer.cc b/src/Packer.cc index 7280cd3a30..7d7a07ed4c 100644 --- a/src/Packer.cc +++ b/src/Packer.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -36,33 +36,33 @@ /* * Rationale: * ---------- - * + * * OK, we have to major interfaces comm.c and store.c. - * + * * Store.c has a nice storeAppend[Printf] capability which makes "storing" - * things easy and painless. - * + * things easy and painless. + * * Comm.c lacks commAppend[Printf] because comm does not handle its own * buffers (no mem_obj equivalent for comm.c). - * + * * Thus, if one wants to be able to store _and_ comm_write an object, s/he * has to implement two almost identical functions. - * + * * Packer * ------ - * + * * Packer provides for a more uniform interface to store and comm modules. * Packer has its own append and printf routines that "know" where to send * incoming data. In case of store interface, Packer sends data to * storeAppend. Otherwise, Packer uses a MemBuf that can be flushed later to * comm_write. - * + * * Thus, one can write just one function that will either "pack" things for * comm_write or "append" things to store, depending on actual packer * supplied. - * + * * It is amazing how much work a tiny object can save. :) - * + * */ @@ -176,8 +176,7 @@ packerPrintf(Packer * p, const char *fmt,...) #else void packerPrintf(va_alist) -va_dcl -{ +va_dcl { va_list args; Packer *p = NULL; const char *fmt = NULL; diff --git a/src/Packer.h b/src/Packer.h index 068f9c6dc5..ed0990cc12 100644 --- a/src/Packer.h +++ b/src/Packer.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/Parsing.cc b/src/Parsing.cc index 8915755d8b..c7b58a8d36 100644 --- a/src/Parsing.cc +++ b/src/Parsing.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/Parsing.h b/src/Parsing.h index 76a77054c0..d97d517c52 100644 --- a/src/Parsing.h +++ b/src/Parsing.h @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/PeerDigest.h b/src/PeerDigest.h index edc6d330e4..fdfa8894d8 100644 --- a/src/PeerDigest.h +++ b/src/PeerDigest.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -40,8 +40,7 @@ #include "cbdata.h" -struct _Version -{ +struct _Version { short int current; /* current version */ short int required; /* minimal version that can safely handle current version */ }; @@ -50,7 +49,7 @@ struct _Version class StoreDigestCBlock { - public: +public: Version ver; int capacity; int count; @@ -62,8 +61,7 @@ class StoreDigestCBlock int reserved[32 - 6]; }; -struct _DigestFetchState -{ +struct _DigestFetchState { PeerDigest *pd; StoreEntry *entry; StoreEntry *old_entry; @@ -76,8 +74,7 @@ struct _DigestFetchState time_t resp_time; time_t expires; - struct - { + struct { int msg; int bytes; } @@ -100,15 +97,13 @@ public: String host; /**< copy of peer->host */ const char *req_result; /**< text status of the last request */ - struct - { + struct { unsigned int needed:1; /**< there were requests for this digest */ unsigned int usable:1; /**< can be used for lookups */ unsigned int requested:1; /**< in process of receiving [fresh] digest */ } flags; - struct - { + struct { /* all times are absolute unless augmented with _delay */ time_t initialized; /* creation */ time_t needed; /* first lookup/use by a peer */ @@ -120,13 +115,11 @@ public: time_t disabled; /* disabled for good */ } times; - struct - { + struct { cd_guess_stats guess; int used_count; - struct - { + struct { int msgs; kb_t kbytes; } sent, recv; diff --git a/src/PeerSelectState.h b/src/PeerSelectState.h index 4a5bef1bb5..8939e40e1d 100644 --- a/src/PeerSelectState.h +++ b/src/PeerSelectState.h @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/PingData.h b/src/PingData.h index f584f92ace..d30d29fafa 100644 --- a/src/PingData.h +++ b/src/PingData.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/ProfStats.cc b/src/ProfStats.cc index 514b93089f..bab20105fb 100644 --- a/src/ProfStats.cc +++ b/src/ProfStats.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -269,10 +269,10 @@ static void xprofRegisterWithCacheManager(void) { CacheManager::GetInstance()-> - registerAction("cpu_profile", "CPU Profiling Stats", xprof_summary, 0, 1); + registerAction("cpu_profile", "CPU Profiling Stats", xprof_summary, 0, 1); } -// FIXME: +// FIXME: // this gets colled once per event. This doesn't seem to make much sense, // does it? static hrtime_t now; diff --git a/src/ProtoPort.cc b/src/ProtoPort.cc index 8ba38aaec1..c186de534c 100644 --- a/src/ProtoPort.cc +++ b/src/ProtoPort.cc @@ -9,7 +9,8 @@ http_port_list::http_port_list(const char *aProtocol) #if USE_SSL - : http(*this) + : + http(*this) #endif { protocol = xstrdup(aProtocol); diff --git a/src/ProtoPort.h b/src/ProtoPort.h index 72f64bbce3..e1d14093eb 100644 --- a/src/ProtoPort.h +++ b/src/ProtoPort.h @@ -7,8 +7,7 @@ //#include "typedefs.h" #include "cbdata.h" -struct http_port_list -{ +struct http_port_list { http_port_list(const char *aProtocol); ~http_port_list(); @@ -30,15 +29,15 @@ struct http_port_list int disable_pmtu_discovery; struct { - unsigned int enabled; - unsigned int idle; - unsigned int interval; - unsigned int timeout; + unsigned int enabled; + unsigned int idle; + unsigned int interval; + unsigned int timeout; } tcp_keepalive; #if USE_SSL - // XXX: temporary hack to ease move of SSL options to http_port - http_port_list &http; + // XXX: temporary hack to ease move of SSL options to http_port + http_port_list &http; char *cert; char *key; @@ -61,8 +60,7 @@ struct http_port_list #if USE_SSL -struct https_port_list: public http_port_list -{ +struct https_port_list: public http_port_list { https_port_list(); }; diff --git a/src/RemovalPolicy.cc b/src/RemovalPolicy.cc index 77e37511d6..5478f8bce7 100644 --- a/src/RemovalPolicy.cc +++ b/src/RemovalPolicy.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/RemovalPolicy.h b/src/RemovalPolicy.h index 7424d95017..9037dd26a6 100644 --- a/src/RemovalPolicy.h +++ b/src/RemovalPolicy.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -62,7 +62,7 @@ public: class RemovalPolicy { - public: +public: const char *_type; void *_data; void (*Free) (RemovalPolicy * policy); @@ -73,30 +73,30 @@ class RemovalPolicy RemovalPolicyWalker *(*WalkInit) (RemovalPolicy * policy); RemovalPurgeWalker *(*PurgeInit) (RemovalPolicy * policy, int max_scan); void (*Stats) (RemovalPolicy * policy, StoreEntry * entry); - private: +private: CBDATA_CLASS2(RemovalPolicy); }; class RemovalPolicyWalker { - public: +public: RemovalPolicy *_policy; void *_data; const StoreEntry *(*Next) (RemovalPolicyWalker * walker); void (*Done) (RemovalPolicyWalker * walker); - private: +private: CBDATA_CLASS2(RemovalPolicyWalker); }; class RemovalPurgeWalker { - public: +public: RemovalPolicy *_policy; void *_data; int scanned, max_scan, locked; StoreEntry *(*Next) (RemovalPurgeWalker * walker); void (*Done) (RemovalPurgeWalker * walker); - private: +private: CBDATA_CLASS2(RemovalPurgeWalker); }; diff --git a/src/SquidNew.cc b/src/SquidNew.cc index db55bd4572..1539edefb2 100644 --- a/src/SquidNew.cc +++ b/src/SquidNew.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/SquidString.h b/src/SquidString.h index fd44707408..6ddeaae18d 100644 --- a/src/SquidString.h +++ b/src/SquidString.h @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -54,12 +54,12 @@ public: static StringRegistry &Instance(); void add - (String const *); + (String const *); StringRegistry(); void remove - (String const *); + (String const *); private: static OBJH Stat; diff --git a/src/SquidTime.h b/src/SquidTime.h index 0b88c955d1..21dbe11c4b 100644 --- a/src/SquidTime.h +++ b/src/SquidTime.h @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/StatHist.cc b/src/StatHist.cc index 3e82bff123..e6bf176a21 100644 --- a/src/StatHist.cc +++ b/src/StatHist.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -35,11 +35,11 @@ /* * Important restrictions on val_in and val_out functions: - * + * * - val_in: ascending, defined on [0, oo), val_in(0) == 0; * - val_out: x == val_out(val_in(x)) where val_in(x) is defined * - * In practice, the requirements are less strict, + * In practice, the requirements are less strict, * but then it gets hard to define them without math notation. * val_in is applied after offseting the value but before scaling * See log and linear based histograms for examples diff --git a/src/Store.cci b/src/Store.cci index 714a73679f..0541982e36 100644 --- a/src/Store.cci +++ b/src/Store.cci @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/Store.h b/src/Store.h index da432a0dd9..485fa3d5ac 100644 --- a/src/Store.h +++ b/src/Store.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -74,7 +74,7 @@ public: virtual const char *getMD5Text() const; StoreEntry(); StoreEntry(const char *url, const char *log_url); - virtual ~StoreEntry(){} + virtual ~StoreEntry() {} virtual HttpReply const *getReply() const; virtual void write (StoreIOBuffer); @@ -140,18 +140,24 @@ public: u_short flags; /* END OF ON-DISK STORE_META_STD */ - sfileno swap_filen:25; +sfileno swap_filen: + 25; - sdirno swap_dirn:7; +sdirno swap_dirn: + 7; u_short lock_count; /* Assume < 65536! */ - mem_status_t mem_status:3; +mem_status_t mem_status: + 3; - ping_status_t ping_status:3; +ping_status_t ping_status: + 3; - store_status_t store_status:3; +store_status_t store_status: + 3; - swap_status_t swap_status:3; +swap_status_t swap_status: + 3; public: static size_t inUseCount(); @@ -159,8 +165,7 @@ public: static void getPublicByRequest(StoreClient * aClient, HttpRequest * request); static void getPublic(StoreClient * aClient, const char *uri, const HttpRequestMethod& method); - virtual bool isNull() - { + virtual bool isNull() { return false; }; @@ -198,24 +203,23 @@ class NullStoreEntry:public StoreEntry public: static NullStoreEntry *getInstance(); - bool isNull() - { + bool isNull() { return true; } const char *getMD5Text() const; _SQUID_INLINE_ HttpReply const *getReply() const; - void write (StoreIOBuffer){} + void write (StoreIOBuffer) {} bool isEmpty () const {return true;} virtual size_t bytesWanted(Range const aRange) const { assert (aRange.size());return aRange.end - 1;} void operator delete(void *address); - void complete(){} + void complete() {} private: - store_client_t storeClientType() const{return STORE_MEM_CLIENT;} + store_client_t storeClientType() const {return STORE_MEM_CLIENT;} char const *getSerialisedMetaData(); bool swapoutPossible() {return false;} @@ -261,11 +265,11 @@ public: /** Retrieve a store entry from the store */ virtual StoreEntry * get - (const cache_key *) = 0; + (const cache_key *) = 0; /** \todo imeplement the async version */ virtual void get - (String const key , STOREGETCLIENT callback, void *cbdata) = 0; + (String const key , STOREGETCLIENT callback, void *cbdata) = 0; /* prepare the store for use. The store need not be usable immediately, * it should respond to readable() and writable() with true as soon diff --git a/src/StoreClient.h b/src/StoreClient.h index c93597e35b..8ff6a3695d 100644 --- a/src/StoreClient.h +++ b/src/StoreClient.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -82,8 +82,7 @@ public: StoreEntry *entry; /* ptr to the parent StoreEntry, argh! */ StoreIOState::Pointer swapin_sio; - struct - { + struct { unsigned int disk_io_pending:1; unsigned int store_copying:1; unsigned int copy_event_pending:1; @@ -114,9 +113,8 @@ private: public: - struct Callback - { - Callback ():callback_handler(NULL), callback_data(NULL){} + struct Callback { + Callback ():callback_handler(NULL), callback_data(NULL) {} Callback (STCB *, void *); bool pending() const; diff --git a/src/StoreEntryStream.h b/src/StoreEntryStream.h index 9ffd25dce0..009c7a1e46 100644 --- a/src/StoreEntryStream.h +++ b/src/StoreEntryStream.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -48,15 +48,13 @@ class StoreEntryStreamBuf : public std::streambuf { public: - StoreEntryStreamBuf(StoreEntry *anEntry) : theEntry(anEntry) - { + StoreEntryStreamBuf(StoreEntry *anEntry) : theEntry(anEntry) { theEntry->lock(); theEntry->buffer(); } - ~StoreEntryStreamBuf() - { + ~StoreEntryStreamBuf() { theEntry->unlock(); } @@ -64,8 +62,7 @@ protected: /* flush the current buffer and the character that is overflowing * to the store entry. */ - virtual int_type overflow(int_type aChar = traits_type::eof()) - { + virtual int_type overflow(int_type aChar = traits_type::eof()) { std::streamsize pending(pptr() - pbase()); if (pending && sync ()) @@ -83,8 +80,7 @@ protected: } /* push the buffer to the store */ - virtual int sync() - { + virtual int sync() { std::streamsize pending(pptr() - pbase()); if (pending) @@ -98,8 +94,7 @@ protected: /* write multiple characters to the store entry * - this is an optimisation method. */ - virtual std::streamsize xsputn(const char * chars, std::streamsize number) - { + virtual std::streamsize xsputn(const char * chars, std::streamsize number) { if (number) theEntry->append(chars, number); diff --git a/src/StoreFileSystem.cc b/src/StoreFileSystem.cc index c8a65158d1..2bf2ce5de5 100644 --- a/src/StoreFileSystem.cc +++ b/src/StoreFileSystem.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/StoreFileSystem.h b/src/StoreFileSystem.h index b1e1d3fd1b..07166cfe6e 100644 --- a/src/StoreFileSystem.h +++ b/src/StoreFileSystem.h @@ -17,12 +17,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -40,7 +40,7 @@ /** \defgroup FileSystems Storage Filesystems - * + * \section Introduction Introduction \par * Traditionally, Squid has always used the Unix filesystem (\link UFS UFS\endlink) @@ -50,7 +50,7 @@ * Our work indicates that the poor performance is mostly * due to the synchronous nature of open() and unlink() * system calls, and perhaps thrashing of inode/buffer caches. - * + * \par * We want to try out our own, customized filesystems with Squid. * In order to do that, we need a well-defined interface @@ -58,7 +58,7 @@ * devices. We also require tighter control of the replacement * policy by each storage module, rather than a single global * replacement policy. - * + * \section BuildStructure Build structure \par * The storage types live in \em src/fs/. Each subdirectory corresponds @@ -68,34 +68,34 @@ * \todo DOCS: add template addition to configure.in for storage module addition. \todo DOCS: add template Makefile.am for storage module addition. - * + * \par * configure will take a list of storage types through the * --enable-store-io parameter. This parameter takes a list of * space seperated storage types. For example, * --enable-store-io="ufs coss" . - * + * \par * Each storage type must create an archive file * in \em src/fs/foo/.a . This file is automatically linked into * squid at compile time. - * + * \par * Each storage filesystem must inherit from StoreFileSystem and provide * all virtual function hooks for squid to operate with. - * + * \section OperationOfStorageModules Operation of a Storage Module \par * Squid understands the concept of multiple diverse storage directories. * Each storage directory provides a caching object store, with object * storage, retrieval, indexing and replacement. - * + * \par * Each open object has associated with it a storeIOState object. The * storeIOState object is used to record the state of the current * object. Each storeIOState can have a storage module specific data * structure containing information private to the storage module. - * + * \par * Each SwapDir has the concept of a maximum object size. This is used * as a basic hint to the storage layer in first choosing a suitable @@ -124,7 +124,7 @@ public: typedef Vector::const_iterator const_iterator; StoreFileSystem() : initialised(false) {} - virtual ~StoreFileSystem(){} + virtual ~StoreFileSystem() {} virtual char const *type () const = 0; virtual SwapDir *createSwapDir() = 0; diff --git a/src/StoreHashIndex.h b/src/StoreHashIndex.h index 8a68148138..e764d11bde 100644 --- a/src/StoreHashIndex.h +++ b/src/StoreHashIndex.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -54,10 +54,10 @@ public: virtual void create(); virtual StoreEntry * get - (const cache_key *); + (const cache_key *); virtual void get - (String const, STOREGETCLIENT, void * cbdata); + (String const, STOREGETCLIENT, void * cbdata); virtual void init(); @@ -85,7 +85,7 @@ private: }; class StoreHashIndexEntry : public StoreEntry -{}; + {}; class StoreSearchHashIndex : public StoreSearch { @@ -96,7 +96,7 @@ public: virtual ~StoreSearchHashIndex(); /* Iterator API - garh, wrong place */ /* callback the client when a new StoreEntry is available - * or an error occurs + * or an error occurs */ virtual void next(void (callback)(void *cbdata), void *cbdata); /* return true if a new StoreEntry is immediately available */ diff --git a/src/StoreIOBuffer.h b/src/StoreIOBuffer.h index ab3ece6e39..4ef3c65923 100644 --- a/src/StoreIOBuffer.h +++ b/src/StoreIOBuffer.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -46,14 +46,12 @@ public: StoreIOBuffer():length(0), offset (0), data (NULL) {flags.error = 0;} StoreIOBuffer(size_t aLength, int64_t anOffset, char *someData) : - offset (anOffset), data (someData) - { + offset (anOffset), data (someData) { /* maintain own state: detect size errors now */ if (aLength <0) { flags.error = 1; length = 0; - } - else { + } else { flags.error = 0; length = aLength; } @@ -64,24 +62,20 @@ public: StoreIOBuffer(MemBuf *aMemBuf, int64_t anOffset) : length(aMemBuf->contentSize()), offset (anOffset), - data(aMemBuf->content()) - { + data(aMemBuf->content()) { flags.error = 0; } - Range range() const - { + Range range() const { return Range(offset, offset + length); } - void dump() const - { - if(fwrite(data, length, 1, stderr)) {} - if(fwrite("\n", 1, 1, stderr)) {} + void dump() const { + if (fwrite(data, length, 1, stderr)) {} + if (fwrite("\n", 1, 1, stderr)) {} } - struct - { + struct { unsigned error:1; } flags; size_t length; diff --git a/src/StoreIOState.cc b/src/StoreIOState.cc index 5c2cd14bcf..e8da90f476 100644 --- a/src/StoreIOState.cc +++ b/src/StoreIOState.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -44,7 +44,7 @@ StoreIOState::operator new (size_t amount) } void -StoreIOState::operator delete (void *address){assert (0);} +StoreIOState::operator delete (void *address) {assert (0);} StoreIOState::StoreIOState() { diff --git a/src/StoreIOState.h b/src/StoreIOState.h index 022be39698..ad82633fc5 100644 --- a/src/StoreIOState.h +++ b/src/StoreIOState.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -95,14 +95,12 @@ public: STIOCB *callback; void *callback_data; - struct - { + struct { STRCB *callback; void *callback_data; } read; - struct - { + struct { unsigned int closing:1; /* debugging aid */ } flags; }; diff --git a/src/StoreMeta.cc b/src/StoreMeta.cc index ae656d2cad..cd6ba81228 100644 --- a/src/StoreMeta.cc +++ b/src/StoreMeta.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -55,8 +55,8 @@ StoreMeta::validType(char type) /* Not yet implemented */ if (type >= STORE_META_END || - type == STORE_META_STOREURL || - type == STORE_META_VARY_ID) { + type == STORE_META_STOREURL || + type == STORE_META_VARY_ID) { debugs(20, 3, "storeSwapMetaUnpack: Not yet implemented (" << type << ") in disk metadata"); return false; } @@ -77,8 +77,7 @@ class IntRange { public: - IntRange (int minimum, int maximum) : _min (minimum), _max (maximum) - { + IntRange (int minimum, int maximum) : _min (minimum), _max (maximum) { if (_min > _max) { int temp = _min; _min = _max; @@ -86,8 +85,7 @@ public: } } - bool includes (int anInt) const - { + bool includes (int anInt) const { if (anInt < _min || anInt > _max) return false; @@ -140,8 +138,8 @@ StoreMeta::Factory (char type, size_t len, void const *value) result = new StoreMetaSTDLFS; break; - case STORE_META_OBJSIZE: - result = new StoreMetaObjSize; + case STORE_META_OBJSIZE: + result = new StoreMetaObjSize; break; case STORE_META_VARY_HEADERS: @@ -204,7 +202,7 @@ StoreMeta::checkConsistency(StoreEntry *e) const break; case STORE_META_OBJSIZE: - break; + break; default: debugs(20, 1, "WARNING: got unused STORE_META type " << getType()); diff --git a/src/StoreMeta.h b/src/StoreMeta.h index 81f47d7b92..f3d1076fb8 100644 --- a/src/StoreMeta.h +++ b/src/StoreMeta.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -152,7 +152,7 @@ public: virtual char getType() const = 0; virtual bool validLength(int) const; virtual bool checkConsistency(StoreEntry *) const; - virtual ~StoreMeta(){} + virtual ~StoreMeta() {} int length; void *value; diff --git a/src/StoreMetaMD5.cc b/src/StoreMetaMD5.cc index 44b45ae1db..5d8df353b3 100644 --- a/src/StoreMetaMD5.cc +++ b/src/StoreMetaMD5.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/StoreMetaMD5.h b/src/StoreMetaMD5.h index 3d494469d1..e2abed3469 100644 --- a/src/StoreMetaMD5.h +++ b/src/StoreMetaMD5.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/StoreMetaObjSize.h b/src/StoreMetaObjSize.h index a996240526..678c2aca35 100644 --- a/src/StoreMetaObjSize.h +++ b/src/StoreMetaObjSize.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/StoreMetaSTD.cc b/src/StoreMetaSTD.cc index fa541c705c..a4456b4a7b 100644 --- a/src/StoreMetaSTD.cc +++ b/src/StoreMetaSTD.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/StoreMetaSTD.h b/src/StoreMetaSTD.h index e64c19b8cd..5dc19f361c 100644 --- a/src/StoreMetaSTD.h +++ b/src/StoreMetaSTD.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/StoreMetaSTDLFS.cc b/src/StoreMetaSTDLFS.cc index 1e097870fd..1cdde635d9 100644 --- a/src/StoreMetaSTDLFS.cc +++ b/src/StoreMetaSTDLFS.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/StoreMetaSTDLFS.h b/src/StoreMetaSTDLFS.h index b4b845e194..5b7784c071 100644 --- a/src/StoreMetaSTDLFS.h +++ b/src/StoreMetaSTDLFS.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/StoreMetaURL.cc b/src/StoreMetaURL.cc index d5af3b2790..376b22b95e 100644 --- a/src/StoreMetaURL.cc +++ b/src/StoreMetaURL.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/StoreMetaURL.h b/src/StoreMetaURL.h index 7259d723d1..b38970378f 100644 --- a/src/StoreMetaURL.h +++ b/src/StoreMetaURL.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/StoreMetaUnpacker.cc b/src/StoreMetaUnpacker.cc index 813d97a516..681a590f80 100644 --- a/src/StoreMetaUnpacker.cc +++ b/src/StoreMetaUnpacker.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -99,7 +99,7 @@ StoreMetaUnpacker::doOneEntry() StoreMeta *newNode = StoreMeta::Factory(type, length, &buf[position]); if (newNode) - tail = StoreMeta::Add (tail, newNode); + tail = StoreMeta::Add (tail, newNode); position += length; diff --git a/src/StoreMetaUnpacker.h b/src/StoreMetaUnpacker.h index 9e3f63fbfa..12d5e746eb 100644 --- a/src/StoreMetaUnpacker.h +++ b/src/StoreMetaUnpacker.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/StoreMetaVary.cc b/src/StoreMetaVary.cc index 9cf20edd4c..a61265e9e9 100644 --- a/src/StoreMetaVary.cc +++ b/src/StoreMetaVary.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/StoreMetaVary.h b/src/StoreMetaVary.h index e87bd508f0..4fd5b1e9dc 100644 --- a/src/StoreMetaVary.h +++ b/src/StoreMetaVary.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/StoreSearch.h b/src/StoreSearch.h index ea9cfc2221..b52d01a993 100644 --- a/src/StoreSearch.h +++ b/src/StoreSearch.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -50,7 +50,7 @@ public: void asList(void (*) (CbDataListswap_file_sz - MemObject->swap_hdr_sz; \endcode \note The swap file content includes the HTTP reply headers and the HTTP reply body (if any). - * + * \par * When reading a swap file, there is a similar process to extract * the swap meta data. First, storeSwapMetaUnpack() converts a @@ -63,7 +63,7 @@ /* * Do we need to have the dirn in here? I don't think so, since we already - * know the dirn .. + * know the dirn .. */ /** \ingroup FielFormatSwapStateAPI @@ -167,10 +167,10 @@ MEMPROXY_CLASS_INLINE(StoreSwapLogData) /**DOCS_NOSEMI*/ class StoreSwapLogHeader { public: - StoreSwapLogHeader(); - char op; - int version; - int record_size; + StoreSwapLogHeader(); + char op; + int version; + int record_size; }; diff --git a/src/String.cc b/src/String.cc index 7271148201..5ea9606568 100644 --- a/src/String.cc +++ b/src/String.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -36,7 +36,7 @@ #include "squid.h" #include "Store.h" -// low-level buffer allocation, +// low-level buffer allocation, // does not free old buffer and does not adjust or look at len_ void String::allocBuffer(size_t sz) @@ -257,14 +257,14 @@ StringRegistry::StringRegistry() { #if DEBUGSTRINGS CacheManager::GetInstance()->registerAction("strings", - "Strings in use in squid", Stat, 0, 1); + "Strings in use in squid", Stat, 0, 1); #endif } void StringRegistry::add - (String const *entry) +(String const *entry) { entries.insert(entry, ptrcmp); } @@ -272,7 +272,7 @@ StringRegistry::add void StringRegistry::remove - (String const *entry) +(String const *entry) { entries.remove(entry, ptrcmp); } diff --git a/src/String.cci b/src/String.cci index 1f82fd4a53..2b2763cb7d 100644 --- a/src/String.cci +++ b/src/String.cci @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -149,7 +149,7 @@ String::caseCmp(char const *aString, size_t count) const void String::set(char const *loc, char const ch) { - if(loc < buf_ || loc > (buf_ + size_) ) return; + if (loc < buf_ || loc > (buf_ + size_) ) return; buf_[loc-buf_] = ch; } @@ -157,12 +157,12 @@ String::set(char const *loc, char const ch) void String::cut(size_t newLength) { - if(newLength < 0 || newLength > len_) return; + if (newLength < 0 || newLength > len_) return; len_ = newLength; // buf_ may be NULL on zero-length strings. - if(len_ == 0 && buf_ == NULL) return; + if (len_ == 0 && buf_ == NULL) return; buf_[newLength] = '\0'; } @@ -170,7 +170,7 @@ String::cut(size_t newLength) void String::cutPointer(char const *loc) { - if(loc < buf_ || loc > (buf_ + size_) ) return; + if (loc < buf_ || loc > (buf_ + size_) ) return; len_ = loc-buf_; buf_[len_] = '\0'; diff --git a/src/SwapDir.cc b/src/SwapDir.cc index 7024bc21a5..91bdcec546 100644 --- a/src/SwapDir.cc +++ b/src/SwapDir.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -44,10 +44,10 @@ SwapDir::~SwapDir() } void -SwapDir::create(){} +SwapDir::create() {} void -SwapDir::dump(StoreEntry &)const{} +SwapDir::dump(StoreEntry &)const {} bool SwapDir::doubleCheck(StoreEntry &) @@ -56,7 +56,7 @@ SwapDir::doubleCheck(StoreEntry &) } void -SwapDir::unlink(StoreEntry &){} +SwapDir::unlink(StoreEntry &) {} void SwapDir::stat(StoreEntry &output) const @@ -79,7 +79,7 @@ void SwapDir::statfs(StoreEntry &)const {} void -SwapDir::maintain(){} +SwapDir::maintain() {} size_t SwapDir::minSize() const @@ -89,10 +89,10 @@ SwapDir::minSize() const } void -SwapDir::reference(StoreEntry &){} +SwapDir::reference(StoreEntry &) {} void -SwapDir::dereference(StoreEntry &){} +SwapDir::dereference(StoreEntry &) {} int SwapDir::callback() @@ -101,7 +101,7 @@ SwapDir::callback() } void -SwapDir::sync(){} +SwapDir::sync() {} /* Move to StoreEntry ? */ bool @@ -129,10 +129,10 @@ SwapDir::canLog(StoreEntry const &e)const } void -SwapDir::openLog(){} +SwapDir::openLog() {} void -SwapDir::closeLog(){} +SwapDir::closeLog() {} int SwapDir::writeCleanStart() @@ -141,10 +141,10 @@ SwapDir::writeCleanStart() } void -SwapDir::writeCleanDone(){} +SwapDir::writeCleanDone() {} void -SwapDir::logEntry(const StoreEntry & e, int op) const{} +SwapDir::logEntry(const StoreEntry & e, int op) const {} char const * SwapDir::type() const @@ -153,7 +153,7 @@ SwapDir::type() const } /* NOT performance critical. Really. Don't bother optimising for speed - * - RBC 20030718 + * - RBC 20030718 */ ConfigOption * SwapDir::getOptionTree() const @@ -263,12 +263,12 @@ SwapDir::optionMaxSizeDump(StoreEntry * e) const } /* Swapdirs do not have an index of their own - thus they ask their parent.. - * but the parent child relationship isn't implemented yet + * but the parent child relationship isn't implemented yet */ StoreEntry * SwapDir::get - (const cache_key *key) +(const cache_key *key) { return Store::Root().get(key); } @@ -276,7 +276,7 @@ SwapDir::get void SwapDir::get - (String const key, STOREGETCLIENT callback, void *cbdata) +(String const key, STOREGETCLIENT callback, void *cbdata) { fatal("not implemented"); } diff --git a/src/SwapDir.h b/src/SwapDir.h index 632f016142..9aa3c2ed86 100644 --- a/src/SwapDir.h +++ b/src/SwapDir.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -55,10 +55,10 @@ public: virtual void create(); virtual StoreEntry * get - (const cache_key *); + (const cache_key *); virtual void get - (String const, STOREGETCLIENT, void * cbdata); + (String const, STOREGETCLIENT, void * cbdata); virtual void init(); @@ -115,8 +115,7 @@ class SwapDir : public Store { public: - SwapDir(char const *aType) : theType (aType), cur_size (0), max_size(0), max_objsize (-1), cleanLog(NULL) - { + SwapDir(char const *aType) : theType (aType), cur_size (0), max_size(0), max_objsize (-1), cleanLog(NULL) { fs.blksize = 1024; path = NULL; } @@ -129,12 +128,12 @@ public: virtual void diskFull(); virtual StoreEntry * get - (const cache_key *); + (const cache_key *); virtual void get - (String const, STOREGETCLIENT, void * cbdata); + (String const, STOREGETCLIENT, void * cbdata); -virtual size_t maxSize() const { return max_size;} + virtual size_t maxSize() const { return max_size;} virtual size_t minSize() const; virtual void stat (StoreEntry &anEntry) const; @@ -167,9 +166,8 @@ public: int removals; int scanned; - struct Flags - { - Flags() : selected(0), read_only(0){} + struct Flags { + Flags() : selected(0), read_only(0) {} unsigned int selected:1; unsigned int read_only:1; } flags; @@ -198,7 +196,7 @@ public: { public: - virtual ~CleanLog(){} + virtual ~CleanLog() {} virtual const StoreEntry *nextEntry() = 0; virtual void write(StoreEntry const &) = 0; @@ -209,8 +207,7 @@ public: virtual void writeCleanDone(); virtual void parse(int index, char *path) = 0; - struct - { + struct { int blksize; } fs; }; diff --git a/src/URL.h b/src/URL.h index a3356dc52a..bacd0ac306 100644 --- a/src/URL.h +++ b/src/URL.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -56,21 +56,21 @@ private: /** \par * The scheme of this URL. This has the 'type code' smell about it. - * In future we may want to make the methods that dispatch based on - * the scheme virtual and have a class per protocol. + * In future we may want to make the methods that dispatch based on + * the scheme virtual and have a class per protocol. \par * On the other hand, having Protocol as an explicit concept is useful, * see for instance the ACLProtocol acl type. One way to represent this - * is to have one prototype URL with no host etc for each scheme, + * is to have one prototype URL with no host etc for each scheme, * another is to have an explicit scheme class, and then each URL class - * could be a subclass of the scheme. Another way is one instance of + * could be a subclass of the scheme. Another way is one instance of * a URLScheme class instance for each URLScheme we support, and one URL * class for each manner of treating the scheme : a Hierarchical URL, a * non-hierarchical URL etc. \par * Deferring the decision, its a type code for now. RBC 20060507. \par - * In order to make taking any of these routes easy, scheme is private + * In order to make taking any of these routes easy, scheme is private * and immutable, only settable at construction time, */ URLScheme const scheme; diff --git a/src/URLScheme.cc b/src/URLScheme.cc index c4bff4a1bd..add46a2470 100644 --- a/src/URLScheme.cc +++ b/src/URLScheme.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -37,22 +37,21 @@ #include "URLScheme.h" #include "wordlist.h" -const char *ProtocolStr[] = - { - "NONE", - "http", - "ftp", - "gopher", - "wais", - "cache_object", - "icp", +const char *ProtocolStr[] = { + "NONE", + "http", + "ftp", + "gopher", + "wais", + "cache_object", + "icp", #if USE_HTCP - "htcp", + "htcp", #endif - "urn", - "whois", - "internal", - "https", - "TOTAL" - }; + "urn", + "whois", + "internal", + "https", + "TOTAL" +}; diff --git a/src/URLScheme.h b/src/URLScheme.h index d9f4bbed9d..92bebc9afe 100644 --- a/src/URLScheme.h +++ b/src/URLScheme.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/WinSvc.cc b/src/WinSvc.cc index ce18682d6e..b43f1921ce 100644 --- a/src/WinSvc.cc +++ b/src/WinSvc.cc @@ -22,12 +22,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -105,13 +105,13 @@ static SERVICE_DESCRIPTION Squid_ServiceDescription = { Squid_ServiceDescription static SERVICE_FAILURE_ACTIONS Squid_ServiceFailureActions = { INFINITE, NULL, NULL, 1, Squid_SCAction }; static char REGKEY[256]=SOFTWARE"\\"VENDOR"\\"SOFTWARENAME"\\"WIN32_VERSION"\\"; static char *keys[] = { - SOFTWAREString, /* key[0] */ - VENDORString, /* key[1] */ - SOFTWARENAMEString, /* key[2] */ - WIN32_VERSIONString, /* key[3] */ - NULL, /* key[4] */ - NULL /* key[5] */ - }; + SOFTWAREString, /* key[0] */ + VENDORString, /* key[1] */ + SOFTWARENAMEString, /* key[2] */ + WIN32_VERSIONString, /* key[3] */ + NULL, /* key[4] */ + NULL /* key[5] */ +}; #endif /* ====================================================================== */ @@ -318,58 +318,58 @@ GetOSVersion() osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); if (!(bOsVersionInfoEx = GetVersionEx((OSVERSIONINFO *) & osvi))) { - osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); - if (!GetVersionEx((OSVERSIONINFO *) & osvi)) - goto GetVerError; + osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); + if (!GetVersionEx((OSVERSIONINFO *) & osvi)) + goto GetVerError; } switch (osvi.dwPlatformId) { case VER_PLATFORM_WIN32_NT: - if (osvi.dwMajorVersion <= 4) { - WIN32_OS_string = xstrdup("Windows NT"); - return _WIN_OS_WINNT; - } - if ((osvi.dwMajorVersion == 5) && (osvi.dwMinorVersion == 0)) { - WIN32_OS_string = xstrdup("Windows 2000"); - return _WIN_OS_WIN2K; - } - if ((osvi.dwMajorVersion == 5) && (osvi.dwMinorVersion == 1)) { - WIN32_OS_string = xstrdup("Windows XP"); - return _WIN_OS_WINXP; - } - if ((osvi.dwMajorVersion == 5) && (osvi.dwMinorVersion == 2)) { - WIN32_OS_string = xstrdup("Windows Server 2003"); - return _WIN_OS_WINNET; - } - if ((osvi.dwMajorVersion == 6) && (osvi.dwMinorVersion == 0)) { - if (osvi.wProductType == VER_NT_WORKSTATION) - WIN32_OS_string = xstrdup("Windows Vista"); - else - WIN32_OS_string = xstrdup("Windows Server 2008"); - return _WIN_OS_WINLON; - } - break; + if (osvi.dwMajorVersion <= 4) { + WIN32_OS_string = xstrdup("Windows NT"); + return _WIN_OS_WINNT; + } + if ((osvi.dwMajorVersion == 5) && (osvi.dwMinorVersion == 0)) { + WIN32_OS_string = xstrdup("Windows 2000"); + return _WIN_OS_WIN2K; + } + if ((osvi.dwMajorVersion == 5) && (osvi.dwMinorVersion == 1)) { + WIN32_OS_string = xstrdup("Windows XP"); + return _WIN_OS_WINXP; + } + if ((osvi.dwMajorVersion == 5) && (osvi.dwMinorVersion == 2)) { + WIN32_OS_string = xstrdup("Windows Server 2003"); + return _WIN_OS_WINNET; + } + if ((osvi.dwMajorVersion == 6) && (osvi.dwMinorVersion == 0)) { + if (osvi.wProductType == VER_NT_WORKSTATION) + WIN32_OS_string = xstrdup("Windows Vista"); + else + WIN32_OS_string = xstrdup("Windows Server 2008"); + return _WIN_OS_WINLON; + } + break; case VER_PLATFORM_WIN32_WINDOWS: - if ((osvi.dwMajorVersion == 4) && (osvi.dwMinorVersion == 0)) { - WIN32_OS_string = xstrdup("Windows 95"); - return _WIN_OS_WIN95; - } - if ((osvi.dwMajorVersion == 4) && (osvi.dwMinorVersion == 10)) { - WIN32_OS_string = xstrdup("Windows 98"); - return _WIN_OS_WIN98; - } - if ((osvi.dwMajorVersion == 4) && (osvi.dwMinorVersion == 90)) { - WIN32_OS_string = xstrdup("Windows Me"); - return _WIN_OS_WINME; - } - break; + if ((osvi.dwMajorVersion == 4) && (osvi.dwMinorVersion == 0)) { + WIN32_OS_string = xstrdup("Windows 95"); + return _WIN_OS_WIN95; + } + if ((osvi.dwMajorVersion == 4) && (osvi.dwMinorVersion == 10)) { + WIN32_OS_string = xstrdup("Windows 98"); + return _WIN_OS_WIN98; + } + if ((osvi.dwMajorVersion == 4) && (osvi.dwMinorVersion == 90)) { + WIN32_OS_string = xstrdup("Windows Me"); + return _WIN_OS_WINME; + } + break; case VER_PLATFORM_WIN32s: - WIN32_OS_string = xstrdup("Windows 3.1 with WIN32S"); - return _WIN_OS_WIN32S; - break; + WIN32_OS_string = xstrdup("Windows 3.1 with WIN32S"); + return _WIN_OS_WIN32S; + break; default: - break; + break; } - GetVerError: +GetVerError: WIN32_OS_string = xstrdup("Unknown Windows system"); return _WIN_OS_UNKNOWN; } @@ -397,8 +397,8 @@ WIN32_IpAddrChangeMonitorExit() DWORD status = ERROR_SUCCESS; if (NotifyAddrChange_thread != INVALID_HANDLE_VALUE) { - TerminateThread(NotifyAddrChange_thread, status); - CloseHandle(NotifyAddrChange_thread); + TerminateThread(NotifyAddrChange_thread, status); + CloseHandle(NotifyAddrChange_thread); } } #endif @@ -440,17 +440,17 @@ WIN32_IpAddrChangeMonitor(LPVOID lpParam) PFNotifyAddrChange NotifyAddrChange; if ((IPHLPAPIHandle = GetModuleHandle("IPHLPAPI")) == NULL) - IPHLPAPIHandle = LoadLibrary("IPHLPAPI"); + IPHLPAPIHandle = LoadLibrary("IPHLPAPI"); NotifyAddrChange = (PFNotifyAddrChange) GetProcAddress(IPHLPAPIHandle, NOTIFYADDRCHANGE); while (1) { - Result = NotifyAddrChange(NULL, NULL); - if (Result != NO_ERROR) { - debugs(1, 1, "NotifyAddrChange error " << Result); - return 1; - } - debugs(1, 1, "Notification of IP address change received, requesting Squid reconfiguration ..."); - reconfigure(SIGHUP); + Result = NotifyAddrChange(NULL, NULL); + if (Result != NO_ERROR) { + debugs(1, 1, "NotifyAddrChange error " << Result); + return 1; + } + debugs(1, 1, "Notification of IP address change received, requesting Squid reconfiguration ..."); + reconfigure(SIGHUP); } return 0; } @@ -462,14 +462,14 @@ WIN32_IpAddrChangeMonitorInit() DWORD threadID = 0, ThrdParam = 0; if ((WIN32_run_mode == _WIN_SQUID_RUN_MODE_SERVICE) && (Config.onoff.WIN32_IpAddrChangeMonitor)) { - NotifyAddrChange_thread = CreateThread(NULL, 0, WIN32_IpAddrChangeMonitor, - &ThrdParam, 0, &threadID); - if (NotifyAddrChange_thread == NULL) { - status = GetLastError(); - NotifyAddrChange_thread = INVALID_HANDLE_VALUE; - debugs(1, 1, "Failed to start IP monitor thread."); - } else - debugs(1, 2, "Starting IP monitor thread [" << threadID << "] ..."); + NotifyAddrChange_thread = CreateThread(NULL, 0, WIN32_IpAddrChangeMonitor, + &ThrdParam, 0, &threadID); + if (NotifyAddrChange_thread == NULL) { + status = GetLastError(); + NotifyAddrChange_thread = INVALID_HANDLE_VALUE; + debugs(1, 1, "Failed to start IP monitor thread."); + } else + debugs(1, 2, "Starting IP monitor thread [" << threadID << "] ..."); } return status; } @@ -929,9 +929,9 @@ WIN32_sendSignal(int WIN32_signal) int main(int argc, char **argv) { SERVICE_TABLE_ENTRY DispatchTable[] = { - {NULL, SquidWinSvcMain}, - {NULL, NULL} - }; + {NULL, SquidWinSvcMain}, + {NULL, NULL} + }; char *c; char stderr_path[256]; diff --git a/src/access_log.cc b/src/access_log.cc index 364fb3c0a7..d1fc5c643f 100644 --- a/src/access_log.cc +++ b/src/access_log.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -61,38 +61,36 @@ static struct sockaddr_in mcast_miss_to; static void mcast_encode(unsigned int *, size_t, const unsigned int *); #endif -const char *log_tags[] = - { - "NONE", - "TCP_HIT", - "TCP_MISS", - "TCP_REFRESH_UNMODIFIED", - "TCP_REFRESH_FAIL", - "TCP_REFRESH_MODIFIED", - "TCP_CLIENT_REFRESH_MISS", - "TCP_IMS_HIT", - "TCP_SWAPFAIL_MISS", - "TCP_NEGATIVE_HIT", - "TCP_MEM_HIT", - "TCP_DENIED", - "TCP_DENIED_REPLY", - "TCP_OFFLINE_HIT", +const char *log_tags[] = { + "NONE", + "TCP_HIT", + "TCP_MISS", + "TCP_REFRESH_UNMODIFIED", + "TCP_REFRESH_FAIL", + "TCP_REFRESH_MODIFIED", + "TCP_CLIENT_REFRESH_MISS", + "TCP_IMS_HIT", + "TCP_SWAPFAIL_MISS", + "TCP_NEGATIVE_HIT", + "TCP_MEM_HIT", + "TCP_DENIED", + "TCP_DENIED_REPLY", + "TCP_OFFLINE_HIT", #if LOG_TCP_REDIRECTS - "TCP_REDIRECT", + "TCP_REDIRECT", #endif - "UDP_HIT", - "UDP_MISS", - "UDP_DENIED", - "UDP_INVALID", - "UDP_MISS_NOFETCH", - "ICP_QUERY", - "LOG_TYPE_MAX" - }; + "UDP_HIT", + "UDP_MISS", + "UDP_DENIED", + "UDP_INVALID", + "UDP_MISS_NOFETCH", + "ICP_QUERY", + "LOG_TYPE_MAX" +}; #if FORW_VIA_DB -typedef struct -{ +typedef struct { hash_link hash; int n; } fvdb_entry; @@ -148,7 +146,7 @@ log_quote(const char *header) buf = static_cast(xcalloc(1, (strlen(header) * 3) + 1)); buf_cursor = buf; /* - * We escape: \x00-\x1F"#%;<>?{}|\\\\^~`\[\]\x7F-\xFF + * We escape: \x00-\x1F"#%;<>?{}|\\\\^~`\[\]\x7F-\xFF * which is the default escape list for the CPAN Perl5 URI module * modulo the inclusion of space (x40) to make the raw logs a bit * more readable. @@ -224,7 +222,7 @@ username_quote(const char *header) buf_cursor = buf; /* * We escape: space \x00-\x1F and space (0x40) and \x7F-\xFF - * to prevent garbage in the logs. CR and LF are also there just in case. + * to prevent garbage in the logs. CR and LF are also there just in case. */ while ((c = *(const unsigned char *) header++) != '\0') { @@ -419,88 +417,86 @@ public: logformat_token *next; /* todo: move from linked list to array */ }; -struct logformat_token_table_entry -{ +struct logformat_token_table_entry { const char *config; logformat_bcode_t token_type; int options; }; -struct logformat_token_table_entry logformat_token_table[] = - { +struct logformat_token_table_entry logformat_token_table[] = { - {">a", LFT_CLIENT_IP_ADDRESS}, + {">a", LFT_CLIENT_IP_ADDRESS}, - { ">p", LFT_CLIENT_PORT}, - {">A", LFT_CLIENT_FQDN}, + { ">p", LFT_CLIENT_PORT}, + {">A", LFT_CLIENT_FQDN}, - /*{ "h", LFT_REQUEST_HEADER}, - {">h", LFT_REQUEST_ALL_HEADERS}, - {"h", LFT_REQUEST_HEADER}, + {">h", LFT_REQUEST_ALL_HEADERS}, + {"v", LFT_REQUEST_VERSION}, - {"rv", LFT_REQUEST_VERSION}, + {"rm", LFT_REQUEST_METHOD}, + {"ru", LFT_REQUEST_URI}, /* doesn't include the query-string */ + {"rp", LFT_REQUEST_URLPATH}, /* doesn't include the host */ + /* { "rq", LFT_REQUEST_QUERY }, * / / * the query-string, INCLUDING the leading ? */ + {">v", LFT_REQUEST_VERSION}, + {"rv", LFT_REQUEST_VERSION}, - { ">st", LFT_REQUEST_SIZE_TOTAL }, - /*{ ">sl", LFT_REQUEST_SIZE_LINE }, * / / * the request line "GET ... " */ - /*{ ">sh", LFT_REQUEST_SIZE_HEADERS }, */ - /*{ ">sb", LFT_REQUEST_SIZE_BODY }, */ - /*{ ">sB", LFT_REQUEST_SIZE_BODY_NO_TE }, */ + { ">st", LFT_REQUEST_SIZE_TOTAL }, + /*{ ">sl", LFT_REQUEST_SIZE_LINE }, * / / * the request line "GET ... " */ + /*{ ">sh", LFT_REQUEST_SIZE_HEADERS }, */ + /*{ ">sb", LFT_REQUEST_SIZE_BODY }, */ + /*{ ">sB", LFT_REQUEST_SIZE_BODY_NO_TE }, */ - {"request) { - outint = al->request->client_addr.GetPort(); - doint = 1; - } - break; + if (al->request) { + outint = al->request->client_addr.GetPort(); + doint = 1; + } + break; /* case LFT_SERVER_IP_ADDRESS: */ @@ -582,7 +578,7 @@ accessLogCustom(AccessLogEntry * al, customlog * log) break; case LFT_TIME_SECONDS_SINCE_EPOCH: - // some platforms store time in 32-bit, some 64-bit... + // some platforms store time in 32-bit, some 64-bit... outoff = static_cast(current_time.tv_sec); dooff = 1; break; @@ -596,25 +592,25 @@ accessLogCustom(AccessLogEntry * al, customlog * log) case LFT_TIME_LOCALTIME: case LFT_TIME_GMT: { - const char *spec; + const char *spec; - struct tm *t; - spec = fmt->data.timespec; + struct tm *t; + spec = fmt->data.timespec; - if (!spec) - spec = "%d/%b/%Y:%H:%M:%S"; + if (!spec) + spec = "%d/%b/%Y:%H:%M:%S"; - if (fmt->type == LFT_TIME_LOCALTIME) - t = localtime(&squid_curtime); - else - t = gmtime(&squid_curtime); + if (fmt->type == LFT_TIME_LOCALTIME) + t = localtime(&squid_curtime); + else + t = gmtime(&squid_curtime); - strftime(tmp, sizeof(tmp), spec, t); + strftime(tmp, sizeof(tmp), spec, t); - out = tmp; - } + out = tmp; + } - break; + break; case LFT_TIME_TO_HANDLE_REQUEST: outint = al->cache.msec; @@ -764,10 +760,10 @@ accessLogCustom(AccessLogEntry * al, customlog * log) break; case LFT_REQUEST_URLPATH: - if (al->request) { - out = al->request->urlpath.buf(); - quote = 1; - } + if (al->request) { + out = al->request->urlpath.buf(); + quote = 1; + } break; case LFT_REQUEST_VERSION: @@ -836,10 +832,10 @@ accessLogCustom(AccessLogEntry * al, customlog * log) break; } - if (dooff) { + if (dooff) { snprintf(tmp, sizeof(tmp), "%0*" PRId64, fmt->zero ? (int) fmt->width : 0, outoff); out = tmp; - + } else if (doint) { snprintf(tmp, sizeof(tmp), "%0*ld", fmt->zero ? (int) fmt->width : 0, outint); out = tmp; @@ -931,7 +927,7 @@ accessLogGetNewLogFormatToken(logformat_token * lt, char *def, enum log_quote *q lt->data.string = cp; while (l > 0) { - switch(*cur) { + switch (*cur) { case '"': @@ -1411,7 +1407,7 @@ accessLogLog(AccessLogEntry * al, ACLChecklist * checklist) xstrncpy(al->hier.host, dash_str, SQUIDHOSTNAMELEN); for (log = Config.Log.accesslogs; log; log = log->next) { - if(checklist && log->aclList && !checklist->matchAclListFast(log->aclList)) + if (checklist && log->aclList && !checklist->matchAclListFast(log->aclList)) continue; switch (log->type) { @@ -1654,7 +1650,7 @@ fvdbRegisterWithCacheManager(void) CacheManager *manager=CacheManager::GetInstance(); manager->registerAction("via_headers", "Via Request Headers", fvdbDumpVia, 0, 1); manager->registerAction("forw_headers", "X-Forwarded-For Request Headers", - fvdbDumpForw, 0, 1); + fvdbDumpForw, 0, 1); } static void diff --git a/src/acl.cc b/src/acl.cc index 0e4926a539..c263f36fd2 100644 --- a/src/acl.cc +++ b/src/acl.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -216,7 +216,7 @@ ACL::matchForCache(ACLChecklist *checklist) } /* - * we lookup an acl's cached results, and if we cannot find the acl being + * we lookup an acl's cached results, and if we cannot find the acl being * checked we check it and cache the result. This function is a template * method to support caching of multiple acl types. * Note that caching of time based acl's is not diff --git a/src/acl_noncore.cc b/src/acl_noncore.cc index 3d2e497734..fc3c5dfdb9 100644 --- a/src/acl_noncore.cc +++ b/src/acl_noncore.cc @@ -4,12 +4,12 @@ * DEBUG: section 28 Access Control * AUTHOR: Duane Wessels * - * This file contains ACL routines that are not part of the + * This file contains ACL routines that are not part of the * ACL class, nor any other class yet, and that need to be - * factored into appropriate places. They are here to reduce + * factored into appropriate places. They are here to reduce * unneeded dependencies between the ACL class and the rest * of squid. - * + * * SQUID Web Proxy Cache http://www.squid-cache.org/ * ---------------------------------------------------------- * @@ -26,12 +26,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -311,7 +311,7 @@ aclDestroyDenyInfoList(acl_deny_info_list ** list) /* * This function traverses all ACL elements referenced - * by an access list (presumably 'http_access'). If + * by an access list (presumably 'http_access'). If * it finds a PURGE method ACL, then it returns TRUE, * otherwise FALSE. */ diff --git a/src/adaptation/AccessCheck.cc b/src/adaptation/AccessCheck.cc index db3586186c..ba1f84a962 100644 --- a/src/adaptation/AccessCheck.cc +++ b/src/adaptation/AccessCheck.cc @@ -17,25 +17,26 @@ cbdata_type Adaptation::AccessCheck::CBDATA_AccessCheck = CBDATA_UNKNOWN; bool Adaptation::AccessCheck::Start(Method method, VectPoint vp, - HttpRequest *req, HttpReply *rep, AccessCheckCallback *cb, void *cbdata) { + HttpRequest *req, HttpReply *rep, AccessCheckCallback *cb, void *cbdata) +{ if (Config::Enabled) { // the new check will call the callback and delete self, eventually AccessCheck *check = new AccessCheck(method, vp, req, rep, cb, cbdata); check->check(); return true; - } + } debugs(83, 3, HERE << "adaptation off, skipping"); return false; } Adaptation::AccessCheck::AccessCheck(Method aMethod, - VectPoint aPoint, - HttpRequest *aReq, - HttpReply *aRep, - AccessCheckCallback *aCallback, - void *aCallbackData): AsyncJob("AccessCheck"), done(FALSE) + VectPoint aPoint, + HttpRequest *aReq, + HttpReply *aRep, + AccessCheckCallback *aCallback, + void *aCallbackData): AsyncJob("AccessCheck"), done(FALSE) { // TODO: assign these at creation time @@ -177,20 +178,21 @@ Adaptation::AccessCheck::do_callback() debugs(93,3,HERE << "do_callback: no rule" << topCandidate()); } candidates.shift(); // done with topCandidate() - } else { + } else { debugs(93,3,HERE << "do_callback: no candidate rules"); - } + } callback(service, validated_cbdata); done = TRUE; } Adaptation::ServicePointer -Adaptation::AccessCheck::findBestService(AccessRule &r, bool preferUp) { +Adaptation::AccessCheck::findBestService(AccessRule &r, bool preferUp) +{ const char *what = preferUp ? "up " : ""; - debugs(93,7,HERE << "looking for the first matching " << - what << "service in group " << r.groupId); + debugs(93,7,HERE << "looking for the first matching " << + what << "service in group " << r.groupId); ServicePointer secondBest; @@ -199,7 +201,7 @@ Adaptation::AccessCheck::findBestService(AccessRule &r, bool preferUp) { if (!g) { debugs(93,5,HERE << "lost " << r.groupId << " group in rule" << r.id); return ServicePointer(); - } + } ServiceGroup::Loop loop(g->initialServices()); typedef ServiceGroup::iterator SGI; @@ -239,8 +241,8 @@ Adaptation::AccessCheck::findBestService(AccessRule &r, bool preferUp) { } debugs(93,5,HERE << "found first matching " << - what << "service for " << r.groupId << " group in rule" << r.id << - ": " << service->cfg().key); + what << "service for " << r.groupId << " group in rule" << r.id << + ": " << service->cfg().key); return service; } @@ -248,12 +250,12 @@ Adaptation::AccessCheck::findBestService(AccessRule &r, bool preferUp) { if (secondBest != NULL) { what = "down "; debugs(93,5,HERE << "found first matching " << - what << "service for " << r.groupId << " group in rule" << r.id << - ": " << secondBest->cfg().key); + what << "service for " << r.groupId << " group in rule" << r.id << + ": " << secondBest->cfg().key); return secondBest; } - debugs(93,5,HERE << "found no matching " << - what << "services for " << r.groupId << " group in rule" << r.id); + debugs(93,5,HERE << "found no matching " << + what << "services for " << r.groupId << " group in rule" << r.id); return ServicePointer(); } diff --git a/src/adaptation/AccessCheck.h b/src/adaptation/AccessCheck.h index e21d7ac2f0..89e54045e2 100644 --- a/src/adaptation/AccessCheck.h +++ b/src/adaptation/AccessCheck.h @@ -8,7 +8,8 @@ class HttpRequest; class HttpReply; -namespace Adaptation { +namespace Adaptation +{ class AccessRule; @@ -19,8 +20,8 @@ public: typedef void AccessCheckCallback(ServicePointer match, void *data); // use this to start async ACL checks; returns true if started - static bool Start(Method method, VectPoint vp, HttpRequest *req, - HttpReply *rep, AccessCheckCallback *cb, void *cbdata); + static bool Start(Method method, VectPoint vp, HttpRequest *req, + HttpReply *rep, AccessCheckCallback *cb, void *cbdata); protected: // use Start to start adaptation checks diff --git a/src/adaptation/AccessRule.cc b/src/adaptation/AccessRule.cc index 2a2a27130c..1fde8c2a82 100644 --- a/src/adaptation/AccessRule.cc +++ b/src/adaptation/AccessRule.cc @@ -29,7 +29,7 @@ Adaptation::AccessRule::parse(ConfigParser &parser) void Adaptation::AccessRule::finalize() { - if (!group()) { // no explicit group + if (!group()) { // no explicit group debugs(93,7, HERE << "no service group: " << groupId); // try to add a one-service group if (FindService(groupId) != NULL) { @@ -41,7 +41,7 @@ Adaptation::AccessRule::finalize() if (!group()) { debugs(93,0, "ERROR: Unknown adaptation service or group name: '" << - groupId << "'"); // TODO: fail on failures + groupId << "'"); // TODO: fail on failures } } diff --git a/src/adaptation/AccessRule.h b/src/adaptation/AccessRule.h index edc9645dd2..6924451c58 100644 --- a/src/adaptation/AccessRule.h +++ b/src/adaptation/AccessRule.h @@ -7,11 +7,13 @@ class acl_access; class ConfigParser; -namespace Adaptation { +namespace Adaptation +{ // manages adaptation_access configuration by associating an acl with // an adaptation service group -class AccessRule { +class AccessRule +{ public: AccessRule(); ~AccessRule(); diff --git a/src/adaptation/Config.cc b/src/adaptation/Config.cc index 61bbc4c8cc..2a68fcb0d3 100644 --- a/src/adaptation/Config.cc +++ b/src/adaptation/Config.cc @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -69,7 +69,7 @@ Adaptation::Config::dumpService(StoreEntry *entry, const char *name) const for (SCI i = AllServices().begin(); i != AllServices().end(); ++i) { const ServiceConfig &cfg = (*i)->cfg(); storeAppendPrintf(entry, "%s %s_%s %s %d %s\n", name, cfg.key.buf(), - cfg.methodStr(), cfg.vectPointStr(), cfg.bypass, cfg.uri.buf()); + cfg.methodStr(), cfg.vectPointStr(), cfg.bypass, cfg.uri.buf()); } } @@ -81,19 +81,19 @@ Adaptation::Config::finalize() const Vector &configs = serviceConfigs; debugs(93,3, "Found " << configs.size() << " service configs."); for (VISCI i = configs.begin(); i != configs.end(); ++i) { - const ServiceConfig &cfg = **i; - if (FindService(cfg.key) != NULL) { - debugs(93,0, "ERROR: Duplicate adaptation service name: " << - cfg.key); - continue; // TODO: make fatal - } + const ServiceConfig &cfg = **i; + if (FindService(cfg.key) != NULL) { + debugs(93,0, "ERROR: Duplicate adaptation service name: " << + cfg.key); + continue; // TODO: make fatal + } ServicePointer s = createService(**i); if (s != NULL) AllServices().push_back(s); } debugs(93,3, "Created " << configs.size() << - " message adaptation services."); + " message adaptation services."); } // poor man for_each @@ -178,7 +178,7 @@ Adaptation::Config::Config() // XXX: should we init members? } -// XXX: this is called for ICAP and eCAP configs, but deals mostly +// XXX: this is called for ICAP and eCAP configs, but deals mostly // with global arrays shared by those individual configs Adaptation::Config::~Config() { diff --git a/src/adaptation/Config.h b/src/adaptation/Config.h index 22c9bc2a89..bf6c330096 100644 --- a/src/adaptation/Config.h +++ b/src/adaptation/Config.h @@ -11,7 +11,8 @@ class ConfigParser; template class RefCount; -namespace Adaptation { +namespace Adaptation +{ class Service; class ServiceConfig; diff --git a/src/adaptation/Elements.cc b/src/adaptation/Elements.cc index 42cb5676e5..613ea0ed08 100644 --- a/src/adaptation/Elements.cc +++ b/src/adaptation/Elements.cc @@ -6,7 +6,7 @@ const char *Adaptation::crlf = "\r\n"; const char * Adaptation::methodStr(Adaptation::Method method) { - switch(method) { + switch (method) { case Adaptation::methodReqmod: return "REQMOD"; @@ -31,7 +31,7 @@ Adaptation::methodStr(Adaptation::Method method) const char * Adaptation::vectPointStr(Adaptation::VectPoint point) { - switch(point) { + switch (point) { case Adaptation::pointPreCache: return "PRECACHE"; diff --git a/src/adaptation/Initiate.cc b/src/adaptation/Initiate.cc index 72a6f24644..cc12306399 100644 --- a/src/adaptation/Initiate.cc +++ b/src/adaptation/Initiate.cc @@ -8,7 +8,8 @@ #include "adaptation/Initiator.h" #include "adaptation/Initiate.h" -namespace Adaptation { +namespace Adaptation +{ // AdaptInitiator::noteAdaptionAnswer Dialer locks/unlocks the message in transit // TODO: replace HTTPMSGLOCK with general RefCounting and delete this class @@ -18,9 +19,9 @@ public: typedef UnaryMemFunT Parent; AnswerDialer(Initiator *obj, Parent::Method meth, HttpMsg *msg): - Parent(obj, meth, msg) { HTTPMSGLOCK(arg1); } + Parent(obj, meth, msg) { HTTPMSGLOCK(arg1); } AnswerDialer(const AnswerDialer &d): - Parent(d) { HTTPMSGLOCK(arg1); } + Parent(d) { HTTPMSGLOCK(arg1); } virtual ~AnswerDialer() { HTTPMSGUNLOCK(arg1); } }; @@ -30,8 +31,8 @@ public: /* Initiate */ Adaptation::Initiate::Initiate(const char *aTypeName, - Initiator *anInitiator, ServicePointer aService): - AsyncJob(aTypeName), theInitiator(anInitiator), theService(aService) + Initiator *anInitiator, ServicePointer aService): + AsyncJob(aTypeName), theInitiator(anInitiator), theService(aService) { assert(theService != NULL); assert(theInitiator); @@ -68,8 +69,8 @@ void Adaptation::Initiate::sendAnswer(HttpMsg *msg) assert(msg); if (theInitiator.isThere()) { CallJob(93, 5, __FILE__, __LINE__, "Initiator::noteAdaptAnswer", - AnswerDialer(theInitiator.ptr(), &Initiator::noteAdaptationAnswer, msg)); - } + AnswerDialer(theInitiator.ptr(), &Initiator::noteAdaptationAnswer, msg)); + } clearInitiator(); } @@ -78,8 +79,8 @@ void Adaptation::Initiate::tellQueryAborted(bool final) { if (theInitiator.isThere()) { CallJobHere1(93, 5, theInitiator.ptr(), - Initiator::noteAdaptationQueryAbort, final); - } + Initiator::noteAdaptationQueryAbort, final); + } clearInitiator(); } @@ -90,7 +91,8 @@ Adaptation::Initiate::service() return *theService; } -const char *Adaptation::Initiate::status() const { +const char *Adaptation::Initiate::status() const +{ return AsyncJob::status(); // for now } @@ -98,7 +100,7 @@ const char *Adaptation::Initiate::status() const { /* InitiatorHolder */ Adaptation::InitiatorHolder::InitiatorHolder(Initiator *anInitiator): - prime(0), cbdata(0) + prime(0), cbdata(0) { if (anInitiator) { cbdata = cbdataReference(anInitiator->toCbdata()); @@ -107,7 +109,7 @@ Adaptation::InitiatorHolder::InitiatorHolder(Initiator *anInitiator): } Adaptation::InitiatorHolder::InitiatorHolder(const InitiatorHolder &anInitiator): - prime(0), cbdata(0) + prime(0), cbdata(0) { if (anInitiator != NULL && cbdataReferenceValid(anInitiator.cbdata)) { cbdata = cbdataReference(anInitiator.cbdata); @@ -120,7 +122,8 @@ Adaptation::InitiatorHolder::~InitiatorHolder() clear(); } -void Adaptation::InitiatorHolder::clear() { +void Adaptation::InitiatorHolder::clear() +{ if (prime) { prime = NULL; cbdataReferenceDone(cbdata); @@ -134,7 +137,8 @@ Adaptation::Initiator *Adaptation::InitiatorHolder::ptr() } bool -Adaptation::InitiatorHolder::isThere() { +Adaptation::InitiatorHolder::isThere() +{ return prime && cbdataReferenceValid(cbdata); } diff --git a/src/adaptation/Initiate.h b/src/adaptation/Initiate.h index ba00d97f36..a94c5889e6 100644 --- a/src/adaptation/Initiate.h +++ b/src/adaptation/Initiate.h @@ -7,14 +7,16 @@ class HttpMsg; -namespace Adaptation { +namespace Adaptation +{ /* Initiator holder associtates an initiator with its cbdata. It is used as * a temporary hack to make cbdata work with multiple inheritance. We need * this hack because we cannot know whether the initiator pointer is still - * valid without dereferencing it to call toCbdata() + * valid without dereferencing it to call toCbdata() * TODO: JobDialer uses the same trick. Factor out or move this code. */ -class InitiatorHolder { +class InitiatorHolder +{ public: InitiatorHolder(Initiator *anInitiator); InitiatorHolder(const InitiatorHolder &anInitiator); @@ -40,7 +42,7 @@ private: /* * The Initiate is a common base for queries or transactions - * initiated by an Initiator. This interface exists to allow an + * initiated by an Initiator. This interface exists to allow an * initiator to signal its "initiatees" that it is aborting and no longer * expecting an answer. The class is also handy for implementing common * initiate actions such as maintaining and notifying the initiator. diff --git a/src/adaptation/Initiator.h b/src/adaptation/Initiator.h index ae51d19423..0d66074850 100644 --- a/src/adaptation/Initiator.h +++ b/src/adaptation/Initiator.h @@ -15,7 +15,8 @@ class HttpMsg; -namespace Adaptation { +namespace Adaptation +{ class Initiator: virtual public AsyncJob { diff --git a/src/adaptation/Message.h b/src/adaptation/Message.h index 8e40b72983..85720d54c5 100644 --- a/src/adaptation/Message.h +++ b/src/adaptation/Message.h @@ -12,7 +12,8 @@ class HttpMsg; class BodyPipe; typedef RefCount BodyPipePointer; -namespace Adaptation { +namespace Adaptation +{ // Manages the header and the body of an HTTP message being worked on. // Adaptation transactions use this class for virgin and adapted HTTP messages. @@ -31,7 +32,7 @@ public: void clear(); void set(Header *aHeader); - static void ShortCircuit(Message &src, Message &dest); + static void ShortCircuit(Message &src, Message &dest); public: // virgin or adapted message being worked on @@ -39,7 +40,7 @@ public: /// Copy of header->body_pipe, in case somebody moves the original. /// \todo Find and fix the code that moves (if any) and remove this. - BodyPipePointer body_pipe; + BodyPipePointer body_pipe; private: Message(const Message &); // not implemented diff --git a/src/adaptation/Service.cc b/src/adaptation/Service.cc index 6f35d33e25..d083c69dbc 100644 --- a/src/adaptation/Service.cc +++ b/src/adaptation/Service.cc @@ -37,6 +37,6 @@ Adaptation::FindService(const Service::Id& key) for (SI i = AllServices().begin(); i != AllServices().end(); ++i) { if ((*i)->cfg().key == key) return *i; - } + } return NULL; } diff --git a/src/adaptation/Service.h b/src/adaptation/Service.h index 15806dd3ea..cb52b142a5 100644 --- a/src/adaptation/Service.h +++ b/src/adaptation/Service.h @@ -12,7 +12,8 @@ class HttpMsg; class HttpRequest; -namespace Adaptation { +namespace Adaptation +{ // manages adaptation service configuration in squid.conf // specific adaptation mechanisms extend this class diff --git a/src/adaptation/ServiceConfig.cc b/src/adaptation/ServiceConfig.cc index 118affb064..6188c30fda 100644 --- a/src/adaptation/ServiceConfig.cc +++ b/src/adaptation/ServiceConfig.cc @@ -6,8 +6,8 @@ #include "ConfigParser.h" #include "adaptation/ServiceConfig.h" -Adaptation::ServiceConfig::ServiceConfig(): - port(-1), method(methodNone), point(pointNone), bypass(false) +Adaptation::ServiceConfig::ServiceConfig(): + port(-1), method(methodNone), point(pointNone), bypass(false) {} const char * @@ -63,24 +63,24 @@ Adaptation::ServiceConfig::parse() ConfigParser::ParseString(&uri); debugs(3, 5, HERE << cfg_filename << ':' << config_lineno << ": " << - key.buf() << " " << method_point << " " << bypass); + key.buf() << " " << method_point << " " << bypass); method = parseMethod(method_point); point = parseVectPoint(method_point); debugs(3, 5, HERE << cfg_filename << ':' << config_lineno << ": " << - "service_configConfig is " << methodStr() << "_" << vectPointStr()); + "service_configConfig is " << methodStr() << "_" << vectPointStr()); // TODO: find core code that parses URLs and extracts various parts // extract scheme and use it as the service_configConfig protocol const char *schemeSuffix = "://"; if (const char *schemeEnd = uri.pos(schemeSuffix)) - protocol.limitInit(uri.buf(), schemeEnd - uri.buf()); - debugs(3, 5, HERE << cfg_filename << ':' << config_lineno << ": " << - "service protocol is " << protocol); - if (!protocol.size()) - return false; + protocol.limitInit(uri.buf(), schemeEnd - uri.buf()); + debugs(3, 5, HERE << cfg_filename << ':' << config_lineno << ": " << + "service protocol is " << protocol); + if (!protocol.size()) + return false; // skip scheme const char *s = uri.buf() + protocol.size() + strlen(schemeSuffix); @@ -101,16 +101,16 @@ Adaptation::ServiceConfig::parse() host.limitInit(s, len); s = e; - port = -1; + port = -1; if (have_port) { s++; if ((e = strchr(s, '/')) != NULL) { char *t; - const unsigned long p = strtoul(s, &t, 0); + const unsigned long p = strtoul(s, &t, 0); - if (p > 65535) // port value is too high - return false; + if (p > 65535) // port value is too high + return false; port = static_cast(p); @@ -132,14 +132,14 @@ Adaptation::ServiceConfig::parse() if (len > 1024) { debugs(3, 0, HERE << cfg_filename << ':' << config_lineno << ": " << - "long resource name (>1024), probably wrong"); + "long resource name (>1024), probably wrong"); } resource.limitInit(s, len + 1); if ((bypass != 0) && (bypass != 1)) { debugs(3, 0, HERE << cfg_filename << ':' << config_lineno << ": " << - "wrong bypass value; 0 or 1 expected: " << bypass); + "wrong bypass value; 0 or 1 expected: " << bypass); return false; } diff --git a/src/adaptation/ServiceConfig.h b/src/adaptation/ServiceConfig.h index a71f3369f1..c9e8110087 100644 --- a/src/adaptation/ServiceConfig.h +++ b/src/adaptation/ServiceConfig.h @@ -5,7 +5,8 @@ #include "RefCount.h" #include "adaptation/Elements.h" -namespace Adaptation { +namespace Adaptation +{ // manages adaptation service configuration in squid.conf class ServiceConfig diff --git a/src/adaptation/ServiceGroups.cc b/src/adaptation/ServiceGroups.cc index 5bd36aa01b..777b59b64e 100644 --- a/src/adaptation/ServiceGroups.cc +++ b/src/adaptation/ServiceGroups.cc @@ -36,7 +36,7 @@ Adaptation::ServiceGroup::finalize() // TODO: fail on failures if (!FindService(id)) debugs(93,0, "ERROR: Unknown adaptation name: " << id); - } + } debugs(93,7, HERE << "finalized " << kind << ": " << id); } @@ -69,7 +69,7 @@ Adaptation::ServiceSet::finalize() /* SingleService */ Adaptation::SingleService::SingleService(const String &aServiceId): - ServiceGroup("single-service group") + ServiceGroup("single-service group") { id = aServiceId; services.push_back(aServiceId); diff --git a/src/adaptation/ServiceGroups.h b/src/adaptation/ServiceGroups.h index 8464d1f9e5..944f0d68e1 100644 --- a/src/adaptation/ServiceGroups.h +++ b/src/adaptation/ServiceGroups.h @@ -5,7 +5,8 @@ #include "Array.h" #include "adaptation/forward.h" -namespace Adaptation { +namespace Adaptation +{ // Interface for grouping adaptation services together. // Specific groups differ in how the first and the next services are selected @@ -18,7 +19,7 @@ public: // Information sufficient to iterate services stored in the group, // grouped together to simplify initial/sequentialServices interfaces. - // The iterators point back to + // The iterators point back to struct Loop { Loop(const iterator &b, const iterator &e): begin(b), end(e) {} iterator begin; diff --git a/src/adaptation/forward.h b/src/adaptation/forward.h index b26fcc9e0b..28b47e3237 100644 --- a/src/adaptation/forward.h +++ b/src/adaptation/forward.h @@ -11,7 +11,8 @@ class RefCount; template class Vector; -namespace Adaptation { +namespace Adaptation +{ class Service; class ServiceConfig; diff --git a/src/asn.cc b/src/asn.cc index 8073e73eb2..7953890161 100644 --- a/src/asn.cc +++ b/src/asn.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -55,7 +55,8 @@ /* 32/128 bits address in memory with length */ -class m_ADDR { +class m_ADDR +{ public: uint8_t len; IPAddress addr; @@ -76,18 +77,16 @@ template cbdata_type CbDataList::CBDATA_CbDataList; /// \endcond /** - * Structure for as number information. it could be simply + * Structure for as number information. it could be simply * a list but it's coded as a structure for future * enhancements (e.g. expires) */ -struct as_info -{ +struct as_info { CbDataList *as_number; time_t expires; /* NOTUSED */ }; -struct ASState -{ +struct ASState { StoreEntry *entry; store_client *sc; HttpRequest *request; @@ -99,8 +98,7 @@ struct ASState }; /** entry into the radix tree */ -struct rtentry_t -{ +struct rtentry_t { struct squid_radix_node e_nodes[2]; as_info *e_info; m_ADDR e_addr; @@ -175,7 +173,7 @@ void ACLASN::prepareForUse() { for (CbDataList *i = data; i; i = i-> - next) + next) asnCacheStart(i->element); } @@ -475,8 +473,7 @@ destroyRadixNode(struct squid_radix_node *rn, void *w) struct squid_radix_node_head *rnh = (struct squid_radix_node_head *) w; - if (rn && !(rn->rn_flags & RNF_ROOT)) - { + if (rn && !(rn->rn_flags & RNF_ROOT)) { rtentry_t *e = (rtentry_t *) rn; rn = squid_rn_delete(rn->rn_key, rn->rn_mask, rnh); @@ -641,7 +638,8 @@ ACLDestinationASNStrategy::match (ACLData * &data, ACLChecklist *chec debugs(28, 3, "asnMatchAcl: Can't yet compare '" << "unknown" /*name*/ << "' ACL for '" << checklist->request->GetHost() << "'"); checklist->changeState (DestinationIPLookup::Instance()); } else { - IPAddress noaddr; noaddr.SetNoAddr(); + IPAddress noaddr; + noaddr.SetNoAddr(); return data->match(noaddr); } diff --git a/src/auth/basic/auth_basic.cc b/src/auth/basic/auth_basic.cc index 121e81f56c..50eb1451a9 100644 --- a/src/auth/basic/auth_basic.cc +++ b/src/auth/basic/auth_basic.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -467,8 +467,8 @@ BasicUser::decode(char const *proxy_auth, AuthUserRequest *auth_user_request) currentRequest = auth_user_request; httpAuthHeader = proxy_auth; if (decodeCleartext ()) { - extractUsername(); - extractPassword(); + extractUsername(); + extractPassword(); } currentRequest = NULL; httpAuthHeader = NULL; @@ -478,9 +478,9 @@ bool BasicUser::valid() const { if (username() == NULL) - return false; + return false; if (passwd == NULL) - return false; + return false; return true; } @@ -548,8 +548,8 @@ BasicUser::updateCached(BasicUser *from) /** * Decode a Basic [Proxy-]Auth string, linking the passed * auth_user_request structure to any existing user structure or creating one - * if needed. Note that just returning will be treated as - * "cannot decode credentials". Use the message field to return a + * if needed. Note that just returning will be treated as + * "cannot decode credentials". Use the message field to return a * descriptive message to the user. */ AuthUserRequest * @@ -627,9 +627,9 @@ void AuthBasicConfig::registerWithCacheManager(void) { CacheManager::GetInstance()-> - registerAction("basicauthenticator", - "Basic User Authenticator Stats", - authenticateBasicStats, 0, 1); + registerAction("basicauthenticator", + "Basic User Authenticator Stats", + authenticateBasicStats, 0, 1); } void @@ -684,13 +684,13 @@ BasicUser::submitRequest(AuthUserRequest * auth_user_request, RH * handler, void r->data = cbdataReference(data); r->auth_user_request = auth_user_request; if (basicConfig.utf8) { - latin1_to_utf8(user, sizeof(user), username()); - latin1_to_utf8(pass, sizeof(pass), passwd); - xstrncpy(user, rfc1738_escape(user), sizeof(user)); - xstrncpy(pass, rfc1738_escape(pass), sizeof(pass)); + latin1_to_utf8(user, sizeof(user), username()); + latin1_to_utf8(pass, sizeof(pass), passwd); + xstrncpy(user, rfc1738_escape(user), sizeof(user)); + xstrncpy(pass, rfc1738_escape(pass), sizeof(pass)); } else { - xstrncpy(user, rfc1738_escape(username()), sizeof(user)); - xstrncpy(pass, rfc1738_escape(passwd), sizeof(pass)); + xstrncpy(user, rfc1738_escape(username()), sizeof(user)); + xstrncpy(pass, rfc1738_escape(passwd), sizeof(pass)); } snprintf(buf, sizeof(buf), "%s %s\n", user, pass); helperSubmit(basicauthenticators, buf, authenticateBasicHandleReply, r); diff --git a/src/auth/basic/auth_basic.h b/src/auth/basic/auth_basic.h index f0abbaecdd..8907885bec 100644 --- a/src/auth/basic/auth_basic.h +++ b/src/auth/basic/auth_basic.h @@ -60,8 +60,7 @@ public: char *passwd; time_t credentials_checkedtime; - struct - { + struct { unsigned int credentials_ok: 2; /*0=unchecked,1=ok,2=failed */ diff --git a/src/auth/basic/basicScheme.cc b/src/auth/basic/basicScheme.cc index 7bcc008f40..e7cdcdfaa6 100644 --- a/src/auth/basic/basicScheme.cc +++ b/src/auth/basic/basicScheme.cc @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/auth/basic/basicScheme.h b/src/auth/basic/basicScheme.h index 9ec329c8a5..3411d8c5da 100644 --- a/src/auth/basic/basicScheme.h +++ b/src/auth/basic/basicScheme.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -44,7 +44,7 @@ class basicScheme : public AuthScheme public: static AuthScheme &GetInstance(); basicScheme(); - virtual ~basicScheme(){} + virtual ~basicScheme() {} /* per scheme */ virtual char const *type () const; diff --git a/src/auth/digest/auth_digest.cc b/src/auth/digest/auth_digest.cc index 1e584835e3..342e879f18 100644 --- a/src/auth/digest/auth_digest.cc +++ b/src/auth/digest/auth_digest.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -116,9 +116,9 @@ authenticateDigestNonceNew(void) * The contents of the nonce are implementation dependent. The quality * of the implementation depends on a good choice. A nonce might, for * example, be constructed as the base 64 encoding of - * + * * time-stamp H(time-stamp ":" ETag ":" private-key) - * + * * where time-stamp is a server-generated time or other non-repeating * value, ETag is the value of the HTTP ETag header associated with * the requested entity, and private-key is data known only to the @@ -135,7 +135,7 @@ authenticateDigestNonceNew(void) * user often go through different proxies in the farm. Also, IP * address spoofing is not that hard.) * ==== - * + * * Now for my reasoning: * We will not accept a unrecognised nonce->we have all recognisable * nonces stored. If we send out unique base64 encodings we guarantee @@ -331,7 +331,7 @@ authenticateDigestNonceFindNonce(const char *nonceb64) if (nonceb64 == NULL) return NULL; - debugs(29, 9, "authDigestNonceFindNonce:looking for nonceb64 '" << nonceb64 << "' in the nonce cache."); + debugs(29, 9, "authDigestNonceFindNonce:looking for nonceb64 '" << nonceb64 << "' in the nonce cache."); nonce = static_cast < digest_nonce_h * >(hash_lookup(digest_nonce_cache, nonceb64)); @@ -706,8 +706,8 @@ AuthDigestUserRequest::module_direction() case Failed: - /* send new challenge */ - return 1; + /* send new challenge */ + return 1; } return -2; @@ -845,7 +845,7 @@ authenticateDigestHandleReply(void *data, char *reply) if (reply && (strncasecmp(reply, "ERR", 3) == 0)) { digest_request->credentials(AuthDigestUserRequest::Failed); - digest_request->flags.invalid_password = 1; + digest_request->flags.invalid_password = 1; if (t && *t) digest_request->setDenyMessage(t); @@ -891,9 +891,9 @@ void AuthDigestConfig::registerWithCacheManager(void) { CacheManager::GetInstance()-> - registerAction("digestauthenticator", - "Digest User Authenticator Stats", - authenticateDigestStats, 0, 1); + registerAction("digestauthenticator", + "Digest User Authenticator Stats", + authenticateDigestStats, 0, 1); } /* free any allocated configuration details */ @@ -1003,7 +1003,7 @@ authDigestNonceUserUnlink(digest_nonce_h * nonce) } /* this reference to user was not locked because freeeing the user frees - * the nonce too. + * the nonce too. */ nonce->user = NULL; } @@ -1367,11 +1367,11 @@ AuthDigestUserRequest::module_start(RH * handler, void *data) r->auth_user_request = this; AUTHUSERREQUESTLOCK(r->auth_user_request, "r"); if (digestConfig.utf8) { - char user[1024]; - latin1_to_utf8(user, sizeof(user), digest_user->username()); - snprintf(buf, 8192, "\"%s\":\"%s\"\n", user, realm); + char user[1024]; + latin1_to_utf8(user, sizeof(user), digest_user->username()); + snprintf(buf, 8192, "\"%s\":\"%s\"\n", user, realm); } else { - snprintf(buf, 8192, "\"%s\":\"%s\"\n", digest_user->username(), realm); + snprintf(buf, 8192, "\"%s\":\"%s\"\n", digest_user->username(), realm); } helperSubmit(digestauthenticators, buf, authenticateDigestHandleReply, r); diff --git a/src/auth/digest/auth_digest.h b/src/auth/digest/auth_digest.h index c1845fb306..74fce505a0 100644 --- a/src/auth/digest/auth_digest.h +++ b/src/auth/digest/auth_digest.h @@ -93,10 +93,9 @@ public: char *uri; /* = "/dir/index.html" */ char *response; - struct - { + struct { unsigned int authinfo_sent:1; - unsigned int invalid_password:1; + unsigned int invalid_password:1; unsigned int helper_queried:1; } flags; digest_nonce_h *nonce; @@ -110,8 +109,7 @@ MEMPROXY_CLASS_INLINE(AuthDigestUserRequest) /**DOCS_NOSEMI*/ /* data to be encoded into the nonce's b64 representation */ -struct _digest_nonce_data -{ +struct _digest_nonce_data { time_t creationtime; /* in memory address of the nonce struct (similar purpose to an ETag) */ digest_nonce_h *self; @@ -120,8 +118,7 @@ struct _digest_nonce_data /* the nonce structure we'll pass around */ -struct _digest_nonce_h : public hash_link -{ +struct _digest_nonce_h : public hash_link { digest_nonce_data noncedata; /* number of uses we've seen of this nonce */ unsigned long nc; @@ -131,8 +128,7 @@ struct _digest_nonce_h : public hash_link DigestUser *user; /* has this nonce been invalidated ? */ - struct - { + struct { unsigned int valid:1; unsigned int incache:1; } flags; diff --git a/src/auth/digest/digestScheme.cc b/src/auth/digest/digestScheme.cc index 5434b4d07e..2fc5054a6a 100644 --- a/src/auth/digest/digestScheme.cc +++ b/src/auth/digest/digestScheme.cc @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/auth/digest/digestScheme.h b/src/auth/digest/digestScheme.h index eb6c5f62cc..338e9fb54e 100644 --- a/src/auth/digest/digestScheme.h +++ b/src/auth/digest/digestScheme.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -44,7 +44,7 @@ class digestScheme : public AuthScheme public: static AuthScheme &GetInstance(); digestScheme(); - virtual ~digestScheme(){} + virtual ~digestScheme() {} /* per scheme */ virtual char const *type () const; diff --git a/src/auth/negotiate/auth_negotiate.cc b/src/auth/negotiate/auth_negotiate.cc index b656b6c46e..7b158ae1d7 100644 --- a/src/auth/negotiate/auth_negotiate.cc +++ b/src/auth/negotiate/auth_negotiate.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -221,9 +221,9 @@ void AuthNegotiateConfig::registerWithCacheManager(void) { CacheManager::GetInstance()-> - registerAction("negotiateauthenticator", - "Negotiate User Authenticator Stats", - authenticateNegotiateStats, 0, 1); + registerAction("negotiateauthenticator", + "Negotiate User Authenticator Stats", + authenticateNegotiateStats, 0, 1); } bool @@ -313,7 +313,7 @@ AuthNegotiateConfig::fixHeader(AuthUserRequest *auth_user_request, HttpReply *re /* Need keep-alive */ if (!request->flags.proxy_keepalive && request->flags.must_keepalive) - return; + return; /* New request, no user details */ if (auth_user_request == NULL) { @@ -448,18 +448,18 @@ authenticateNegotiateHandleReply(void *data, void *lastserver, char *reply) if (arg) *arg++ = '\0'; safe_free(negotiate_request->server_blob); - negotiate_request->request->flags.must_keepalive = 1; - if (negotiate_request->request->flags.proxy_keepalive) { - negotiate_request->server_blob = xstrdup(blob); - negotiate_request->auth_state = AUTHENTICATE_STATE_IN_PROGRESS; - auth_user_request->denyMessage("Authentication in progress"); - debugs(29, 4, "authenticateNegotiateHandleReply: Need to challenge the client with a server blob '" << blob << "'"); - result = S_HELPER_RESERVE; - } else { - negotiate_request->auth_state = AUTHENTICATE_STATE_FAILED; - auth_user_request->denyMessage("NTLM authentication requires a persistent connection"); - result = S_HELPER_RELEASE; - } + negotiate_request->request->flags.must_keepalive = 1; + if (negotiate_request->request->flags.proxy_keepalive) { + negotiate_request->server_blob = xstrdup(blob); + negotiate_request->auth_state = AUTHENTICATE_STATE_IN_PROGRESS; + auth_user_request->denyMessage("Authentication in progress"); + debugs(29, 4, "authenticateNegotiateHandleReply: Need to challenge the client with a server blob '" << blob << "'"); + result = S_HELPER_RESERVE; + } else { + negotiate_request->auth_state = AUTHENTICATE_STATE_FAILED; + auth_user_request->denyMessage("NTLM authentication requires a persistent connection"); + result = S_HELPER_RELEASE; + } } else if (strncasecmp(reply, "AF ", 3) == 0 && arg != NULL) { /* we're finished, release the helper */ @@ -487,7 +487,7 @@ authenticateNegotiateHandleReply(void *data, void *lastserver, char *reply) /* see if this is an existing user with a different proxy_auth * string */ AuthUserHashPointer *usernamehash = static_cast(hash_lookup(proxy_auth_username_cache, negotiate_user->username())); - AuthUser *local_auth_user = negotiate_request->user(); + AuthUser *local_auth_user = negotiate_request->user(); while (usernamehash && (usernamehash->user()->auth_type != AUTH_NEGOTIATE || strcmp(usernamehash->user()->username(), negotiate_user->username()) != 0)) usernamehash = static_cast(usernamehash->next); if (usernamehash) { @@ -507,7 +507,7 @@ authenticateNegotiateHandleReply(void *data, void *lastserver, char *reply) * existing user or a new user */ local_auth_user->expiretime = current_time.tv_sec; authenticateNegotiateReleaseServer(negotiate_request); - negotiate_request->auth_state = AUTHENTICATE_STATE_DONE; + negotiate_request->auth_state = AUTHENTICATE_STATE_DONE; } else if (strncasecmp(reply, "NA ", 3) == 0 && arg != NULL) { /* authentication failure (wrong password, etc.) */ @@ -546,8 +546,8 @@ authenticateNegotiateHandleReply(void *data, void *lastserver, char *reply) } if (negotiate_request->request) { - HTTPMSGUNLOCK(negotiate_request->request); - negotiate_request->request = NULL; + HTTPMSGUNLOCK(negotiate_request->request); + negotiate_request->request = NULL; } r->handler(r->data, NULL); cbdataReferenceDone(r->data); @@ -621,8 +621,8 @@ authenticateNegotiateReleaseServer(AuthUserRequest * auth_user_request) /* DPW 2007-05-07 * yes, it is possible */ if (negotiate_request->authserver) { - helperStatefulReleaseServer(negotiate_request->authserver); - negotiate_request->authserver = NULL; + helperStatefulReleaseServer(negotiate_request->authserver); + negotiate_request->authserver = NULL; } } @@ -720,7 +720,7 @@ AuthNegotiateUserRequest::authenticate(HttpRequest * request, ConnStateData * co /* locate second word */ blob = proxy_auth; - if(blob) { + if (blob) { while (xisspace(*blob) && *blob) blob++; @@ -742,9 +742,9 @@ AuthNegotiateUserRequest::authenticate(HttpRequest * request, ConnStateData * co conn->auth_type = AUTH_NEGOTIATE; assert(conn->auth_user_request == NULL); conn->auth_user_request = this; - AUTHUSERREQUESTLOCK(conn->auth_user_request, "conn"); - this->request = request; - HTTPMSGLOCK(this->request); + AUTHUSERREQUESTLOCK(conn->auth_user_request, "conn"); + this->request = request; + HTTPMSGLOCK(this->request); return; break; @@ -764,18 +764,18 @@ AuthNegotiateUserRequest::authenticate(HttpRequest * request, ConnStateData * co client_blob = xstrdup (blob); - if (this->request) - HTTPMSGUNLOCK(this->request); - this->request = request; - HTTPMSGLOCK(this->request); + if (this->request) + HTTPMSGUNLOCK(this->request); + this->request = request; + HTTPMSGLOCK(this->request); return; break; case AUTHENTICATE_STATE_DONE: - fatal("AuthNegotiateUserRequest::authenticate: unexpect auth state DONE! Report a bug to the squid developers.\n"); + fatal("AuthNegotiateUserRequest::authenticate: unexpect auth state DONE! Report a bug to the squid developers.\n"); - break; + break; case AUTHENTICATE_STATE_FAILED: /* we've failed somewhere in authentication */ @@ -790,7 +790,7 @@ AuthNegotiateUserRequest::authenticate(HttpRequest * request, ConnStateData * co } AuthNegotiateUserRequest::AuthNegotiateUserRequest() : - /*conn(NULL),*/ auth_state(AUTHENTICATE_STATE_NONE), + /*conn(NULL),*/ auth_state(AUTHENTICATE_STATE_NONE), _theUser(NULL) { waiting=0; @@ -811,8 +811,8 @@ AuthNegotiateUserRequest::~AuthNegotiateUserRequest() authserver = NULL; } if (request) { - HTTPMSGUNLOCK(request); - request = NULL; + HTTPMSGUNLOCK(request); + request = NULL; } } diff --git a/src/auth/negotiate/auth_negotiate.h b/src/auth/negotiate/auth_negotiate.h index e46604afa6..8f32e78213 100644 --- a/src/auth/negotiate/auth_negotiate.h +++ b/src/auth/negotiate/auth_negotiate.h @@ -34,8 +34,7 @@ typedef enum { /* Generic */ /// \ingroup AuthNegotiateAPI -typedef struct -{ +typedef struct { void *data; AuthUserRequest *auth_user_request; RH *handler; diff --git a/src/auth/negotiate/negotiateScheme.cc b/src/auth/negotiate/negotiateScheme.cc index 5332465ccb..00ec076b42 100644 --- a/src/auth/negotiate/negotiateScheme.cc +++ b/src/auth/negotiate/negotiateScheme.cc @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/auth/negotiate/negotiateScheme.h b/src/auth/negotiate/negotiateScheme.h index d883af227b..6aae584bd2 100644 --- a/src/auth/negotiate/negotiateScheme.h +++ b/src/auth/negotiate/negotiateScheme.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -44,7 +44,7 @@ class negotiateScheme : public AuthScheme public: static AuthScheme &GetInstance(); negotiateScheme(); - virtual ~negotiateScheme(){}; + virtual ~negotiateScheme() {}; /* per scheme */ virtual char const *type () const; diff --git a/src/auth/ntlm/auth_ntlm.cc b/src/auth/ntlm/auth_ntlm.cc index edeb966d0d..d5c9ea35de 100644 --- a/src/auth/ntlm/auth_ntlm.cc +++ b/src/auth/ntlm/auth_ntlm.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -201,9 +201,9 @@ void AuthNTLMConfig::registerWithCacheManager(void) { CacheManager::GetInstance()-> - registerAction("ntlmauthenticator", - "NTLM User Authenticator Stats", - authenticateNTLMStats, 0, 1); + registerAction("ntlmauthenticator", + "NTLM User Authenticator Stats", + authenticateNTLMStats, 0, 1); } bool @@ -271,7 +271,7 @@ AuthNTLMConfig::fixHeader(AuthUserRequest *auth_user_request, HttpReply *rep, ht /* Need keep-alive */ if (!request->flags.proxy_keepalive && request->flags.must_keepalive) - return; + return; /* New request, no user details */ if (auth_user_request == NULL) { @@ -388,18 +388,18 @@ authenticateNTLMHandleReply(void *data, void *lastserver, char *reply) if (strncasecmp(reply, "TT ", 3) == 0) { /* we have been given a blob to send to the client */ safe_free(ntlm_request->server_blob); - ntlm_request->request->flags.must_keepalive = 1; - if (ntlm_request->request->flags.proxy_keepalive) { - ntlm_request->server_blob = xstrdup(blob); - ntlm_request->auth_state = AUTHENTICATE_STATE_IN_PROGRESS; - auth_user_request->denyMessage("Authentication in progress"); - debugs(29, 4, "authenticateNTLMHandleReply: Need to challenge the client with a server blob '" << blob << "'"); - result = S_HELPER_RESERVE; - } else { - ntlm_request->auth_state = AUTHENTICATE_STATE_FAILED; - auth_user_request->denyMessage("NTLM authentication requires a persistent connection"); - result = S_HELPER_RELEASE; - } + ntlm_request->request->flags.must_keepalive = 1; + if (ntlm_request->request->flags.proxy_keepalive) { + ntlm_request->server_blob = xstrdup(blob); + ntlm_request->auth_state = AUTHENTICATE_STATE_IN_PROGRESS; + auth_user_request->denyMessage("Authentication in progress"); + debugs(29, 4, "authenticateNTLMHandleReply: Need to challenge the client with a server blob '" << blob << "'"); + result = S_HELPER_RESERVE; + } else { + ntlm_request->auth_state = AUTHENTICATE_STATE_FAILED; + auth_user_request->denyMessage("NTLM authentication requires a persistent connection"); + result = S_HELPER_RELEASE; + } } else if (strncasecmp(reply, "AF ", 3) == 0) { /* we're finished, release the helper */ ntlm_user->username(blob); @@ -413,7 +413,7 @@ authenticateNTLMHandleReply(void *data, void *lastserver, char *reply) /* see if this is an existing user with a different proxy_auth * string */ auth_user_hash_pointer *usernamehash = static_cast(hash_lookup(proxy_auth_username_cache, ntlm_user->username())); - AuthUser *local_auth_user = ntlm_request->user(); + AuthUser *local_auth_user = ntlm_request->user(); while (usernamehash && (usernamehash->user()->auth_type != AUTH_NTLM || strcmp(usernamehash->user()->username(), ntlm_user->username()) != 0)) usernamehash = static_cast(usernamehash->next); if (usernamehash) { @@ -433,7 +433,7 @@ authenticateNTLMHandleReply(void *data, void *lastserver, char *reply) * existing user or a new user */ local_auth_user->expiretime = current_time.tv_sec; authenticateNTLMReleaseServer(ntlm_request); - ntlm_request->auth_state = AUTHENTICATE_STATE_DONE; + ntlm_request->auth_state = AUTHENTICATE_STATE_DONE; } else if (strncasecmp(reply, "NA ", 3) == 0) { /* authentication failure (wrong password, etc.) */ auth_user_request->denyMessage(blob); @@ -460,8 +460,8 @@ authenticateNTLMHandleReply(void *data, void *lastserver, char *reply) } if (ntlm_request->request) { - HTTPMSGUNLOCK(ntlm_request->request); - ntlm_request->request = NULL; + HTTPMSGUNLOCK(ntlm_request->request); + ntlm_request->request = NULL; } r->handler(r->data, NULL); cbdataReferenceDone(r->data); @@ -535,8 +535,8 @@ authenticateNTLMReleaseServer(AuthUserRequest * auth_user_request) * yes, it is possible */ assert(ntlm_request != NULL); if (ntlm_request->authserver) { - helperStatefulReleaseServer(ntlm_request->authserver); - ntlm_request->authserver = NULL; + helperStatefulReleaseServer(ntlm_request->authserver); + ntlm_request->authserver = NULL; } } @@ -635,7 +635,7 @@ AuthNTLMUserRequest::authenticate(HttpRequest * request, ConnStateData * conn, h blob = proxy_auth; /* if proxy_auth is actually NULL, we'd better not manipulate it. */ - if(blob) { + if (blob) { while (xisspace(*blob) && *blob) blob++; @@ -657,9 +657,9 @@ AuthNTLMUserRequest::authenticate(HttpRequest * request, ConnStateData * conn, h conn->auth_type = AUTH_NTLM; assert(conn->auth_user_request == NULL); conn->auth_user_request = this; - AUTHUSERREQUESTLOCK(conn->auth_user_request, "conn"); - this->request = request; - HTTPMSGLOCK(this->request); + AUTHUSERREQUESTLOCK(conn->auth_user_request, "conn"); + this->request = request; + HTTPMSGLOCK(this->request); return; break; @@ -679,18 +679,18 @@ AuthNTLMUserRequest::authenticate(HttpRequest * request, ConnStateData * conn, h client_blob = xstrdup (blob); - if (this->request) - HTTPMSGUNLOCK(this->request); - this->request = request; - HTTPMSGLOCK(this->request); + if (this->request) + HTTPMSGUNLOCK(this->request); + this->request = request; + HTTPMSGLOCK(this->request); return; break; case AUTHENTICATE_STATE_DONE: - fatal("AuthNTLMUserRequest::authenticate: unexpect auth state DONE! Report a bug to the squid developers.\n"); + fatal("AuthNTLMUserRequest::authenticate: unexpect auth state DONE! Report a bug to the squid developers.\n"); - break; + break; case AUTHENTICATE_STATE_FAILED: /* we've failed somewhere in authentication */ @@ -705,7 +705,7 @@ AuthNTLMUserRequest::authenticate(HttpRequest * request, ConnStateData * conn, h } AuthNTLMUserRequest::AuthNTLMUserRequest() : - /*conn(NULL),*/ auth_state(AUTHENTICATE_STATE_NONE), + /*conn(NULL),*/ auth_state(AUTHENTICATE_STATE_NONE), _theUser(NULL) { waiting=0; @@ -726,8 +726,8 @@ AuthNTLMUserRequest::~AuthNTLMUserRequest() authserver = NULL; } if (request) { - HTTPMSGUNLOCK(request); - request = NULL; + HTTPMSGUNLOCK(request); + request = NULL; } } diff --git a/src/auth/ntlm/auth_ntlm.h b/src/auth/ntlm/auth_ntlm.h index cb76a9c214..684d21f280 100644 --- a/src/auth/ntlm/auth_ntlm.h +++ b/src/auth/ntlm/auth_ntlm.h @@ -25,8 +25,7 @@ typedef enum { /* Generic */ -typedef struct -{ +typedef struct { void *data; AuthUserRequest *auth_user_request; RH *handler; diff --git a/src/auth/ntlm/ntlmScheme.cc b/src/auth/ntlm/ntlmScheme.cc index 901fbbd959..8830bf3e94 100644 --- a/src/auth/ntlm/ntlmScheme.cc +++ b/src/auth/ntlm/ntlmScheme.cc @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/auth/ntlm/ntlmScheme.h b/src/auth/ntlm/ntlmScheme.h index e73e5cf090..01d52bc79c 100644 --- a/src/auth/ntlm/ntlmScheme.h +++ b/src/auth/ntlm/ntlmScheme.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -44,7 +44,7 @@ class ntlmScheme : public AuthScheme public: static AuthScheme &GetInstance(); ntlmScheme(); - virtual ~ntlmScheme(){}; + virtual ~ntlmScheme() {}; /* per scheme */ virtual char const *type () const; diff --git a/src/authenticate.cc b/src/authenticate.cc index 6e4d4143d8..35f75bd74c 100644 --- a/src/authenticate.cc +++ b/src/authenticate.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/authenticate.h b/src/authenticate.h index c74ba2d663..65f79d7a9b 100644 --- a/src/authenticate.h +++ b/src/authenticate.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -46,8 +46,7 @@ class AuthUser; * \todo Inheritance in a struct? this should be a class. */ -struct AuthUserHashPointer : public hash_link -{ +struct AuthUserHashPointer : public hash_link { /* first two items must be same as hash_link */ public: diff --git a/src/cache_cf.cc b/src/cache_cf.cc index ad85e549ea..1034576d65 100644 --- a/src/cache_cf.cc +++ b/src/cache_cf.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -231,20 +231,20 @@ parseManyConfigFiles(char* files, int depth) int i; memset(&globbuf, 0, sizeof(globbuf)); for (path = strwordtok(files, &saveptr); path; path = strwordtok(NULL, &saveptr)) { - if (glob(path, globbuf.gl_pathc ? GLOB_APPEND : 0, NULL, &globbuf) != 0) { - fatalf("Unable to find configuration file: %s: %s", - path, xstrerror()); - } - } + if (glob(path, globbuf.gl_pathc ? GLOB_APPEND : 0, NULL, &globbuf) != 0) { + fatalf("Unable to find configuration file: %s: %s", + path, xstrerror()); + } + } for (i = 0; i < (int)globbuf.gl_pathc; i++) { - error_count += parseOneConfigFile(globbuf.gl_pathv[i], depth); + error_count += parseOneConfigFile(globbuf.gl_pathv[i], depth); } globfree(&globbuf); #else char* file = strwordtok(files, &saveptr); while (file != NULL) { - error_count += parseOneConfigFile(file, depth); - file = strwordtok(NULL, &saveptr); + error_count += parseOneConfigFile(file, depth); + file = strwordtok(NULL, &saveptr); } #endif /* HAVE_GLOB */ return error_count; @@ -351,13 +351,13 @@ parseOneConfigFile(const char *file_name, unsigned int depth) debugs(3, 5, "Processing: '" << tmp_line << "'"); - /* Handle includes here */ + /* Handle includes here */ if (tmp_line_len >= 9 && strncmp(tmp_line, "include", 7) == 0 && xisspace(tmp_line[7])) { err_count += parseManyConfigFiles(tmp_line + 8, depth + 1); - } else if (!parse_line(tmp_line)) { + } else if (!parse_line(tmp_line)) { debugs(3, 0, HERE << cfg_filename << ":" << config_lineno << " unrecognized: '" << tmp_line << "'"); - err_count++; - } + err_count++; + } safe_free(tmp_line); tmp_line_len = 0; @@ -409,9 +409,9 @@ parseConfigFile(const char *file_name) if (opt_send_signal == -1) { manager->registerAction("config", - "Current Squid Configuration", - dump_config, - 1, 1); + "Current Squid Configuration", + dump_config, + 1, 1); } return err_count; @@ -428,8 +428,8 @@ configDoConfigure(void) #if SIZEOF_OFF_T <= 4 if (Config.Store.maxObjectSize > 0x7FFF0000) { - debugs(3, 0, "WARNING: This Squid binary can not handle files larger than 2GB. Limiting maximum_object_size to just below 2GB"); - Config.Store.maxObjectSize = 0x7FFF0000; + debugs(3, 0, "WARNING: This Squid binary can not handle files larger than 2GB. Limiting maximum_object_size to just below 2GB"); + Config.Store.maxObjectSize = 0x7FFF0000; } #endif if (0 == Store::Root().maxSize()) @@ -520,7 +520,7 @@ configDoConfigure(void) requirePathnameExists("Icon Directory", Config.icons.directory); - if(Config.errorDirectory) + if (Config.errorDirectory) requirePathnameExists("Error Directory", Config.errorDirectory); #if HTTP_VIOLATIONS @@ -528,8 +528,7 @@ configDoConfigure(void) { const refresh_t *R; - for (R = Config.Refresh; R; R = R->next) - { + for (R = Config.Refresh; R; R = R->next) { if (!R->flags.override_expire) continue; @@ -538,8 +537,7 @@ configDoConfigure(void) break; } - for (R = Config.Refresh; R; R = R->next) - { + for (R = Config.Refresh; R; R = R->next) { if (!R->flags.override_lastmod) continue; @@ -548,8 +546,7 @@ configDoConfigure(void) break; } - for (R = Config.Refresh; R; R = R->next) - { + for (R = Config.Refresh; R; R = R->next) { if (!R->flags.reload_into_ims) continue; @@ -558,8 +555,7 @@ configDoConfigure(void) break; } - for (R = Config.Refresh; R; R = R->next) - { + for (R = Config.Refresh; R; R = R->next) { if (!R->flags.ignore_reload) continue; @@ -568,8 +564,7 @@ configDoConfigure(void) break; } - for (R = Config.Refresh; R; R = R->next) - { + for (R = Config.Refresh; R; R = R->next) { if (!R->flags.ignore_no_cache) continue; @@ -578,8 +573,7 @@ configDoConfigure(void) break; } - for (R = Config.Refresh; R; R = R->next) - { + for (R = Config.Refresh; R; R = R->next) { if (!R->flags.ignore_no_store) continue; @@ -588,8 +582,7 @@ configDoConfigure(void) break; } - for (R = Config.Refresh; R; R = R->next) - { + for (R = Config.Refresh; R; R = R->next) { if (!R->flags.ignore_private) continue; @@ -598,8 +591,7 @@ configDoConfigure(void) break; } - for (R = Config.Refresh; R; R = R->next) - { + for (R = Config.Refresh; R; R = R->next) { if (!R->flags.ignore_auth) continue; @@ -748,9 +740,9 @@ parseTimeLine(time_t * tptr, const char *units) if (0 == d) (void) 0; else if ((token = strtok(NULL, w_space)) == NULL) - debugs(3, 0, "WARNING: No units on '" << - config_input_line << "', assuming " << - d << " " << units ); + debugs(3, 0, "WARNING: No units on '" << + config_input_line << "', assuming " << + d << " " << units ); else if ((m = parseTimeUnits(token)) == 0) self_destruct(); @@ -822,9 +814,9 @@ parseBytesLine64(int64_t * bptr, const char *units) if (0.0 == d) (void) 0; else if ((token = strtok(NULL, w_space)) == NULL) - debugs(3, 0, "WARNING: No units on '" << - config_input_line << "', assuming " << - d << " " << units ); + debugs(3, 0, "WARNING: No units on '" << + config_input_line << "', assuming " << + d << " " << units ); else if ((m = parseBytesUnits(token)) == 0) { self_destruct(); return; @@ -867,9 +859,9 @@ parseBytesLine(size_t * bptr, const char *units) if (0.0 == d) (void) 0; else if ((token = strtok(NULL, w_space)) == NULL) - debugs(3, 0, "WARNING: No units on '" << - config_input_line << "', assuming " << - d << " " << units ); + debugs(3, 0, "WARNING: No units on '" << + config_input_line << "', assuming " << + d << " " << units ); else if ((m = parseBytesUnits(token)) == 0) { self_destruct(); return; @@ -998,17 +990,13 @@ parse_address(IPAddress *addr) return; } - if (!strcmp(token,"any_addr")) - { + if (!strcmp(token,"any_addr")) { addr->SetAnyAddr(); - (void) 0; - } - else if ( (!strcmp(token,"no_addr")) || (!strcmp(token,"full_mask")) ) - { + (void) 0; + } else if ( (!strcmp(token,"no_addr")) || (!strcmp(token,"full_mask")) ) { addr->SetNoAddr(); - (void) 0; - } - else + (void) 0; + } else *addr = token; } @@ -1399,7 +1387,7 @@ dump_cachedir(StoreEntry * entry, const char *name, SquidConfig::_cacheSwap swap for (i = 0; i < swap.n_configured; i++) { s = dynamic_cast(swap.swapDirs[i].getRaw()); - if(!s) continue; + if (!s) continue; storeAppendPrintf(entry, "%s %s %s", name, s->type(), s->path); s->dump(*entry); storeAppendPrintf(entry, "\n"); @@ -1505,7 +1493,7 @@ parse_cachedir(SquidConfig::_cacheSwap * swap) if ((strcasecmp(path_str, dynamic_cast(swap->swapDirs[i].getRaw())->path) ) == 0) { /* this is specific to on-fs Stores. The right - * way to handle this is probably to have a mapping + * way to handle this is probably to have a mapping * from paths to stores, and have on-fs stores * register with that, and lookip in that in their * own setup logic. RBC 20041225. TODO. @@ -1622,8 +1610,8 @@ GetService(const char *proto) /** Parses a port number or service name from the squid.conf */ char *token = strtok(NULL, w_space); if (token == NULL) { - self_destruct(); - return 0; /* NEVER REACHED */ + self_destruct(); + return 0; /* NEVER REACHED */ } /** Returns either the service port number from /etc/services */ port = getservbyname(token, proto); @@ -1671,7 +1659,7 @@ parse_peer(peer ** head) self_destruct(); p->host = xstrdup(token); - + p->name = xstrdup(token); if ((token = strtok(NULL, w_space)) == NULL) @@ -1732,7 +1720,7 @@ parse_peer(peer ** head) p->options.htcp_oldsquid = 1; } else if (!strcasecmp(token, "htcp-no-clr")) { if (p->options.htcp_only_clr) - fatalf("parse_peer: can't set htcp-no-clr and htcp-only-clr simultaneously"); + fatalf("parse_peer: can't set htcp-no-clr and htcp-only-clr simultaneously"); p->options.htcp = 1; p->options.htcp_no_clr = 1; } else if (!strcasecmp(token, "htcp-no-purge-clr")) { @@ -1740,7 +1728,7 @@ parse_peer(peer ** head) p->options.htcp_no_purge_clr = 1; } else if (!strcasecmp(token, "htcp-only-clr")) { if (p->options.htcp_no_clr) - fatalf("parse_peer: can't set htcp-no-clr and htcp-only-clr simultaneously"); + fatalf("parse_peer: can't set htcp-no-clr and htcp-only-clr simultaneously"); p->options.htcp = 1; p->options.htcp_only_clr = 1; } else if (!strcasecmp(token, "htcp-forward-clr")) { @@ -1844,7 +1832,7 @@ parse_peer(peer ** head) p->front_end_https = 1; } else if (strcmp(token, "front-end-https=auto") == 0) { p->front_end_https = 2; - }else if (strcmp(token, "connection-auth=off") == 0) { + } else if (strcmp(token, "connection-auth=off") == 0) { p->connection_auth = 0; } else if (strcmp(token, "connection-auth") == 0) { p->connection_auth = 1; @@ -2320,7 +2308,7 @@ parse_refreshpattern(refresh_t ** head) #endif } else - debugs(22, 0, "redreshAddToList: Unknown option '" << pattern << "': " << token); + debugs(22, 0, "redreshAddToList: Unknown option '" << pattern << "': " << token); } if ((errcode = regcomp(&comp, pattern, flags)) != 0) { @@ -2778,30 +2766,30 @@ parse_IPAddress_list_token(IPAddress_list ** head, char *token) #if USE_IPV6 if (*token == '[') { /* [host]:port */ - host = token + 1; - t = strchr(host, ']'); - if (!t) - self_destruct(); - *t++ = '\0'; - if (*t != ':') - self_destruct(); - port = xatos(t + 1); + host = token + 1; + t = strchr(host, ']'); + if (!t) + self_destruct(); + *t++ = '\0'; + if (*t != ':') + self_destruct(); + port = xatos(t + 1); } else #endif - if ((t = strchr(token, ':'))) { - /* host:port */ - host = token; - *t = '\0'; - port = xatos(t + 1); - - if (0 == port) - self_destruct(); - } else if ((port = strtol(token, &tmp, 10)), !*tmp) { - /* port */ - } else { - host = token; - port = 0; - } + if ((t = strchr(token, ':'))) { + /* host:port */ + host = token; + *t = '\0'; + port = xatos(t + 1); + + if (0 == port) + self_destruct(); + } else if ((port = strtol(token, &tmp, 10)), !*tmp) { + /* port */ + } else { + host = token; + port = 0; + } if (NULL == host) ipa.SetAnyAddr(); @@ -2848,7 +2836,8 @@ dump_IPAddress_list(StoreEntry * e, const char *n, const IPAddress_list * s) static void free_IPAddress_list(IPAddress_list ** head) { - if(*head) delete *head; *head = NULL; + if (*head) delete *head; + *head = NULL; } #if CURRENTLY_UNUSED @@ -2881,34 +2870,34 @@ parse_http_port_specification(http_port_list * s, char *token) #if USE_IPV6 if (*token == '[') { /* [ipv6]:port */ - host = token + 1; - t = strchr(host, ']'); - if (!t) { + host = token + 1; + t = strchr(host, ']'); + if (!t) { debugs(3, 0, "http(s)_port: missing ']' on IPv6 address: " << token); - self_destruct(); + self_destruct(); } - *t++ = '\0'; - if (*t != ':') { + *t++ = '\0'; + if (*t != ':') { debugs(3, 0, "http(s)_port: missing Port in: " << token); - self_destruct(); + self_destruct(); } - port = xatos(t + 1); + port = xatos(t + 1); } else #endif - if ((t = strchr(token, ':'))) { - /* host:port */ - /* ipv4:port */ - host = token; - *t = '\0'; - port = xatos(t + 1); - - } else if ((port = strtol(token, &junk, 10)), !*junk) { - /* port */ - debugs(3, 3, "http(s)_port: found Listen on Port: " << port); - } else { - debugs(3, 0, "http(s)_port: missing Port: " << token); - self_destruct(); - } + if ((t = strchr(token, ':'))) { + /* host:port */ + /* ipv4:port */ + host = token; + *t = '\0'; + port = xatos(t + 1); + + } else if ((port = strtol(token, &junk, 10)), !*junk) { + /* port */ + debugs(3, 3, "http(s)_port: found Listen on Port: " << port); + } else { + debugs(3, 0, "http(s)_port: missing Port: " << token); + self_destruct(); + } if (port == 0) { debugs(3, 0, "http(s)_port: Port cannot be 0: " << token); @@ -2919,18 +2908,15 @@ parse_http_port_specification(http_port_list * s, char *token) s->s.SetAnyAddr(); s->s.SetPort(port); debugs(3, 3, "http(s)_port: found Listen on wildcard address: " << s->s); - } - else if ( s->s = host ) { /* check/parse numeric IPA */ + } else if ( s->s = host ) { /* check/parse numeric IPA */ s->s.SetPort(port); debugs(3, 3, "http(s)_port: Listen on Host/IP: " << host << " --> " << s->s); - } - else if ( s->s.GetHostByName(host) ) { /* check/parse for FQDN */ + } else if ( s->s.GetHostByName(host) ) { /* check/parse for FQDN */ /* dont use ipcache */ s->defaultsite = xstrdup(host); s->s.SetPort(port); debugs(3, 3, "http(s)_port: found Listen as Host " << s->defaultsite << " on IP: " << s->s); - } - else { + } else { debugs(3, 0, "http(s)_port: failed to resolve Host/IP: " << host); self_destruct(); } @@ -2963,11 +2949,11 @@ parse_http_port_option(http_port_list * s, char *token) } else if (strcmp(token, "no-connection-auth") == 0) { s->connection_auth_disabled = true; } else if (strcmp(token, "connection-auth=off") == 0) { - s->connection_auth_disabled = true; + s->connection_auth_disabled = true; } else if (strcmp(token, "connection-auth") == 0) { - s->connection_auth_disabled = false; + s->connection_auth_disabled = false; } else if (strcmp(token, "connection-auth=on") == 0) { - s->connection_auth_disabled = false; + s->connection_auth_disabled = false; } else if (strncmp(token, "disable-pmtu-discovery=", 23) == 0) { if (!strcasecmp(token + 23, "off")) s->disable_pmtu_discovery = DISABLE_PMTU_OFF; @@ -2988,13 +2974,13 @@ parse_http_port_option(http_port_list * s, char *token) #if USE_IPV6 /* INET6: until transparent REDIRECT works on IPv6 SOCKET, force wildcard to IPv4 */ debugs(3, DBG_IMPORTANT, "Disabling IPv6 on port " << s->s << " (interception enabled)"); - if( !s->s.SetIPv4() ) { + if ( !s->s.SetIPv4() ) { debugs(3, DBG_CRITICAL, "http(s)_port: IPv6 addresses cannot be transparent (protocol does not provide NAT)" << s->s ); self_destruct(); } #endif } else if (strcmp(token, "tproxy") == 0) { - if(s->intercepted || s->accel) { + if (s->intercepted || s->accel) { debugs(3,DBG_CRITICAL, "http(s)_port: TPROXY option requires its own interception port. It cannot be shared."); self_destruct(); } @@ -3007,7 +2993,7 @@ parse_http_port_option(http_port_list * s, char *token) #if USE_IPV6 /* INET6: until target TPROXY is known to work on IPv6 SOCKET, force wildcard to IPv4 */ debugs(3, DBG_IMPORTANT, "Disabling IPv6 on port " << s->s << " (interception enabled)"); - if( s->s.IsIPv6() && !s->s.SetIPv4() ) { + if ( s->s.IsIPv6() && !s->s.SetIPv4() ) { debugs(3, DBG_CRITICAL, "http(s)_port: IPv6 addresses cannot be transparent (protocol does not provide NAT)" << s->s ); self_destruct(); } @@ -3015,28 +3001,28 @@ parse_http_port_option(http_port_list * s, char *token) } else if (strcmp(token, "ipv4") == 0) { #if USE_IPV6 - if( !s->s.SetIPv4() ) { + if ( !s->s.SetIPv4() ) { debugs(3, 0, "http(s)_port: IPv6 addresses cannot be used a IPv4-Only." << s->s ); self_destruct(); } #endif - }else if (strcmp(token, "tcpkeepalive") == 0) { - s->tcp_keepalive.enabled = 1; + } else if (strcmp(token, "tcpkeepalive") == 0) { + s->tcp_keepalive.enabled = 1; } else if (strncmp(token, "tcpkeepalive=", 13) == 0) { - char *t = token + 13; - s->tcp_keepalive.enabled = 1; - s->tcp_keepalive.idle = atoi(t); - t = strchr(t, ','); - if (t) { - t++; - s->tcp_keepalive.interval = atoi(t); - t = strchr(t, ','); - } - if (t) { - t++; - s->tcp_keepalive.timeout = atoi(t); - t = strchr(t, ','); - } + char *t = token + 13; + s->tcp_keepalive.enabled = 1; + s->tcp_keepalive.idle = atoi(t); + t = strchr(t, ','); + if (t) { + t++; + s->tcp_keepalive.interval = atoi(t); + t = strchr(t, ','); + } + if (t) { + t++; + s->tcp_keepalive.timeout = atoi(t); + t = strchr(t, ','); + } #if USE_SSL } else if (strncmp(token, "cert=", 5) == 0) { safe_free(s->cert); @@ -3083,7 +3069,7 @@ parse_http_port_option(http_port_list * s, char *token) self_destruct(); } - if( s->spoof_client_ip && (s->intercepted || s->accel) ) { + if ( s->spoof_client_ip && (s->intercepted || s->accel) ) { debugs(3,DBG_CRITICAL, "http(s)_port: TPROXY option requires its own interception port. It cannot be shared."); self_destruct(); } @@ -3166,49 +3152,49 @@ dump_generic_http_port(StoreEntry * e, const char *n, const http_port_list * s) } if (s->tcp_keepalive.enabled) { - if (s->tcp_keepalive.idle || s->tcp_keepalive.interval || s->tcp_keepalive.timeout) { - storeAppendPrintf(e, " tcp_keepalive=%d,%d,%d", s->tcp_keepalive.idle, s->tcp_keepalive.interval, s->tcp_keepalive.timeout); - } else { - storeAppendPrintf(e, " tcp_keepalive"); - } + if (s->tcp_keepalive.idle || s->tcp_keepalive.interval || s->tcp_keepalive.timeout) { + storeAppendPrintf(e, " tcp_keepalive=%d,%d,%d", s->tcp_keepalive.idle, s->tcp_keepalive.interval, s->tcp_keepalive.timeout); + } else { + storeAppendPrintf(e, " tcp_keepalive"); + } } #if USE_SSL - if (s->cert) - storeAppendPrintf(e, " cert=%s", s->cert); + if (s->cert) + storeAppendPrintf(e, " cert=%s", s->cert); - if (s->key) - storeAppendPrintf(e, " key=%s", s->key); + if (s->key) + storeAppendPrintf(e, " key=%s", s->key); - if (s->version) - storeAppendPrintf(e, " version=%d", s->version); + if (s->version) + storeAppendPrintf(e, " version=%d", s->version); - if (s->options) - storeAppendPrintf(e, " options=%s", s->options); + if (s->options) + storeAppendPrintf(e, " options=%s", s->options); - if (s->cipher) - storeAppendPrintf(e, " cipher=%s", s->cipher); + if (s->cipher) + storeAppendPrintf(e, " cipher=%s", s->cipher); - if (s->cafile) - storeAppendPrintf(e, " cafile=%s", s->cafile); + if (s->cafile) + storeAppendPrintf(e, " cafile=%s", s->cafile); - if (s->capath) - storeAppendPrintf(e, " capath=%s", s->capath); + if (s->capath) + storeAppendPrintf(e, " capath=%s", s->capath); - if (s->crlfile) - storeAppendPrintf(e, " crlfile=%s", s->crlfile); + if (s->crlfile) + storeAppendPrintf(e, " crlfile=%s", s->crlfile); - if (s->dhfile) - storeAppendPrintf(e, " dhparams=%s", s->dhfile); + if (s->dhfile) + storeAppendPrintf(e, " dhparams=%s", s->dhfile); - if (s->sslflags) - storeAppendPrintf(e, " sslflags=%s", s->sslflags); + if (s->sslflags) + storeAppendPrintf(e, " sslflags=%s", s->sslflags); - if (s->sslcontext) - storeAppendPrintf(e, " sslcontext=%s", s->sslcontext); + if (s->sslcontext) + storeAppendPrintf(e, " sslcontext=%s", s->sslcontext); - if (s->sslBump) - storeAppendPrintf(e, " sslBump"); + if (s->sslBump) + storeAppendPrintf(e, " sslBump"); #endif } @@ -3542,7 +3528,7 @@ static void parse_icap_class_type() { debugs(93, 0, "WARNING: 'icap_class' is depricated. " << - "Use 'adaptation_service_set' instead"); + "Use 'adaptation_service_set' instead"); Adaptation::Config::ParseServiceSet(); } @@ -3550,7 +3536,7 @@ static void parse_icap_access_type() { debugs(93, 0, "WARNING: 'icap_access' is depricated. " << - "Use 'adaptation_access' instead"); + "Use 'adaptation_access' instead"); Adaptation::Config::ParseAccess(LegacyParser); } diff --git a/src/cache_diff.cc b/src/cache_diff.cc index 95eed12418..c8ef339f94 100644 --- a/src/cache_diff.cc +++ b/src/cache_diff.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -40,8 +40,7 @@ #include "squid.h" -typedef struct -{ +typedef struct { const char *name; hash_table *hash; int count; /* #currently cached entries */ @@ -51,8 +50,7 @@ typedef struct } CacheIndex; -typedef struct _CacheEntry -{ +typedef struct _CacheEntry { const cache_key *key; struct _CacheEntry *next; @@ -62,17 +60,16 @@ typedef struct _CacheEntry /* copied from url.c */ -const char *RequestMethodStr[] = - { - "NONE", - "GET", - "POST", - "PUT", - "HEAD", - "CONNECT", - "TRACE", - "PURGE" - }; +const char *RequestMethodStr[] = { + "NONE", + "GET", + "POST", + "PUT", + "HEAD", + "CONNECT", + "TRACE", + "PURGE" +}; static int cacheIndexScan(CacheIndex * idx, const char *fname, FILE * file); diff --git a/src/cache_manager.cc b/src/cache_manager.cc index f983ae7684..5f2609367a 100644 --- a/src/cache_manager.cc +++ b/src/cache_manager.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -79,7 +79,7 @@ CacheManager::registerAction(char const * action, char const * desc, OBJH * hand /** \ingroup CacheManagerAPI - * Registers a C++-style action, via a poiner to a subclass of + * Registers a C++-style action, via a poiner to a subclass of * a CacheManagerAction object, whose run() method will be invoked when * CacheManager identifies that the user has requested the action. */ @@ -299,14 +299,14 @@ CacheManager::Start(int fd, HttpRequest * request, StoreEntry * entry) /* warn if user specified incorrect password */ if (mgr->passwd) - debugs(16, DBG_IMPORTANT, "CacheManager: " << - (mgr->user_name ? mgr->user_name : "") << "@" << - fd_table[fd].ipaddr << ": incorrect password for '" << + debugs(16, DBG_IMPORTANT, "CacheManager: " << + (mgr->user_name ? mgr->user_name : "") << "@" << + fd_table[fd].ipaddr << ": incorrect password for '" << mgr->action << "'" ); else - debugs(16, DBG_IMPORTANT, "CacheManager: " << - (mgr->user_name ? mgr->user_name : "") << "@" << - fd_table[fd].ipaddr << ": password needed for '" << + debugs(16, DBG_IMPORTANT, "CacheManager: " << + (mgr->user_name ? mgr->user_name : "") << "@" << + fd_table[fd].ipaddr << ": password needed for '" << mgr->action << "'" ); rep = err->BuildHttpReply(); @@ -331,9 +331,9 @@ CacheManager::Start(int fd, HttpRequest * request, StoreEntry * entry) return; } - debugs(16, DBG_IMPORTANT, "CacheManager: " << - (mgr->user_name ? mgr->user_name : "") << "@" << - fd_table[fd].ipaddr << " requesting '" << + debugs(16, DBG_IMPORTANT, "CacheManager: " << + (mgr->user_name ? mgr->user_name : "") << "@" << + fd_table[fd].ipaddr << " requesting '" << mgr->action << "'" ); /* retrieve object requested */ a = findAction(mgr->action); @@ -431,7 +431,7 @@ CacheManager::MenuAction::run(StoreEntry * sentry) for (a = cmgr->ActionsList.begin(); a != cmgr->ActionsList.end(); ++a) { debugs(16, 5, " showing action " << (*a)->action); storeAppendPrintf(sentry, " %-22s\t%-32s\t%s\n", - (*a)->action, (*a)->desc, cmgr->ActionProtection(*a)); + (*a)->action, (*a)->desc, cmgr->ActionProtection(*a)); } } /// \ingroup CacheManagerInternal @@ -469,19 +469,20 @@ CacheManager* CacheManager::instance=0; * Singleton accessor method. */ CacheManager* -CacheManager::GetInstance() { - if (instance == 0) { - debugs(16, 6, "CacheManager::GetInstance: starting cachemanager up"); - instance = new CacheManager; - } - return instance; +CacheManager::GetInstance() +{ + if (instance == 0) { + debugs(16, 6, "CacheManager::GetInstance: starting cachemanager up"); + instance = new CacheManager; + } + return instance; } /// \ingroup CacheManagerInternal void CacheManagerActionLegacy::run(StoreEntry *sentry) { - handler(sentry); + handler(sentry); } /// \ingroup CacheManagerInternal CacheManagerAction::CacheManagerAction(char const *anAction, char const *aDesc, unsigned int isPwReq, unsigned int isAtomic) diff --git a/src/carp.cc b/src/carp.cc index ab49036d31..e6e36b6513 100644 --- a/src/carp.cc +++ b/src/carp.cc @@ -22,12 +22,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -56,7 +56,7 @@ static void carpRegisterWithCacheManager(void) { CacheManager::GetInstance()-> - registerAction("carp", "CARP information", carpCachemgr, 0, 1); + registerAction("carp", "CARP information", carpCachemgr, 0, 1); } void @@ -192,7 +192,7 @@ carpSelectParent(HttpRequest * request) combined_hash += combined_hash * 0x62531965; combined_hash = ROTATE_LEFT(combined_hash, 21); score = combined_hash * tp->carp.load_multiplier; - debugs(39, 3, "carpSelectParent: " << tp->name << " combined_hash " << combined_hash << + debugs(39, 3, "carpSelectParent: " << tp->name << " combined_hash " << combined_hash << " score " << std::setprecision(0) << score); if ((score > high_score) && peerHTTPOkay(tp, request)) { diff --git a/src/cbdata.cc b/src/cbdata.cc index 462354d74c..5fba1c7685 100644 --- a/src/cbdata.cc +++ b/src/cbdata.cc @@ -23,12 +23,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -71,7 +71,7 @@ class CBDataCall { public: - CBDataCall (char const *callLabel, char const *aFile, int aLine) : label(callLabel), file(aFile), line(aLine){} + CBDataCall (char const *callLabel, char const *aFile, int aLine) : label(callLabel), file(aFile), line(aLine) {} char const *label; char const *file; @@ -111,8 +111,7 @@ public: cbdata_type type; #if CBDATA_DEBUG - void addHistory(char const *label, char const *file, int line) - { + void addHistory(char const *label, char const *file, int line) { if (calls.size() > 1000) return; @@ -179,8 +178,7 @@ static OBJH cbdataDumpHistory; #endif /// \ingroup CBDATAInternal -struct CBDataIndex -{ +struct CBDataIndex { MemAllocator *pool; FREE *free_func; } @@ -253,7 +251,7 @@ cbdataInternalInitType(cbdata_type type, const char *name, int size, FREE * free #if HASHED_CBDATA if (!cbdata_htable) - cbdata_htable = hash_create(cbdata_cmp, 1 << 12, cbdata_hash); + cbdata_htable = hash_create(cbdata_cmp, 1 << 12, cbdata_hash); #endif } @@ -368,10 +366,10 @@ cbdataInternalFree(void *p) #endif /* This is ugly. But: operator delete doesn't get - * the type parameter, so we can't use that + * the type parameter, so we can't use that * to free the memory. * So, we free it ourselves. - * Note that this means a non-placement + * Note that this means a non-placement * new would be a seriously bad idea. * Lastly, if we where a templated class, * we could use the normal delete operator @@ -478,10 +476,10 @@ cbdataInternalUnlock(const void *p) #endif /* This is ugly. But: operator delete doesn't get - * the type parameter, so we can't use that + * the type parameter, so we can't use that * to free the memory. * So, we free it ourselves. - * Note that this means a non-placement + * Note that this means a non-placement * new would be a seriously bad idea. * Lastly, if we where a templated class, * we could use the normal delete operator @@ -561,12 +559,10 @@ cbdata::dump(StoreEntry *sentry) const '!', p, type, locks, file, line); } -struct CBDataDumper : public unary_function -{ - CBDataDumper(StoreEntry *anEntry):where(anEntry){} +struct CBDataDumper : public unary_function { + CBDataDumper(StoreEntry *anEntry):where(anEntry) {} - void operator()(cbdata const &x) - { + void operator()(cbdata const &x) { x.dump(where); } @@ -612,24 +608,20 @@ CBDATA_CLASS_INIT(generic_cbdata); #if CBDATA_DEBUG -struct CBDataCallDumper : public unary_function -{ - CBDataCallDumper (StoreEntry *anEntry):where(anEntry){} +struct CBDataCallDumper : public unary_function { + CBDataCallDumper (StoreEntry *anEntry):where(anEntry) {} - void operator()(CBDataCall const &x) - { + void operator()(CBDataCall const &x) { storeAppendPrintf(where, "%s\t%s\t%d\n", x.label, x.file, x.line); } StoreEntry *where; }; -struct CBDataHistoryDumper : public CBDataDumper -{ - CBDataHistoryDumper(StoreEntry *anEntry):CBDataDumper(anEntry),where(anEntry), callDumper(anEntry){} +struct CBDataHistoryDumper : public CBDataDumper { + CBDataHistoryDumper(StoreEntry *anEntry):CBDataDumper(anEntry),where(anEntry), callDumper(anEntry) {} - void operator()(cbdata const &x) - { + void operator()(cbdata const &x) { CBDataDumper::operator()(x); storeAppendPrintf(where, "\n"); storeAppendPrintf(where, "Action\tFile\tLine\n"); diff --git a/src/cbdata.h b/src/cbdata.h index 6a9eb4f750..4b26606ce7 100644 --- a/src/cbdata.h +++ b/src/cbdata.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -409,7 +409,7 @@ extern cbdata_type cbdataInternalAddType(cbdata_type type, const char *label, in /** \ingroup CBDATAAPI - * + * * Initializes the cbdatatype. Must be called prior to the first use of cbdataAlloc() for the type. * \par @@ -421,7 +421,7 @@ extern cbdata_type cbdataInternalAddType(cbdata_type type, const char *label, in /** \ingroup CBDATAAPI - * + * * Initializes the cbdatatype. Must be called prior to the first use of cbdataAlloc() for the type. * \par @@ -441,15 +441,14 @@ extern cbdata_type cbdataInternalAddType(cbdata_type type, const char *label, in */ class generic_cbdata { - public: +public: generic_cbdata(void * data) : data(data) {} - templatevoid unwrap(wrapped_type **output) - { - *output = static_cast(data); - delete this; - } + templatevoid unwrap(wrapped_type **output) { + *output = static_cast(data); + delete this; + } /** * The wrapped data - only public to allow the mild abuse of this facility @@ -459,7 +458,7 @@ class generic_cbdata \todo CODE: make this a private field. */ void *data; /* the wrapped data */ - private: +private: CBDATA_CLASS2(generic_cbdata); }; diff --git a/src/cf_gen.cc b/src/cf_gen.cc index af83cc316b..587f7c74a7 100644 --- a/src/cf_gen.cc +++ b/src/cf_gen.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -65,22 +65,19 @@ enum State { sEXIT }; -typedef struct Line -{ +typedef struct Line { char *data; struct Line *next; } Line; -typedef struct EntryAlias -{ +typedef struct EntryAlias { struct EntryAlias *next; char *name; } EntryAlias; -typedef struct Entry -{ +typedef struct Entry { char *name; EntryAlias *alias; char *type; @@ -96,15 +93,13 @@ typedef struct Entry struct Entry *next; } Entry; -typedef struct TypeDep -{ +typedef struct TypeDep { char *name; TypeDep *next; } TypeDep; -typedef struct Type -{ +typedef struct Type { char *name; TypeDep *depend; @@ -138,21 +133,21 @@ checkDepend(const char *directive, const char *name, const Type *types, const En { const Type *type; for (type = types; type; type = type->next) { - const TypeDep *dep; - if (strcmp(type->name, name) != 0) - continue; - for (dep = type->depend; dep; dep = dep->next) { - const Entry *entry; - for (entry = entries; entry; entry = entry->next) { - if (strcmp(entry->name, dep->name) == 0) - break; - } - if (!entry) { - fprintf(stderr, "ERROR: '%s' (%s) depends on '%s'\n", directive, name, dep->name); - exit(1); - } - } - return; + const TypeDep *dep; + if (strcmp(type->name, name) != 0) + continue; + for (dep = type->depend; dep; dep = dep->next) { + const Entry *entry; + for (entry = entries; entry; entry = entry->next) { + if (strcmp(entry->name, dep->name) == 0) + break; + } + if (!entry) { + fprintf(stderr, "ERROR: '%s' (%s) depends on '%s'\n", directive, name, dep->name); + exit(1); + } + } + return; } fprintf(stderr, "ERROR: Dependencies for cf.data type '%s' used in '%s' not defined\n", name, directive); exit(1); @@ -192,20 +187,20 @@ main(int argc, char *argv[]) } while ((NULL != fgets(buff, MAX_LINE, fp))) { - const char *type = strtok(buff, WS); - const char *dep; - if (!type || type[0] == '#') - continue; - Type *t = (Type *)xcalloc(1, sizeof(*t)); - t->name = xstrdup(type); - while ((dep = strtok(NULL, WS)) != NULL) { - TypeDep *d = (TypeDep *)xcalloc(1, sizeof(*d)); - d->name = xstrdup(dep); - d->next = t->depend; - t->depend = d; - } - t->next = types; - types = t; + const char *type = strtok(buff, WS); + const char *dep; + if (!type || type[0] == '#') + continue; + Type *t = (Type *)xcalloc(1, sizeof(*t)); + t->name = xstrdup(type); + while ((dep = strtok(NULL, WS)) != NULL) { + TypeDep *d = (TypeDep *)xcalloc(1, sizeof(*d)); + d->name = xstrdup(dep); + d->next = t->depend; + t->depend = d; + } + t->next = types; + types = t; } fclose(fp); @@ -324,7 +319,7 @@ main(int argc, char *argv[]) *(ptr + strlen(ptr) - 2) = '\0'; } - checkDepend(curr->name, ptr, types, entries); + checkDepend(curr->name, ptr, types, entries); curr->type = xstrdup(ptr); } else if (!strncmp(buff, "IFDEF:", 6)) { if ((ptr = strtok(buff + 6, WS)) == NULL) { @@ -781,7 +776,7 @@ gen_conf(Entry * head, FILE * fp) for (entry = head; entry != NULL; entry = entry->next) { Line *line; int blank = 1; - int enabled = 1; + int enabled = 1; if (!strcmp(entry->name, "comment")) (void) 0; @@ -796,7 +791,7 @@ gen_conf(Entry * head, FILE * fp) if (!defined(entry->ifdef)) { fprintf(fp, "# Note: This option is only available if Squid is rebuilt with the\n"); fprintf(fp, "# %s\n#\n", available_if(entry->ifdef)); - enabled = 0; + enabled = 0; } for (line = entry->doc; line != NULL; line = line->next) { @@ -843,10 +838,10 @@ gen_conf(Entry * head, FILE * fp) fprintf(fp, "#\n"); for (line = entry->nocomment; line != NULL; line = line->next) { - if (!enabled && line->data[0] != '#') - fprintf(fp, "#%s\n", line->data); - else - fprintf(fp, "%s\n", line->data); + if (!enabled && line->data[0] != '#') + fprintf(fp, "#%s\n", line->data); + else + fprintf(fp, "%s\n", line->data); } if (entry->doc != NULL) { diff --git a/src/clientStream.cc b/src/clientStream.cc index 64c473f59f..3acd85740d 100644 --- a/src/clientStream.cc +++ b/src/clientStream.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with thisObject program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -49,14 +49,14 @@ \par * Each pipe node has a data push function, and a data request function. * This limits flexability - the data flow is no longer assembled at each - * step. + * step. * \par * An alternative approach is to pass each node in the pipe the call- - * back to use on each IO call. This allows the callbacks to be changed - * very easily by a participating node, but requires more maintenance - * in each node (store the callback to the most recent IO request in - * the nodes context.) Such an approach also prevents dynamically + * back to use on each IO call. This allows the callbacks to be changed + * very easily by a participating node, but requires more maintenance + * in each node (store the callback to the most recent IO request in + * the nodes context.) Such an approach also prevents dynamically * changing the pipeline from outside without an additional interface * method to extract the callback and context from the next node. * @@ -70,12 +70,12 @@ * Each node including the HEAD of the clientStream has a cbdataReference * held by the stream. Freeing the stream then removes that reference * and cbdataFree()'s every node. - * Any node with other References, and all nodes downstream will only + * Any node with other References, and all nodes downstream will only * free when those references are released. - * Stream nodes MAY hold references to the data member of the node. + * Stream nodes MAY hold references to the data member of the node. * \par - * Specifically - on creation no reference is made. + * Specifically - on creation no reference is made. * If you pass a data variable to a node, give it an initial reference. * If the data member is non-null on FREE, cbdataFree WILL be called. * This you must never call cbdataFree on your own context without @@ -86,7 +86,7 @@ * No data member may hold a reference to it's stream node. * The stream guarantees that DETACH will be called before * freeing the node, alowing data members to cleanup. - * + * \par * If a node's data holds a reference to something that needs to * free the stream a circular reference list will occur. @@ -184,7 +184,7 @@ clientStreamCallback(clientStreamNode * thisObject, ClientHttpRequest * http, assert(thisObject && http && thisObject->node.next); next = thisObject->next(); - debugs(87, 3, "clientStreamCallback: Calling " << next->callback << " with cbdata " << + debugs(87, 3, "clientStreamCallback: Calling " << next->callback << " with cbdata " << next->data.getRaw() << " from node " << thisObject); next->callback(next, http, rep, replyBuffer); } diff --git a/src/clientStream.h b/src/clientStream.h index 818d51f9dc..99db571360 100644 --- a/src/clientStream.h +++ b/src/clientStream.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -83,7 +83,7 @@ * \todo ClientStreams: These details should really be codified as a class which all ClientStream nodes inherit from. * - \par Each node must have: + \par Each node must have: \li read method - to allow loose coupling in the pipeline. (The reader may therefore change if the pipeline is altered, even mid-flow). \li callback method - likewise. @@ -188,7 +188,7 @@ SQUIDCEXTERN void clientStreamDetach(clientStreamNode *thisObject, ClientHttpReq /** \ingroup ClientStreamAPI * - * Detachs the tail of the stream. CURRENTLY DOES NOT clean up the tail node data - + * Detachs the tail of the stream. CURRENTLY DOES NOT clean up the tail node data - * this must be done separately. Thus Abort may ONLY be called by the tail node. * \param thisObject 'this' reference for the client stream diff --git a/src/client_db.cc b/src/client_db.cc index 33d9203216..dc9b9dec19 100644 --- a/src/client_db.cc +++ b/src/client_db.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -66,8 +66,7 @@ clientdbAdd(const IPAddress &addr) hash_join(client_table, &c->hash); statCounter.client_http.clients++; - if ((statCounter.client_http.clients > max_clients) && !cleanup_running && cleanup_scheduled < 2) - { + if ((statCounter.client_http.clients > max_clients) && !cleanup_running && cleanup_scheduled < 2) { cleanup_scheduled++; eventAdd("client_db garbage collector", clientdbScheduledGC, NULL, 90, 0); } @@ -79,7 +78,7 @@ static void clientdbRegisterWithCacheManager(void) { CacheManager::GetInstance()-> - registerAction("client_list", "Cache Client List", clientdbDump, 0, 1); + registerAction("client_list", "Cache Client List", clientdbDump, 0, 1); } void @@ -113,16 +112,14 @@ clientdbUpdate(const IPAddress &addr, log_type ltype, protocol_t p, size_t size) if (c == NULL) debug_trap("clientdbUpdate: Failed to add entry"); - if (p == PROTO_HTTP) - { + if (p == PROTO_HTTP) { c->Http.n_requests++; c->Http.result_hist[ltype]++; kb_incr(&c->Http.kbytes_out, size); if (logTypeIsATcpHit(ltype)) kb_incr(&c->Http.hit_kbytes_out, size); - } else if (p == PROTO_ICP) - { + } else if (p == PROTO_ICP) { c->Icp.n_requests++; c->Icp.result_hist[ltype]++; kb_incr(&c->Icp.kbytes_out, size); @@ -391,29 +388,27 @@ client_entry(IPAddress *current) ClientInfo *c = NULL; char key[MAX_IPSTRLEN]; - if (current) - { + if (current) { current->NtoA(key,MAX_IPSTRLEN); hash_first(client_table); while ((c = (ClientInfo *) hash_next(client_table))) { - if (!strcmp(key, hashKeyStr(&c->hash))) + if (!strcmp(key, hashKeyStr(&c->hash))) break; } - + + c = (ClientInfo *) hash_next(client_table); + } else { + hash_first(client_table); c = (ClientInfo *) hash_next(client_table); - } else - { - hash_first(client_table); - c = (ClientInfo *) hash_next(client_table); } hash_last(client_table); if (c) - return (&c->addr); + return (&c->addr); else - return (NULL); - + return (NULL); + } variable_list * @@ -442,28 +437,26 @@ snmp_meshCtblFn(variable_list * Var, snint * ErrP) switch (Var->name[LEN_SQ_NET + 2]) { - case MESH_CTBL_ADDR_TYPE: - { - int ival; - ival = c->addr.IsIPv4() ? INETADDRESSTYPE_IPV4 : INETADDRESSTYPE_IPV6 ; - Answer = snmp_var_new_integer(Var->name, Var->name_length, - ival, SMI_INTEGER); - } - break; - - case MESH_CTBL_ADDR: - { - Answer = snmp_var_new(Var->name, Var->name_length); - // InetAddress doesn't have its own ASN.1 type, - // like IpAddr does (SMI_IPADDRESS) - // See: rfc4001.txt - Answer->type = ASN_OCTET_STR; - char client[MAX_IPSTRLEN]; - c->addr.NtoA(client,MAX_IPSTRLEN); - Answer->val_len = strlen(client); - Answer->val.string = (u_char *) xstrdup(client); - } - break; + case MESH_CTBL_ADDR_TYPE: { + int ival; + ival = c->addr.IsIPv4() ? INETADDRESSTYPE_IPV4 : INETADDRESSTYPE_IPV6 ; + Answer = snmp_var_new_integer(Var->name, Var->name_length, + ival, SMI_INTEGER); + } + break; + + case MESH_CTBL_ADDR: { + Answer = snmp_var_new(Var->name, Var->name_length); + // InetAddress doesn't have its own ASN.1 type, + // like IpAddr does (SMI_IPADDRESS) + // See: rfc4001.txt + Answer->type = ASN_OCTET_STR; + char client[MAX_IPSTRLEN]; + c->addr.NtoA(client,MAX_IPSTRLEN); + Answer->val_len = strlen(client); + Answer->val.string = (u_char *) xstrdup(client); + } + break; case MESH_CTBL_HTBYTES: Answer = snmp_var_new_integer(Var->name, Var->name_length, (snint) c->Http.kbytes_out.kb, diff --git a/src/client_side_reply.cc b/src/client_side_reply.cc index 7bb1f456f6..6d9a58d804 100644 --- a/src/client_side_reply.cc +++ b/src/client_side_reply.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -110,10 +110,9 @@ clientReplyContext::setReplyToError( createStoreEntry(method, request_flags()); - if (auth_user_request) - { + if (auth_user_request) { errstate->auth_user_request = auth_user_request; - AUTHUSERREQUESTLOCK(errstate->auth_user_request, "errstate"); + AUTHUSERREQUESTLOCK(errstate->auth_user_request, "errstate"); } assert(errstate->callback_data == NULL); @@ -214,7 +213,7 @@ void clientReplyContext::triggerInitialStoreRead() { /* when confident, 0 becomes reqofs, and then this factors into - * startSendProcess + * startSendProcess */ assert(reqofs == 0); StoreIOBuffer tempBuffer (next()->readBuffer.length, 0, next()->readBuffer.data); @@ -233,7 +232,7 @@ clientReplyContext::processExpired() assert(http->storeEntry()->lastmod >= 0); /* * check if we are allowed to contact other servers - * @?@: Instead of a 504 (Gateway Timeout) reply, we may want to return + * @?@: Instead of a 504 (Gateway Timeout) reply, we may want to return * a stale entry *if* it matches client requirements */ @@ -359,42 +358,42 @@ clientReplyContext::handleIMSReply(StoreIOBuffer result) // origin replied 304 if (status == HTTP_NOT_MODIFIED) { - http->logType = LOG_TCP_REFRESH_UNMODIFIED; + http->logType = LOG_TCP_REFRESH_UNMODIFIED; - // update headers on existing entry - HttpReply *old_rep = (HttpReply *) old_entry->getReply(); - old_rep->updateOnNotModified(http->storeEntry()->getReply()); - old_entry->timestampsSet(); + // update headers on existing entry + HttpReply *old_rep = (HttpReply *) old_entry->getReply(); + old_rep->updateOnNotModified(http->storeEntry()->getReply()); + old_entry->timestampsSet(); - // if client sent IMS + // if client sent IMS - if (http->request->flags.ims) { - // forward the 304 from origin - debugs(88, 3, "handleIMSReply: origin replied 304, revalidating existing entry and forwarding 304 to client"); - sendClientUpstreamResponse(); - } else { - // send existing entry, it's still valid - debugs(88, 3, "handleIMSReply: origin replied 304, revalidating existing entry and sending " << - old_rep->sline.status << " to client"); - sendClientOldEntry(); - } + if (http->request->flags.ims) { + // forward the 304 from origin + debugs(88, 3, "handleIMSReply: origin replied 304, revalidating existing entry and forwarding 304 to client"); + sendClientUpstreamResponse(); + } else { + // send existing entry, it's still valid + debugs(88, 3, "handleIMSReply: origin replied 304, revalidating existing entry and sending " << + old_rep->sline.status << " to client"); + sendClientOldEntry(); + } } // origin replied with a non-error code else if (status > HTTP_STATUS_NONE && status < HTTP_INTERNAL_SERVER_ERROR) { - // forward response from origin - http->logType = LOG_TCP_REFRESH_MODIFIED; - debugs(88, 3, "handleIMSReply: origin replied " << status << ", replacing existing entry and forwarding to client"); - sendClientUpstreamResponse(); + // forward response from origin + http->logType = LOG_TCP_REFRESH_MODIFIED; + debugs(88, 3, "handleIMSReply: origin replied " << status << ", replacing existing entry and forwarding to client"); + sendClientUpstreamResponse(); } // origin replied with an error else { - // ignore and let client have old entry - http->logType = LOG_TCP_REFRESH_FAIL; - debugs(88, 3, "handleIMSReply: origin replied with error " << - status << ", sending old entry (" << old_rep->sline.status << ") to client"); - sendClientOldEntry(); + // ignore and let client have old entry + http->logType = LOG_TCP_REFRESH_FAIL; + debugs(88, 3, "handleIMSReply: origin replied with error " << + status << ", sending old entry (" << old_rep->sline.status << ") to client"); + sendClientOldEntry(); } } @@ -459,7 +458,7 @@ clientReplyContext::cacheHit(StoreIOBuffer result) assert(http->logType == LOG_TCP_HIT); if (strcmp(e->mem_obj->url, urlCanonical(r)) != 0) { - debugs(33, 1, "clientProcessHit: URL mismatch, '" << e->mem_obj->url << "' != '" << urlCanonical(r) << "'"); + debugs(33, 1, "clientProcessHit: URL mismatch, '" << e->mem_obj->url << "' != '" << urlCanonical(r) << "'"); processMiss(); return; } @@ -484,7 +483,7 @@ clientReplyContext::cacheHit(StoreIOBuffer result) /* Note: varyEvalyateMatch updates the request with vary information * so we only get here once. (it also takes care of cancelling loops) */ - debugs(88, 2, "clientProcessHit: Vary detected!"); + debugs(88, 2, "clientProcessHit: Vary detected!"); clientGetMoreData(ourNode, http); return; @@ -595,10 +594,10 @@ clientReplyContext::cacheHit(StoreIOBuffer result) http->logType = LOG_TCP_MISS; else #endif - if (e->mem_status == IN_MEMORY) - http->logType = LOG_TCP_MEM_HIT; - else if (Config.onoff.offline) - http->logType = LOG_TCP_OFFLINE_HIT; + if (e->mem_status == IN_MEMORY) + http->logType = LOG_TCP_MEM_HIT; + else if (Config.onoff.offline) + http->logType = LOG_TCP_OFFLINE_HIT; sendMoreData(result); } @@ -635,8 +634,8 @@ clientReplyContext::processMiss() } if (r->method == METHOD_OTHER) { - // invalidate all cache entries - purgeAllCached(); + // invalidate all cache entries + purgeAllCached(); } if (http->onlyIfCached()) { @@ -655,7 +654,7 @@ clientReplyContext::processMiss() triggerInitialStoreRead(); return; } else { - assert(http->out.offset == 0); + assert(http->out.offset == 0); createStoreEntry(r->method, r->flags); triggerInitialStoreRead(); @@ -702,13 +701,13 @@ clientReplyContext::processOnlyIfCachedMiss() void clientReplyContext::purgeRequestFindObjectToPurge() -{ +{ /* Try to find a base entry */ http->flags.purging = 1; lookingforstore = 1; - - // TODO: can we use purgeAllCached() here instead of doing the - // getPublicByRequestMethod() dance? + + // TODO: can we use purgeAllCached() here instead of doing the + // getPublicByRequestMethod() dance? StoreEntry::getPublicByRequestMethod(this, http->request, METHOD_GET); } @@ -724,7 +723,7 @@ purgeEntriesByUrl(HttpRequest * req, const char *url) #if USE_HTCP bool get_or_head_sent = false; #endif - + for (HttpRequestMethod m(METHOD_NONE); m != METHOD_ENUM_END; ++m) { if (m.isCacheble()) { if (StoreEntry *entry = storeGetPublic(url, m)) { @@ -747,10 +746,10 @@ purgeEntriesByUrl(HttpRequest * req, const char *url) #endif } -void +void clientReplyContext::purgeAllCached() { - const char *url = urlCanonical(http->request); + const char *url = urlCanonical(http->request); purgeEntriesByUrl(http->request, url); } @@ -980,7 +979,7 @@ clientReplyContext::checkTransferDone() /* * Handle STORE_OK objects. * objectLen(entry) will be set proprely. - * RC: Does objectLen(entry) include the Headers? + * RC: Does objectLen(entry) include the Headers? * RC: Yes. */ if (entry->store_status == STORE_OK) { @@ -994,10 +993,10 @@ int clientReplyContext::storeOKTransferDone() const { if (http->out.offset >= http->storeEntry()->objectLen() - headers_sz) { - debugs(88,3,HERE << "storeOKTransferDone " << - " out.offset=" << http->out.offset << - " objectLen()=" << http->storeEntry()->objectLen() << - " headers_sz=" << headers_sz); + debugs(88,3,HERE << "storeOKTransferDone " << + " out.offset=" << http->out.offset << + " objectLen()=" << http->storeEntry()->objectLen() << + " headers_sz=" << headers_sz); return 1; } @@ -1041,9 +1040,9 @@ clientReplyContext::storeNotOKTransferDone() const if (http->out.size < expectedLength) return 0; else { - debugs(88,3,HERE << "storeNotOKTransferDone " << - " out.size=" << http->out.size << - " expectedLength=" << expectedLength); + debugs(88,3,HERE << "storeNotOKTransferDone " << + " out.size=" << http->out.size << + " expectedLength=" << expectedLength); return 1; } } @@ -1161,8 +1160,8 @@ clientReplyContext::replyStatus() * which breaks the rep_mime_type acl, which * coincidentally, is the most common acl for reply access lists. * A better long term fix for this is to allow acl matchs on the various - * status codes, and then supply a default ruleset that puts these - * codes before any user defines access entries. That way the user + * status codes, and then supply a default ruleset that puts these + * codes before any user defines access entries. That way the user * can choose to block these responses where appropriate, but won't get * mysterious breakages. */ @@ -1212,10 +1211,10 @@ clientReplyContext::buildReplyHeader() if (is_hit) hdr->delById(HDR_SET_COOKIE); - // if there is not configured a peer proxy with login=PASS option enabled + // if there is not configured a peer proxy with login=PASS option enabled // remove the Proxy-Authenticate header if ( !(request->peer_login && strcmp(request->peer_login,"PASS") ==0)) - reply->header.delById(HDR_PROXY_AUTHENTICATE); + reply->header.delById(HDR_PROXY_AUTHENTICATE); reply->header.removeHopByHopEntries(); @@ -1281,7 +1280,7 @@ clientReplyContext::buildReplyHeader() HttpHeaderPos pos = HttpHeaderInitPos; HttpHeaderEntry *e; - int connection_auth_blocked = 0; + int connection_auth_blocked = 0; while ((e = hdr->getEntry(&pos))) { if (e->id == HDR_WWW_AUTHENTICATE) { const char *value = e->value.buf(); @@ -1291,27 +1290,26 @@ clientReplyContext::buildReplyHeader() || (strncasecmp(value, "Negotiate", 9) == 0 && (value[9] == '\0' || value[9] == ' ')) - || - (strncasecmp(value, "Kerberos", 8) == 0 && - (value[8] == '\0' || value[8] == ' '))) - { - if (request->flags.connection_auth_disabled) { - hdr->delAt(pos, connection_auth_blocked); + || + (strncasecmp(value, "Kerberos", 8) == 0 && + (value[8] == '\0' || value[8] == ' '))) { + if (request->flags.connection_auth_disabled) { + hdr->delAt(pos, connection_auth_blocked); continue; } - request->flags.must_keepalive = 1; - if (!request->flags.accelerated && !request->flags.intercepted) { + request->flags.must_keepalive = 1; + if (!request->flags.accelerated && !request->flags.intercepted) { httpHeaderPutStrf(hdr, HDR_PROXY_SUPPORT, "Session-Based-Authentication"); - /* - We send "[Proxy-]Connection: Proxy-Support" header to mark - Proxy-Support as a hop-by-hop header for intermediaries that do not - understand the semantics of this header. The RFC should have included - this recommendation. - */ + /* + We send "[Proxy-]Connection: Proxy-Support" header to mark + Proxy-Support as a hop-by-hop header for intermediaries that do not + understand the semantics of this header. The RFC should have included + this recommendation. + */ httpHeaderPutStrf(hdr, HDR_CONNECTION, "Proxy-support"); } break; - } + } } } @@ -1320,19 +1318,18 @@ clientReplyContext::buildReplyHeader() } /* Handle authentication headers */ - if(http->logType == LOG_TCP_DENIED && - ( reply->sline.status == HTTP_PROXY_AUTHENTICATION_REQUIRED || - reply->sline.status == HTTP_UNAUTHORIZED) - ){ - /* Add authentication header */ - /*! \todo alter errorstate to be accel on|off aware. The 0 on the next line - * depends on authenticate behaviour: all schemes to date send no extra - * data on 407/401 responses, and do not check the accel state on 401/407 - * responses - */ - authenticateFixHeader(reply, request->auth_user_request, request, 0, 1); - } - else if (request->auth_user_request) + if (http->logType == LOG_TCP_DENIED && + ( reply->sline.status == HTTP_PROXY_AUTHENTICATION_REQUIRED || + reply->sline.status == HTTP_UNAUTHORIZED) + ) { + /* Add authentication header */ + /*! \todo alter errorstate to be accel on|off aware. The 0 on the next line + * depends on authenticate behaviour: all schemes to date send no extra + * data on 407/401 responses, and do not check the accel state on 401/407 + * responses + */ + authenticateFixHeader(reply, request->auth_user_request, request, 0, 1); + } else if (request->auth_user_request) authenticateFixHeader(reply, request->auth_user_request, request, http->flags.accel, 0); @@ -1373,10 +1370,10 @@ clientReplyContext::buildReplyHeader() debugs(88, 3, "clientBuildReplyHeader: Shutting down, don't keep-alive."); request->flags.proxy_keepalive = 0; } - - if (request->flags.connection_auth && !reply->keep_alive) { - debugs(33, 2, "clientBuildReplyHeader: Connection oriented auth but server side non-persistent"); - request->flags.proxy_keepalive = 0; + + if (request->flags.connection_auth && !reply->keep_alive) { + debugs(33, 2, "clientBuildReplyHeader: Connection oriented auth but server side non-persistent"); + request->flags.proxy_keepalive = 0; } @@ -1384,7 +1381,7 @@ clientReplyContext::buildReplyHeader() if (Config.onoff.via) { LOCAL_ARRAY(char, bbuf, MAX_URL + 32); String strVia; - hdr->getList(HDR_VIA, &strVia); + hdr->getList(HDR_VIA, &strVia); snprintf(bbuf, sizeof(bbuf), "%d.%d %s", reply->sline.version.major, reply->sline.version.minor, @@ -1638,8 +1635,7 @@ clientReplyContext::doGetMoreData() assert(http->out.size == 0); assert(http->out.offset == 0); #if USE_ZPH_QOS - if (Config.zph_tos_local) - { + if (Config.zph_tos_local) { debugs(33, 2, "ZPH Local hit, TOS="<getConn()->fd,Config.zph_tos_local); } @@ -1697,7 +1693,7 @@ clientReplyContext::sendStreamError(StoreIOBuffer const &result) /* We call into the stream, because we don't know that there is a * client socket! */ - debugs(88, 5, "clientReplyContext::sendStreamError: A stream error has occured, marking as complete and sending no data."); + debugs(88, 5, "clientReplyContext::sendStreamError: A stream error has occured, marking as complete and sending no data."); StoreIOBuffer tempBuffer; flags.complete = 1; tempBuffer.flags.error = result.flags.error; @@ -1736,14 +1732,15 @@ clientReplyContext::next() const void clientReplyContext::sendBodyTooLargeError() { - IPAddress tmp_noaddr; tmp_noaddr.SetNoAddr(); // TODO: make a global const + IPAddress tmp_noaddr; + tmp_noaddr.SetNoAddr(); // TODO: make a global const ErrorState *err = clientBuildError(ERR_TOO_BIG, HTTP_FORBIDDEN, NULL, - http->getConn() != NULL ? http->getConn()->peer : tmp_noaddr, - http->request); + http->getConn() != NULL ? http->getConn()->peer : tmp_noaddr, + http->request); removeClientStoreReference(&(sc), http); HTTPMSGUNLOCK(reply); startError(err); - + } void @@ -1752,13 +1749,13 @@ clientReplyContext::processReplyAccess () assert(reply); /* Dont't block our own responses or HTTP status messages */ if (http->logType == LOG_TCP_DENIED || - http->logType == LOG_TCP_DENIED_REPLY || - alwaysAllowResponse(reply->sline.status)) { + http->logType == LOG_TCP_DENIED_REPLY || + alwaysAllowResponse(reply->sline.status)) { headers_sz = reply->hdr_sz; - processReplyAccessResult(1); - return; + processReplyAccessResult(1); + return; } - + if (reply->expectedBodyTooLarge(*http->request)) { sendBodyTooLargeError(); return; @@ -1767,8 +1764,8 @@ clientReplyContext::processReplyAccess () headers_sz = reply->hdr_sz; if (!Config.accessList.reply) { - processReplyAccessResult(1); - return; + processReplyAccessResult(1); + return; } ACLChecklist *replyChecklist; @@ -1787,10 +1784,10 @@ clientReplyContext::ProcessReplyAccessResult (int rv, void *voidMe) void clientReplyContext::processReplyAccessResult(bool accessAllowed) { - debugs(88, 2, "The reply for " << RequestMethodStr(http->request->method) - << " " << http->uri << " is " - << ( accessAllowed ? "ALLOWED" : "DENIED") - << ", because it matched '" + debugs(88, 2, "The reply for " << RequestMethodStr(http->request->method) + << " " << http->uri << " is " + << ( accessAllowed ? "ALLOWED" : "DENIED") + << ", because it matched '" << (AclMatchedName ? AclMatchedName : "NO ACL's") << "'" ); if (!accessAllowed) { @@ -1803,10 +1800,11 @@ clientReplyContext::processReplyAccessResult(bool accessAllowed) if (page_id == ERR_NONE) page_id = ERR_ACCESS_DENIED; - IPAddress tmp_noaddr; tmp_noaddr.SetNoAddr(); + IPAddress tmp_noaddr; + tmp_noaddr.SetNoAddr(); err = clientBuildError(page_id, HTTP_FORBIDDEN, NULL, - http->getConn() != NULL ? http->getConn()->peer : tmp_noaddr, - http->request); + http->getConn() != NULL ? http->getConn()->peer : tmp_noaddr, + http->request); removeClientStoreReference(&sc, http); @@ -1823,8 +1821,8 @@ clientReplyContext::processReplyAccessResult(bool accessAllowed) ssize_t body_size = reqofs - reply->hdr_sz; if (body_size < 0) { - reqofs = reply->hdr_sz; - body_size = 0; + reqofs = reply->hdr_sz; + body_size = 0; } debugs(88, 3, "clientReplyContext::sendMoreData: Appending " << @@ -1914,24 +1912,21 @@ clientReplyContext::sendMoreData (StoreIOBuffer result) } #if USE_ZPH_QOS - if (reqofs==0 && !logTypeIsATcpHit(http->logType)) - { + if (reqofs==0 && !logTypeIsATcpHit(http->logType)) { assert(fd >= 0); // the beginning of this method implies fd may be -1 int tos = 0; - if (Config.zph_tos_peer && - (http->request->hier.code==SIBLING_HIT || - (Config.onoff.zph_tos_parent && http->request->hier.code==PARENT_HIT) ) ) - { + if (Config.zph_tos_peer && + (http->request->hier.code==SIBLING_HIT || + (Config.onoff.zph_tos_parent && http->request->hier.code==PARENT_HIT) ) ) { tos = Config.zph_tos_peer; debugs(33, 2, "ZPH: Peer hit with hier.code="<request->hier.code<<", TOS="<url() << "'" << - " out.offset=" << http->out.offset); + " FD " << fd << + " '" << entry->url() << "'" << + " out.offset=" << http->out.offset); /* update size of the request */ reqsize = reqofs; @@ -1974,13 +1969,13 @@ clientReplyContext::sendMoreData (StoreIOBuffer result) /* handle headers */ if (Config.onoff.log_mime_hdrs) { - size_t k; + size_t k; - if ((k = headersEnd(buf, reqofs))) { - safe_free(http->al.headers.reply); - http->al.headers.reply = (char *)xcalloc(k + 1, 1); - xstrncpy(http->al.headers.reply, buf, k); - } + if ((k = headersEnd(buf, reqofs))) { + safe_free(http->al.headers.reply); + http->al.headers.reply = (char *)xcalloc(k + 1, 1); + xstrncpy(http->al.headers.reply, buf, k); + } } holdingBuffer = result; @@ -2022,7 +2017,7 @@ clientReplyContext::createStoreEntry(const HttpRequestMethod& m, request_flags f /* http->reqbuf = http->norm_reqbuf; */ // assert(http->reqbuf == http->norm_reqbuf); /* The next line is illegal because we don't know if the client stream - * buffers have been set up + * buffers have been set up */ // storeClientCopy(http->sc, e, 0, HTTP_REQBUF_SZ, http->reqbuf, // SendMoreData, this); @@ -2031,7 +2026,7 @@ clientReplyContext::createStoreEntry(const HttpRequestMethod& m, request_flags f /* and get the caller to request a read, from whereever they are */ /* NOTE: after ANY data flows down the pipe, even one step, - * this function CAN NOT be used to manage errors + * this function CAN NOT be used to manage errors */ http->storeEntry(e); } diff --git a/src/client_side_reply.h b/src/client_side_reply.h index 40bf5900be..ffaacdb0a6 100644 --- a/src/client_side_reply.h +++ b/src/client_side_reply.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -105,12 +105,11 @@ public: const char *lookup_type; /* temporary hack: storeGet() result: HIT/MISS/NONE */ #endif - struct - { + struct { -unsigned storelogiccomplete: 1; + unsigned storelogiccomplete:1; -unsigned complete: 1; /* we have read all we can from upstream */ + unsigned complete:1; /* we have read all we can from upstream */ bool headersSent; } flags; clientStreamNode *ourNode; /* This will go away if/when this file gets refactored some more */ diff --git a/src/client_side_request.cc b/src/client_side_request.cc index 49a4219ae8..49a4646a2e 100644 --- a/src/client_side_request.cc +++ b/src/client_side_request.cc @@ -1,10 +1,10 @@ /* * $Id: client_side_request.cc,v 1.105 2008/02/12 23:07:52 rousskov Exp $ - * + * * DEBUG: section 85 Client-side Request Routines * AUTHOR: Robert Collins (Originally Duane Wessels in client_side.c) - * + * * SQUID Web Proxy Cache http://www.squid-cache.org/ * ---------------------------------------------------------- * @@ -36,7 +36,7 @@ /* * General logic of request processing: - * + * * We run a series of tests to determine if access will be permitted, and to do * any redirection. Then we call into the result clientStream to retrieve data. * From that point on it's up to reply management. @@ -147,11 +147,11 @@ ClientHttpRequest::operator delete (void *address) cbdataFree(t); } -ClientHttpRequest::ClientHttpRequest(ConnStateData * aConn) : +ClientHttpRequest::ClientHttpRequest(ConnStateData * aConn) : #if USE_ADAPTATION -AsyncJob("ClientHttpRequest"), + AsyncJob("ClientHttpRequest"), #endif -loggingEntry_(NULL) + loggingEntry_(NULL) { start_time = current_time; setConn(aConn); @@ -182,7 +182,7 @@ ClientHttpRequest::onlyIfCached()const * mode where we only return UDP_HIT or UDP_MISS_NOFETCH. Neighbors * will only fetch HITs from us if they are using the ICP protocol. We * stay in this mode for 5 minutes. - * + * * Duane W., Sept 16, 1996 */ @@ -246,7 +246,7 @@ ClientHttpRequest::~ClientHttpRequest() // because we did not initiate that pipe (ConnStateData did) /* the ICP check here was erroneous - * - StoreEntry::releaseRequest was always called if entry was valid + * - StoreEntry::releaseRequest was always called if entry was valid */ assert(logType < LOG_TYPE_MAX); @@ -269,8 +269,8 @@ ClientHttpRequest::~ClientHttpRequest() if (calloutContext) delete calloutContext; - if(conn_) - cbdataReferenceDone(conn_); + if (conn_) + cbdataReferenceDone(conn_); /* moving to the next connection is handled by the context free */ dlinkDelete(&active, &ClientActiveRequests); @@ -352,7 +352,7 @@ clientBeginRequest(const HttpRequestMethod& method, char const *url, CSCB * stre #if FOLLOW_X_FORWARDED_FOR request->indirect_client_addr.SetNoAddr(); #endif /* FOLLOW_X_FORWARDED_FOR */ - + request->my_addr.SetNoAddr(); /* undefined for internal requests */ request->my_addr.SetPort(0); @@ -407,7 +407,7 @@ clientFollowXForwardedForCheck(int answer, void *data) if (!calloutContext->httpStateIsValid()) return; - http = calloutContext->http; + http = calloutContext->http; request = http->request; /* * answer should be be ACCESS_ALLOWED or ACCESS_DENIED if we are @@ -415,8 +415,7 @@ clientFollowXForwardedForCheck(int answer, void *data) * there's nothing left to do. */ if (answer == ACCESS_ALLOWED && - request->x_forwarded_for_iterator.size () != 0) - { + request->x_forwarded_for_iterator.size () != 0) { /* * The IP address currently in request->indirect_client_addr * is trusted to use X-Forwarded-For. Remove the last @@ -448,12 +447,10 @@ clientFollowXForwardedForCheck(int answer, void *data) while (l > 0 && ! (p[l-1] == ',' || xisspace(p[l-1]))) l--; asciiaddr = p+l; - if (xinet_pton(AF_INET, asciiaddr, &addr) != 0) - { + if (xinet_pton(AF_INET, asciiaddr, &addr) != 0) { request->indirect_client_addr = addr; request->x_forwarded_for_iterator.cut(l); - if (! Config.onoff.acl_uses_indirect_client) - { + if (! Config.onoff.acl_uses_indirect_client) { /* * If acl_uses_indirect_client is off, then it's impossible * to follow more than one level of X-Forwarded-For. @@ -461,7 +458,7 @@ clientFollowXForwardedForCheck(int answer, void *data) request->x_forwarded_for_iterator.clean(); } calloutContext->acl_checklist = - clientAclChecklistCreate(Config.accessList.followXFF, http); + clientAclChecklistCreate(Config.accessList.followXFF, http); calloutContext->acl_checklist-> nonBlockingCheck(clientFollowXForwardedForCheck, data); return; @@ -470,8 +467,7 @@ clientFollowXForwardedForCheck(int answer, void *data) request->x_forwarded_for_iterator.size () != 0)*/ /* clean up, and pass control to clientAccessCheck */ - if (Config.onoff.log_uses_indirect_client) - { + if (Config.onoff.log_uses_indirect_client) { /* * Ensure that the access log shows the indirect client * instead of the direct client. @@ -504,10 +500,9 @@ ClientRequestContext::clientAccessCheck() { #if FOLLOW_X_FORWARDED_FOR if (!http->request->flags.done_follow_x_forwarded_for && - Config.accessList.followXFF && - http->request->header.has(HDR_X_FORWARDED_FOR)) - { - http->request->x_forwarded_for_iterator = + Config.accessList.followXFF && + http->request->header.has(HDR_X_FORWARDED_FOR)) { + http->request->x_forwarded_for_iterator = http->request->header.getList(HDR_X_FORWARDED_FOR); clientFollowXForwardedForCheck(ACCESS_ALLOWED, this); return; @@ -535,12 +530,12 @@ ClientRequestContext::clientAccessCheckDone(int answer) acl_checklist = NULL; err_type page_id; http_status status; - debugs(85, 2, "The request " << - RequestMethodStr(http->request->method) << " " << - http->uri << " is " << - (answer == ACCESS_ALLOWED ? "ALLOWED" : "DENIED") << - ", because it matched '" << - (AclMatchedName ? AclMatchedName : "NO ACL's") << "'" ); + debugs(85, 2, "The request " << + RequestMethodStr(http->request->method) << " " << + http->uri << " is " << + (answer == ACCESS_ALLOWED ? "ALLOWED" : "DENIED") << + ", because it matched '" << + (AclMatchedName ? AclMatchedName : "NO ACL's") << "'" ); char const *proxy_auth_msg = ""; if (http->getConn() != NULL && http->getConn()->auth_user_request != NULL) @@ -588,7 +583,8 @@ ClientRequestContext::clientAccessCheckDone(int answer) clientStreamNode *node = (clientStreamNode *)http->client_stream.tail->prev->data; clientReplyContext *repContext = dynamic_cast(node->data.getRaw()); assert (repContext); - IPAddress tmpnoaddr; tmpnoaddr.SetNoAddr(); + IPAddress tmpnoaddr; + tmpnoaddr.SetNoAddr(); repContext->setReplyToError(page_id, status, http->request->method, NULL, http->getConn() != NULL ? http->getConn()->peer : tmpnoaddr, @@ -779,7 +775,7 @@ clientInterpretRequestHeaders(ClientHttpRequest * http) } if (request->method == METHOD_OTHER) { - no_cache++; + no_cache++; } #endif @@ -805,7 +801,7 @@ clientInterpretRequestHeaders(ClientHttpRequest * http) clientStreamNode *node = (clientStreamNode *)http->client_stream.tail->data; /* XXX: This is suboptimal. We should give the stream the range set, * and thereby let the top of the stream set the offset when the - * size becomes known. As it is, we will end up requesting from 0 + * size becomes known. As it is, we will end up requesting from 0 * for evey -X range specification. * RBC - this may be somewhat wrong. We should probably set the range * iter up at this point. @@ -832,15 +828,15 @@ clientInterpretRequestHeaders(ClientHttpRequest * http) assert(http_conn); request->flags.connection_auth_disabled = http_conn->port->connection_auth_disabled; if (!request->flags.connection_auth_disabled) { - if (http_conn->pinning.fd != -1) { - if (http_conn->pinning.auth) { - request->flags.connection_auth = 1; - request->flags.auth = 1; - } else { - request->flags.connection_proxy_auth = 1; - } - request->setPinnedConnection(http_conn); - } + if (http_conn->pinning.fd != -1) { + if (http_conn->pinning.auth) { + request->flags.connection_auth = 1; + request->flags.auth = 1; + } else { + request->flags.connection_proxy_auth = 1; + } + request->setPinnedConnection(http_conn); + } } /* check if connection auth is used, and flag as candidate for pinning @@ -849,32 +845,32 @@ clientInterpretRequestHeaders(ClientHttpRequest * http) * is already pinned if it was pinned earlier due to proxy auth */ if (!request->flags.connection_auth) { - if (req_hdr->has(HDR_AUTHORIZATION) || req_hdr->has(HDR_PROXY_AUTHORIZATION)) { - HttpHeaderPos pos = HttpHeaderInitPos; - HttpHeaderEntry *e; - int may_pin = 0; - while ((e = req_hdr->getEntry(&pos))) { - if (e->id == HDR_AUTHORIZATION || e->id == HDR_PROXY_AUTHORIZATION) { - const char *value = e->value.buf(); - if (strncasecmp(value, "NTLM ", 5) == 0 - || - strncasecmp(value, "Negotiate ", 10) == 0 - || - strncasecmp(value, "Kerberos ", 9) == 0) { - if (e->id == HDR_AUTHORIZATION) { - request->flags.connection_auth = 1; - may_pin = 1; - } else { - request->flags.connection_proxy_auth = 1; - may_pin = 1; - } - } - } - } - if (may_pin && !request->pinnedConnection()) { - request->setPinnedConnection(http->getConn()); - } - } + if (req_hdr->has(HDR_AUTHORIZATION) || req_hdr->has(HDR_PROXY_AUTHORIZATION)) { + HttpHeaderPos pos = HttpHeaderInitPos; + HttpHeaderEntry *e; + int may_pin = 0; + while ((e = req_hdr->getEntry(&pos))) { + if (e->id == HDR_AUTHORIZATION || e->id == HDR_PROXY_AUTHORIZATION) { + const char *value = e->value.buf(); + if (strncasecmp(value, "NTLM ", 5) == 0 + || + strncasecmp(value, "Negotiate ", 10) == 0 + || + strncasecmp(value, "Kerberos ", 9) == 0) { + if (e->id == HDR_AUTHORIZATION) { + request->flags.connection_auth = 1; + may_pin = 1; + } else { + request->flags.connection_proxy_auth = 1; + may_pin = 1; + } + } + } + } + if (may_pin && !request->pinnedConnection()) { + request->setPinnedConnection(http->getConn()); + } + } } @@ -903,10 +899,10 @@ clientInterpretRequestHeaders(ClientHttpRequest * http) s.clean(); } -/** - \todo --enable-useragent-log and --enable-referer-log. We should - probably drop those two as the custom log formats accomplish pretty much the same thing.. -*/ + /** + \todo --enable-useragent-log and --enable-referer-log. We should + probably drop those two as the custom log formats accomplish pretty much the same thing.. + */ #if USE_USERAGENT_LOG if ((str = req_hdr->getStr(HDR_USER_AGENT))) logUserAgent(fqdnFromAddr(http->getConn()->log_addr), str); @@ -1097,7 +1093,8 @@ ClientHttpRequest::httpStart() // determines whether we should bump the CONNECT request bool -ClientHttpRequest::sslBumpNeeded() const { +ClientHttpRequest::sslBumpNeeded() const +{ if (!getConn()->port->sslBump || !Config.accessList.ssl_bump) return false; @@ -1105,11 +1102,11 @@ ClientHttpRequest::sslBumpNeeded() const { ACLChecklist check; check.src_addr = request->client_addr; - check.my_addr = request->my_addr; - check.request = HTTPMSGLOCK(request); - check.accessList = cbdataReference(Config.accessList.ssl_bump); - /* cbdataReferenceDone() happens in either fastCheck() or ~ACLCheckList */ - return check.fastCheck() == 1; + check.my_addr = request->my_addr; + check.request = HTTPMSGLOCK(request); + check.accessList = cbdataReference(Config.accessList.ssl_bump); + /* cbdataReferenceDone() happens in either fastCheck() or ~ACLCheckList */ + return check.fastCheck() == 1; } // called when comm_write has completed @@ -1151,7 +1148,7 @@ ClientHttpRequest::sslBumpStart() static const char *const conn_established = "HTTP/1.0 200 Connection established\r\n\r\n"; comm_write(fd, conn_established, strlen(conn_established), - &SslBumpEstablish, this, NULL); + &SslBumpEstablish, this, NULL); } #endif @@ -1238,8 +1235,8 @@ ClientHttpRequest::doCallouts() if (!calloutContext->adaptation_acl_check_done) { calloutContext->adaptation_acl_check_done = true; if (Adaptation::AccessCheck::Start( - Adaptation::methodReqmod, Adaptation::pointPreCache, - request, NULL, adaptationAclCheckDoneWrapper, calloutContext)) + Adaptation::methodReqmod, Adaptation::pointPreCache, + request, NULL, adaptationAclCheckDoneWrapper, calloutContext)) return; // will call callback } #endif @@ -1303,7 +1300,7 @@ ClientHttpRequest::doCallouts() #if USE_ADAPTATION /* - * Initiate an ICAP transaction. Return false on errors. + * Initiate an ICAP transaction. Return false on errors. * The caller must handle errors. */ bool @@ -1322,7 +1319,7 @@ ClientHttpRequest::startAdaptation(Adaptation::ServicePointer service) assert(!virginHeadSource); assert(!adaptedBodySource); virginHeadSource = initiateAdaptation(service->makeXactLauncher( - this, request, NULL)); + this, request, NULL)); return virginHeadSource != NULL; } @@ -1410,7 +1407,7 @@ ClientHttpRequest::noteBodyProductionEnded(BodyPipe::Pointer) { assert(!virginHeadSource); if (adaptedBodySource != NULL) { // did not end request satisfaction yet - // We do not expect more because noteMoreBodyDataAvailable always + // We do not expect more because noteMoreBodyDataAvailable always // consumes everything. We do not even have a mechanism to consume // leftovers after noteMoreBodyDataAvailable notifications seize. assert(adaptedBodySource->exhausted()); @@ -1419,7 +1416,8 @@ ClientHttpRequest::noteBodyProductionEnded(BodyPipe::Pointer) } void -ClientHttpRequest::endRequestSatisfaction() { +ClientHttpRequest::endRequestSatisfaction() +{ debugs(85,4, HERE << this << " ends request satisfaction"); assert(request_satisfaction_mode); stopConsumingFrom(adaptedBodySource); @@ -1443,7 +1441,7 @@ ClientHttpRequest::handleAdaptationFailure(bool bypassable) const bool usedStore = storeEntry() && !storeEntry()->isEmpty(); const bool usedPipe = request->body_pipe != NULL && - request->body_pipe->consumedSize() > 0; + request->body_pipe->consumedSize() > 0; if (bypassable && !usedStore && !usedPipe) { debugs(85,3, HERE << "ICAP REQMOD callout failed, bypassing: " << calloutContext); @@ -1458,17 +1456,17 @@ ClientHttpRequest::handleAdaptationFailure(bool bypassable) clientReplyContext *repContext = dynamic_cast(node->data.getRaw()); assert(repContext); - // The original author of the code also wanted to pass an errno to + // The original author of the code also wanted to pass an errno to // setReplyToError, but it seems unlikely that the errno reflects the // true cause of the error at this point, so I did not pass it. IPAddress noAddr; noAddr.SetNoAddr(); ConnStateData * c = getConn(); repContext->setReplyToError(ERR_ICAP_FAILURE, HTTP_INTERNAL_SERVER_ERROR, - request->method, NULL, - (c != NULL ? c->peer : noAddr), request, NULL, - (c != NULL && c->auth_user_request ? - c->auth_user_request : request->auth_user_request)); + request->method, NULL, + (c != NULL ? c->peer : noAddr), request, NULL, + (c != NULL && c->auth_user_request ? + c->auth_user_request : request->auth_user_request)); node = (clientStreamNode *)client_stream.tail->data; clientStreamRead(node, this, node->readBuffer); diff --git a/src/client_side_request.cci b/src/client_side_request.cci index c32b249383..a87df5f3e4 100644 --- a/src/client_side_request.cci +++ b/src/client_side_request.cci @@ -3,7 +3,7 @@ * $Id: client_side_request.cci,v 1.6 2008/02/13 00:00:57 rousskov Exp $ * * DEBUG: section 85 Client-side Request Routines - * AUTHOR: Robert Collins + * AUTHOR: Robert Collins * * SQUID Web Proxy Cache http://www.squid-cache.org/ * ---------------------------------------------------------- @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -52,8 +52,8 @@ ClientHttpRequest::memObject() const ConnStateData * ClientHttpRequest::getConn() { - if(!cbdataReferenceValid(conn_)) - return NULL; + if (!cbdataReferenceValid(conn_)) + return NULL; return conn_; } @@ -61,8 +61,8 @@ ClientHttpRequest::getConn() ConnStateData * const ClientHttpRequest::getConn() const { - if(!cbdataReferenceValid(conn_)) - return NULL; + if (!cbdataReferenceValid(conn_)) + return NULL; return conn_; } @@ -72,8 +72,8 @@ ClientHttpRequest::setConn(ConnStateData * aConn) { assert (conn_ == NULL || aConn == NULL); - if(conn_) - cbdataReferenceDone(conn_); + if (conn_) + cbdataReferenceDone(conn_); conn_ = cbdataReference(aConn); } diff --git a/src/client_side_request.h b/src/client_side_request.h index b2f5b7fcd5..e9347031d8 100644 --- a/src/client_side_request.h +++ b/src/client_side_request.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -61,8 +61,8 @@ class ClientRequestContext; class ClientHttpRequest #if USE_ADAPTATION - : public Adaptation::Initiator, // to start adaptation transactions - public BodyConsumer // to receive reply bodies in request satisf. mode + : public Adaptation::Initiator, // to start adaptation transactions + public BodyConsumer // to receive reply bodies in request satisf. mode #endif { @@ -100,8 +100,7 @@ public: char *uri; char *log_uri; - struct - { + struct { int64_t offset; int64_t size; size_t headers_sz; @@ -114,8 +113,7 @@ public: struct timeval start_time; AccessLogEntry al; - struct - { + struct { unsigned int accel:1; unsigned int intercepted:1; unsigned int spoof_client_ip:1; @@ -124,8 +122,7 @@ public: unsigned int purging:1; } flags; - struct - { + struct { http_status status; char *location; } redirect; @@ -139,8 +136,10 @@ public: #if USE_ADAPTATION // AsyncJob virtual methods - virtual bool doneAll() const { return Initiator::doneAll() && - BodyConsumer::doneAll() && false;} + virtual bool doneAll() const { + return Initiator::doneAll() && + BodyConsumer::doneAll() && false; + } #endif private: diff --git a/src/comm_epoll.cc b/src/comm_epoll.cc index 87f4e9a80a..949fe8fc40 100644 --- a/src/comm_epoll.cc +++ b/src/comm_epoll.cc @@ -104,7 +104,7 @@ comm_select_init(void) static const char* epolltype_atoi(int x) { - switch(x) { + switch (x) { case EPOLL_CTL_ADD: return "EPOLL_CTL_ADD"; @@ -136,13 +136,13 @@ commSetSelect(int fd, unsigned int type, PF * handler, struct epoll_event ev; assert(fd >= 0); - debugs(5, DEBUG_EPOLL ? 0 : 8, "commSetSelect(FD " << fd << ",type=" << type << - ",handler=" << handler << ",client_data=" << client_data << + debugs(5, DEBUG_EPOLL ? 0 : 8, "commSetSelect(FD " << fd << ",type=" << type << + ",handler=" << handler << ",client_data=" << client_data << ",timeout=" << timeout << ")"); if (RUNNING_ON_VALGRIND) { - /* Keep valgrind happy.. complains about uninitialized bytes otherwise */ - memset(&ev, 0, sizeof(ev)); + /* Keep valgrind happy.. complains about uninitialized bytes otherwise */ + memset(&ev, 0, sizeof(ev)); } ev.events = 0; ev.data.fd = fd; @@ -156,11 +156,11 @@ commSetSelect(int fd, unsigned int type, PF * handler, if (type & COMM_SELECT_READ) { if (handler) { - // Hack to keep the events flowing if there is data immediately ready - if (F->flags.read_pending) - ev.events |= EPOLLOUT; + // Hack to keep the events flowing if there is data immediately ready + if (F->flags.read_pending) + ev.events |= EPOLLOUT; ev.events |= EPOLLIN; - } + } F->read_handler = handler; @@ -197,7 +197,7 @@ commSetSelect(int fd, unsigned int type, PF * handler, F->epoll_state = ev.events; if (epoll_ctl(kdpfd, epoll_ctl_type, fd, &ev) < 0) { - debugs(5, DEBUG_EPOLL ? 0 : 8, "commSetSelect: epoll_ctl(," << epolltype_atoi(epoll_ctl_type) << + debugs(5, DEBUG_EPOLL ? 0 : 8, "commSetSelect: epoll_ctl(," << epolltype_atoi(epoll_ctl_type) << ",,): failed on FD " << fd << ": " << xstrerror()); } } @@ -221,9 +221,9 @@ static void commEPollRegisterWithCacheManager(void) { CacheManager::GetInstance()-> - registerAction("comm_epoll_incoming", - "comm_incoming() stats", - commIncomingStats, 0, 1); + registerAction("comm_epoll_incoming", + "comm_incoming() stats", + commIncomingStats, 0, 1); } static void @@ -291,9 +291,9 @@ comm_select(int msec) for (i = 0, cevents = pevents; i < num; i++, cevents++) { fd = cevents->data.fd; F = &fd_table[fd]; - debugs(5, DEBUG_EPOLL ? 0 : 8, "comm_select(): got FD " << fd << " events=" << - std::hex << cevents->events << " monitoring=" << F->epoll_state << - " F->read_handler=" << F->read_handler << " F->write_handler=" << F->write_handler); + debugs(5, DEBUG_EPOLL ? 0 : 8, "comm_select(): got FD " << fd << " events=" << + std::hex << cevents->events << " monitoring=" << F->epoll_state << + " F->read_handler=" << F->read_handler << " F->write_handler=" << F->write_handler); // TODO: add EPOLLPRI?? diff --git a/src/comm_epoll.h b/src/comm_epoll.h index 720570f008..17c9ebe2cb 100644 --- a/src/comm_epoll.h +++ b/src/comm_epoll.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/comm_kqueue.cc b/src/comm_kqueue.cc index 391ffab871..b87fc2af90 100644 --- a/src/comm_kqueue.cc +++ b/src/comm_kqueue.cc @@ -133,7 +133,7 @@ kq_update_events(int fd, short filter, PF * handler) EV_SET(kep, (uintptr_t) fd, filter, kep_flags, 0, 0, 0); - /* Check if we've used the last one. If we have then submit them all */ + /* Check if we've used the last one. If we have then submit them all */ if (kqoff == kqmax - 1) { int ret; @@ -218,10 +218,10 @@ commResetSelect(int fd) { fde *F = &fd_table[fd]; if (F->read_handler) { - kq_update_events(fd, EVFILT_READ, (PF *)1); + kq_update_events(fd, EVFILT_READ, (PF *)1); } if (F->write_handler) { - kq_update_events(fd, EVFILT_WRITE, (PF *)1); + kq_update_events(fd, EVFILT_WRITE, (PF *)1); } } @@ -296,7 +296,7 @@ comm_select(int msec) if ((hdl = F->read_handler) != NULL) { F->read_handler = NULL; - F->flags.read_pending = 0; + F->flags.read_pending = 0; hdl(fd, F->read_data); } diff --git a/src/comm_kqueue.h b/src/comm_kqueue.h index 33517c35fc..9933dd0434 100644 --- a/src/comm_kqueue.h +++ b/src/comm_kqueue.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/comm_poll.cc b/src/comm_poll.cc index dd2be81a9b..36a625eff5 100644 --- a/src/comm_poll.cc +++ b/src/comm_poll.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -69,7 +69,7 @@ static void comm_poll_dns_incoming(void); * of incoming ICP, then we need to check these sockets more than * if we just have HTTP. * - * The variables 'incoming_icp_interval' and 'incoming_http_interval' + * The variables 'incoming_icp_interval' and 'incoming_http_interval' * determine how many normal I/O events to process before checking * incoming sockets again. Note we store the incoming_interval * multipled by a factor of (2^INCOMING_FACTOR) to have some @@ -90,7 +90,7 @@ static void comm_poll_dns_incoming(void); * incoming_interval = incoming_interval + target_average - number_of_events_processed * * There are separate incoming_interval counters for both HTTP and ICP events - * + * * You can see the current values of the incoming_interval's, as well as * a histogram of 'incoming_events' by asking the cache manager * for 'comm_incoming', e.g.: @@ -437,7 +437,7 @@ comm_select(int msec) continue; /* scan each socket but the accept socket. Poll this - * more frequently to minimize losses due to the 5 connect + * more frequently to minimize losses due to the 5 connect * limit in SunOS */ PROF_start(comm_handle_ready_fd); @@ -480,7 +480,7 @@ comm_select(int msec) else { PROF_start(comm_read_handler); F->read_handler = NULL; - F->flags.read_pending = 0; + F->flags.read_pending = 0; hdl(fd, F->read_data); PROF_stop(comm_read_handler); statCounter.select_fds++; @@ -522,7 +522,7 @@ comm_select(int msec) debugs(5, 0, "WARNING: FD " << fd << " has handlers, but it's invalid."); debugs(5, 0, "FD " << fd << " is a " << fdTypeStr[F->type]); debugs(5, 0, "--> " << F->desc); - debugs(5, 0, "tmout:" << F->timeoutHandler << "read:" << + debugs(5, 0, "tmout:" << F->timeoutHandler << "read:" << F->read_handler << " write:" << F->write_handler); for (ch = F->closeHandler; ch != NULL; ch = ch->Next()) @@ -532,7 +532,7 @@ comm_select(int msec) commCallCloseHandlers(fd); } else if (F->timeoutHandler != NULL) { debugs(5, 0, "comm_poll: Calling Timeout Handler"); - ScheduleCallHere(F->timeoutHandler); + ScheduleCallHere(F->timeoutHandler); } F->closeHandler = NULL; @@ -606,9 +606,9 @@ static void commPollRegisterWithCacheManager(void) { CacheManager::GetInstance()-> - registerAction("comm_poll_incoming", - "comm_incoming() stats", - commIncomingStats, 0, 1); + registerAction("comm_poll_incoming", + "comm_incoming() stats", + commIncomingStats, 0, 1); } void diff --git a/src/comm_poll.h b/src/comm_poll.h index e3ee514daf..9f6a7df7a9 100644 --- a/src/comm_poll.h +++ b/src/comm_poll.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/comm_select.cc b/src/comm_select.cc index aa96b3ec20..f0d7233e9d 100644 --- a/src/comm_select.cc +++ b/src/comm_select.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -79,7 +79,7 @@ static int nwritefds; * of incoming ICP, then we need to check these sockets more than * if we just have HTTP. * - * The variables 'incoming_icp_interval' and 'incoming_http_interval' + * The variables 'incoming_icp_interval' and 'incoming_http_interval' * determine how many normal I/O events to process before checking * incoming sockets again. Note we store the incoming_interval * multipled by a factor of (2^INCOMING_FACTOR) to have some @@ -100,7 +100,7 @@ static int nwritefds; * incoming_interval = incoming_interval + target_average - number_of_events_processed * * There are separate incoming_interval counters for both HTTP and ICP events - * + * * You can see the current values of the incoming_interval's, as well as * a histogram of 'incoming_events' by asking the cache manager * for 'comm_incoming', e.g.: @@ -523,7 +523,7 @@ comm_select(int msec) (void) 0; else { F->read_handler = NULL; - F->flags.read_pending = 0; + F->flags.read_pending = 0; commUpdateReadBits(fd, NULL); hdl(fd, F->read_data); statCounter.select_fds++; @@ -658,9 +658,9 @@ static void commSelectRegisterWithCacheManager(void) { CacheManager::GetInstance()-> - registerAction("comm_select_incoming", - "comm_incoming() stats", - commIncomingStats, 0, 1); + registerAction("comm_select_incoming", + "comm_incoming() stats", + commIncomingStats, 0, 1); } void @@ -682,7 +682,7 @@ comm_select_init(void) * and the server side of a cache fetch simultaneoulsy abort the * connection. While I haven't really studied the code to figure out how * it happens, the snippet below may prevent the cache from exitting: - * + * * Call this from where the select loop fails. */ static int @@ -732,7 +732,7 @@ examine_select(fd_set * readfds, fd_set * writefds) commCallCloseHandlers(fd); } else if (F->timeoutHandler != NULL) { debugs(5, 0, "examine_select: Calling Timeout Handler"); - ScheduleCallHere(F->timeoutHandler); + ScheduleCallHere(F->timeoutHandler); } F->closeHandler = NULL; diff --git a/src/comm_select.h b/src/comm_select.h index c80ac3108b..d09be163af 100644 --- a/src/comm_select.h +++ b/src/comm_select.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/comm_select_win32.cc b/src/comm_select_win32.cc index d7ec487876..aceb7e0fea 100644 --- a/src/comm_select_win32.cc +++ b/src/comm_select_win32.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -79,7 +79,7 @@ static int nwritefds; * of incoming ICP, then we need to check these sockets more than * if we just have HTTP. * - * The variables 'incoming_icp_interval' and 'incoming_http_interval' + * The variables 'incoming_icp_interval' and 'incoming_http_interval' * determine how many normal I/O events to process before checking * incoming sockets again. Note we store the incoming_interval * multipled by a factor of (2^INCOMING_FACTOR) to have some @@ -100,7 +100,7 @@ static int nwritefds; * incoming_interval = incoming_interval + target_average - number_of_events_processed * * There are separate incoming_interval counters for both HTTP and ICP events - * + * * You can see the current values of the incoming_interval's, as well as * a histogram of 'incoming_events' by asking the cache manager * for 'comm_incoming', e.g.: @@ -680,9 +680,9 @@ static void commSelectRegisterWithCacheManager(void) { CacheManager::GetInstance()-> - registerAction("comm_select_incoming", - "comm_incoming() stats", - commIncomingStats, 0, 1); + registerAction("comm_select_incoming", + "comm_incoming() stats", + commIncomingStats, 0, 1); } void @@ -704,7 +704,7 @@ comm_select_init(void) * and the server side of a cache fetch simultaneoulsy abort the * connection. While I haven't really studied the code to figure out how * it happens, the snippet below may prevent the cache from exitting: - * + * * Call this from where the select loop fails. */ static int @@ -754,7 +754,7 @@ examine_select(fd_set * readfds, fd_set * writefds) commCallCloseHandlers(fd); } else if (F->timeoutHandler != NULL) { debugs(5, 0, "examine_select: Calling Timeout Handler"); - ScheduleCallHere(F->timeoutHandler); + ScheduleCallHere(F->timeoutHandler); } F->closeHandler = NULL; diff --git a/src/debug.cc b/src/debug.cc index 25d15ee06b..28bd0d37bc 100644 --- a/src/debug.cc +++ b/src/debug.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -66,8 +66,7 @@ _db_print(const char *format,...) { #else _db_print(va_alist) -va_dcl -{ +va_dcl { const char *format = NULL; #endif @@ -84,8 +83,7 @@ va_dcl #ifdef _SQUID_MSWIN_ /* Multiple WIN32 threads may call this simultaneously */ - if (!dbg_mutex) - { + if (!dbg_mutex) { HMODULE krnl_lib = GetModuleHandle("Kernel32"); PFInitializeCriticalSectionAndSpinCount InitializeCriticalSectionAndSpinCount = NULL; @@ -175,7 +173,7 @@ _db_print_file(const char *format, va_list args) { vfprintf(debug_log, format, args); //*AYJ:*/ if (!Config.onoff.buffered_logs) - fflush(debug_log); + fflush(debug_log); } static void @@ -230,7 +228,7 @@ debugArg(const char *arg) { l = atoi(arg); assert(s >= -1); - if(s >= MAX_DEBUG_SECTIONS) + if (s >= MAX_DEBUG_SECTIONS) s = MAX_DEBUG_SECTIONS-1; if (l < 0) @@ -290,109 +288,109 @@ static struct syslog_facility_name { syslog_facility_names[] = { #ifdef LOG_AUTH - { - "auth", LOG_AUTH - }, + { + "auth", LOG_AUTH + }, #endif #ifdef LOG_AUTHPRIV - { - "authpriv", LOG_AUTHPRIV - }, + { + "authpriv", LOG_AUTHPRIV + }, #endif #ifdef LOG_CRON - { - "cron", LOG_CRON - }, + { + "cron", LOG_CRON + }, #endif #ifdef LOG_DAEMON - { - "daemon", LOG_DAEMON - }, + { + "daemon", LOG_DAEMON + }, #endif #ifdef LOG_FTP - { - "ftp", LOG_FTP - }, + { + "ftp", LOG_FTP + }, #endif #ifdef LOG_KERN - { - "kern", LOG_KERN - }, + { + "kern", LOG_KERN + }, #endif #ifdef LOG_LPR - { - "lpr", LOG_LPR - }, + { + "lpr", LOG_LPR + }, #endif #ifdef LOG_MAIL - { - "mail", LOG_MAIL - }, + { + "mail", LOG_MAIL + }, #endif #ifdef LOG_NEWS - { - "news", LOG_NEWS - }, + { + "news", LOG_NEWS + }, #endif #ifdef LOG_SYSLOG - { - "syslog", LOG_SYSLOG - }, + { + "syslog", LOG_SYSLOG + }, #endif #ifdef LOG_USER - { - "user", LOG_USER - }, + { + "user", LOG_USER + }, #endif #ifdef LOG_UUCP - { - "uucp", LOG_UUCP - }, + { + "uucp", LOG_UUCP + }, #endif #ifdef LOG_LOCAL0 - { - "local0", LOG_LOCAL0 - }, + { + "local0", LOG_LOCAL0 + }, #endif #ifdef LOG_LOCAL1 - { - "local1", LOG_LOCAL1 - }, + { + "local1", LOG_LOCAL1 + }, #endif #ifdef LOG_LOCAL2 - { - "local2", LOG_LOCAL2 - }, + { + "local2", LOG_LOCAL2 + }, #endif #ifdef LOG_LOCAL3 - { - "local3", LOG_LOCAL3 - }, + { + "local3", LOG_LOCAL3 + }, #endif #ifdef LOG_LOCAL4 - { - "local4", LOG_LOCAL4 - }, + { + "local4", LOG_LOCAL4 + }, #endif #ifdef LOG_LOCAL5 - { - "local5", LOG_LOCAL5 - }, + { + "local5", LOG_LOCAL5 + }, #endif #ifdef LOG_LOCAL6 - { - "local6", LOG_LOCAL6 - }, + { + "local6", LOG_LOCAL6 + }, #endif #ifdef LOG_LOCAL7 - { - "local7", LOG_LOCAL7 - }, + { + "local7", LOG_LOCAL7 + }, #endif - { - NULL, 0 - } - }; + { + NULL, 0 + } +}; #endif @@ -438,7 +436,7 @@ Debug::parseOptions(char const *options) { char *p = NULL; char *s = NULL; - if(Config.onoff.debug_override_X) { + if (Config.onoff.debug_override_X) { debugs(0, 9, "command-line -X overrides: " << options); return; } @@ -505,7 +503,7 @@ _db_rotate_log(void) { #ifdef _SQUID_MSWIN_ remove - (to); + (to); #endif @@ -527,7 +525,7 @@ _db_rotate_log(void) { #ifdef _SQUID_MSWIN_ remove - (to); + (to); #endif @@ -579,15 +577,15 @@ xassert(const char *msg, const char *file, int line) { * * Rationale * --------- - * + * * When you have a long nested processing sequence, it is often impossible * for low level routines to know in what larger context they operate. If a * routine coredumps, one can restore the context using debugger trace. * However, in many case you do not want to coredump, but just want to report * a potential problem. A report maybe useless out of problem context. - * + * * To solve this potential problem, use the following approach: - * + * * int * top_level_foo(const char *url) * { @@ -601,7 +599,7 @@ xassert(const char *msg, const char *file, int line) { * // exit, clean after yourself * ctx_exit(ctx); * } - * + * * void * bottom_level_boo(int status, void *data) * { @@ -611,32 +609,32 @@ xassert(const char *msg, const char *file, int line) { * debugs(13, 6, "DOS attack detected, data: " << data); * ... * } - * + * * Current implementation is extremely simple but still very handy. It has a * negligible overhead (descriptions are not duplicated). - * + * * When the _first_ debug message for a given context is printed, it is * prepended with the current context description. Context is printed with * the same debugging level as the original message. - * + * * Note that we do not print context every type you do ctx_enter(). This * approach would produce too many useless messages. For the same reason, a * context description is printed at most _once_ even if you have 10 * debugging messages within one context. - * + * * Contexts can be nested, of course. You must use ctx_enter() to enter a * context (push it onto stack). It is probably safe to exit several nested * contexts at _once_ by calling ctx_exit() at the top level (this will pop * all context till current one). However, as in any stack, you cannot start * in the middle. - * - * Analysis: + * + * Analysis: * i) locate debugging message, * ii) locate current context by going _upstream_ in your log file, * iii) hack away. * * - * To-Do: + * To-Do: * ----- * * decide if we want to dup() descriptions (adds overhead) but allows to @@ -772,10 +770,10 @@ Debug::finishDebug() { // Relies on assert macro calling xassert() without a specific scope. void Debug::xassert(const char *msg, const char *file, int line) { - + if (CurrentDebug) { *CurrentDebug << "assertion failed: " << file << ":" << line << - ": \"" << msg << "\""; + ": \"" << msg << "\""; } abort(); } diff --git a/src/defines.h b/src/defines.h index ae1c701c3c..faf89395d6 100644 --- a/src/defines.h +++ b/src/defines.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/delay_pools.cc b/src/delay_pools.cc index 31efc28c46..766bb51894 100644 --- a/src/delay_pools.cc +++ b/src/delay_pools.cc @@ -22,12 +22,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -553,7 +553,7 @@ void DelayPools::RegisterWithCacheManager(void) { CacheManager::GetInstance()-> - registerAction("delay", "Delay Pool Levels", Stats, 0, 1); + registerAction("delay", "Delay Pool Levels", Stats, 0, 1); } void @@ -864,7 +864,7 @@ unsigned int IndividualPool::makeKey (IPAddress &src_addr) const { /* FIXME INET6 : IPv6 requires a 64-128 bit result from this function */ - if( !src_addr.IsIPv4() ) + if ( !src_addr.IsIPv4() ) return 1; /* Temporary bypass for IPv4-only */ @@ -891,7 +891,7 @@ unsigned int ClassCNetPool::makeKey (IPAddress &src_addr) const { /* FIXME INET6 : IPv6 requires a 64-128 bit result from this function */ - if( !src_addr.IsIPv4() ) + if ( !src_addr.IsIPv4() ) return 1; /* Temporary bypass for IPv4-only */ @@ -965,7 +965,7 @@ unsigned char ClassCHostPool::makeHostKey (IPAddress &src_addr) const { /* FIXME INET6 : IPv6 requires a 64-128 bit result from this function */ - if( !src_addr.IsIPv4() ) + if ( !src_addr.IsIPv4() ) return 1; /* Temporary bypass for IPv4-only */ @@ -978,7 +978,7 @@ unsigned int ClassCHostPool::makeKey (IPAddress &src_addr) const { /* FIXME INET6 : IPv6 requires a 64-128 bit result from this function */ - if( !src_addr.IsIPv4() ) + if ( !src_addr.IsIPv4() ) return 1; /* Temporary bypass for IPv4-only */ diff --git a/src/disk.cc b/src/disk.cc index 0053483f82..9853426344 100644 --- a/src/disk.cc +++ b/src/disk.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -173,8 +173,7 @@ diskCombineWrites(struct _fde_disk *fdd) * XXX This currently ignores any seeks (file_offset) */ - if (fdd->write_q != NULL && fdd->write_q->next != NULL) - { + if (fdd->write_q != NULL && fdd->write_q->next != NULL) { len = 0; for (q = fdd->write_q; q != NULL; q = q->next) @@ -485,7 +484,7 @@ diskHandleRead(int fd, void *data) /* start read operation */ /* buffer must be allocated from the caller. - * It must have at least req_len space in there. + * It must have at least req_len space in there. * call handler when a reading is complete. */ void file_read(int fd, char *buf, int req_len, off_t offset, DRCB * handler, void *client_data) @@ -516,7 +515,7 @@ safeunlink(const char *s, int quiet) /* * Same as rename(2) but complains if something goes wrong; - * the caller is responsible for handing and explaining the + * the caller is responsible for handing and explaining the * consequences of errors. */ int @@ -526,7 +525,7 @@ xrename(const char *from, const char *to) #if defined (_SQUID_OS2_) || defined (_SQUID_WIN32_) remove - (to); + (to); #endif diff --git a/src/dlink.h b/src/dlink.h index b2e9942c57..d449d17069 100644 --- a/src/dlink.h +++ b/src/dlink.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -38,15 +38,14 @@ class dlink_node { public: - dlink_node() : data(NULL), prev(NULL), next(NULL){} + dlink_node() : data(NULL), prev(NULL), next(NULL) {} void *data; dlink_node *prev; dlink_node *next; }; -struct dlink_list -{ +struct dlink_list { dlink_node *head; dlink_node *tail; }; diff --git a/src/dns.cc b/src/dns.cc index 2b0b0a7451..ae432a6597 100644 --- a/src/dns.cc +++ b/src/dns.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -59,7 +59,7 @@ static void dnsRegisterWithCacheManager(void) { CacheManager::GetInstance-> - registerAction("dns", "Dnsserver Statistics", dnsStats, 0, 1); + registerAction("dns", "Dnsserver Statistics", dnsStats, 0, 1); } void diff --git a/src/dns_internal.cc b/src/dns_internal.cc index be81dc5917..ac9c862aff 100644 --- a/src/dns_internal.cc +++ b/src/dns_internal.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -92,8 +92,7 @@ typedef struct _sp sp; typedef struct _nsvc nsvc; -struct _idns_query -{ +struct _idns_query { hash_link hash; rfc1035_query query; char buf[RESOLV_BUFSZ]; @@ -123,8 +122,7 @@ struct _idns_query } initial_AAAA; }; -struct _nsvc -{ +struct _nsvc { int ns; int fd; unsigned short msglen; @@ -134,16 +132,14 @@ struct _nsvc bool busy; }; -struct _ns -{ +struct _ns { IPAddress S; int nqueries; int nreplies; nsvc *vc; }; -struct _sp -{ +struct _sp { char domain[NS_MAXDNAME]; int queries; }; @@ -318,17 +314,17 @@ idnsParseResolvConf(void) idnsAddNameserver(t); } else if (strcasecmp(t, "domain") == 0) { - idnsFreeSearchpath(); - t = strtok(NULL, w_space); + idnsFreeSearchpath(); + t = strtok(NULL, w_space); - if (NULL == t) - continue; + if (NULL == t) + continue; - debugs(78, 1, "Adding domain " << t << " from " << _PATH_RESCONF); + debugs(78, 1, "Adding domain " << t << " from " << _PATH_RESCONF); - idnsAddPathComponent(t); + idnsAddPathComponent(t); } else if (strcasecmp(t, "search") == 0) { - idnsFreeSearchpath(); + idnsFreeSearchpath(); while (NULL != t) { t = strtok(NULL, w_space); @@ -358,9 +354,9 @@ idnsParseResolvConf(void) } } if (npc == 0 && (t = getMyHostname())) { - t = strchr(t, '.'); - if (t) - idnsAddPathComponent(t+1); + t = strchr(t, '.'); + if (t) + idnsAddPathComponent(t+1); } fclose(fp); @@ -382,18 +378,18 @@ idnsParseWIN32SearchList(const char * Separator) DWORD Type = 0; DWORD Size = 0; LONG Result; - Result = - RegQueryValueEx(hndKey, "Domain", NULL, &Type, NULL, - &Size); - - if (Result == ERROR_SUCCESS && Size) { - t = (char *) xmalloc(Size); - RegQueryValueEx(hndKey, "Domain", NULL, &Type, (LPBYTE) t, - &Size); - debugs(78, 1, "Adding domain " << t << " from Registry"); - idnsAddPathComponent(t); - xfree(t); - } + Result = + RegQueryValueEx(hndKey, "Domain", NULL, &Type, NULL, + &Size); + + if (Result == ERROR_SUCCESS && Size) { + t = (char *) xmalloc(Size); + RegQueryValueEx(hndKey, "Domain", NULL, &Type, (LPBYTE) t, + &Size); + debugs(78, 1, "Adding domain " << t << " from Registry"); + idnsAddPathComponent(t); + xfree(t); + } Result = RegQueryValueEx(hndKey, "SearchList", NULL, &Type, NULL, &Size); @@ -409,15 +405,15 @@ idnsParseWIN32SearchList(const char * Separator) debugs(78, 1, "Adding domain " << token << " from Registry"); token = strtok(NULL, Separator); } - xfree(t); + xfree(t); } RegCloseKey(hndKey); } if (npc == 0 && (t = (char *) getMyHostname())) { - t = strchr(t, '.'); - if (t) - idnsAddPathComponent(t + 1); + t = strchr(t, '.'); + if (t) + idnsAddPathComponent(t + 1); } } @@ -454,7 +450,7 @@ idnsParseWIN32Registry(void) debugs(78, 1, "Adding DHCP nameserver " << token << " from Registry"); token = strtok(NULL, ","); } - xfree(t); + xfree(t); } Result = @@ -470,7 +466,7 @@ idnsParseWIN32Registry(void) idnsAddNameserver(token); token = strtok(NULL, ", "); } - xfree(t); + xfree(t); } RegCloseKey(hndKey); @@ -524,7 +520,7 @@ idnsParseWIN32Registry(void) idnsAddNameserver(token); token = strtok(NULL, ", "); } - xfree(t); + xfree(t); } Result = @@ -542,7 +538,7 @@ idnsParseWIN32Registry(void) idnsAddNameserver(token); token = strtok(NULL, ", "); } - xfree(t); + xfree(t); } RegCloseKey(hndKey2); @@ -583,7 +579,7 @@ idnsParseWIN32Registry(void) idnsAddNameserver(token); token = strtok(NULL, ", "); } - xfree(t); + xfree(t); } RegCloseKey(hndKey); @@ -838,9 +834,9 @@ idnsSendQuery(idns_query * q) if (x < 0) debugs(50, 1, "idnsSendQuery: FD " << DnsSocket << ": sendto: " << xstrerror()); - } while( x<0 && q->nsends % nns != 0); + } while ( x<0 && q->nsends % nns != 0); - if(x >= 0) { + if (x >= 0) { fd_bytes(DnsSocket, x, FD_WRITE); commSetSelect(DnsSocket, COMM_SELECT_READ, idnsRead, NULL, 0); } @@ -856,8 +852,7 @@ idnsFromKnownNameserver(IPAddress const &from) { int i; - for (i = 0; i < nns; i++) - { + for (i = 0; i < nns; i++) { if (nameservers[i].S != from) continue; @@ -892,7 +887,7 @@ idnsQueryID(void) unsigned short id = squid_random() & 0xFFFF; unsigned short first_id = id; - while(idnsFindQuery(id)) { + while (idnsFindQuery(id)) { id++; if (id == first_id) { @@ -916,7 +911,7 @@ idnsCallback(idns_query *q, rfc1035_rr *answers, int n, const char *error) if (cbdataReferenceValidDone(q->callback_data, &cbdata)) callback(cbdata, answers, n, error); - while(q->queue) { + while (q->queue) { idns_query *q2 = q->queue; q->queue = q2->queue; callback = q2->callback; @@ -1034,11 +1029,10 @@ idnsGrokReply(const char *buf, size_t sz) q->id = idnsQueryID(); rfc1035SetQueryID(q->buf, q->id); #if USE_IPV6 - if(q->query.qtype == RFC1035_TYPE_AAAA) { + if (q->query.qtype == RFC1035_TYPE_AAAA) { debugs(78, 3, "idnsGrokReply: Trying AAAA Query for " << q->name); q->sz = rfc3596BuildAAAAQuery(q->name, q->buf, sizeof(q->buf), q->id, &q->query); - } - else + } else #endif { debugs(78, 3, "idnsGrokReply: Trying A Query for " << q->name); @@ -1051,8 +1045,7 @@ idnsGrokReply(const char *buf, size_t sz) } #if USE_IPV6 - if(q->need_A && (Config.onoff.dns_require_A == 1 || n <= 0 ) ) - { + if (q->need_A && (Config.onoff.dns_require_A == 1 || n <= 0 ) ) { /* ERROR or NO AAAA exist. Failover to A records. */ /* Apparently its also a good idea to lookup and store the A records * just in case the AAAA are not available when we need them. @@ -1060,15 +1053,15 @@ idnsGrokReply(const char *buf, size_t sz) * thus the || above allowing the user to request always both. */ - if(n == 0) + if (n == 0) debugs(78, 3, "idnsGrokReply: " << q->name << " has no AAAA records. Looking up A record instead."); - else if(q->need_A && n <= 0) + else if (q->need_A && n <= 0) debugs(78, 3, "idnsGrokReply: " << q->name << " AAAA query failed. Trying A now instead."); else // admin requested this. debugs(78, 3, "idnsGrokReply: " << q->name << " AAAA query done. Configured to retrieve A now also."); // move the initial message results into the failover query for merging later. - if(n > 0) { + if (n > 0) { q->initial_AAAA.count = message->ancount; q->initial_AAAA.answers = message->answer; message->answer = NULL; @@ -1088,8 +1081,8 @@ idnsGrokReply(const char *buf, size_t sz) } #endif - /** If there are two result sets from preceeding AAAA and A lookups merge them with a preference for AAAA */ - if(q->initial_AAAA.count > 0 && n > 0) { + /** If there are two result sets from preceeding AAAA and A lookups merge them with a preference for AAAA */ + if (q->initial_AAAA.count > 0 && n > 0) { /* two sets of RR need merging */ rfc1035_rr *result = (rfc1035_rr*) xmalloc( sizeof(rfc1035_rr)*(n + q->initial_AAAA.count) ); rfc1035_rr *tmp = result; @@ -1108,8 +1101,7 @@ idnsGrokReply(const char *buf, size_t sz) message->answer = result; n += q->initial_AAAA.count; q->initial_AAAA.count=0; - } - else if(q->initial_AAAA.count > 0 && n <= 0) { + } else if (q->initial_AAAA.count > 0 && n <= 0) { /* initial of dual queries was the only result set. */ debugs(78, 6, HERE << "Merging DNS results " << q->name << " AAAA has " << q->initial_AAAA.count << " RR, A has " << n << " RR"); rfc1035RRDestroy(&(message->answer), n); @@ -1187,10 +1179,10 @@ idnsRead(int fd, void *data) if (squid_curtime - last_warning > 60) { debugs(78, 1, "WARNING: Reply from unknown nameserver " << from); last_warning = squid_curtime; - } - else { + } else { debugs(78, 1, "WARNING: Reply from unknown nameserver " << from << " (retrying..." << (squid_curtime-last_warning) << "<=60)" ); - } continue; + } + continue; } idnsGrokReply(rbuf, len); @@ -1219,7 +1211,7 @@ idnsCheckQueue(void *unused) /* Anything to process in the queue? */ if (tvSubDsec(q->queue_t, current_time) < Config.Timeout.idns_retransmit ) - break; + break; /* Query timer expired? */ if (tvSubDsec(q->sent_t, current_time) < Config.Timeout.idns_retransmit * 1 << ((q->nsends - 1) / nns)) { @@ -1236,9 +1228,9 @@ idnsCheckQueue(void *unused) if (tvSubDsec(q->start_t, current_time) < Config.Timeout.idns_query) { idnsSendQuery(q); } else { - debugs(78, 2, "idnsCheckQueue: ID " << std::hex << q->id << - ": giving up after " << std::dec << q->nsends << " tries and " << - std::setw(5)<< std::setprecision(2) << tvSubDsec(q->start_t, current_time) << " seconds"); + debugs(78, 2, "idnsCheckQueue: ID " << std::hex << q->id << + ": giving up after " << std::dec << q->nsends << " tries and " << + std::setw(5)<< std::setprecision(2) << tvSubDsec(q->start_t, current_time) << " seconds"); if (q->rcode != 0) idnsCallback(q, NULL, -q->rcode, q->error); @@ -1333,7 +1325,7 @@ static void idnsRegisterWithCacheManager(void) { CacheManager::GetInstance()-> - registerAction("idns", "Internal DNS Statistics", idnsStats, 0, 1); + registerAction("idns", "Internal DNS Statistics", idnsStats, 0, 1); } void @@ -1499,7 +1491,7 @@ idnsALookup(const char *name, IDNSCB * callback, void *data) } #if USE_IPV6 - q->sz = rfc3596BuildAAAAQuery(q->name, q->buf, sizeof(q->buf), q->id, &q->query); + q->sz = rfc3596BuildAAAAQuery(q->name, q->buf, sizeof(q->buf), q->id, &q->query); q->need_A = true; #else q->sz = rfc3596BuildAQuery(q->name, q->buf, sizeof(q->buf), q->id, &q->query); @@ -1513,7 +1505,7 @@ idnsALookup(const char *name, IDNSCB * callback, void *data) return; } - debugs(78, 3, "idnsALookup: buf is " << q->sz << " bytes for " << q->name << + debugs(78, 3, "idnsALookup: buf is " << q->sz << " bytes for " << q->name << ", id = 0x" << std::hex << q->id); q->callback = callback; @@ -1541,12 +1533,11 @@ idnsPTRLookup(const IPAddress &addr, IDNSCB * callback, void *data) q->id = idnsQueryID(); #if USE_IPV6 - if( addr.IsIPv6() ) { + if ( addr.IsIPv6() ) { struct in6_addr addr6; addr.GetInAddr(addr6); q->sz = rfc3596BuildPTRQuery6(addr6, q->buf, sizeof(q->buf), q->id, &q->query); - } - else + } else #endif { struct in_addr addr4; @@ -1557,8 +1548,7 @@ idnsPTRLookup(const IPAddress &addr, IDNSCB * callback, void *data) /* PTR does not do inbound A/AAAA */ q->need_A = false; - if (q->sz < 0) - { + if (q->sz < 0) { /* problem with query data -- query not sent */ callback(data, NULL, 0, "Internal error"); cbdataFree(q); @@ -1566,11 +1556,11 @@ idnsPTRLookup(const IPAddress &addr, IDNSCB * callback, void *data) } if (idnsCachedLookup(q->query.name, callback, data)) { - cbdataFree(q); - return; + cbdataFree(q); + return; } - debugs(78, 3, "idnsPTRLookup: buf is " << q->sz << " bytes for " << ip << + debugs(78, 3, "idnsPTRLookup: buf is " << q->sz << " bytes for " << ip << ", id = 0x" << std::hex << q->id); q->callback = callback; diff --git a/src/dnsserver.cc b/src/dnsserver.cc index 14a2877a0c..87b80e9af5 100644 --- a/src/dnsserver.cc +++ b/src/dnsserver.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -220,7 +220,7 @@ lookup(const char *buf) xfreeaddrinfo(AI); AI = NULL; - if( 0 == (res = xgetaddrinfo(buf,NULL,&hints,&AI)) ) + if ( 0 == (res = xgetaddrinfo(buf,NULL,&hints,&AI)) ) break; if (res != EAI_AGAIN) @@ -234,10 +234,10 @@ lookup(const char *buf) /* check if it's already an IP address in text form. */ ipa = buf; - if( ipa.IsAnyAddr() ) { + if ( ipa.IsAnyAddr() ) { /* its a domain name. Use the forward-DNS lookup already done */ - if(res == 0) { + if (res == 0) { #if LIBRESOLV_DNS_TTL_HACK /* DNS TTL handling - bne@CareNet.hu * for first try it's a dirty hack, by hacking getanswer @@ -249,25 +249,24 @@ lookup(const char *buf) i = 0; aiptr = AI; - while(NULL != aiptr && 32 >= i) { + while (NULL != aiptr && 32 >= i) { memset(ntoabuf, 0, MAX_IPSTRLEN); /* getaddrinfo given a host has a nasty tendency to return duplicate addr's */ /* BUT sorted fortunately, so we can drop most of them easily */ - if( prev_addr && - prev_addr->ai_family==aiptr->ai_family && - memcmp(aiptr->ai_addr, prev_addr->ai_addr, aiptr->ai_addrlen)==0 - ) { + if ( prev_addr && + prev_addr->ai_family==aiptr->ai_family && + memcmp(aiptr->ai_addr, prev_addr->ai_addr, aiptr->ai_addrlen)==0 + ) { prev_addr = aiptr; aiptr = aiptr->ai_next; continue; - } - else { + } else { prev_addr = aiptr; } /* annoying inet_ntop breaks the nice code by requiring the in*_addr */ - switch(aiptr->ai_family) { + switch (aiptr->ai_family) { case AF_INET: xinet_ntop(aiptr->ai_family, &((struct sockaddr_in*)aiptr->ai_addr)->sin_addr, ntoabuf, MAX_IPSTRLEN); break; @@ -288,16 +287,14 @@ lookup(const char *buf) prev_addr=NULL; printf("\n"); } - } - else /* its an IPA in text form. perform rDNS */ - { + } else { /* its an IPA in text form. perform rDNS */ /* You'd expect getaddrinfo given AI_CANONNAME would do a lookup on * missing FQDN. But no, it only copies the input string to that * position regardless of its content. */ - if(NULL != AI && NULL != AI->ai_addr) { - for(;;) { - if( 0 == (res = xgetnameinfo(AI->ai_addr, AI->ai_addrlen, ntoabuf, MAX_IPSTRLEN, NULL,0,0)) ) + if (NULL != AI && NULL != AI->ai_addr) { + for (;;) { + if ( 0 == (res = xgetnameinfo(AI->ai_addr, AI->ai_addrlen, ntoabuf, MAX_IPSTRLEN, NULL,0,0)) ) break; if (res != EAI_AGAIN) @@ -310,7 +307,7 @@ lookup(const char *buf) } } - if(res == 0) { + if (res == 0) { #if LIBRESOLV_DNS_TTL_HACK /* DNS TTL handling - bne@CareNet.hu * for first try it's a dirty hack, by hacking getanswer @@ -323,32 +320,32 @@ lookup(const char *buf) } } - switch(res) { - case 0: - /* no error. */ - break; + switch (res) { + case 0: + /* no error. */ + break; - case EAI_AGAIN: - printf("$fail Name Server for domain '%s' is unavailable.\n", buf); - break; + case EAI_AGAIN: + printf("$fail Name Server for domain '%s' is unavailable.\n", buf); + break; - case EAI_FAIL: - printf("$fail DNS Domain/IP '%s' does not exist: %s.\n", buf, xgai_strerror(res)); - break; + case EAI_FAIL: + printf("$fail DNS Domain/IP '%s' does not exist: %s.\n", buf, xgai_strerror(res)); + break; #if defined(EAI_NODATA) || defined(EAI_NONAME) #ifdef EAI_NODATA /* deprecated. obsolete on some OS */ - case EAI_NODATA: + case EAI_NODATA: #endif #ifdef EAI_NONAME - case EAI_NONAME: + case EAI_NONAME: #endif - printf("$fail DNS Domain/IP '%s' exists without any FQDN/IPs: %s.\n", buf, xgai_strerror(res)); - break; + printf("$fail DNS Domain/IP '%s' exists without any FQDN/IPs: %s.\n", buf, xgai_strerror(res)); + break; #endif - default: - printf("$fail A system error occured looking up Domain/IP '%s': %s.\n", buf, xgai_strerror(res)); + default: + printf("$fail A system error occured looking up Domain/IP '%s': %s.\n", buf, xgai_strerror(res)); } xfreeaddrinfo(AI); @@ -365,7 +362,7 @@ usage(void) "\t-v Version\n" "\t-s nameserver Specify alternate name server(s). 'nameserver'\n" "\t must be an IPv4 address, -s option may be repeated\n" - ); + ); } #ifdef _SQUID_RES_NSADDR6_LARRAY @@ -434,35 +431,33 @@ main(int argc, char *argv[]) opt_s = 1; } -/* AYJ: - * I experimented with all the permutations of mixed/unmixed nscount/nscount6 IPv4/IPv6/Both/invalid - * - * I'm not sure if splitting them really helps. - * I've seen no evidence of IPv4 resolver *ever* being used when some IPv6 are set (or not even) - * BUT, have seen segfault when IPv4 is added to NSADDR6 list (_res._u._ext). - * It also appears to not do ANY lookup when _res.nscount==0. - * - * BUT, even if _res.nsaddrs is memset to NULL, it resolves IFF IPv6 set in _ext. - * - * SO, am splittig the IPv4/v6 into the seperate _res fields - * and making nscount a total of IPv4+IPv6 /w nscount6 the IPv6 sub-counter - * ie. nscount = count(NSv4)+count(NSv6) & nscount6 = count(NSv6) - * - * If ANYONE knows better please let us know. - * - */ - if( !(ipa = optarg) ) { + /* AYJ: + * I experimented with all the permutations of mixed/unmixed nscount/nscount6 IPv4/IPv6/Both/invalid + * + * I'm not sure if splitting them really helps. + * I've seen no evidence of IPv4 resolver *ever* being used when some IPv6 are set (or not even) + * BUT, have seen segfault when IPv4 is added to NSADDR6 list (_res._u._ext). + * It also appears to not do ANY lookup when _res.nscount==0. + * + * BUT, even if _res.nsaddrs is memset to NULL, it resolves IFF IPv6 set in _ext. + * + * SO, am splittig the IPv4/v6 into the seperate _res fields + * and making nscount a total of IPv4+IPv6 /w nscount6 the IPv6 sub-counter + * ie. nscount = count(NSv4)+count(NSv6) & nscount6 = count(NSv6) + * + * If ANYONE knows better please let us know. + * + */ + if ( !(ipa = optarg) ) { fprintf(stderr, "%s appears to be a bad nameserver FQDN/IP.\n",optarg); - } - else if( ipa.IsIPv4() ) { + } else if ( ipa.IsIPv4() ) { if (_SQUID_RES_NSADDR_COUNT == MAXNS) { fprintf(stderr, "Too many -s options, only %d are allowed\n", MAXNS); break; } _SQUID_RES_NSADDR_LIST[_SQUID_RES_NSADDR_COUNT] = _SQUID_RES_NSADDR_LIST[0]; ipa.GetInAddr(_SQUID_RES_NSADDR_LIST[_SQUID_RES_NSADDR_COUNT++].sin_addr); - } - else if( ipa.IsIPv6() ) { + } else if ( ipa.IsIPv6() ) { #if USE_IPV6 && defined(_SQUID_RES_NSADDR6_LIST) /* because things NEVER seem to resolve in tests without _res.nscount being a total. */ @@ -517,12 +512,12 @@ main(int argc, char *argv[]) for (;;) { memset(request, '\0', REQ_SZ); - if (fgets(request, REQ_SZ, stdin) == NULL) { + if (fgets(request, REQ_SZ, stdin) == NULL) { #ifdef _SQUID_MSWIN_ - WSACleanup(); + WSACleanup(); #endif - exit(1); - } + exit(1); + } t = strrchr(request, '\n'); diff --git a/src/eCAP/Config.cc b/src/eCAP/Config.cc index 73057d8e66..b8d3263ef1 100644 --- a/src/eCAP/Config.cc +++ b/src/eCAP/Config.cc @@ -21,10 +21,11 @@ Ecap::Config::~Config() } void -Ecap::Config::finalize() { - Adaptation::Config::finalize(); - libecap::shared_ptr host(new Ecap::Host); - libecap::RegisterHost(host); +Ecap::Config::finalize() +{ + Adaptation::Config::finalize(); + libecap::shared_ptr host(new Ecap::Host); + libecap::RegisterHost(host); } Adaptation::ServicePointer diff --git a/src/eCAP/Config.h b/src/eCAP/Config.h index 84e7bff5e2..5f3e11d1a9 100644 --- a/src/eCAP/Config.h +++ b/src/eCAP/Config.h @@ -9,7 +9,8 @@ #include "adaptation/Config.h" -namespace Ecap { +namespace Ecap +{ class Config: public Adaptation::Config { @@ -18,7 +19,7 @@ public: Config(); ~Config(); - virtual void finalize(); + virtual void finalize(); private: Config(const Config &); // not implemented diff --git a/src/eCAP/Host.cc b/src/eCAP/Host.cc index 813f9fa1ae..9fae209313 100644 --- a/src/eCAP/Host.cc +++ b/src/eCAP/Host.cc @@ -47,43 +47,43 @@ Ecap::Host::describe(std::ostream &os) const void Ecap::Host::noteService(const libecap::weak_ptr &weak) { - // Many ecap_service lines may use the same service URI. Find each + // Many ecap_service lines may use the same service URI. Find each // matching service rep, make sure it is an eCAP rep, - // and update it with the actual eCAP service. + // and update it with the actual eCAP service. int found = 0; - libecap::shared_ptr shared(weak); + libecap::shared_ptr shared(weak); typedef Adaptation::Services::iterator SI; for (SI i = Adaptation::AllServices().begin(); i != Adaptation::AllServices().end(); ++i) { if ((*i)->cfg().uri == shared->uri().c_str()) { ServiceRep *rep = dynamic_cast(i->getRaw()); - Must(rep); - rep->noteService(shared); + Must(rep); + rep->noteService(shared); ++found; - } - } + } + } - debugs(93,5, "Found " << found << " ecap_service configs for " << - shared->uri()); + debugs(93,5, "Found " << found << " ecap_service configs for " << + shared->uri()); if (!found) { - debugs(93,1, "Warning: ignoring loaded eCAP module service without " << - "a matching ecap_service configuration: " << shared->uri()); - } + debugs(93,1, "Warning: ignoring loaded eCAP module service without " << + "a matching ecap_service configuration: " << shared->uri()); + } } static int SquidLogLevel(libecap::LogVerbosity lv) { - if (lv.critical()) - return DBG_CRITICAL; // is it a good idea to ignore other flags? + if (lv.critical()) + return DBG_CRITICAL; // is it a good idea to ignore other flags? - if (lv.large()) - return DBG_DATA; // is it a good idea to ignore other flags? + if (lv.large()) + return DBG_DATA; // is it a good idea to ignore other flags? - if (lv.application()) - return DBG_DATA; // is it a good idea to ignore other flags? + if (lv.application()) + return DBG_DATA; // is it a good idea to ignore other flags? - return 2 + 2*lv.debugging() + 3*lv.operation() + 2*lv.xaction(); + return 2 + 2*lv.debugging() + 3*lv.operation() + 2*lv.xaction(); } std::ostream * @@ -92,15 +92,15 @@ Ecap::Host::openDebug(libecap::LogVerbosity lv) const int squidLevel = SquidLogLevel(lv); const int squidSection = 93; // XXX: this should be a global constant // XXX: Debug.h should provide this to us - if ((Debug::level = squidLevel) <= Debug::Levels[squidSection]) - return &Debug::getDebugOut(); - else - return NULL; + if ((Debug::level = squidLevel) <= Debug::Levels[squidSection]) + return &Debug::getDebugOut(); + else + return NULL; } void Ecap::Host::closeDebug(std::ostream *debug) { - if (debug) - Debug::finishDebug(); + if (debug) + Debug::finishDebug(); } diff --git a/src/eCAP/Host.h b/src/eCAP/Host.h index 569f6190d5..48fa1c3fdb 100644 --- a/src/eCAP/Host.h +++ b/src/eCAP/Host.h @@ -8,24 +8,25 @@ #include -namespace Ecap { +namespace Ecap +{ // Squid wrapper, providing host application functionality to eCAP services. class Host : public libecap::host::Host { public: - Host(); + Host(); - // About - virtual std::string uri() const; // unique across all vendors - virtual void describe(std::ostream &os) const; // free-format info + // About + virtual std::string uri() const; // unique across all vendors + virtual void describe(std::ostream &os) const; // free-format info - // Service management - virtual void noteService(const libecap::weak_ptr &s); + // Service management + virtual void noteService(const libecap::weak_ptr &s); - // Logging - virtual std::ostream *openDebug(libecap::LogVerbosity lv); - virtual void closeDebug(std::ostream *debug); + // Logging + virtual std::ostream *openDebug(libecap::LogVerbosity lv); + virtual void closeDebug(std::ostream *debug); }; extern const libecap::Name protocolInternal; diff --git a/src/eCAP/MessageRep.cc b/src/eCAP/MessageRep.cc index 100caa76f9..0f3eaf0abb 100644 --- a/src/eCAP/MessageRep.cc +++ b/src/eCAP/MessageRep.cc @@ -18,7 +18,7 @@ /* HeaderRep */ Ecap::HeaderRep::HeaderRep(HttpMsg &aMessage): theHeader(aMessage.header), - theMessage(aMessage) + theMessage(aMessage) { } @@ -28,8 +28,8 @@ Ecap::HeaderRep::hasAny(const Name &name) const const http_hdr_type squidId = TranslateHeaderId(name); // XXX: optimize to remove getByName: we do not need the value here return squidId == HDR_OTHER ? - theHeader.getByName(name.image().c_str()).size() > 0: - (bool)theHeader.has(squidId); + theHeader.getByName(name.image().c_str()).size() > 0: + (bool)theHeader.has(squidId); } Ecap::HeaderRep::Value @@ -37,8 +37,8 @@ Ecap::HeaderRep::value(const Name &name) const { const http_hdr_type squidId = TranslateHeaderId(name); const String value = squidId == HDR_OTHER ? - theHeader.getByName(name.image().c_str()) : - theHeader.getStrOrList(squidId); + theHeader.getByName(name.image().c_str()) : + theHeader.getStrOrList(squidId); return Value::FromTempString(value.buf()); } @@ -47,7 +47,7 @@ Ecap::HeaderRep::add(const Name &name, const Value &value) { const http_hdr_type squidId = TranslateHeaderId(name); // HDR_OTHER OK HttpHeaderEntry *e = new HttpHeaderEntry(squidId, name.image().c_str(), - value.toString().c_str()); + value.toString().c_str()); theHeader.addEntry(e); } @@ -104,7 +104,7 @@ libecap::Version Ecap::FirstLineRep::version() const { return libecap::Version(theMessage.http_ver.major, - theMessage.http_ver.minor); + theMessage.http_ver.minor); } void @@ -119,22 +119,35 @@ Ecap::FirstLineRep::protocol() const { // TODO: optimize? switch (theMessage.protocol) { - case PROTO_HTTP: return libecap::protocolHttp; - case PROTO_HTTPS: return libecap::protocolHttps; - case PROTO_FTP: return libecap::protocolFtp; - case PROTO_GOPHER: return libecap::protocolGopher; - case PROTO_WAIS: return libecap::protocolWais; - case PROTO_WHOIS: return libecap::protocolWhois; - case PROTO_URN: return libecap::protocolUrn; - case PROTO_ICP: return protocolIcp; + case PROTO_HTTP: + return libecap::protocolHttp; + case PROTO_HTTPS: + return libecap::protocolHttps; + case PROTO_FTP: + return libecap::protocolFtp; + case PROTO_GOPHER: + return libecap::protocolGopher; + case PROTO_WAIS: + return libecap::protocolWais; + case PROTO_WHOIS: + return libecap::protocolWhois; + case PROTO_URN: + return libecap::protocolUrn; + case PROTO_ICP: + return protocolIcp; #if USE_HTCP - case PROTO_HTCP: return protocolHtcp; + case PROTO_HTCP: + return protocolHtcp; #endif - case PROTO_CACHEOBJ: return protocolCacheObj; - case PROTO_INTERNAL: return protocolInternal; - case PROTO_NONE: return Name(); - - case PROTO_MAX: break; // should not happen + case PROTO_CACHEOBJ: + return protocolCacheObj; + case PROTO_INTERNAL: + return protocolInternal; + case PROTO_NONE: + return Name(); + + case PROTO_MAX: + break; // should not happen // no default to catch PROTO_ additions } Must(false); // not reached @@ -160,7 +173,7 @@ Ecap::FirstLineRep::TranslateProtocolId(const Name &name) /* RequestHeaderRep */ Ecap::RequestLineRep::RequestLineRep(HttpRequest &aMessage): - FirstLineRep(aMessage), theMessage(aMessage) + FirstLineRep(aMessage), theMessage(aMessage) { } @@ -180,7 +193,7 @@ Ecap::RequestLineRep::Area Ecap::RequestLineRep::uri() const { return Area::FromTempBuffer(theMessage.urlpath.buf(), - theMessage.urlpath.size()); + theMessage.urlpath.size()); } void @@ -194,7 +207,7 @@ Ecap::RequestLineRep::method(const Name &aMethod) } else { const std::string &image = aMethod.image(); theMessage.method = HttpRequestMethod(image.data(), - image.data() + image.size()); + image.data() + image.size()); } } @@ -202,14 +215,22 @@ Ecap::RequestLineRep::Name Ecap::RequestLineRep::method() const { switch (theMessage.method.id()) { - case METHOD_GET: return libecap::methodGet; - case METHOD_POST: return libecap::methodPost; - case METHOD_PUT: return libecap::methodPut; - case METHOD_HEAD: return libecap::methodHead; - case METHOD_CONNECT: return libecap::methodConnect; - case METHOD_DELETE: return libecap::methodDelete; - case METHOD_TRACE: return libecap::methodTrace; - default: return Name(theMessage.method.image()); + case METHOD_GET: + return libecap::methodGet; + case METHOD_POST: + return libecap::methodPost; + case METHOD_PUT: + return libecap::methodPut; + case METHOD_HEAD: + return libecap::methodHead; + case METHOD_CONNECT: + return libecap::methodConnect; + case METHOD_DELETE: + return libecap::methodDelete; + case METHOD_TRACE: + return libecap::methodTrace; + default: + return Name(theMessage.method.image()); } } @@ -241,7 +262,7 @@ Ecap::RequestLineRep::protocol(const Name &p) /* ReplyHeaderRep */ Ecap::StatusLineRep::StatusLineRep(HttpReply &aMessage): - FirstLineRep(aMessage), theMessage(aMessage) + FirstLineRep(aMessage), theMessage(aMessage) { } @@ -270,7 +291,7 @@ Ecap::StatusLineRep::Area Ecap::StatusLineRep::reasonPhrase() const { return theMessage.sline.reason ? - Area::FromTempString(std::string(theMessage.sline.reason)) : Area(); + Area::FromTempString(std::string(theMessage.sline.reason)) : Area(); } libecap::Version @@ -321,18 +342,18 @@ Ecap::BodyRep::bodySize() const /* MessageRep */ Ecap::MessageRep::MessageRep(HttpMsg *rawHeader): - theMessage(rawHeader), theFirstLineRep(NULL), - theHeaderRep(NULL), theBodyRep(NULL) + theMessage(rawHeader), theFirstLineRep(NULL), + theHeaderRep(NULL), theBodyRep(NULL) { Must(theMessage.header); // we do not want to represent a missing message if (HttpRequest *req = dynamic_cast(theMessage.header)) theFirstLineRep = new RequestLineRep(*req); else - if (HttpReply *rep = dynamic_cast(theMessage.header)) - theFirstLineRep = new StatusLineRep(*rep); - else - Must(false); // unknown message header type + if (HttpReply *rep = dynamic_cast(theMessage.header)) + theFirstLineRep = new StatusLineRep(*rep); + else + Must(false); // unknown message header type theHeaderRep = new HeaderRep(*theMessage.header); diff --git a/src/eCAP/MessageRep.h b/src/eCAP/MessageRep.h index 74032664d0..2fae383079 100644 --- a/src/eCAP/MessageRep.h +++ b/src/eCAP/MessageRep.h @@ -11,7 +11,8 @@ #include #include -namespace Ecap { +namespace Ecap +{ class XactionRep; diff --git a/src/eCAP/Registry.h b/src/eCAP/Registry.h index 954ddd236b..c64de56d43 100644 --- a/src/eCAP/Registry.h +++ b/src/eCAP/Registry.h @@ -1 +1 @@ -// TBD +// TBD diff --git a/src/eCAP/ServiceRep.cc b/src/eCAP/ServiceRep.cc index 5d1cba501d..c57c2975b5 100644 --- a/src/eCAP/ServiceRep.cc +++ b/src/eCAP/ServiceRep.cc @@ -6,7 +6,7 @@ #include "eCAP/XactionRep.h" Ecap::ServiceRep::ServiceRep(const Adaptation::ServiceConfig &cfg): - /*AsyncJob("Ecap::ServiceRep"),*/ Adaptation::Service(cfg) + /*AsyncJob("Ecap::ServiceRep"),*/ Adaptation::Service(cfg) { } @@ -14,30 +14,33 @@ Ecap::ServiceRep::~ServiceRep() { } -void Ecap::ServiceRep::noteService(const AdapterService &s) { +void Ecap::ServiceRep::noteService(const AdapterService &s) +{ Must(s != NULL); - theService = s; - debugs(93,7, "Matched loaded and configured eCAP services: " << - s->uri() << ' ' << cfg().key << "\n"); + theService = s; + debugs(93,7, "Matched loaded and configured eCAP services: " << + s->uri() << ' ' << cfg().key << "\n"); } -void Ecap::ServiceRep::invalidate() { - theService->retire(); - theService.reset(); +void Ecap::ServiceRep::invalidate() +{ + theService->retire(); + theService.reset(); } -void Ecap::ServiceRep::noteFailure() { - assert(false); // XXX: should this be ICAP-specific? +void Ecap::ServiceRep::noteFailure() +{ + assert(false); // XXX: should this be ICAP-specific? } void Ecap::ServiceRep::finalize() { - Adaptation::Service::finalize(); + Adaptation::Service::finalize(); if (!theService) { - debugs(93,1, "Warning: configured ecap_service was not loaded: " << - cfg().uri); - } + debugs(93,1, "Warning: configured ecap_service was not loaded: " << + cfg().uri); + } } bool Ecap::ServiceRep::probed() const @@ -58,11 +61,11 @@ bool Ecap::ServiceRep::wantsUrl(const String &urlPath) const Adaptation::Initiate * Ecap::ServiceRep::makeXactLauncher(Adaptation::Initiator *initiator, - HttpMsg *virgin, HttpRequest *cause) + HttpMsg *virgin, HttpRequest *cause) { - Must(up()); - XactionRep *rep = new XactionRep(initiator, virgin, cause, Pointer(this)); - XactionRep::AdapterXaction x(theService->makeXaction(rep)); + Must(up()); + XactionRep *rep = new XactionRep(initiator, virgin, cause, Pointer(this)); + XactionRep::AdapterXaction x(theService->makeXaction(rep)); rep->master(x); return rep; } @@ -72,5 +75,5 @@ const char *Ecap::ServiceRep::status() const { assert(false); // move generic stuff from ICAP to Adaptation // add theService->status()? - return NULL; + return NULL; } diff --git a/src/eCAP/ServiceRep.h b/src/eCAP/ServiceRep.h index 69a7b92964..1eadd36754 100644 --- a/src/eCAP/ServiceRep.h +++ b/src/eCAP/ServiceRep.h @@ -11,10 +11,11 @@ #include #include -namespace Ecap { +namespace Ecap +{ /* The eCAP service representative maintains information about a single eCAP - service that Squid communicates with. One eCAP module may register many + service that Squid communicates with. One eCAP module may register many eCAP services. */ class ServiceRep : public Adaptation::Service diff --git a/src/eCAP/XactionRep.cc b/src/eCAP/XactionRep.cc index e7cd344d41..fa106cdf21 100644 --- a/src/eCAP/XactionRep.cc +++ b/src/eCAP/XactionRep.cc @@ -14,12 +14,12 @@ cbdata_type Ecap::XactionRep::CBDATA_XactionRep = CBDATA_UNKNOWN; Ecap::XactionRep::XactionRep(Adaptation::Initiator *anInitiator, - HttpMsg *virginHeader, HttpRequest *virginCause, - const Adaptation::ServicePointer &aService): - AsyncJob("Ecap::XactionRep"), - Adaptation::Initiate("Ecap::XactionRep", anInitiator, aService), - theVirginRep(virginHeader), theCauseRep(NULL), - proxyingVb(opUndecided), proxyingAb(opUndecided), canAccessVb(false) + HttpMsg *virginHeader, HttpRequest *virginCause, + const Adaptation::ServicePointer &aService): + AsyncJob("Ecap::XactionRep"), + Adaptation::Initiate("Ecap::XactionRep", anInitiator, aService), + theVirginRep(virginHeader), theCauseRep(NULL), + proxyingVb(opUndecided), proxyingAb(opUndecided), canAccessVb(false) { if (virginCause) theCauseRep = new MessageRep(virginCause); @@ -121,7 +121,7 @@ bool Ecap::XactionRep::doneAll() const { return proxyingVb >= opComplete && proxyingAb >= opComplete && - Adaptation::Initiate::doneAll(); + Adaptation::Initiate::doneAll(); } // stops receiving virgin and enables auto-consumption @@ -142,7 +142,7 @@ Ecap::XactionRep::dropVirgin(const char *reason) // called from adapter handler so does not inform adapter } -void +void Ecap::XactionRep::useVirgin() { debugs(93,3, HERE << status()); @@ -163,16 +163,16 @@ Ecap::XactionRep::useVirgin() canAccessVb = false; proxyingVb = opComplete; } else - if (proxyingVb == opUndecided) { - vbody_pipe = NULL; // it is not our pipe anymore - proxyingVb = opNever; - } + if (proxyingVb == opUndecided) { + vbody_pipe = NULL; // it is not our pipe anymore + proxyingVb = opNever; + } sendAnswer(clone); Must(done()); } -void +void Ecap::XactionRep::useAdapted(const libecap::shared_ptr &m) { debugs(93,3, HERE << status()); @@ -253,11 +253,11 @@ Ecap::XactionRep::vbContent(libecap::size_type o, libecap::size_type s) // nsize means no size limit: all content starting from offset const size_t size = s == libecap::nsize ? - haveSize - offset : static_cast(s); + haveSize - offset : static_cast(s); // XXX: optimize by making theBody a shared_ptr (see Area::FromTemp*() src) return libecap::Area::FromTempBuffer(p->buf().content() + offset, - min(static_cast(haveSize - offset), size)); + min(static_cast(haveSize - offset), size)); } void @@ -305,11 +305,11 @@ void Ecap::XactionRep::adaptationDelayed(const libecap::Delay &d) { debugs(93,3, HERE << "adapter needs time: " << - d.state << '/' << d.progress); + d.state << '/' << d.progress); // XXX: set timeout? } -void +void Ecap::XactionRep::adaptationAborted() { tellQueryAborted(true); // should eCAP support retries? @@ -322,14 +322,14 @@ Ecap::XactionRep::callable() const return !done(); } -void +void Ecap::XactionRep::noteMoreBodySpaceAvailable(RefCount bp) { Must(proxyingAb == opOn); moveAbContent(); } -void +void Ecap::XactionRep::noteBodyConsumerAborted(RefCount bp) { Must(proxyingAb == opOn); diff --git a/src/eCAP/XactionRep.h b/src/eCAP/XactionRep.h index cf979fc43b..3098ba1a5d 100644 --- a/src/eCAP/XactionRep.h +++ b/src/eCAP/XactionRep.h @@ -16,13 +16,14 @@ #include #include -namespace Ecap { +namespace Ecap +{ /* The eCAP xaction representative maintains information about a single eCAP - xaction that Squid communicates with. One eCAP module may register many + xaction that Squid communicates with. One eCAP module may register many eCAP xactions. */ class XactionRep : public Adaptation::Initiate, public libecap::host::Xaction, - public BodyConsumer, public BodyProducer + public BodyConsumer, public BodyProducer { public: XactionRep(Adaptation::Initiator *anInitiator, HttpMsg *virginHeader, HttpRequest *virginCause, const Adaptation::ServicePointer &service); diff --git a/src/enums.h b/src/enums.h index 0b8a164086..559c0ee8c4 100644 --- a/src/enums.h +++ b/src/enums.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -338,7 +338,7 @@ typedef enum { STREAM_NONE, /* No particular status */ STREAM_COMPLETE, /* All data has been flushed, no more reads allowed */ /* an unpredicted end has occured, no more - * reads occured, but no need to tell + * reads occured, but no need to tell * downstream that an error occured */ STREAM_UNPLANNED_COMPLETE, diff --git a/src/errorpage.h b/src/errorpage.h index 243782ffd2..475bbe04d8 100644 --- a/src/errorpage.h +++ b/src/errorpage.h @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -129,13 +129,11 @@ public: ERCB *callback; void *callback_data; - struct - { + struct { unsigned int flag_cbdata:1; } flags; - struct - { + struct { wordlist *server_msg; char *request; char *reply; diff --git a/src/event.cc b/src/event.cc index 9b069e6198..d05cc7706c 100644 --- a/src/event.cc +++ b/src/event.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -43,7 +43,7 @@ static OBJH eventDump; static const char *last_event_ran = NULL; -// This AsyncCall dialer can be configured to check that the event cbdata is +// This AsyncCall dialer can be configured to check that the event cbdata is // valid before calling the event handler class EventDialer: public CallDialer { @@ -66,14 +66,14 @@ private: }; EventDialer::EventDialer(EVH *aHandler, void *anArg, bool lockedArg): - theHandler(aHandler), theArg(anArg), isLockedArg(lockedArg) + theHandler(aHandler), theArg(anArg), isLockedArg(lockedArg) { if (isLockedArg) (void)cbdataReference(theArg); } EventDialer::EventDialer(const EventDialer &d): - theHandler(d.theHandler), theArg(d.theArg), isLockedArg(d.isLockedArg) + theHandler(d.theHandler), theArg(d.theArg), isLockedArg(d.isLockedArg) { if (isLockedArg) (void)cbdataReference(theArg); @@ -86,7 +86,8 @@ EventDialer::~EventDialer() } bool -EventDialer::canDial(AsyncCall &call) { +EventDialer::canDial(AsyncCall &call) +{ // TODO: add Parent::canDial() that always returns true //if (!Parent::canDial()) // return false; @@ -108,9 +109,9 @@ EventDialer::print(std::ostream &os) const ev_entry::ev_entry(char const * name, EVH * func, void * arg, double when, - int weight, bool cbdata) : name(name), func(func), - arg(cbdata ? cbdataReference(arg) : arg), when(when), weight(weight), - cbdata(cbdata) + int weight, bool cbdata) : name(name), func(func), + arg(cbdata ? cbdataReference(arg) : arg), when(when), weight(weight), + cbdata(cbdata) { } @@ -152,7 +153,7 @@ void eventInit(void) { CacheManager::GetInstance()-> - registerAction("events", "Event Queue", eventDump, 0, 1); + registerAction("events", "Event Queue", eventDump, 0, 1); } static void @@ -200,23 +201,23 @@ EventScheduler::cancel(EVH * func, void *arg) delete event; - if (arg) - return; - /* - * DPW 2007-04-12 - * Since this method may now delete multiple events (when - * arg is NULL) it no longer returns after a deletion and - * we have a potential NULL pointer problem. If we just - * deleted the last event in the list then *E is now equal - * to NULL. We need to break here or else we'll get a NULL - * pointer dereference in the last clause of the for loop. - */ - if (NULL == *E) - break; + if (arg) + return; + /* + * DPW 2007-04-12 + * Since this method may now delete multiple events (when + * arg is NULL) it no longer returns after a deletion and + * we have a potential NULL pointer problem. If we just + * deleted the last event in the list then *E is now equal + * to NULL. We need to break here or else we'll get a NULL + * pointer dereference in the last clause of the for loop. + */ + if (NULL == *E) + break; } if (arg) - debug_trap("eventDelete: event not found"); + debug_trap("eventDelete: event not found"); } int @@ -255,19 +256,19 @@ EventScheduler::checkEvents(int timeout) /* XXX assumes event->name is static memory! */ AsyncCall::Pointer call = asyncCall(41,5, event->name, - EventDialer(event->func, event->arg, event->cbdata)); + EventDialer(event->func, event->arg, event->cbdata)); ScheduleCallHere(call); last_event_ran = event->name; // XXX: move this to AsyncCallQueue const bool heavy = event->weight && - (!event->cbdata || cbdataReferenceValid(event->arg)); + (!event->cbdata || cbdataReferenceValid(event->arg)); tasks = event->next; delete event; // XXX: We may be called again during the same event loop iteration. // Is there a point in breaking now? - if (heavy) + if (heavy) break; // do not dequeue events following a heavy event } diff --git a/src/event.h b/src/event.h index 36b3952caf..9afec3baaf 100644 --- a/src/event.h +++ b/src/event.h @@ -19,12 +19,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/external_acl.cc b/src/external_acl.cc index 59200fe014..52b2ff132f 100644 --- a/src/external_acl.cc +++ b/src/external_acl.cc @@ -28,12 +28,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -89,7 +89,7 @@ public: external_acl *next; void add - (ExternalACLEntry *); + (ExternalACLEntry *); void trimCache(); @@ -123,8 +123,7 @@ public: bool require_auth; - enum - { + enum { QUOTE_METHOD_SHELL = 1, QUOTE_METHOD_URL } quote; @@ -132,8 +131,7 @@ public: IPAddress local_addr; }; -struct _external_acl_format -{ +struct _external_acl_format { enum format_type { EXT_ACL_UNKNOWN, EXT_ACL_LOGIN, @@ -250,7 +248,7 @@ parse_header_token(external_acl_format *format, char *header, const _external_ac format->member = xstrdup(member); - if(type == _external_acl_format::EXT_ACL_HEADER_REQUEST) + if (type == _external_acl_format::EXT_ACL_HEADER_REQUEST) format->type = _external_acl_format::EXT_ACL_HEADER_REQUEST_MEMBER; else format->type = _external_acl_format::EXT_ACL_HEADER_REQUEST_MEMBER; @@ -263,12 +261,12 @@ parse_header_token(external_acl_format *format, char *header, const _external_ac if (format->header_id != -1) { if (member) { - if(type == _external_acl_format::EXT_ACL_HEADER_REQUEST) + if (type == _external_acl_format::EXT_ACL_HEADER_REQUEST) format->type = _external_acl_format::EXT_ACL_HEADER_REQUEST_ID_MEMBER; else format->type = _external_acl_format::EXT_ACL_HEADER_REPLY_ID_MEMBER; } else { - if(type == _external_acl_format::EXT_ACL_HEADER_REQUEST) + if (type == _external_acl_format::EXT_ACL_HEADER_REQUEST) format->type = _external_acl_format::EXT_ACL_HEADER_REQUEST_ID; else format->type = _external_acl_format::EXT_ACL_HEADER_REPLY_ID; @@ -328,13 +326,13 @@ parse_externalAclHelper(external_acl ** list) } else if (strcmp(token, "quote=shell") == 0) { a->quote = external_acl::QUOTE_METHOD_SHELL; - /* INET6: allow admin to configure some helpers explicitly to - bind to IPv4/v6 localhost port. */ + /* INET6: allow admin to configure some helpers explicitly to + bind to IPv4/v6 localhost port. */ } else if (strcmp(token, "ipv4") == 0) { #if IPV6_SPECIAL_LOCALHOST debugs(3, 0, "WARNING: --with-localhost-ipv6 conflicts with external ACL helper to using IPv4: " << a->name ); #endif - if( !a->local_addr.SetIPv4() ) { + if ( !a->local_addr.SetIPv4() ) { debugs(3, 0, "WARNING: Error converting " << a->local_addr << " to IPv4 in " << a->name ); } } else if (strcmp(token, "ipv6") == 0) { @@ -374,7 +372,7 @@ parse_externalAclHelper(external_acl ** list) if (strncmp(token, "%>{", 3) == 0) { parse_header_token(format, (token+3), _external_acl_format::EXT_ACL_HEADER_REQUEST); - } + } if (strncmp(token, "%<{", 3) == 0) { parse_header_token(format, (token+3), _external_acl_format::EXT_ACL_HEADER_REPLY); @@ -592,7 +590,7 @@ find_externalAclHelper(const char *name) void external_acl::add - (ExternalACLEntry *anEntry) +(ExternalACLEntry *anEntry) { trimCache(); assert (anEntry->def == NULL); @@ -614,8 +612,7 @@ external_acl::trimCache() * external acl type */ -struct _external_acl_data -{ +struct _external_acl_data { external_acl *def; wordlist *arguments; }; @@ -919,28 +916,28 @@ makeExternalAclKey(ACLChecklist * ch, external_acl_data * acl_data) break; case _external_acl_format::EXT_ACL_HEADER_REPLY: - if(reply) { + if (reply) { sb = reply->header.getByName(format->header); str = sb.buf(); } break; case _external_acl_format::EXT_ACL_HEADER_REPLY_ID: - if(reply) { + if (reply) { sb = reply->header.getStrOrList(format->header_id); str = sb.buf(); } break; case _external_acl_format::EXT_ACL_HEADER_REPLY_MEMBER: - if(reply) { + if (reply) { sb = reply->header.getByNameListMember(format->header, format->member, format->separator); str = sb.buf(); } break; case _external_acl_format::EXT_ACL_HEADER_REPLY_ID_MEMBER: - if(reply) { + if (reply) { sb = reply->header.getListMember(format->header_id, format->member, format->separator); str = sb.buf(); } @@ -1104,8 +1101,7 @@ external_acl_cache_delete(external_acl * def, external_acl_entry * entry) typedef struct _externalAclState externalAclState; -struct _externalAclState -{ +struct _externalAclState { EAH *callback; void *callback_data; char *key; @@ -1143,8 +1139,8 @@ free_externalAclState(void *data) * * Other keywords may be added to the protocol later * - * value needs to be enclosed in quotes if it may contain whitespace, or - * the whitespace escaped using \ (\ escaping obviously also applies to + * value needs to be enclosed in quotes if it may contain whitespace, or + * the whitespace escaped using \ (\ escaping obviously also applies to * any " characters) */ @@ -1373,9 +1369,9 @@ static void externalAclRegisterWithCacheManager(void) { CacheManager::GetInstance()-> - registerAction("external_acl", - "External ACL stats", - externalAclStats, 0, 1); + registerAction("external_acl", + "External ACL stats", + externalAclStats, 0, 1); } void diff --git a/src/fd.cc b/src/fd.cc index d4931af13b..cc98eb9fec 100644 --- a/src/fd.cc +++ b/src/fd.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -46,15 +46,14 @@ int file_read_method(int, char *, int); int file_write_method(int, const char *, int); #endif -const char *fdTypeStr[] = - { - "None", - "Log", - "File", - "Socket", - "Pipe", - "Unknown" - }; +const char *fdTypeStr[] = { + "None", + "Log", + "File", + "Socket", + "Pipe", + "Unknown" +}; static void fdUpdateBiggest(int fd, int); @@ -265,9 +264,9 @@ fdDumpOpen(void) if (i == fileno(debug_log)) continue; - debugs(51, 1, "Open FD "<< std::left<< std::setw(10) << + debugs(51, 1, "Open FD "<< std::left<< std::setw(10) << (F->bytes_read && F->bytes_written ? "READ/WRITE" : - F->bytes_read ? "READING" : F->bytes_written ? "WRITING" : + F->bytes_read ? "READING" : F->bytes_written ? "WRITING" : "UNSTARTED") << " "<< std::right << std::setw(4) << i << " " << F->desc); } @@ -324,7 +323,7 @@ fdAdjustReserved(void) } if (Squid_MaxFD - newReserve < XMIN(256, Squid_MaxFD / 2)) - fatalf("Too few filedescriptors available in the system (%d usable of %d).\n", Squid_MaxFD - newReserve, Squid_MaxFD); + fatalf("Too few filedescriptors available in the system (%d usable of %d).\n", Squid_MaxFD - newReserve, Squid_MaxFD); debugs(51, 0, "Reserved FD adjusted from " << RESERVED_FD << " to " << newReserve << " due to failures"); RESERVED_FD = newReserve; diff --git a/src/fde.cc b/src/fde.cc index 8153261ef9..a4846baf2b 100644 --- a/src/fde.cc +++ b/src/fde.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/filemap.cc b/src/filemap.cc index bb4a7ba2bf..b6b833f454 100644 --- a/src/filemap.cc +++ b/src/filemap.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/forward.cc b/src/forward.cc index 9fc1cbe56b..39471e21d9 100644 --- a/src/forward.cc +++ b/src/forward.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -268,7 +268,7 @@ FwdState::fwdStart(int client_fd, StoreEntry *entry, HttpRequest *request) /* If we need to transparently proxy the request * then we need the client source protocol, address and port */ - if(request->flags.spoof_client_ip) { + if (request->flags.spoof_client_ip) { fwd->src = request->client_addr; // AYJ: do we need to pass on the transparent flag also? } @@ -409,7 +409,7 @@ fwdPeerClosed(int fd, void *data) /* * FwdState::checkRetry - * + * * Return TRUE if the request SHOULD be retried. This method is * called when the HTTP connection fails, or when the connection * is closed before server-side read the end of HTTP headers. @@ -501,7 +501,8 @@ FwdState::serverClosed(int fd) } void -FwdState::retryOrBail() { +FwdState::retryOrBail() +{ if (!self) { // we have aborted before the server called us back debugs(17, 5, HERE << "not retrying because of earlier abort"); // we will be destroyed when the server clears its Pointer to us @@ -549,7 +550,7 @@ void FwdState::handleUnregisteredServerEnd() { debugs(17, 2, "handleUnregisteredServerEnd: self=" << self << - " err=" << err << ' ' << entry->url()); + " err=" << err << ' ' << entry->url()); assert(server_fd < 0); retryOrBail(); } @@ -576,9 +577,9 @@ FwdState::negotiateSSL(int fd) return; default: - debugs(81, 1, "fwdNegotiateSSL: Error negotiating SSL connection on FD " << fd << - ": " << ERR_error_string(ERR_get_error(), NULL) << " (" << ssl_error << - "/" << ret << "/" << errno << ")"); + debugs(81, 1, "fwdNegotiateSSL: Error negotiating SSL connection on FD " << fd << + ": " << ERR_error_string(ERR_get_error(), NULL) << " (" << ssl_error << + "/" << ret << "/" << errno << ")"); ErrorState *anErr = errorCon(ERR_SECURE_CONNECT_FAIL, HTTP_SERVICE_UNAVAILABLE, request); #ifdef EPROTO @@ -750,7 +751,7 @@ FwdState::connectTimeout(int fd) anErr->xerrno = ETIMEDOUT; fail(anErr); /* - * This marks the peer DOWN ... + * This marks the peer DOWN ... */ if (servers) @@ -807,11 +808,11 @@ FwdState::connectStart() request->flags.pinned = 0; if (fs->code == PINNED) { - ConnStateData *pinned_connection = request->pinnedConnection(); - assert(pinned_connection); + ConnStateData *pinned_connection = request->pinnedConnection(); + assert(pinned_connection); fd = pinned_connection->validatePinnedConnection(request, fs->_peer); if (fd >= 0) { - pinned_connection->unpinConnection(); + pinned_connection->unpinConnection(); #if 0 if (!fs->_peer) fs->code = HIER_DIRECT; @@ -825,13 +826,13 @@ FwdState::connectStart() connectDone(fd, COMM_OK, 0); return; } - /* Failure. Fall back on next path */ + /* Failure. Fall back on next path */ request->releasePinnedConnection(); servers = fs->next; fwdServerFree(fs); connectStart(); return; - } + } fd = fwdPconnPool->pop(host, port, domain, client_addr, checkRetriable()); if (fd >= 0) { @@ -905,7 +906,7 @@ FwdState::connectStart() if (!fs->_peer && request->flags.spoof_client_ip) { // try to set the outgoing address using TPROXY v2 // if it fails we abort any further TPROXY actions on this connection - if(IPInterceptor.SetTproxy2OutgoingAddr(int fd, const IPAddress &src) == -1) { + if (IPInterceptor.SetTproxy2OutgoingAddr(int fd, const IPAddress &src) == -1) { request->flags.spoof_client_ip = 0; } } @@ -969,46 +970,37 @@ FwdState::dispatch() * remote server's TOS in the response to the client in case of a MISS. */ fde * clientFde = &fd_table[client_fd]; - if (clientFde) - { - int tos = 1; - int tos_len = sizeof(tos); - clientFde->upstreamTOS = 0; - if (setsockopt(server_fd,SOL_IP,IP_RECVTOS,&tos,tos_len)==0) - { - unsigned char buf[512]; - int len = 512; - if (getsockopt(server_fd,SOL_IP,IP_PKTOPTIONS,buf,(socklen_t*)&len) == 0) - { - /* Parse the PKTOPTIONS structure to locate the TOS data message - * prepared in the kernel by the ZPH incoming TCP TOS preserving - * patch. - */ - unsigned char * p = buf; - while (p-buf < len) - { - struct cmsghdr *o = (struct cmsghdr*)p; - if (o->cmsg_len<=0) - break; - - if (o->cmsg_level == SOL_IP && o->cmsg_type == IP_TOS) - { - clientFde->upstreamTOS = (unsigned char)(*(int*)CMSG_DATA(o)); - break; - } - p += CMSG_LEN(o->cmsg_len); - } - } - else - { - debugs(33, 1, "ZPH: error in getsockopt(IP_PKTOPTIONS) on FD "<upstreamTOS = 0; + if (setsockopt(server_fd,SOL_IP,IP_RECVTOS,&tos,tos_len)==0) { + unsigned char buf[512]; + int len = 512; + if (getsockopt(server_fd,SOL_IP,IP_PKTOPTIONS,buf,(socklen_t*)&len) == 0) { + /* Parse the PKTOPTIONS structure to locate the TOS data message + * prepared in the kernel by the ZPH incoming TCP TOS preserving + * patch. + */ + unsigned char * p = buf; + while (p-buf < len) { + struct cmsghdr *o = (struct cmsghdr*)p; + if (o->cmsg_len<=0) + break; + + if (o->cmsg_level == SOL_IP && o->cmsg_type == IP_TOS) { + clientFde->upstreamTOS = (unsigned char)(*(int*)CMSG_DATA(o)); + break; + } + p += CMSG_LEN(o->cmsg_len); + } + } else { + debugs(33, 1, "ZPH: error in getsockopt(IP_PKTOPTIONS) on FD "<_peer)) { @@ -1214,7 +1206,7 @@ void FwdState::RegisterWithCacheManager(void) { CacheManager::GetInstance()-> - registerAction("forward", "Request Forwarding Statistics", fwdStats, 0, 1); + registerAction("forward", "Request Forwarding Statistics", fwdStats, 0, 1); } void @@ -1256,7 +1248,7 @@ It does not matter from a functional perspective if it gets called a few times more than what is really needed, but calling it too often may obviously hurt performance. -\todo Current code looks fine, even if using !fs->_peer as condition +\todo Current code looks fine, even if using !fs->_peer as condition instead of HIER_DIRECT would be clearer. */ // updates HierarchyLogEntry, guessing nextHop and its format @@ -1304,8 +1296,7 @@ aclMapAddr(acl_address * head, ACLChecklist * ch) IPAddress addr; - for (l = head; l; l = l->next) - { + for (l = head; l; l = l->next) { if (ch->matchAclListFast(l->aclList)) return l->addr; } @@ -1339,8 +1330,7 @@ getOutgoingAddr(HttpRequest * request) if (request && request->flags.spoof_client_ip) return request->client_addr; - if (request) - { + if (request) { ch.src_addr = request->client_addr; ch.my_addr = request->my_addr; ch.request = HTTPMSGLOCK(request); diff --git a/src/forward.h b/src/forward.h index b9a9b90e1a..dbfffe391f 100644 --- a/src/forward.h +++ b/src/forward.h @@ -93,8 +93,7 @@ private: http_status last_status; #endif - struct - { + struct { unsigned int dont_retry:1; unsigned int ftp_pasv_failed:1; unsigned int forward_completed:1; diff --git a/src/fqdncache.cc b/src/fqdncache.cc index 70b1f95ff8..21e74c2477 100644 --- a/src/fqdncache.cc +++ b/src/fqdncache.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -93,8 +93,7 @@ typedef struct _fqdncache_entry fqdncache_entry; * where structures of type fqdncache_entry whose most * interesting members are: */ -struct _fqdncache_entry -{ +struct _fqdncache_entry { hash_link hash; /* must be first */ time_t lastref; time_t expires; @@ -108,16 +107,14 @@ struct _fqdncache_entry dlink_node lru; unsigned short locks; - struct - { + struct { unsigned int negcached:1; unsigned int fromhosts:1; } flags; }; /// \ingroup FQDNCacheInternal -static struct _fqdn_cache_stats -{ +static struct _fqdn_cache_stats { int requests; int replies; int hits; @@ -529,8 +526,7 @@ fqdncache_nbgethostbyaddr(IPAddress &addr, FQDNH * handler, void *handlerData) debugs(35, 4, "fqdncache_nbgethostbyaddr: Name '" << name << "'."); FqdncacheStats.requests++; - if (name[0] == '\0') - { + if (name[0] == '\0') { debugs(35, 4, "fqdncache_nbgethostbyaddr: Invalid name!"); dns_error_message = "Invalid hostname"; handler(NULL, handlerData); @@ -539,17 +535,14 @@ fqdncache_nbgethostbyaddr(IPAddress &addr, FQDNH * handler, void *handlerData) f = fqdncache_get(name); - if (NULL == f) - { + if (NULL == f) { /* miss */ (void) 0; - } else if (fqdncacheExpiredEntry(f)) - { + } else if (fqdncacheExpiredEntry(f)) { /* hit, but expired -- bummer */ fqdncacheRelease(f); f = NULL; - } else - { + } else { /* hit */ debugs(35, 4, "fqdncache_nbgethostbyaddr: HIT for '" << name << "'"); @@ -587,8 +580,8 @@ static void fqdncacheRegisterWithCacheManager(void) { CacheManager::GetInstance()-> - registerAction("fqdncache", "FQDN Cache Stats and Contents", - fqdnStats, 0, 1); + registerAction("fqdncache", "FQDN Cache Stats and Contents", + fqdnStats, 0, 1); } @@ -651,20 +644,16 @@ fqdncache_gethostbyaddr(IPAddress &addr, int flags) FqdncacheStats.requests++; f = fqdncache_get(name); - if (NULL == f) - { + if (NULL == f) { (void) 0; - } else if (fqdncacheExpiredEntry(f)) - { + } else if (fqdncacheExpiredEntry(f)) { fqdncacheRelease(f); f = NULL; - } else if (f->flags.negcached) - { + } else if (f->flags.negcached) { FqdncacheStats.negative_hits++; dns_error_message = f->error_message; return NULL; - } else - { + } else { FqdncacheStats.hits++; f->lastref = squid_curtime; dns_error_message = f->error_message; @@ -675,8 +664,7 @@ fqdncache_gethostbyaddr(IPAddress &addr, int flags) FqdncacheStats.misses++; - if (flags & FQDN_LOOKUP_IF_MISS) - { + if (flags & FQDN_LOOKUP_IF_MISS) { fqdncache_nbgethostbyaddr(addr, dummy_handler, NULL); } @@ -948,7 +936,7 @@ const char * dns_error_message_safe() { if (dns_error_message) - return dns_error_message; - debugs(35,DBG_IMPORTANT, "Internal error: lost DNS error info"); - return "lost DNS error"; + return dns_error_message; + debugs(35,DBG_IMPORTANT, "Internal error: lost DNS error info"); + return "lost DNS error"; } diff --git a/src/fs/aufs/StoreFSaufs.cc b/src/fs/aufs/StoreFSaufs.cc index 65748e5d6f..f2f6d5074c 100644 --- a/src/fs/aufs/StoreFSaufs.cc +++ b/src/fs/aufs/StoreFSaufs.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/fs/coss/CossSwapDir.h b/src/fs/coss/CossSwapDir.h index d2160ca404..355887919f 100644 --- a/src/fs/coss/CossSwapDir.h +++ b/src/fs/coss/CossSwapDir.h @@ -113,7 +113,7 @@ public: ~StoreSearchCoss(); /* Iterator API - garh, wrong place */ /* callback the client when a new StoreEntry is available - * or an error occurs + * or an error occurs */ virtual void next(void (callback)(void *cbdata), void *cbdata); /* return true if a new StoreEntry is immediately available */ diff --git a/src/fs/coss/StoreFScoss.cc b/src/fs/coss/StoreFScoss.cc index 6bc7a5d111..c368f38bd8 100644 --- a/src/fs/coss/StoreFScoss.cc +++ b/src/fs/coss/StoreFScoss.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/fs/coss/StoreFScoss.h b/src/fs/coss/StoreFScoss.h index 69ac6dd988..db53d2e527 100644 --- a/src/fs/coss/StoreFScoss.h +++ b/src/fs/coss/StoreFScoss.h @@ -17,12 +17,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -47,8 +47,7 @@ public: void stat(StoreEntry * sentry); int stripes; - struct - { + struct { int alloc; int realloc; int collisions; @@ -58,8 +57,7 @@ public: int open_mem_hits; int open_mem_misses; - struct - { + struct { int ops; int success; int fail; diff --git a/src/fs/coss/store_coss.h b/src/fs/coss/store_coss.h index 3c1103853b..b6c538d4f8 100644 --- a/src/fs/coss/store_coss.h +++ b/src/fs/coss/store_coss.h @@ -35,16 +35,14 @@ public: int lockcount; char buffer[COSS_MEMBUF_SZ]; - struct _cossmembuf_flags - { + struct _cossmembuf_flags { unsigned int full:1; unsigned int writing:1; } flags; }; /// \ingroup COSS -struct _cossindex -{ +struct _cossindex { /** \note The dlink_node MUST be the first member of the structure. * This member is later pointer typecasted to coss_index_node *. @@ -72,8 +70,7 @@ public: size_t requestoffset; /* in blocks */ int64_t reqdiskoffset; /* in blocks */ - struct - { + struct { unsigned int reading:1; unsigned int writing:1; } flags; diff --git a/src/fs/coss/store_dir_coss.cc b/src/fs/coss/store_dir_coss.cc index e44a05f9be..96f9a4ee99 100644 --- a/src/fs/coss/store_dir_coss.cc +++ b/src/fs/coss/store_dir_coss.cc @@ -1,7 +1,7 @@ /* * $Id: store_dir_coss.cc,v 1.77 2007/11/15 16:47:36 wessels Exp $ - * vim: set et : + * vim: set et : * * DEBUG: section 47 Store COSS Directory Routines * AUTHOR: Eric Stern @@ -22,12 +22,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -58,15 +58,13 @@ MemAllocator *coss_index_pool = NULL; typedef struct _RebuildState RebuildState; -struct _RebuildState -{ +struct _RebuildState { CossSwapDir *sd; int n_read; FILE *log; int speed; - struct - { + struct { unsigned int clean:1; } flags; @@ -444,7 +442,8 @@ storeCossRebuildFromSwapLog(void *data) storeCossRemove(rb->sd, e); rb->counts.objcount--; rb->counts.cancelcount++; - } continue; + } + continue; } else { x = log(static_cast(++rb->counts.bad_log_op)) / log(10.0); @@ -750,7 +749,7 @@ CossSwapDir::writeCleanStart() /* RBC 20050101 - I think there is a race condition here, * *current can be freed as its not ref counted, if/when - * the store overruns the log writer + * the store overruns the log writer */ const StoreEntry * CossCleanLog::nextEntry() @@ -1042,7 +1041,7 @@ CossSwapDir::parse(int anIndex, char *aPath) parseOptions(0); - if (NULL == io) + if (NULL == io) changeIO(DiskIOModule::FindDefault()); /* Enforce maxobjsize being set to something */ diff --git a/src/fs/coss/store_io_coss.cc b/src/fs/coss/store_io_coss.cc index 5d6954c0ce..245d871a00 100644 --- a/src/fs/coss/store_io_coss.cc +++ b/src/fs/coss/store_io_coss.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -226,7 +226,7 @@ CossSwapDir::openStoreIO(StoreEntry & e, StoreIOState::STFNCB * file_callback, } else { /* Do the allocation */ /* this is the first time we've been called on a new sio - * read the whole object into memory, then return the + * read the whole object into memory, then return the * requested amount */ StoreFScoss::GetInstance().stats.open_mem_misses++; @@ -320,7 +320,7 @@ CossState::read_(char *buf, size_t size, off_t offset, STRCB * callback, void *c * It was copied from memory in storeCossOpen() */ ReadRequest::Pointer readRequest = new CossRead(ReadRequest( - (char *)readbuffer,st_size, 0), this); + (char *)readbuffer,st_size, 0), this); SD->readCompleted(readbuffer, st_size, 0, readRequest); } } @@ -617,9 +617,9 @@ CossState::~CossState() void CossMemBuf::describe(int level, int line) { - debugs(79, level, "membuf " << this << ", LC:" << std::setfill('0') << - std::setw(2) << lockcount << ", ST:" << - std::setw(10) << (unsigned long) diskstart << ", FL:" << - (flags.full ? 'F' : '.') << (flags.writing ? 'W' : '.')); + debugs(79, level, "membuf " << this << ", LC:" << std::setfill('0') << + std::setw(2) << lockcount << ", ST:" << + std::setw(10) << (unsigned long) diskstart << ", FL:" << + (flags.full ? 'F' : '.') << (flags.writing ? 'W' : '.')); } diff --git a/src/fs/diskd/StoreFSdiskd.cc b/src/fs/diskd/StoreFSdiskd.cc index 84e9063672..112c37a276 100644 --- a/src/fs/diskd/StoreFSdiskd.cc +++ b/src/fs/diskd/StoreFSdiskd.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/fs/ufs/StoreFSufs.cc b/src/fs/ufs/StoreFSufs.cc index 0b16c5ec68..6a409bf840 100644 --- a/src/fs/ufs/StoreFSufs.cc +++ b/src/fs/ufs/StoreFSufs.cc @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/fs/ufs/StoreFSufs.h b/src/fs/ufs/StoreFSufs.h index cee80d768e..2f0fe82008 100644 --- a/src/fs/ufs/StoreFSufs.h +++ b/src/fs/ufs/StoreFSufs.h @@ -17,12 +17,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -45,7 +45,7 @@ class DiskIOModule; \ingroup UFS, FileSystems * * Core UFS class. This template provides compile time aliases for - * ufs/aufs/diskd to ease configuration conversion - each becomes a + * ufs/aufs/diskd to ease configuration conversion - each becomes a * StoreFS module whose createSwapDir method parameterises the common * UFSSwapDir with an IO module instance. */ diff --git a/src/fs/ufs/store_dir_ufs.cc b/src/fs/ufs/store_dir_ufs.cc index 913ddff465..7e63abc25b 100644 --- a/src/fs/ufs/store_dir_ufs.cc +++ b/src/fs/ufs/store_dir_ufs.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -103,7 +103,7 @@ UFSSwapDir::parseSizeL1L2() /* * storeUfsDirReconfigure * - * This routine is called when the given swapdir needs reconfiguring + * This routine is called when the given swapdir needs reconfiguring */ void @@ -396,8 +396,8 @@ UFSSwapDir::maintain() } walker->Done(walker); - debugs(47, (removed ? 2 : 3), "UFSSwapDir::maintain: " << path << - " removed " << removed << "/" << max_remove << " f=" << + debugs(47, (removed ? 2 : 3), "UFSSwapDir::maintain: " << path << + " removed " << removed << "/" << max_remove << " f=" << std::setprecision(4) << f << " max_scan=" << max_scan); } @@ -788,12 +788,12 @@ UFSSwapDir::openTmpSwapLog(int *clean_flag, int *zero_flag) /* open a write-only FD for the new log */ fd = file_open(new_path, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY); - + if (fd < 0) { debugs(50, 1, "" << new_path << ": " << xstrerror()); fatal("storeDirOpenTmpSwapLog: Failed to open swap log."); } - + swaplog_fd = fd; head = new StoreSwapLogHeader; @@ -895,7 +895,7 @@ UFSSwapDir::writeCleanStart() fchmod(state->fd, sb.st_mode); #endif - + cleanLog = state; return 0; @@ -1211,7 +1211,7 @@ UFSSwapDir::IsUFSDir(SwapDir * sd) * Does swapfile number 'fn' belong in cachedir #F0, * level1 dir #F1, level2 dir #F2? * XXX: this is broken - it assumes all cache dirs use the same - * l1 and l2 scheme. -RBC 20021215. Partial fix is in place - + * l1 and l2 scheme. -RBC 20021215. Partial fix is in place - * if not UFSSwapDir return 0; */ int @@ -1274,9 +1274,9 @@ UFSSwapDir::validFileno(sfileno filn, int flag) const void UFSSwapDir::unlinkFile(sfileno f) { - debugs(79, 3, "UFSSwapDir::unlinkFile: unlinking fileno " << std::setfill('0') << - std::hex << std::uppercase << std::setw(8) << f << " '" << - fullPath(f,NULL) << "'"); + debugs(79, 3, "UFSSwapDir::unlinkFile: unlinking fileno " << std::setfill('0') << + std::hex << std::uppercase << std::setw(8) << f << " '" << + fullPath(f,NULL) << "'"); /* commonUfsDirMapBitReset(this, f); */ IO->unlinkFile(fullPath(f,NULL)); } diff --git a/src/fs/ufs/store_io_ufs.cc b/src/fs/ufs/store_io_ufs.cc index 6158a31578..463a7aa61d 100644 --- a/src/fs/ufs/store_io_ufs.cc +++ b/src/fs/ufs/store_io_ufs.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -345,9 +345,9 @@ UFSStoreState::readCompleted(const char *buf, int len, int errflag, RefCount writeRequest) { - debugs(79, 3, "UFSStoreState::writeCompleted: dirno " << swap_dirn << ", fileno " << - std::setfill('0') << std::hex << std::uppercase << std::setw(8) << swap_filen << - ", len " << len ); + debugs(79, 3, "UFSStoreState::writeCompleted: dirno " << swap_dirn << ", fileno " << + std::setfill('0') << std::hex << std::uppercase << std::setw(8) << swap_filen << + ", len " << len ); /* * DPW 2006-05-24 * See doWrites() for why we don't update UFSStoreState::writing @@ -370,9 +370,9 @@ UFSStoreState::writeCompleted(int errflag, size_t len, RefCount wr * flag here. */ if (flags.try_closing) { - debugs(72, 2, HERE << "UFSStoreState::writeCompleted" << - " flags.try_closing is set"); - tryClosing(); + debugs(72, 2, HERE << "UFSStoreState::writeCompleted" << + " flags.try_closing is set"); + tryClosing(); } } @@ -499,7 +499,7 @@ UFSStoreState::drainWriteQueue() * drainWriteQueue(). */ if (flags.write_draining) - return; + return; if (!theFile->canWrite()) return; @@ -532,8 +532,8 @@ UFSStoreState::tryClosing() " ioInProgress = " << theFile->ioInProgress()); if (theFile->ioInProgress()) { - debugs(79, 3, HERE << this << - " won't close since ioInProgress is true, bailing"); + debugs(79, 3, HERE << this << + " won't close since ioInProgress is true, bailing"); flags.try_closing = true; return; } diff --git a/src/fs/ufs/ufscommon.cc b/src/fs/ufs/ufscommon.cc index 11d0abd5ce..02cb3bb8f6 100644 --- a/src/fs/ufs/ufscommon.cc +++ b/src/fs/ufs/ufscommon.cc @@ -1,6 +1,6 @@ /* * $Id: ufscommon.cc,v 1.15 2007/11/15 16:47:38 wessels Exp $ - * vim: set et : + * vim: set et : * * DEBUG: section 47 Store Directory Routines * AUTHOR: Robert Collins @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -46,36 +46,37 @@ CBDATA_CLASS_INIT(RebuildState); -class UFSSwapLogParser_old:public UFSSwapLogParser{ +class UFSSwapLogParser_old:public UFSSwapLogParser +{ public: - struct StoreSwapLogDataOld{ - char op; - sfileno swap_filen; - time_t timestamp; - time_t lastref; - time_t expires; - time_t lastmod; - size_t swap_file_sz; - u_short refcount; - u_short flags; - unsigned char key[SQUID_MD5_DIGEST_LENGTH]; + struct StoreSwapLogDataOld { + char op; + sfileno swap_filen; + time_t timestamp; + time_t lastref; + time_t expires; + time_t lastmod; + size_t swap_file_sz; + u_short refcount; + u_short flags; + unsigned char key[SQUID_MD5_DIGEST_LENGTH]; }; - UFSSwapLogParser_old(FILE *fp):UFSSwapLogParser(fp) - { - record_size = sizeof(UFSSwapLogParser_old::StoreSwapLogDataOld); + UFSSwapLogParser_old(FILE *fp):UFSSwapLogParser(fp) { + record_size = sizeof(UFSSwapLogParser_old::StoreSwapLogDataOld); } bool ReadRecord(StoreSwapLogData &swapData); }; -bool UFSSwapLogParser_old::ReadRecord(StoreSwapLogData &swapData){ +bool UFSSwapLogParser_old::ReadRecord(StoreSwapLogData &swapData) +{ UFSSwapLogParser_old::StoreSwapLogDataOld readData; int bytes = sizeof(UFSSwapLogParser_old::StoreSwapLogDataOld); assert(log); - if (fread(&readData, bytes, 1, log) != 1){ - return false; + if (fread(&readData, bytes, 1, log) != 1) { + return false; } swapData.op = readData.op; swapData.swap_filen = readData.swap_filen; @@ -91,11 +92,11 @@ bool UFSSwapLogParser_old::ReadRecord(StoreSwapLogData &swapData){ } -class UFSSwapLogParser_v1:public UFSSwapLogParser{ +class UFSSwapLogParser_v1:public UFSSwapLogParser +{ public: - UFSSwapLogParser_v1(FILE *fp):UFSSwapLogParser(fp) - { - record_size = sizeof(StoreSwapLogData); + UFSSwapLogParser_v1(FILE *fp):UFSSwapLogParser(fp) { + record_size = sizeof(StoreSwapLogData); } bool ReadRecord(StoreSwapLogData &swapData); }; @@ -106,8 +107,8 @@ bool UFSSwapLogParser_v1::ReadRecord(StoreSwapLogData &swapData) int bytes = sizeof(StoreSwapLogData); assert(log); - - if (fread(&swapData, bytes, 1, log) != 1){ + + if (fread(&swapData, bytes, 1, log) != 1) { return false; } return true; @@ -121,44 +122,45 @@ UFSSwapLogParser *UFSSwapLogParser::GetUFSSwapLogParser(FILE *fp) assert(fp); if (fread(&header, sizeof(StoreSwapLogHeader), 1, fp) != 1) - return NULL; + return NULL; - if (header.op != SWAP_LOG_VERSION){ - debugs(47, 1, "Old swap file detected... "); - fseek(fp, 0, SEEK_SET); - return new UFSSwapLogParser_old(fp); + if (header.op != SWAP_LOG_VERSION) { + debugs(47, 1, "Old swap file detected... "); + fseek(fp, 0, SEEK_SET); + return new UFSSwapLogParser_old(fp); } - if (header.version == 1){ - if (fseek(fp, header.record_size, SEEK_SET) != 0) - return NULL; - - if (header.record_size == sizeof(struct UFSSwapLogParser_old::StoreSwapLogDataOld)){ - debugs(47, 1, "Version 1 of swap file without LFS support detected... "); - return new UFSSwapLogParser_old(fp); - } - - if (header.record_size == sizeof(StoreSwapLogData)){ - debugs(47, 1, "Version 1 of swap file with LFS support detected... "); - return new UFSSwapLogParser_v1(fp); - } - - debugs(47, 1, "The swap file has wrong format!... "); - return NULL; - } + if (header.version == 1) { + if (fseek(fp, header.record_size, SEEK_SET) != 0) + return NULL; + + if (header.record_size == sizeof(struct UFSSwapLogParser_old::StoreSwapLogDataOld)) { + debugs(47, 1, "Version 1 of swap file without LFS support detected... "); + return new UFSSwapLogParser_old(fp); + } + + if (header.record_size == sizeof(StoreSwapLogData)) { + debugs(47, 1, "Version 1 of swap file with LFS support detected... "); + return new UFSSwapLogParser_v1(fp); + } + + debugs(47, 1, "The swap file has wrong format!... "); + return NULL; + } return NULL; } -int UFSSwapLogParser::SwapLogEntries(){ +int UFSSwapLogParser::SwapLogEntries() +{ struct stat sb; - + if (log_entries >= 0) - return log_entries; + return log_entries; - if (log && record_size && 0 == fstat(fileno(log), &sb)){ - log_entries = sb.st_size/record_size; - return log_entries; + if (log && record_size && 0 == fstat(fileno(log), &sb)) { + log_entries = sb.st_size/record_size; + return log_entries; } return 0; @@ -181,7 +183,7 @@ RebuildState::RebuildState (RefCount aSwapDir) : sd (aSwapDir),LogPa FILE *fp = sd->openTmpSwapLog(&clean, &zeroLengthLog); if (fp && !zeroLengthLog) - LogParser = UFSSwapLogParser::GetUFSSwapLogParser(fp); + LogParser = UFSSwapLogParser::GetUFSSwapLogParser(fp); if (LogParser == NULL ) { fromLog = false; @@ -190,8 +192,8 @@ RebuildState::RebuildState (RefCount aSwapDir) : sd (aSwapDir),LogPa fclose(fp); } else { - fromLog = true; - flags.clean = (unsigned int) clean; + fromLog = true; + flags.clean = (unsigned int) clean; } if (!clean) @@ -205,7 +207,7 @@ RebuildState::~RebuildState() sd->closeTmpSwapLog(); if (LogParser) - delete LogParser; + delete LogParser; } void @@ -232,12 +234,10 @@ RebuildState::rebuildStep() rebuildFromDirectory(); } -struct InitStoreEntry : public unary_function -{ - InitStoreEntry(StoreEntry *anEntry, cache_key *aKey):what(anEntry),index(aKey){} +struct InitStoreEntry : public unary_function { + InitStoreEntry(StoreEntry *anEntry, cache_key *aKey):what(anEntry),index(aKey) {} - void operator()(StoreMeta const &x) - { + void operator()(StoreMeta const &x) { switch (x.getType()) { case STORE_META_KEY: @@ -246,7 +246,7 @@ struct InitStoreEntry : public unary_function break; case STORE_META_STD: - struct old_metahdr{ + struct old_metahdr { time_t timestamp; time_t lastref; time_t expires; @@ -255,19 +255,19 @@ struct InitStoreEntry : public unary_function u_short refcount; u_short flags; } *tmp; - tmp = (struct old_metahdr *)x.value; + tmp = (struct old_metahdr *)x.value; assert(x.length == STORE_HDR_METASIZE_OLD); - what->timestamp = tmp->timestamp; - what->lastref = tmp->lastref; - what->expires = tmp->expires; - what->lastmod = tmp->lastmod; - what->swap_file_sz = tmp->swap_file_sz; - what->refcount = tmp->refcount; - what->flags = tmp->flags; + what->timestamp = tmp->timestamp; + what->lastref = tmp->lastref; + what->expires = tmp->expires; + what->lastmod = tmp->lastmod; + what->swap_file_sz = tmp->swap_file_sz; + what->refcount = tmp->refcount; + what->flags = tmp->flags; break; - case STORE_META_STD_LFS: - assert(x.length == STORE_HDR_METASIZE); + case STORE_META_STD_LFS: + assert(x.length == STORE_HDR_METASIZE); xmemcpy(&what->timestamp, x.value, STORE_HDR_METASIZE); break; @@ -321,7 +321,7 @@ RebuildState::rebuildFromDirectory() if ((++counts.scancount & 0xFFFF) == 0) debugs(47, 3, " " << sd->path << " " << std::setw(7) << counts.scancount << " files opened so far."); - debugs(47, 9, "file_in: fd=" << fd << " "<< std::setfill('0') << std::hex << std::uppercase << std::setw(8) << filn); + debugs(47, 9, "file_in: fd=" << fd << " "<< std::setfill('0') << std::hex << std::uppercase << std::setw(8) << filn); statCounter.syscalls.disk.reads++; @@ -410,7 +410,7 @@ RebuildState::rebuildFromDirectory() * which will conflict when the in core index gets around to scanning * store B. * - * this suggests that rather than searching for duplicates, the + * this suggests that rather than searching for duplicates, the * index rebuild should just assume its the most recent accurate * store entry and whoever indexes the stores handles duplicates. */ @@ -429,7 +429,7 @@ RebuildState::rebuildFromDirectory() } counts.objcount++; - // tmpe.dump(5); + // tmpe.dump(5); currentEntry(sd->addDiskRestore(key, filn, tmpe.swap_file_sz, @@ -470,8 +470,8 @@ RebuildState::rebuildFromSwapLog() if (LogParser->ReadRecord(swapData) != 1) { debugs(47, 1, "Done reading " << sd->path << " swaplog (" << n_read << " entries)"); LogParser->Close(); - delete LogParser; - LogParser = NULL; + delete LogParser; + LogParser = NULL; _done = true; return; } @@ -488,7 +488,7 @@ RebuildState::rebuildFromSwapLog() * BC: during 2.4 development, we changed the way swap file * numbers are assigned and stored. The high 16 bits used * to encode the SD index number. There used to be a call - * to storeDirProperFileno here that re-assigned the index + * to storeDirProperFileno here that re-assigned the index * bits. Now, for backwards compatibility, we just need * to mask it off. */ @@ -535,7 +535,8 @@ RebuildState::rebuildFromSwapLog() currentEntry()->release(); counts.objcount--; counts.cancelcount++; - } continue; + } + continue; } else { x = ::log(static_cast(++counts.bad_log_op)) / ::log(10.0); @@ -602,16 +603,17 @@ RebuildState::rebuildFromSwapLog() } else { debug_trap("commonUfsDirRebuildFromSwapLog: bad condition"); debugs(47, 1, "\tSee " << __FILE__ << ":" << __LINE__); - } continue; + } + continue; } else if (used) { /* swapfile in use, not by this URL, log entry is newer */ /* This is sorta bad: the log entry should NOT be newer at this * point. If the log is dirty, the filesize check should have * caught this. If the log is clean, there should never be a * newer entry. */ - debugs(47, 1, "WARNING: newer swaplog entry for dirno " << - sd->index << ", fileno "<< std::setfill('0') << std::hex << - std::uppercase << std::setw(8) << swapData.swap_filen); + debugs(47, 1, "WARNING: newer swaplog entry for dirno " << + sd->index << ", fileno "<< std::setfill('0') << std::hex << + std::uppercase << std::setw(8) << swapData.swap_filen); /* I'm tempted to remove the swapfile here just to be safe, * but there is a bad race condition in the NOVM version if @@ -716,7 +718,7 @@ RebuildState::getNextFile(sfileno * filn_p, int *size) entry = readdir(td); if (entry == NULL && errno == ENOENT) - debugs(47, 1, "commonUfsDirGetNextFile: directory does not exist!."); + debugs(47, 1, "commonUfsDirGetNextFile: directory does not exist!."); debugs(47, 3, "commonUfsDirGetNextFile: Directory " << fullpath); } } diff --git a/src/fs/ufs/ufscommon.cci b/src/fs/ufs/ufscommon.cci index 6cc3eff611..3d5fa0cf1a 100644 --- a/src/fs/ufs/ufscommon.cci +++ b/src/fs/ufs/ufscommon.cci @@ -20,12 +20,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/fs/ufs/ufscommon.h b/src/fs/ufs/ufscommon.h index 4059fec7d3..57de6e89a7 100644 --- a/src/fs/ufs/ufscommon.h +++ b/src/fs/ufs/ufscommon.h @@ -17,12 +17,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -251,8 +251,7 @@ protected: /** \todo These should be in the IO strategy */ - struct - { + struct { /** * DPW 2006-05-24 * the write_draining flag is used to avoid recursion inside @@ -339,21 +338,20 @@ public: FILE *log; int log_entries; int record_size; - - UFSSwapLogParser(FILE *fp):log(fp),log_entries(-1), record_size(0){ + + UFSSwapLogParser(FILE *fp):log(fp),log_entries(-1), record_size(0) { } - virtual ~UFSSwapLogParser(){}; - + virtual ~UFSSwapLogParser() {}; + static UFSSwapLogParser *GetUFSSwapLogParser(FILE *fp); - + virtual bool ReadRecord(StoreSwapLogData &swapData) = 0; int SwapLogEntries(); - void Close() - { - if(log){ - fclose(log); - log = NULL; - } + void Close() { + if (log) { + fclose(log); + log = NULL; + } } }; @@ -371,7 +369,7 @@ public: /** \todo Iterator API - garh, wrong place */ /** * callback the client when a new StoreEntry is available - * or an error occurs + * or an error occurs */ virtual void next(void (callback)(void *cbdata), void *cbdata); @@ -386,14 +384,13 @@ public: RefCount sd; int n_read; -/* FILE *log;*/ + /* FILE *log;*/ UFSSwapLogParser *LogParser; int speed; int curlvl1; int curlvl2; - struct - { + struct { unsigned int need_to_validate:1; unsigned int clean:1; unsigned int init:1; diff --git a/src/globals.h b/src/globals.h index 3af974ff11..6c128efe7c 100644 --- a/src/globals.h +++ b/src/globals.h @@ -18,12 +18,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. diff --git a/src/gopher.cc b/src/gopher.cc index 24ebff5e1c..0d195b71ea 100644 --- a/src/gopher.cc +++ b/src/gopher.cc @@ -21,12 +21,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. @@ -114,8 +114,7 @@ #define MAX_CSO_RESULT 1024 /// \ingroup ServerProtocolGopherInternal -typedef struct gopher_ds -{ +typedef struct gopher_ds { StoreEntry *entry; enum { NORMAL, @@ -537,213 +536,212 @@ gopherToHTML(GopherStateData * gopherState, char *inbuf, int len) case gopher_ds::HTML_INDEX_RESULT: case gopher_ds::HTML_DIR: { - tline = line; - gtype = *tline++; - name = tline; - selector = strchr(tline, TAB); + tline = line; + gtype = *tline++; + name = tline; + selector = strchr(tline, TAB); + + if (selector) { + *selector++ = '\0'; + host = strchr(selector, TAB); - if (selector) { - *selector++ = '\0'; - host = strchr(selector, TAB); + if (host) { + *host++ = '\0'; + port = strchr(host, TAB); - if (host) { - *host++ = '\0'; - port = strchr(host, TAB); + if (port) { + char *junk; + port[0] = ':'; + junk = strchr(host, TAB); - if (port) { - char *junk; - port[0] = ':'; - junk = strchr(host, TAB); + if (junk) + *junk++ = 0; /* Chop port */ + else { + junk = strchr(host, '\r'); if (junk) *junk++ = 0; /* Chop port */ else { - junk = strchr(host, '\r'); + junk = strchr(host, '\n'); if (junk) *junk++ = 0; /* Chop port */ - else { - junk = strchr(host, '\n'); - - if (junk) - *junk++ = 0; /* Chop port */ - } } - - if ((port[1] == '0') && (!port[2])) - port[0] = 0; /* 0 means none */ } - /* escape a selector here */ - escaped_selector = xstrdup(rfc1738_escape_part(selector)); + if ((port[1] == '0') && (!port[2])) + port[0] = 0; /* 0 means none */ + } - switch (gtype) { + /* escape a selector here */ + escaped_selector = xstrdup(rfc1738_escape_part(selector)); - case GOPHER_DIRECTORY: - icon_url = mimeGetIconURL("internal-menu"); - break; + switch (gtype) { - case GOPHER_HTML: + case GOPHER_DIRECTORY: + icon_url = mimeGetIconURL("internal-menu"); + break; - case GOPHER_FILE: - icon_url = mimeGetIconURL("internal-text"); - break; + case GOPHER_HTML: - case GOPHER_INDEX: + case GOPHER_FILE: + icon_url = mimeGetIconURL("internal-text"); + break; - case GOPHER_CSO: - icon_url = mimeGetIconURL("internal-index"); - break; + case GOPHER_INDEX: - case GOPHER_IMAGE: + case GOPHER_CSO: + icon_url = mimeGetIconURL("internal-index"); + break; - case GOPHER_GIF: + case GOPHER_IMAGE: - case GOPHER_PLUS_IMAGE: - icon_url = mimeGetIconURL("internal-image"); - break; + case GOPHER_GIF: - case GOPHER_SOUND: + case GOPHER_PLUS_IMAGE: + icon_url = mimeGetIconURL("internal-image"); + break; - case GOPHER_PLUS_SOUND: - icon_url = mimeGetIconURL("internal-sound"); - break; + case GOPHER_SOUND: - case GOPHER_PLUS_MOVIE: - icon_url = mimeGetIconURL("internal-movie"); - break; + case GOPHER_PLUS_SOUND: + icon_url = mimeGetIconURL("internal-sound"); + break; - case GOPHER_TELNET: + case GOPHER_PLUS_MOVIE: + icon_url = mimeGetIconURL("internal-movie"); + break; - case GOPHER_3270: - icon_url = mimeGetIconURL("internal-telnet"); - break; + case GOPHER_TELNET: - case GOPHER_BIN: + case GOPHER_3270: + icon_url = mimeGetIconURL("internal-telnet"); + break; - case GOPHER_MACBINHEX: + case GOPHER_BIN: - case GOPHER_DOSBIN: + case GOPHER_MACBINHEX: - case GOPHER_UUENCODED: - icon_url = mimeGetIconURL("internal-binary"); - break; + case GOPHER_DOSBIN: - case GOPHER_INFO: - icon_url = NULL; - break; + case GOPHER_UUENCODED: + icon_url = mimeGetIconURL("internal-binary"); + break; - default: - icon_url = mimeGetIconURL("internal-unknown"); - break; - } + case GOPHER_INFO: + icon_url = NULL; + break; - memset(tmpbuf, '\0', TEMP_BUF_SIZE); + default: + icon_url = mimeGetIconURL("internal-unknown"); + break; + } - if ((gtype == GOPHER_TELNET) || (gtype == GOPHER_3270)) { - if (strlen(escaped_selector) != 0) - snprintf(tmpbuf, TEMP_BUF_SIZE, " %s\n", - icon_url, escaped_selector, rfc1738_escape_part(host), - *port ? ":" : "", port, html_quote(name)); - else - snprintf(tmpbuf, TEMP_BUF_SIZE, " %s\n", - icon_url, rfc1738_escape_part(host), *port ? ":" : "", - port, html_quote(name)); + memset(tmpbuf, '\0', TEMP_BUF_SIZE); - } else if (gtype == GOPHER_INFO) { - snprintf(tmpbuf, TEMP_BUF_SIZE, "\t%s\n", html_quote(name)); - } else { - if (strncmp(selector, "GET /", 5) == 0) { - /* WWW link */ - snprintf(tmpbuf, TEMP_BUF_SIZE, " %s\n", - icon_url, host, rfc1738_escape_unescaped(selector + 5), html_quote(name)); - } else { - /* Standard link */ - snprintf(tmpbuf, TEMP_BUF_SIZE, " %s\n", - icon_url, host, gtype, escaped_selector, html_quote(name)); - } - } + if ((gtype == GOPHER_TELNET) || (gtype == GOPHER_3270)) { + if (strlen(escaped_selector) != 0) + snprintf(tmpbuf, TEMP_BUF_SIZE, " %s\n", + icon_url, escaped_selector, rfc1738_escape_part(host), + *port ? ":" : "", port, html_quote(name)); + else + snprintf(tmpbuf, TEMP_BUF_SIZE, " %s\n", + icon_url, rfc1738_escape_part(host), *port ? ":" : "", + port, html_quote(name)); - safe_free(escaped_selector); - outbuf.append(tmpbuf); + } else if (gtype == GOPHER_INFO) { + snprintf(tmpbuf, TEMP_BUF_SIZE, "\t%s\n", html_quote(name)); } else { - memset(line, '\0', TEMP_BUF_SIZE); - continue; + if (strncmp(selector, "GET /", 5) == 0) { + /* WWW link */ + snprintf(tmpbuf, TEMP_BUF_SIZE, " %s\n", + icon_url, host, rfc1738_escape_unescaped(selector + 5), html_quote(name)); + } else { + /* Standard link */ + snprintf(tmpbuf, TEMP_BUF_SIZE, " %s\n", + icon_url, host, gtype, escaped_selector, html_quote(name)); + } } + + safe_free(escaped_selector); + outbuf.append(tmpbuf); } else { memset(line, '\0', TEMP_BUF_SIZE); continue; } + } else { + memset(line, '\0', TEMP_BUF_SIZE); + continue; + } - break; - } /* HTML_DIR, HTML_INDEX_RESULT */ + break; + } /* HTML_DIR, HTML_INDEX_RESULT */ case gopher_ds::HTML_CSO_RESULT: { - if (line[0] == '-') { - int code, recno; - char *s_code, *s_recno, *result; + if (line[0] == '-') { + int code, recno; + char *s_code, *s_recno, *result; - s_code = strtok(line + 1, ":\n"); - s_recno = strtok(NULL, ":\n"); - result = strtok(NULL, "\n"); - - if (!result) - break; + s_code = strtok(line + 1, ":\n"); + s_recno = strtok(NULL, ":\n"); + result = strtok(NULL, "\n"); - code = atoi(s_code); - - recno = atoi(s_recno); + if (!result) + break; - if (code != 200) - break; + code = atoi(s_code); - if (gopherState->cso_recno != recno) { - snprintf(tmpbuf, TEMP_BUF_SIZE, "

Record# %d
%s

\n
", recno, html_quote(result));
-                        gopherState->cso_recno = recno;
-                    } else {
-                        snprintf(tmpbuf, TEMP_BUF_SIZE, "%s\n", html_quote(result));
-                    }
+                recno = atoi(s_recno);
 
-                    outbuf.append(tmpbuf);
+                if (code != 200)
                     break;
+
+                if (gopherState->cso_recno != recno) {
+                    snprintf(tmpbuf, TEMP_BUF_SIZE, "

Record# %d
%s

\n
", recno, html_quote(result));
+                    gopherState->cso_recno = recno;
                 } else {
-                    int code;
-                    char *s_code, *result;
+                    snprintf(tmpbuf, TEMP_BUF_SIZE, "%s\n", html_quote(result));
+                }
 
-                    s_code = strtok(line, ":");
-                    result = strtok(NULL, "\n");
+                outbuf.append(tmpbuf);
+                break;
+            } else {
+                int code;
+                char *s_code, *result;
 
-                    if (!result)
-                        break;
+                s_code = strtok(line, ":");
+                result = strtok(NULL, "\n");
 
-                    code = atoi(s_code);
+                if (!result)
+                    break;
 
-                    switch (code) {
+                code = atoi(s_code);
 
-                    case 200: {
-                            /* OK */
-                            /* Do nothing here */
-                            break;
-                        }
+                switch (code) {
 
-                    case 102:	/* Number of matches */
+                case 200: {
+                    /* OK */
+                    /* Do nothing here */
+                    break;
+                }
 
-                    case 501:	/* No Match */
+                case 102:	/* Number of matches */
 
-                    case 502:	/* Too Many Matches */
-                        {
-                            /* Print the message the server returns */
-                            snprintf(tmpbuf, TEMP_BUF_SIZE, "

%s

\n
", html_quote(result));
-                            outbuf.append(tmpbuf);
-                            break;
-                        }
+                case 501:	/* No Match */
+
+                case 502: {	/* Too Many Matches */
+                    /* Print the message the server returns */
+                    snprintf(tmpbuf, TEMP_BUF_SIZE, "

%s

\n
", html_quote(result));
+                    outbuf.append(tmpbuf);
+                    break;
+                }
 
 
-                    }
                 }
+            }
 
-            }			/* HTML_CSO_RESULT */
+        }			/* HTML_CSO_RESULT */
 
         default:
             break;		/* do nothing */
@@ -881,7 +879,7 @@ gopherReadReply(int fd, char *buf, size_t len, comm_err_t flag, int xerrno, void
 
     if (do_next_read)
         comm_read(fd, buf, read_sz, gopherReadReply, gopherState);
-    
+
     return;
 }
 
@@ -953,7 +951,7 @@ gopherSendComplete(int fd, char *buf, size_t size, comm_err_t errflag, int xerrn
 
     /* Schedule read reply. */
     AsyncCall::Pointer call =  commCbCall(10,5, "gopherReadReply",
-				 CommIoCbPtrFun(gopherReadReply, gopherState));
+                                          CommIoCbPtrFun(gopherReadReply, gopherState));
     entry->delayAwareRead(fd, gopherState->replybuf, BUFSIZ, call);
 
     if (buf)
diff --git a/src/helper.cc b/src/helper.cc
index 7be7352bde..b7a11a6303 100644
--- a/src/helper.cc
+++ b/src/helper.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -175,7 +175,7 @@ helperOpenServers(helper * hlp)
 
 /*
  * DPW 2007-05-08
- * 
+ *
  * helperStatefulOpenServers: create the stateful child helper processes
  */
 void
@@ -214,17 +214,17 @@ helperStatefulOpenServers(statefulhelper * hlp)
 
     for (int k = 0; k < hlp->n_to_start; k++) {
         getCurrentTime();
-	int rfd = -1;
-	int wfd = -1;
-	void * hIpc;
+        int rfd = -1;
+        int wfd = -1;
+        void * hIpc;
         pid_t pid = ipcCreate(hlp->ipc_type,
-                        progname,
-                        args,
-                        shortname,
-                        hlp->addr,
-                        &rfd,
-                        &wfd,
-                        &hIpc);
+                              progname,
+                              args,
+                              shortname,
+                              hlp->addr,
+                              &rfd,
+                              &wfd,
+                              &hIpc);
 
         if (pid < 0) {
             debugs(84, 1, "WARNING: Cannot run '" << progname << "' process.");
@@ -337,7 +337,7 @@ helperStatefulSubmit(statefulhelper * hlp, const char *buf, HLPSCB * callback, v
         debugs(84, 5, "StatefulSubmit with lastserver " << lastserver);
         /* the queue doesn't count for this assert because queued requests
          * have already gone through here and been tested.
-         * It's legal to have deferred_requests == 0 and queue entries 
+         * It's legal to have deferred_requests == 0 and queue entries
          * and status of S_HELPEER_DEFERRED.
          * BUT:  It's not legal to submit a new request w/lastserver in
          * that state.
@@ -358,7 +358,7 @@ helperStatefulSubmit(statefulhelper * hlp, const char *buf, HLPSCB * callback, v
             StatefulServerEnqueue(lastserver, r);
         }
     } else {
-	helper_stateful_server *srv;
+        helper_stateful_server *srv;
         if ((srv = StatefulGetFirstAvailable(hlp))) {
             helperStatefulDispatch(srv, r);
         } else
@@ -498,19 +498,19 @@ helperStatefulReleaseServer(helper_stateful_server * srv)
     if (srv->flags.reserved == S_HELPER_DEFERRED) {
         assert(srv->deferred_requests);
         srv->deferred_requests--;
-	if (srv->deferred_requests) {
-	    debugs(0,0,HERE << "helperStatefulReleaseServer srv->deferred_requests=" << srv->deferred_requests);
-	    return;
-	}
-	if (srv->queue.head) {
-	    debugs(0,0,HERE << "helperStatefulReleaseServer srv->queue.head not NULL");
-	    return;
-	}
+        if (srv->deferred_requests) {
+            debugs(0,0,HERE << "helperStatefulReleaseServer srv->deferred_requests=" << srv->deferred_requests);
+            return;
+        }
+        if (srv->queue.head) {
+            debugs(0,0,HERE << "helperStatefulReleaseServer srv->queue.head not NULL");
+            return;
+        }
     }
 
     srv->flags.reserved = S_HELPER_FREE;
     if (srv->parent->OnEmptyQueue != NULL && srv->data)
-	srv->parent->OnEmptyQueue(srv->data);
+        srv->parent->OnEmptyQueue(srv->data);
 }
 
 void *
@@ -606,7 +606,7 @@ helperStatefulStats(StoreEntry * sentry, statefulhelper * hlp, const char *label
     for (dlink_node *link = hlp->servers.head; link; link = link->next) {
         helper_stateful_server *srv = (helper_stateful_server *)link->data;
         double tt = 0.001 * tvSubMsec(srv->dispatch_time,
-                               srv->flags.busy ? current_time : srv->answer_time);
+                                      srv->flags.busy ? current_time : srv->answer_time);
         storeAppendPrintf(sentry, "%7d\t%7d\t%7d\t%11d\t%20d\t%c%c%c%c%c\t%7.3f\t%7d\t%s\n",
                           srv->index + 1,
                           srv->rfd,
@@ -1074,7 +1074,7 @@ helperHandleRead(int fd, char *buf, size_t len, comm_err_t flag, int xerrno, voi
             srv->wfd = -1;
             srv->flags.closing=1;
             comm_close(wfd);
-	    return;
+            return;
         } else
             helperKickQueue(hlp);
     }
@@ -1137,7 +1137,7 @@ helperStatefulHandleRead(int fd, char *buf, size_t len, comm_err_t flag, int xer
             switch ((r->callback(r->data, srv, srv->rbuf))) {	/*if non-zero reserve helper */
 
             case S_HELPER_UNKNOWN:
-                    fatal("helperStatefulHandleRead: either a non-state aware callback was give to the stateful helper routines, or an uninitialised callback response was received.\n");
+                fatal("helperStatefulHandleRead: either a non-state aware callback was give to the stateful helper routines, or an uninitialised callback response was received.\n");
                 break;
 
             case S_HELPER_RELEASE:	/* helper finished with */
@@ -1282,7 +1282,7 @@ StatefulServerEnqueue(helper_stateful_server * srv, helper_stateful_request * r)
     dlinkAddTail(r, link, &srv->queue);
     /* TODO: warning if the queue on this server is more than X
      * We don't check the queue size at the moment, because
-     * requests hitting here are deferrable 
+     * requests hitting here are deferrable
      */
     /*    hlp->stats.queue_size++;
      * if (hlp->stats.queue_size < hlp->n_running)
@@ -1413,7 +1413,7 @@ StatefulGetFirstAvailable(statefulhelper * hlp)
         if ((hlp->IsAvailable != NULL) && (srv->data != NULL) && !(hlp->IsAvailable(srv->data)))
             continue;
 
-	debugs(84, 5, "StatefulGetFirstAvailable: returning srv-" << srv->index);
+        debugs(84, 5, "StatefulGetFirstAvailable: returning srv-" << srv->index);
         return srv;
     }
 
@@ -1607,7 +1607,7 @@ helperRequestFree(helper_request * r)
 static void
 helperStatefulRequestFree(helper_stateful_request * r)
 {
-    if(r) {
+    if (r) {
         cbdataReferenceDone(r->data);
         xfree(r->buf);
         delete r;
diff --git a/src/helper.h b/src/helper.h
index cc08c45d31..43332d4bae 100644
--- a/src/helper.h
+++ b/src/helper.h
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -56,8 +56,7 @@ typedef struct _helper_stateful_flags helper_stateful_flags;
 
 typedef stateful_helper_callback_t HLPSCB(void *, void *lastserver, char *buf);
 
-struct _helper
-{
+struct _helper {
     wordlist *cmdline;
     dlink_list servers;
     dlink_list queue;
@@ -71,8 +70,7 @@ struct _helper
     time_t last_queue_warn;
     time_t last_restart;
 
-    struct
-    {
+    struct {
         int requests;
         int replies;
         int queue_size;
@@ -80,8 +78,7 @@ struct _helper
     } stats;
 };
 
-struct _helper_stateful
-{
+struct _helper_stateful {
     wordlist *cmdline;
     dlink_list servers;
     dlink_list queue;
@@ -97,8 +94,7 @@ struct _helper_stateful
     time_t last_queue_warn;
     time_t last_restart;
 
-    struct
-    {
+    struct {
         int requests;
         int replies;
         int queue_size;
@@ -106,8 +102,7 @@ struct _helper_stateful
     } stats;
 };
 
-struct _helper_server
-{
+struct _helper_server {
     int index;
     int pid;
     IPAddress addr;
@@ -127,15 +122,13 @@ struct _helper_server
     helper *parent;
     helper_request **requests;
 
-    struct _helper_flags
-    {
+    struct _helper_flags {
         unsigned int writing:1;
         unsigned int closing:1;
         unsigned int shutdown:1;
     } flags;
 
-    struct
-    {
+    struct {
         int uses;
         unsigned int pending;
     } stats;
@@ -145,8 +138,7 @@ struct _helper_server
 
 class helper_stateful_request;
 
-struct _helper_stateful_server
-{
+struct _helper_stateful_server {
     int index;
     int pid;
     IPAddress addr;
@@ -167,16 +159,14 @@ struct _helper_stateful_server
     statefulhelper *parent;
     helper_stateful_request *request;
 
-    struct _helper_stateful_flags
-    {
+    struct _helper_stateful_flags {
         unsigned int busy:1;
         unsigned int closing:1;
         unsigned int shutdown:1;
         stateful_helper_reserve_t reserved;
     } flags;
 
-    struct
-    {
+    struct {
         int uses;
         int submits;
         int releases;
diff --git a/src/htcp.cc b/src/htcp.cc
index 96f4f2d55f..a0d9f503c8 100644
--- a/src/htcp.cc
+++ b/src/htcp.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -59,21 +59,18 @@ typedef struct _htcpStuff htcpStuff;
 
 typedef struct _htcpDetail htcpDetail;
 
-struct _Countstr
-{
+struct _Countstr {
     u_int16_t length;
     char *text;
 };
 
-struct _htcpHeader
-{
+struct _htcpHeader {
     u_int16_t length;
     u_char major;
     u_char minor;
 };
 
-struct _htcpDataHeaderSquid
-{
+struct _htcpDataHeaderSquid {
     u_int16_t length;
 
 #if !WORDS_BIGENDIAN
@@ -97,26 +94,35 @@ struct _htcpDataHeaderSquid
     u_int32_t msg_id;
 };
 
-struct _htcpDataHeader
-{
+struct _htcpDataHeader {
     u_int16_t length;
 
 #if WORDS_BIGENDIAN
-    u_int8_t opcode:4;
-    u_int8_t response:4;
+u_int8_t opcode:
+    4;
+u_int8_t response:
+    4;
 #else
-    u_int8_t response:4;
-    u_int8_t opcode:4;
+u_int8_t response:
+    4;
+u_int8_t opcode:
+    4;
 #endif
 
 #if WORDS_BIGENDIAN
-    u_int8_t reserved:6;
-    u_int8_t F1:1;
-    u_int8_t RR:1;
+u_int8_t reserved:
+    6;
+u_int8_t F1:
+    1;
+u_int8_t RR:
+    1;
 #else
-    u_int8_t RR:1;
-    u_int8_t F1:1;
-    u_int8_t reserved:6;
+u_int8_t RR:
+    1;
+u_int8_t F1:
+    1;
+u_int8_t reserved:
+    6;
 #endif
 
     u_int32_t msg_id;
@@ -127,8 +133,7 @@ struct _htcpDataHeader
 /* RR == 0 --> REQUEST */
 /* RR == 1 --> RESPONSE */
 
-struct _htcpAuthHeader
-{
+struct _htcpAuthHeader {
     u_int16_t length;
     time_t sig_time;
     time_t sig_expire;
@@ -163,15 +168,13 @@ private:
 
 MEMPROXY_CLASS_INLINE(htcpSpecifier)		/**DOCS_NOSEMI*/
 
-struct _htcpDetail
-{
+struct _htcpDetail {
     char *resp_hdrs;
     char *entity_hdrs;
     char *cache_hdrs;
 };
 
-struct _htcpStuff
-{
+struct _htcpStuff {
     int op;
     int rr;
     int f1;
@@ -191,15 +194,14 @@ enum {
     HTCP_END
 };
 
-static const char *const htcpOpcodeStr[] =
-    {
-        "HTCP_NOP",
-        "HTCP_TST",
-        "HTCP_MON",
-        "HTCP_SET",
-        "HTCP_CLR",
-        "HTCP_END"
-    };
+static const char *const htcpOpcodeStr[] = {
+    "HTCP_NOP",
+    "HTCP_TST",
+    "HTCP_MON",
+    "HTCP_SET",
+    "HTCP_CLR",
+    "HTCP_END"
+};
 
 /*
  * values for htcpDataHeader->response
@@ -304,7 +306,7 @@ htcpBuildAuth(char *buf, size_t buflen)
     auth.length = htons(2);
     copy_sz += 2;
     if (buflen < copy_sz)
-	return -1;
+        return -1;
     xmemcpy(buf, &auth, copy_sz);
     return copy_sz;
 }
@@ -441,7 +443,7 @@ static ssize_t
 htcpBuildClrOpData(char *buf, size_t buflen, htcpStuff * stuff)
 {
     u_short reason;
-    
+
     switch (stuff->rr) {
     case RR_REQUEST:
         debugs(31, 3, "htcpBuildClrOpData: RR_REQUEST");
@@ -453,7 +455,7 @@ htcpBuildClrOpData(char *buf, size_t buflen, htcpStuff * stuff)
     default:
         fatal_dump("htcpBuildClrOpData: bad RR value");
     }
-    
+
     return 0;
 }
 
@@ -736,7 +738,7 @@ htcpUnpackSpecifier(char *buf, int sz)
     debugs(31, 3, "htcpUnpackSpecifier: " << sz << " bytes left");
 
     /*
-     * Add terminating null to REQ-HDRS. This is possible because we allocated 
+     * Add terminating null to REQ-HDRS. This is possible because we allocated
      * an extra byte when we received the packet. This will overwrite any following
      * AUTH block.
      */
@@ -750,7 +752,7 @@ htcpUnpackSpecifier(char *buf, int sz)
     s->request = HttpRequest::CreateFromUrlAndMethod(s->uri, method == METHOD_NONE ? HttpRequestMethod(METHOD_GET) : method);
 
     if (s->request)
-       HTTPMSGLOCK(s->request);
+        HTTPMSGLOCK(s->request);
 
     return s;
 }
@@ -831,7 +833,7 @@ htcpUnpackDetail(char *buf, int sz)
     debugs(31, 3, "htcpUnpackDetail: " << sz << " bytes left");
 
     /*
-     * Add terminating null to CACHE-HDRS. This is possible because we allocated 
+     * Add terminating null to CACHE-HDRS. This is possible because we allocated
      * an extra byte when we received the packet. This will overwrite any following
      * AUTH block.
      */
@@ -877,8 +879,7 @@ htcpTstReply(htcpDataHeader * dhdr, StoreEntry * e, htcpSpecifier * spec, IPAddr
     debugs(31, 3, "htcpTstReply: response = " << stuff.response);
     stuff.msg_id = dhdr->msg_id;
 
-    if (spec)
-    {
+    if (spec) {
         mb.init();
         packerToMemInit(&p, &mb);
         stuff.S.method = spec->method;
@@ -934,8 +935,7 @@ htcpTstReply(htcpDataHeader * dhdr, StoreEntry * e, htcpSpecifier * spec, IPAddr
     safe_free(stuff.D.entity_hdrs);
     safe_free(stuff.D.cache_hdrs);
 
-    if (!pktlen)
-    {
+    if (!pktlen) {
         debugs(31, 3, "htcpTstReply: htcpBuildPacket() failed");
         return;
     }
@@ -972,8 +972,7 @@ htcpClrReply(htcpDataHeader * dhdr, int purgeSucceeded, IPAddress &from)
 
     pktlen = htcpBuildPacket(pkt, sizeof(pkt), &stuff);
 
-    if (pktlen == 0)
-    {
+    if (pktlen == 0) {
         debugs(31, 3, "htcpClrReply: htcpBuildPacket() failed");
         return;
     }
@@ -1021,14 +1020,11 @@ htcpSpecifier::created (StoreEntry *e)
 
     if (e->isNull()) {
         debugs(31, 3, "htcpCheckHit: NO; public object not found");
-    }
-    else if (!e->validToSend()) {
+    } else if (!e->validToSend()) {
         debugs(31, 3, "htcpCheckHit: NO; entry not valid to send" );
-    }
-    else if (refreshCheckHTCP(e, checkHitRequest)) {
+    } else if (refreshCheckHTCP(e, checkHitRequest)) {
         debugs(31, 3, "htcpCheckHit: NO; cached response is stale");
-    }
-    else {
+    } else {
         debugs(31, 3, "htcpCheckHit: YES!?");
         hit = e;
     }
@@ -1107,8 +1103,7 @@ htcpHandleTstResponse(htcpDataHeader * hdr, char *buf, int sz, IPAddress &from)
     htcpDetail *d = NULL;
     char *t;
 
-    if (queried_id[hdr->msg_id % N_QUERIED_KEYS] != hdr->msg_id)
-    {
+    if (queried_id[hdr->msg_id % N_QUERIED_KEYS] != hdr->msg_id) {
         debugs(31, 2, "htcpHandleTstResponse: No matching query id '" <<
                hdr->msg_id << "' (expected " <<
                queried_id[hdr->msg_id % N_QUERIED_KEYS] << ") from '" <<
@@ -1119,22 +1114,19 @@ htcpHandleTstResponse(htcpDataHeader * hdr, char *buf, int sz, IPAddress &from)
 
     key = queried_keys[hdr->msg_id % N_QUERIED_KEYS];
 
-    if (!key)
-    {
+    if (!key) {
         debugs(31, 3, "htcpHandleTstResponse: No query key for response id '" << hdr->msg_id << "' from '" << from << "'");
         return;
     }
 
     peer = &queried_addr[hdr->msg_id % N_QUERIED_KEYS];
 
-    if ( *peer != from || peer->GetPort() != from.GetPort() )
-    {
+    if ( *peer != from || peer->GetPort() != from.GetPort() ) {
         debugs(31, 3, "htcpHandleTstResponse: Unexpected response source " << from );
         return;
     }
 
-    if (hdr->F1 == 1)
-    {
+    if (hdr->F1 == 1) {
         debugs(31, 2, "htcpHandleTstResponse: error condition, F1/MO == 1");
         return;
     }
@@ -1143,11 +1135,9 @@ htcpHandleTstResponse(htcpDataHeader * hdr, char *buf, int sz, IPAddress &from)
     debugs(31, 3, "htcpHandleTstResponse: msg_id = " << htcpReply.msg_id);
     htcpReply.hit = hdr->response ? 0 : 1;
 
-    if (hdr->F1)
-    {
+    if (hdr->F1) {
         debugs(31, 3, "htcpHandleTstResponse: MISS");
-    } else
-    {
+    } else {
         debugs(31, 3, "htcpHandleTstResponse: HIT");
         d = htcpUnpackDetail(buf, sz);
 
@@ -1181,8 +1171,7 @@ htcpHandleTstRequest(htcpDataHeader * dhdr, char *buf, int sz, IPAddress &from)
     /* buf should be a SPECIFIER */
     htcpSpecifier *s;
 
-    if (sz == 0)
-    {
+    if (sz == 0) {
         debugs(31, 3, "htcpHandleTst: nothing to do");
         return;
     }
@@ -1197,21 +1186,18 @@ htcpHandleTstRequest(htcpDataHeader * dhdr, char *buf, int sz, IPAddress &from)
 
     s->setDataHeader (dhdr);
 
-    if (NULL == s)
-    {
+    if (NULL == s) {
         debugs(31, 2, "htcpHandleTstRequest: htcpUnpackSpecifier failed");
         return;
     }
 
-    if (!s->request)
-    {
+    if (!s->request) {
         debugs(31, 2, "htcpHandleTstRequest: failed to parse request");
         htcpFreeSpecifier(s);
         return;
     }
 
-    if (!htcpAccessCheck(Config.accessList.htcp, s, from))
-    {
+    if (!htcpAccessCheck(Config.accessList.htcp, s, from)) {
         debugs(31, 2, "htcpHandleTstRequest: Access denied");
         htcpFreeSpecifier(s);
         return;
@@ -1260,22 +1246,19 @@ htcpHandleClr(htcpDataHeader * hdr, char *buf, int sz, IPAddress &from)
 
     /* buf should be a SPECIFIER */
 
-    if (sz == 0)
-    {
+    if (sz == 0) {
         debugs(31, 4, "htcpHandleClr: nothing to do");
         return;
     }
 
     s = htcpUnpackSpecifier(buf, sz);
 
-    if (NULL == s)
-    {
+    if (NULL == s) {
         debugs(31, 3, "htcpHandleClr: htcpUnpackSpecifier failed");
         return;
     }
 
-    if (!htcpAccessCheck(Config.accessList.htcp_clr, s, from))
-    {
+    if (!htcpAccessCheck(Config.accessList.htcp_clr, s, from)) {
         debugs(31, 2, "htcpHandleClr: Access denied");
         htcpFreeSpecifier(s);
         return;
@@ -1288,8 +1271,7 @@ htcpHandleClr(htcpDataHeader * hdr, char *buf, int sz, IPAddress &from)
      * analog to clientPurgeRequest in client_side.c
      */
 
-    switch (htcpClrStore(s))
-    {
+    switch (htcpClrStore(s)) {
 
     case 1:
         htcpClrReply(hdr, 1, from);	/* hit */
@@ -1314,7 +1296,7 @@ static void
 htcpForwardClr(char *buf, int sz)
 {
     peer *p;
-    
+
     for (p = Config.peers; p; p = p->next) {
         if (!p->options.htcp) {
             continue;
@@ -1322,7 +1304,7 @@ htcpForwardClr(char *buf, int sz)
         if (!p->options.htcp_forward_clr) {
             continue;
         }
-        
+
         htcpSend(buf, sz, p->in_addr);
     }
 }
@@ -1344,8 +1326,7 @@ htcpHandleMsg(char *buf, int sz, IPAddress &from)
     int hsz;
     assert (sz >= 0);
 
-    if ((size_t)sz < sizeof(htcpHeader))
-    {
+    if ((size_t)sz < sizeof(htcpHeader)) {
         debugs(31, 3, "htcpHandle: msg size less than htcpHeader size");
         return;
     }
@@ -1363,16 +1344,14 @@ htcpHandleMsg(char *buf, int sz, IPAddress &from)
     debugs(31, 3, "htcpHandle: htcpHdr.major = " << htcpHdr.major);
     debugs(31, 3, "htcpHandle: htcpHdr.minor = " << htcpHdr.minor);
 
-    if (sz != htcpHdr.length)
-    {
+    if (sz != htcpHdr.length) {
         debugs(31, 3, "htcpHandle: sz/" << sz << " != htcpHdr.length/" <<
                htcpHdr.length << " from " << from );
 
         return;
     }
 
-    if (htcpHdr.major != 0)
-    {
+    if (htcpHdr.major != 0) {
         debugs(31, 3, "htcpHandle: Unknown major version " << htcpHdr.major << " from " << from );
 
         return;
@@ -1381,14 +1360,12 @@ htcpHandleMsg(char *buf, int sz, IPAddress &from)
     hbuf = buf + sizeof(htcpHeader);
     hsz = sz - sizeof(htcpHeader);
 
-    if ((size_t)hsz < sizeof(htcpDataHeader))
-    {
+    if ((size_t)hsz < sizeof(htcpDataHeader)) {
         debugs(31, 3, "htcpHandleData: msg size less than htcpDataHeader size");
         return;
     }
 
-    if (!old_squid_format)
-    {
+    if (!old_squid_format) {
         xmemcpy(&hdr, hbuf, sizeof(hdr));
     } else {
         htcpDataHeaderSquid hdrSquid;
@@ -1579,7 +1556,7 @@ htcpQuery(StoreEntry * e, HttpRequest * req, peer * p)
         debugs(31, 3, "htcpQuery: htcpBuildPacket() failed");
         return;
     }
-    
+
     htcpSend(pkt, (int) pktlen, p->in_addr);
 
     queried_id[stuff.msg_id % N_QUERIED_KEYS] = stuff.msg_id;
@@ -1605,12 +1582,12 @@ htcpClear(StoreEntry * e, const char *uri, HttpRequest * req, const HttpRequestM
     http_state_flags flags;
 
     if (htcpInSocket < 0)
-    	return;
+        return;
 
     old_squid_format = p->options.htcp_oldsquid;
     memset(&flags, '\0', sizeof(flags));
     snprintf(vbuf, sizeof(vbuf), "%d/%d",
-	req->http_ver.major, req->http_ver.minor);
+             req->http_ver.major, req->http_ver.minor);
     stuff.op = HTCP_CLR;
     stuff.rr = RR_REQUEST;
     stuff.f1 = 0;
@@ -1618,20 +1595,20 @@ htcpClear(StoreEntry * e, const char *uri, HttpRequest * req, const HttpRequestM
     stuff.msg_id = ++msg_id_counter;
     switch (reason) {
     case HTCP_CLR_INVALIDATION:
-    	stuff.reason = 1;
-    	break;
+        stuff.reason = 1;
+        break;
     default:
-    	stuff.reason = 0;
-    	break;
+        stuff.reason = 0;
+        break;
     }
     stuff.S.method = (char *) RequestMethodStr(req->method);
     if (e == NULL || e->mem_obj == NULL) {
-    	if (uri == NULL) {
+        if (uri == NULL) {
             return;
-    	}
-    	stuff.S.uri = xstrdup(uri);
+        }
+        stuff.S.uri = xstrdup(uri);
     } else {
-    	stuff.S.uri = (char *) e->url();
+        stuff.S.uri = (char *) e->url();
     }
     stuff.S.version = vbuf;
     if (reason != HTCP_CLR_INVALIDATION) {
@@ -1641,7 +1618,7 @@ htcpClear(StoreEntry * e, const char *uri, HttpRequest * req, const HttpRequestM
         hdr.packInto(&pa);
         hdr.clean();
         packerClean(&pa);
-    	stuff.S.req_hdrs = mb.buf;
+        stuff.S.req_hdrs = mb.buf;
     } else {
         stuff.S.req_hdrs = NULL;
     }
@@ -1650,13 +1627,13 @@ htcpClear(StoreEntry * e, const char *uri, HttpRequest * req, const HttpRequestM
         mb.clean();
     }
     if (e == NULL) {
-    	xfree(stuff.S.uri);
+        xfree(stuff.S.uri);
     }
     if (!pktlen) {
-    	debugs(31, 3, "htcpClear: htcpBuildPacket() failed");
-    	return;
+        debugs(31, 3, "htcpClear: htcpBuildPacket() failed");
+        return;
     }
-    
+
     htcpSend(pkt, (int) pktlen, p->in_addr);
 }
 
diff --git a/src/htcp.h b/src/htcp.h
index c0f02c0f9d..fc65b9f4f5 100644
--- a/src/htcp.h
+++ b/src/htcp.h
@@ -18,12 +18,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -48,8 +48,7 @@ public:
     u_int32_t msg_id;
     double version;
 
-    struct cto_t
-    {
+    struct cto_t {
         /* cache-to-origin */
         double rtt;
         int samp;
diff --git a/src/http.h b/src/http.h
index 7c1ee2daa9..a317d270ab 100644
--- a/src/http.h
+++ b/src/http.h
@@ -19,12 +19,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/src/icmp.cc b/src/icmp.cc
index ab4e77ec13..8d6d30a7c5 100644
--- a/src/icmp.cc
+++ b/src/icmp.cc
@@ -20,12 +20,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -48,7 +48,7 @@ void
 ICMP::Close()
 {
 #if USE_ICMP
-    if(icmp_sock > 0)
+    if (icmp_sock > 0)
         close(icmp_sock);
     icmp_sock = -1;
     icmp_ident = 0;
@@ -64,7 +64,7 @@ ICMP::CheckSum(unsigned short *ptr, int size)
     unsigned short oddbyte;
     unsigned short answer;
 
-    if(!ptr) return 65535; // bad input.
+    if (!ptr) return 65535; // bad input.
 
     sum = 0;
 
diff --git a/src/icp_v2.cc b/src/icp_v2.cc
index 2c5b592cbf..facf268318 100644
--- a/src/icp_v2.cc
+++ b/src/icp_v2.cc
@@ -20,12 +20,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -105,8 +105,8 @@ _icp_common_t::getOpCode() const
 /* ICPState */
 
 ICPState::ICPState(icp_common_t &aHeader, HttpRequest *aRequest):
-	header(aHeader),
-	request(HTTPMSGLOCK(aRequest)),
+        header(aHeader),
+        request(HTTPMSGLOCK(aRequest)),
         fd(-1),
         url(NULL)
 {}
@@ -128,8 +128,7 @@ class ICP2State : public ICPState, public StoreClient
 
 public:
     ICP2State(icp_common_t & aHeader, HttpRequest *aRequest):
-	ICPState(aHeader, aRequest),rtt(0),src_rtt(0),flags(0)
-    {}
+            ICPState(aHeader, aRequest),rtt(0),src_rtt(0),flags(0) {}
 
     ~ICP2State();
     void created(StoreEntry * newEntry);
@@ -284,14 +283,12 @@ icpUdpSend(int fd,
 
     x = comm_udp_sendto(fd, to, msg, len);
 
-    if (x >= 0)
-    {
+    if (x >= 0) {
         /* successfully written */
         icpLogIcp(to, logcode, len, (char *) (msg + 1), delay);
         icpCount(msg, SENT, (size_t) len, delay);
         safe_free(msg);
-    } else if (0 == delay)
-    {
+    } else if (0 == delay) {
         /* send failed, but queue it */
         queue = (icpUdpData *) xcalloc(1, sizeof(icpUdpData));
         queue->address = to;
@@ -313,8 +310,7 @@ icpUdpSend(int fd,
 
         commSetSelect(fd, COMM_SELECT_WRITE, icpUdpSendQueue, NULL, 0);
         statCounter.icp.replies_queued++;
-    } else
-    {
+    } else {
         /* don't queue it */
         statCounter.icp.replies_dropped++;
     }
@@ -394,15 +390,13 @@ icpDenyAccess(IPAddress &from, char *url, int reqnum, int fd)
 {
     debugs(12, 2, "icpDenyAccess: Access Denied for " << from << " by " << AclMatchedName << ".");
 
-    if (clientdbCutoffDenied(from))
-    {
+    if (clientdbCutoffDenied(from)) {
         /*
          * count this DENIED query in the clientdb, even though
          * we're not sending an ICP reply...
          */
         clientdbUpdate(from, LOG_UDP_DENIED, PROTO_ICP, 0);
-    } else
-    {
+    } else {
         icpCreateAndSend(ICP_DENIED, 0, url, reqnum, 0, fd, from);
     }
 }
@@ -432,8 +426,7 @@ icpGetUrlToSend(char *url)
 HttpRequest *
 icpGetRequest(char *url, int reqnum, int fd, IPAddress &from)
 {
-    if (strpbrk(url, w_space))
-    {
+    if (strpbrk(url, w_space)) {
         url = rfc1738_escape(url);
         icpCreateAndSend(ICP_ERR, 0, rfc1738_escape(url), reqnum, 0, fd, from);
         return NULL;
@@ -463,15 +456,13 @@ doV2Query(int fd, IPAddress &from, char *buf, icp_common_t header)
 
     HTTPMSGLOCK(icp_request);
 
-    if (!icpAccessAllowed(from, icp_request))
-    {
+    if (!icpAccessAllowed(from, icp_request)) {
         icpDenyAccess(from, url, header.reqnum, fd);
         HTTPMSGUNLOCK(icp_request);
         return;
     }
 
-    if (header.flags & ICP_FLAG_SRC_RTT)
-    {
+    if (header.flags & ICP_FLAG_SRC_RTT) {
         rtt = netdbHostRtt(icp_request->GetHost());
         int hops = netdbHostHops(icp_request->GetHost());
         src_rtt = ((hops & 0xFFFF) << 16) | (rtt & 0xFFFF);
@@ -503,8 +494,7 @@ doV2Query(int fd, IPAddress &from, char *buf, icp_common_t header)
 void
 _icp_common_t::handleReply(char *buf, IPAddress &from)
 {
-    if (neighbors_do_private_keys && reqnum == 0)
-    {
+    if (neighbors_do_private_keys && reqnum == 0) {
         debugs(12, 0, "icpHandleIcpV2: Neighbor " << from << " returned reqnum = 0");
         debugs(12, 0, "icpHandleIcpV2: Disabling use of private keys");
         neighbors_do_private_keys = 0;
@@ -521,8 +511,7 @@ _icp_common_t::handleReply(char *buf, IPAddress &from)
 static void
 icpHandleIcpV2(int fd, IPAddress &from, char *buf, int len)
 {
-    if (len <= 0)
-    {
+    if (len <= 0) {
         debugs(12, 3, "icpHandleIcpV2: ICP message is too small");
         return;
     }
@@ -532,14 +521,12 @@ icpHandleIcpV2(int fd, IPAddress &from, char *buf, int len)
      * Length field should match the number of bytes read
      */
 
-    if (len != header.length)
-    {
+    if (len != header.length) {
         debugs(12, 3, "icpHandleIcpV2: ICP message is too small");
         return;
     }
 
-    switch (header.opcode)
-    {
+    switch (header.opcode) {
 
     case ICP_QUERY:
         /* We have a valid packet */
@@ -651,8 +638,8 @@ icpHandleUdp(int sock, void *data)
         else if (icp_version == ICP_VERSION_3)
             icpHandleIcpV3(sock, from, buf, len);
         else
-        debugs(12, 1, "WARNING: Unused ICP version " << icp_version <<
-               " received from " << from);
+            debugs(12, 1, "WARNING: Unused ICP version " << icp_version <<
+                   " received from " << from);
     }
 }
 
@@ -740,7 +727,7 @@ icpConnectionsOpen(void)
 }
 
 /**
- * icpConnectionShutdown only closes the 'in' socket if it is 
+ * icpConnectionShutdown only closes the 'in' socket if it is
  * different than the 'out' socket.
  */
 void
diff --git a/src/icp_v3.cc b/src/icp_v3.cc
index a8daceb983..c9759f9c2b 100644
--- a/src/icp_v3.cc
+++ b/src/icp_v3.cc
@@ -20,12 +20,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -48,8 +48,7 @@ class ICP3State : public ICPState, public StoreClient
 
 public:
     ICP3State(icp_common_t &aHeader, HttpRequest *aRequest) :
-	ICPState(aHeader, aRequest)
-	{}
+            ICPState(aHeader, aRequest) {}
 
     ~ICP3State();
     void created (StoreEntry *newEntry);
@@ -66,8 +65,7 @@ doV3Query(int fd, IPAddress &from, char *buf, icp_common_t header)
     if (!icp_request)
         return;
 
-    if (!icpAccessAllowed(from, icp_request))
-    {
+    if (!icpAccessAllowed(from, icp_request)) {
         icpDenyAccess (from, url, header.reqnum, fd);
         delete icp_request;
         return;
@@ -113,8 +111,7 @@ ICP3State::created(StoreEntry *newEntry)
 void
 icpHandleIcpV3(int fd, IPAddress&from, char *buf, int len)
 {
-    if (len <= 0)
-    {
+    if (len <= 0) {
         debugs(12, 3, "icpHandleIcpV3: ICP message is too small");
         return;
     }
@@ -124,14 +121,12 @@ icpHandleIcpV3(int fd, IPAddress&from, char *buf, int len)
      * Length field should match the number of bytes read
      */
 
-    if (len != header.length)
-    {
+    if (len != header.length) {
         debugs(12, 3, "icpHandleIcpV3: ICP message is too small");
         return;
     }
 
-    switch (header.opcode)
-    {
+    switch (header.opcode) {
 
     case ICP_QUERY:
         doV3Query(fd, from, buf, header);
diff --git a/src/ident.cc b/src/ident.cc
index 5e9b6836b9..aa6df07569 100644
--- a/src/ident.cc
+++ b/src/ident.cc
@@ -20,12 +20,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -40,16 +40,14 @@
 #define IDENT_PORT 113
 #define IDENT_KEY_SZ 50
 
-typedef struct _IdentClient
-{
+typedef struct _IdentClient {
     IDCB *callback;
     void *callback_data;
 
     struct _IdentClient *next;
 } IdentClient;
 
-typedef struct _IdentStateData
-{
+typedef struct _IdentStateData {
     hash_link hash;		/* must be first */
     int fd;			/* IDENT fd */
 
@@ -217,8 +215,7 @@ identStart(IPAddress &me, IPAddress &my_peer, IDCB * callback, void *data)
     my_peer.ToURL(key2, IDENT_KEY_SZ);
     snprintf(key, IDENT_KEY_SZ, "%s,%s", key1, key2);
 
-    if ((state = (IdentStateData *)hash_lookup(ident_hash, key)) != NULL)
-    {
+    if ((state = (IdentStateData *)hash_lookup(ident_hash, key)) != NULL) {
         identClientAdd(state, callback, data);
         return;
     }
@@ -229,8 +226,7 @@ identStart(IPAddress &me, IPAddress &my_peer, IDCB * callback, void *data)
                    COMM_NONBLOCKING,
                    "ident");
 
-    if (fd == COMM_ERROR)
-    {
+    if (fd == COMM_ERROR) {
         /* Failed to get a local socket */
         callback(NULL, data);
         return;
diff --git a/src/int.cc b/src/int.cc
index 9cdc2b3e1a..dd051f46aa 100644
--- a/src/int.cc
+++ b/src/int.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/src/internal.cc b/src/internal.cc
index d4a1ddeb0d..a5527564eb 100644
--- a/src/internal.cc
+++ b/src/internal.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -43,7 +43,7 @@
 #include "wordlist.h"
 
 /* called when we "miss" on an internal object;
- * generate known dynamic objects, 
+ * generate known dynamic objects,
  * return HTTP_NOT_FOUND for others
  */
 void
diff --git a/src/ipc.cc b/src/ipc.cc
index a413b05b6a..83c7559465 100644
--- a/src/ipc.cc
+++ b/src/ipc.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -342,7 +342,7 @@ ipcCreate(int type, const char *prog, const char *const args[], const char *name
 
     PutEnvironment();
     /*
-     * This double-dup stuff avoids problems when one of 
+     * This double-dup stuff avoids problems when one of
      *  crfd, cwfd, or debug_log are in the rage 0-2.
      */
 
diff --git a/src/ipc_win32.cc b/src/ipc_win32.cc
index dc813966b5..174669d184 100644
--- a/src/ipc_win32.cc
+++ b/src/ipc_win32.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -43,8 +43,7 @@
 #endif
 #include 
 
-struct ipc_params
-{
+struct ipc_params {
     int type;
     int crfd;
     int cwfd;
@@ -54,8 +53,7 @@ struct ipc_params
     char **args;
 };
 
-struct thread_params
-{
+struct thread_params {
     int type;
     int rfd;
     int send_fd;
@@ -240,7 +238,7 @@ ipcCreate(int type, const char *prog, const char *const args[], const char *name
     params.cwfd = cwfd;
 
     params.PS = *aiPS;
-    
+
     params.local_addr = local_addr;
 
     params.prog = prog;
@@ -364,10 +362,8 @@ static unsigned int __stdcall
 ipc_thread_1(void *in_params)
 {
     int t1, t2, t3, retval = -1;
-    int p2c[2] =
-        {-1, -1};
-    int c2p[2] =
-        {-1, -1};
+    int p2c[2] = {-1, -1};
+    int c2p[2] = {-1, -1};
     HANDLE hProcess = NULL, thread = NULL;
     pid_t pid = -1;
 
@@ -394,7 +390,7 @@ ipc_thread_1(void *in_params)
 
     IPAddress PS = params->PS;
     IPAddress local_addr = params->local_addr;
-    
+
     buf1 = (char *)xcalloc(1, 8192);
     strcpy(buf1, params->prog);
     prog = strtok(buf1, w_space);
@@ -708,7 +704,7 @@ ipc_thread_1(void *in_params)
     if (-1 == ipcSend(cwfd, buf1, strlen(buf1)))
         goto cleanup;
 
-        debugs(54, 2, "ipc(" << prog << "," << pid << "): started successfully");
+    debugs(54, 2, "ipc(" << prog << "," << pid << "): started successfully");
 
     /* cycle */
     for (;;) {
diff --git a/src/ipcache.cc b/src/ipcache.cc
index 74be02a7eb..f95c7f7b69 100644
--- a/src/ipcache.cc
+++ b/src/ipcache.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -91,8 +91,7 @@ typedef struct _ipcache_entry ipcache_entry;
  * where structures of type ipcache_entry whose most
  * interesting members are:
  */
-struct _ipcache_entry
-{
+struct _ipcache_entry {
     hash_link hash;		/* must be first */
     time_t lastref;
     time_t expires;
@@ -108,16 +107,14 @@ struct _ipcache_entry
     unsigned short cname_wait;
 #endif
 
-    struct
-    {
+    struct {
         unsigned int negcached:1;
         unsigned int fromhosts:1;
     } flags;
 };
 
 /// \ingroup IPCacheInternal
-static struct _ipcache_stats
-{
+static struct _ipcache_stats {
     int requests;
     int replies;
     int hits;
@@ -175,12 +172,12 @@ extern int _dns_ttl_;
 static void
 ipcacheRelease(ipcache_entry * i, bool dofree)
 {
-    if(!i) {
+    if (!i) {
         debugs(14, 0, "ipcacheRelease: Releasing entry with i=");
         return;
     }
 
-    if(!i || !i->hash.key) {
+    if (!i || !i->hash.key) {
         debugs(14, 0, "ipcacheRelease: Releasing entry without hash link!");
         return;
     }
@@ -189,7 +186,7 @@ ipcacheRelease(ipcache_entry * i, bool dofree)
 
     hash_remove_link(ip_table, (hash_link *) i);
     dlinkDelete(&i->lru, &lru_list);
-    if(dofree)
+    if (dofree)
         ipcacheFreeEntry(i);
 }
 
@@ -310,12 +307,11 @@ ipcacheAddEntry(ipcache_entry * i)
         /* avoid colission */
         ipcache_entry *q = (ipcache_entry *) e;
 #if DNS_CNAME
-        if(q == i)  {
+        if (q == i)  {
             /* can occur with Multiple-depth CNAME Recursion if parent returned early with additional */
             /* just need to drop from the hash without releasing actual memory */
             ipcacheRelease(q, false);
-        }
-        else
+        } else
 #endif
             ipcacheRelease(q);
     }
@@ -425,7 +421,7 @@ ipcacheParse(ipcache_entry *i, const char *inbuf)
         int j, k;
 
         i->addrs.in_addrs = (IPAddress *)xcalloc(ipcount, sizeof(IPAddress));
-        for(int l = 0; l < ipcount; l++)
+        for (int l = 0; l < ipcount; l++)
             i->addrs.in_addrs[l].SetEmpty(); // perform same init actions as constructor would.
         i->addrs.bad_mask = (unsigned char *)xcalloc(ipcount, sizeof(unsigned char));
         memset(i->addrs.bad_mask, 0, sizeof(unsigned char) * ipcount);
@@ -497,27 +493,27 @@ ipcacheParse(ipcache_entry *i, rfc1035_rr * answers, int nr, const char *error_m
 
 #if USE_IPV6
         if (answers[k].type == RFC1035_TYPE_AAAA) {
-	    if (answers[k].rdlength != sizeof(struct in6_addr)) {
-		debugs(14, 1, "ipcacheParse: Invalid IPv6 address in response to '" << name << "'");
-		continue;
-	    }
-	    na++;
+            if (answers[k].rdlength != sizeof(struct in6_addr)) {
+                debugs(14, 1, "ipcacheParse: Invalid IPv6 address in response to '" << name << "'");
+                continue;
+            }
+            na++;
             IpcacheStats.rr_aaaa++;
-	    continue;
-	}
+            continue;
+        }
 #endif
 
         if (answers[k].type == RFC1035_TYPE_A) {
-	    if (answers[k].rdlength != sizeof(struct in_addr)) {
-		debugs(14, 1, "ipcacheParse: Invalid IPv4 address in response to '" << name << "'");
-		continue;
-	    }
-	    na++;
+            if (answers[k].rdlength != sizeof(struct in_addr)) {
+                debugs(14, 1, "ipcacheParse: Invalid IPv4 address in response to '" << name << "'");
+                continue;
+            }
+            na++;
             IpcacheStats.rr_a++;
-	    continue;
-	}
+            continue;
+        }
 
-            /* With A and AAAA, the CNAME does not necessarily come with additional records to use. */
+        /* With A and AAAA, the CNAME does not necessarily come with additional records to use. */
         if (answers[k].type == RFC1035_TYPE_CNAME) {
             cname_found=1;
             IpcacheStats.rr_cname++;
@@ -525,11 +521,10 @@ ipcacheParse(ipcache_entry *i, rfc1035_rr * answers, int nr, const char *error_m
 #if DNS_CNAME
             debugs(14, 5, "ipcacheParse: " << name << " CNAME " << answers[k].rdata << " (checking destination: " << i << ").");
             const ipcache_addrs *res = ipcache_gethostbyname(answers[k].rdata, 0);
-            if(res) {
+            if (res) {
                 na += res->count;
                 debugs(14, 5, "ipcacheParse: CNAME " << answers[k].rdata << " already has " << res->count << " IPs cached.");
-            }
-            else {
+            } else {
                 /* keep going on this, but flag the fact that we need to wait for a CNAME lookup to finish */
                 debugs(14, 5, "ipcacheParse: CNAME " << answers[k].rdata << " has no IPs! Recursing.");
                 ipcache_nbgethostbyname(answers[k].rdata, ipcacheHandleCnameRecurse, new generic_cbdata(i) );
@@ -545,7 +540,7 @@ ipcacheParse(ipcache_entry *i, rfc1035_rr * answers, int nr, const char *error_m
     }
 
 #if DNS_CNAME
-    if(na == 0 && i->cname_wait >0 ) {
+    if (na == 0 && i->cname_wait >0 ) {
         /* don't set any error message (yet). Allow recursion to do its work first. */
         IpcacheStats.cname_only++;
         return 0;
@@ -555,13 +550,13 @@ ipcacheParse(ipcache_entry *i, rfc1035_rr * answers, int nr, const char *error_m
     if (na == 0) {
         debugs(14, 1, "ipcacheParse: No Address records in response to '" << name << "'");
         i->error_message = xstrdup("No Address records");
-        if(cname_found)
+        if (cname_found)
             IpcacheStats.cname_only++;
         return 0;
     }
 
     i->addrs.in_addrs = (IPAddress *)xcalloc(na, sizeof(IPAddress));
-    for(int l = 0; l < na; l++)
+    for (int l = 0; l < na; l++)
         i->addrs.in_addrs[l].SetEmpty(); // perform same init actions as constructor would.
     i->addrs.bad_mask = (unsigned char *)xcalloc(na, sizeof(unsigned char));
 
@@ -595,15 +590,14 @@ ipcacheParse(ipcache_entry *i, rfc1035_rr * answers, int nr, const char *error_m
         else if (answers[k].type == RFC1035_TYPE_CNAME) {
             debugs(14, 3, "ipcacheParse: " << name << " #x CNAME " << answers[k].rdata);
             const ipcache_addrs *res = ipcache_gethostbyname(answers[k].rdata, 0);
-            if(res) {
+            if (res) {
                 /* NP: the results of *that* query need to be integrated in place of the CNAME */
                 /* Ideally we should also integrate the min TTL of the above IPA's into ttl.   */
-                for(int l = 0; l < res->count; l++, j++) {
+                for (int l = 0; l < res->count; l++, j++) {
                     i->addrs.in_addrs[j] = res->in_addrs[l];
                     debugs(14, 3, "ipcacheParse: " << name << " #" << j << " " << i->addrs.in_addrs[j] );
                 }
-            }
-            else {
+            } else {
                 debugs(14, 9, "ipcacheParse: " << answers[k].rdata << " (CNAME) waiting on A/AAAA records.");
             }
         }
@@ -634,7 +628,7 @@ ipcacheParse(ipcache_entry *i, rfc1035_rr * answers, int nr, const char *error_m
     /* SPECIAL CASE: may get here IFF CNAME received with Additional records */
     /*               reurn  0/'wait for further details' value.              */
     /*               NP: 'No DNS Results' is a return -1 +msg                */
-    if(i->cname_wait)
+    if (i->cname_wait)
         return 0;
     else
 #endif /* DNS_CNAME */
@@ -665,7 +659,7 @@ ipcacheHandleReply(void *data, rfc1035_rr * answers, int na, const char *error_m
     done = ipcacheParse(i, answers, na, error_message);
 
     /* If we have not produced either IPs or Error immediately, wait for recursion to finish. */
-    if(done != 0 || error_message != NULL)
+    if (done != 0 || error_message != NULL)
 #endif
 
     {
@@ -685,9 +679,9 @@ ipcacheHandleReply(void *data, rfc1035_rr * answers, int na, const char *error_m
  * XXX: on hits and some errors, the handler is called immediately instead
  * of scheduling an async call. This reentrant behavior means that the
  * user job must be extra careful after calling ipcache_nbgethostbyname,
- * especially if the handler destroys the job. Moreover, the job has 
+ * especially if the handler destroys the job. Moreover, the job has
  * no way of knowing whether the reentrant call happened. commConnectStart
- * protects the job by scheduling an async call, but some user code calls 
+ * protects the job by scheduling an async call, but some user code calls
  * ipcache_nbgethostbyname directly.
  */
 void
@@ -764,9 +758,9 @@ static void
 ipcacheRegisterWithCacheManager(void)
 {
     CacheManager::GetInstance()->
-        registerAction("ipcache",
-                       "IP Cache Stats and Contents",
-                       stat_ipcache_get, 0, 1);
+    registerAction("ipcache",
+                   "IP Cache Stats and Contents",
+                   stat_ipcache_get, 0, 1);
 }
 
 
@@ -864,11 +858,11 @@ ipcacheStatPrint(ipcache_entry * i, StoreEntry * sentry)
     int count = i->addrs.count;
     char buf[MAX_IPSTRLEN];
 
-    if(!sentry) {
+    if (!sentry) {
         debugs(14, 0, HERE << "CRITICAL: sentry is NULL!");
     }
 
-    if(!i) {
+    if (!i) {
         debugs(14, 0, HERE << "CRITICAL: ipcache_entry is NULL!");
         storeAppendPrintf(sentry, "CRITICAL ERROR\n");
         return;
@@ -885,7 +879,7 @@ ipcacheStatPrint(ipcache_entry * i, StoreEntry * sentry)
 
     /** \par
      * Negative-cached entries have no IPs listed. */
-    if(i->flags.negcached) {
+    if (i->flags.negcached) {
         storeAppendPrintf(sentry, "\n");
         return;
     }
@@ -894,7 +888,7 @@ ipcacheStatPrint(ipcache_entry * i, StoreEntry * sentry)
      * Cached entries have IPs listed with a BNF of:    '-' ('OK'|'BAD') */
     for (k = 0; k < count; k++) {
         /* Display tidy-up: IPv6 are so big make the list vertical */
-        if(k == 0)
+        if (k == 0)
             storeAppendPrintf(sentry, " %45.45s-%3s\n",
                               i->addrs.in_addrs[k].NtoA(buf,MAX_IPSTRLEN),
                               i->addrs.bad_mask[k] ? "BAD" : "OK ");
@@ -986,25 +980,25 @@ ipcacheMergeIPLists(const IPAddress *aaddrs, const int alen,
 #endif
 
     // for each unique address in list A - grab ptr
-    for(t = 0; t < alen; t++) {
-        if(aaddrs[t].IsIPv4()) {
+    for (t = 0; t < alen; t++) {
+        if (aaddrs[t].IsIPv4()) {
             // check against IPv4 pruned list
-            for(c = 0; c <= num_ip4; c++) {
-                if(ip4ptrs[c] && aaddrs[t] == *(ip4ptrs[c]) ) break; // duplicate.
+            for (c = 0; c <= num_ip4; c++) {
+                if (ip4ptrs[c] && aaddrs[t] == *(ip4ptrs[c]) ) break; // duplicate.
             }
-            if(c > num_ip4) {
+            if (c > num_ip4) {
                 ip4ptrs[num_ip4] = &aaddrs[t];
                 num_ip4++;
             }
         }
 #if USE_IPV6
-        else if(aaddrs[t].IsIPv6()) {
-debugs(14,8, HERE << "A[" << t << "]=IPv6 " << aaddrs[t]);
+        else if (aaddrs[t].IsIPv6()) {
+            debugs(14,8, HERE << "A[" << t << "]=IPv6 " << aaddrs[t]);
             // check against IPv6 pruned list
-            for(c = 0; c <= num_ip6; c++) {
-                if(ip6ptrs[c] && aaddrs[t] == *ip6ptrs[c]) break; // duplicate.
+            for (c = 0; c <= num_ip6; c++) {
+                if (ip6ptrs[c] && aaddrs[t] == *ip6ptrs[c]) break; // duplicate.
             }
-            if(c > num_ip6) {
+            if (c > num_ip6) {
                 ip6ptrs[num_ip6] = &aaddrs[t];
                 num_ip6++;
             }
@@ -1013,24 +1007,24 @@ debugs(14,8, HERE << "A[" << t << "]=IPv6 " << aaddrs[t]);
     }
 
     // for each unique address in list B - grab ptr
-    for(t = 0; t < blen; t++) {
-        if(baddrs[t].IsIPv4()) {
+    for (t = 0; t < blen; t++) {
+        if (baddrs[t].IsIPv4()) {
             // check against IPv4 pruned list
-            for(c = 0; c <= num_ip4; c++) {
-                if(ip4ptrs[c] && baddrs[t] == *ip4ptrs[c]) break; // duplicate.
+            for (c = 0; c <= num_ip4; c++) {
+                if (ip4ptrs[c] && baddrs[t] == *ip4ptrs[c]) break; // duplicate.
             }
-            if(c > num_ip4) {
+            if (c > num_ip4) {
                 ip4ptrs[num_ip4] = &baddrs[t];
                 num_ip4++;
             }
         }
 #if USE_IPV6
-        else if(baddrs[t].IsIPv6()) {
+        else if (baddrs[t].IsIPv6()) {
             // check against IPv6 pruned list
-            for(c = 0; c <= num_ip6; c++) {
-                if(ip6ptrs[c] && baddrs[t] == *ip6ptrs[c]) break; // duplicate.
+            for (c = 0; c <= num_ip6; c++) {
+                if (ip6ptrs[c] && baddrs[t] == *ip6ptrs[c]) break; // duplicate.
             }
-            if(c > num_ip6) {
+            if (c > num_ip6) {
                 ip6ptrs[num_ip6] = &baddrs[t];
                 num_ip6++;
             }
@@ -1053,13 +1047,13 @@ debugs(14,8, HERE << "A[" << t << "]=IPv6 " << aaddrs[t]);
 #if USE_IPV6
     /* IPv6 are preferred (tried first) over IPv4 */
 
-    for(int l = 0; outlen < num_ip6; l++, outlen++) {
+    for (int l = 0; outlen < num_ip6; l++, outlen++) {
         (*out)[outlen] = *ip6ptrs[l];
         debugs(14, 5, "ipcacheMergeIPLists:  #" << outlen << " " << (*out)[outlen] );
     }
 #endif /* USE_IPV6 */
 
-    for(int l = 0; outlen < num_ip4; l++, outlen++) {
+    for (int l = 0; outlen < num_ip4; l++, outlen++) {
         (*out)[outlen] = *ip4ptrs[l];
         debugs(14, 5, "ipcacheMergeIPLists:  #" << outlen << " " << (*out)[outlen] );
     }
@@ -1086,7 +1080,7 @@ ipcacheHandleCnameRecurse(const ipcache_addrs *addrs, void *cbdata)
     debugs(14, 5, "ipcacheHandleCnameRecurse: Handling basic A/AAAA response.");
 
     /* IFF no CNAME recursion being processed. do nothing. */
-    if(cbdata == NULL)
+    if (cbdata == NULL)
         return;
 
     gcb->unwrap(&i);
@@ -1102,13 +1096,13 @@ ipcacheHandleCnameRecurse(const ipcache_addrs *addrs, void *cbdata)
 
     debugs(14, 5, "ipcacheHandleCnameRecurse: Handling CNAME recursion. CBDATA('" << gcb->data << "')='" << pname << "' -> " << std::hex << i);
 
-    if(i == NULL) {
+    if (i == NULL) {
         return; // Parent has expired. Don't merge, just leave for future Ref:
     }
 
     /* IFF addrs is NULL (Usually an Error or Timeout occured on lookup.) */
     /* Ignore it and HOPE that we got some Additional records to use.     */
-    if(addrs == NULL)
+    if (addrs == NULL)
         return;
 
     ccount = (0+ addrs->count);
@@ -1116,11 +1110,11 @@ ipcacheHandleCnameRecurse(const ipcache_addrs *addrs, void *cbdata)
     ttl = i->expires;
 
     /* IFF no CNAME results. do none of the processing BUT finish anyway. */
-    if(addrs) {
+    if (addrs) {
 
         debugs(14, 5, "ipcacheHandleCnameRecurse: Merge IP Lists for " << pname << " (" << pcount << "+" << ccount << ")");
 
-            /* add new IP records to entry */
+        /* add new IP records to entry */
         tmpbuf = i->addrs.in_addrs;
         i->addrs.in_addrs = NULL;
         ipcacheMergeIPLists(tmpbuf, pcount, addrs->in_addrs, ccount, &(i->addrs.in_addrs), fc);
@@ -1128,13 +1122,13 @@ ipcacheHandleCnameRecurse(const ipcache_addrs *addrs, void *cbdata)
         assert( (pcount>0 ? tmpbuf!=NULL : tmpbuf==NULL) );
         safe_free(tmpbuf);
 
-        if( pcount > 0) {
+        if ( pcount > 0) {
             /* IFF the parent initial lookup was given Additional records with A */
             // clear the 'bad IP mask'
             safe_free(i->addrs.bad_mask);
         }
         // create a new bad IP mask to fit the new size needed.
-        if(fc > 0) {
+        if (fc > 0) {
             i->addrs.bad_mask = (unsigned char*)xcalloc(fc, sizeof(unsigned char));
             memset(i->addrs.bad_mask, 0, sizeof(unsigned char)*fc);
         }
@@ -1159,12 +1153,12 @@ ipcacheHandleCnameRecurse(const ipcache_addrs *addrs, void *cbdata)
         i->addrs.badcount = 0;
     }
 
-    if(fc == 0) {
+    if (fc == 0) {
         i->error_message = xstrdup("No DNS Records");
     }
 
     /* finish the lookup we were doing on parent when we got side-tracked for CNAME loop */
-    if(i->cname_wait == 0) {
+    if (i->cname_wait == 0) {
         ipcacheAddEntry(i);
         ipcacheCallback(i);
     }
@@ -1216,7 +1210,7 @@ ipcacheCheckNumeric(const char *name)
     /* check if it's already a IP address in text form. */
 
     /* it may be IPv6-wrapped */
-    if(name[0] == '[') {
+    if (name[0] == '[') {
         char *tmp = xstrdup(&name[1]);
         tmp[strlen(tmp)-1] = '\0';
         if (!(ip = tmp)) {
@@ -1224,8 +1218,7 @@ ipcacheCheckNumeric(const char *name)
             return NULL;
         }
         delete tmp;
-    }
-    else if (!(ip = name))
+    } else if (!(ip = name))
         return NULL;
 
     debugs(14, 4, "ipcacheCheckNumeric: HIT_BYPASS for '" << name << "' == " << ip );
@@ -1257,7 +1250,7 @@ ipcacheLockEntry(ipcache_entry * i)
 static void
 ipcacheUnlockEntry(ipcache_entry * i)
 {
-    if(i->locks < 1) {
+    if (i->locks < 1) {
         debugs(14, 1, "WARNING: ipcacheEntry unlocked with no lock! locks=" << i->locks);
         return;
     }
@@ -1328,8 +1321,7 @@ ipcacheMarkBadAddr(const char *name, IPAddress &addr)
 
     ia = &i->addrs;
 
-    for (k = 0; k < (int) ia->count; k++)
-    {
+    for (k = 0; k < (int) ia->count; k++) {
         if (addr == ia->in_addrs[k] )
             break;
     }
@@ -1339,8 +1331,7 @@ ipcacheMarkBadAddr(const char *name, IPAddress &addr)
         return;
 
     /** Marks the given address as BAD */
-    if (!ia->bad_mask[k])
-    {
+    if (!ia->bad_mask[k]) {
         ia->bad_mask[k] = TRUE;
         ia->badcount++;
         i->expires = XMIN(squid_curtime + XMAX((time_t)60, Config.negativeDnsTtl), i->expires);
@@ -1364,8 +1355,7 @@ ipcacheMarkGoodAddr(const char *name, IPAddress &addr)
 
     ia = &i->addrs;
 
-    for (k = 0; k < (int) ia->count; k++)
-    {
+    for (k = 0; k < (int) ia->count; k++) {
         if (addr == ia->in_addrs[k])
             break;
     }
@@ -1447,7 +1437,7 @@ ipcacheAddEntryFromHosts(const char *name, const char *ipaddr)
             debugs(14, 1, "ipcacheAddEntryFromHosts: Bad IP address '" << ipaddr << "'");
         }
 #else
-	debugs(14, 1, "ipcacheAddEntryFromHosts: Bad IP address '" << ipaddr << "'");
+        debugs(14, 1, "ipcacheAddEntryFromHosts: Bad IP address '" << ipaddr << "'");
 #endif
 
         return 1;
diff --git a/src/list.cc b/src/list.cc
index c2683a1b6d..ebfb59c6ba 100644
--- a/src/list.cc
+++ b/src/list.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/src/logfile.cc b/src/logfile.cc
index 7762c56ef0..d61b940a08 100644
--- a/src/logfile.cc
+++ b/src/logfile.cc
@@ -20,12 +20,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -45,8 +45,7 @@ static void logfileWriteWrapper(Logfile * lf, const void *buf, size_t len);
 #define LOG_AUTHPRIV LOG_AUTH
 #endif
 
-struct syslog_symbol_t
-{
+struct syslog_symbol_t {
     const char* name;
     int value;
 };
@@ -55,24 +54,24 @@ static int syslog_ntoa (const char* s)
 {
 #define syslog_symbol(a) #a, a
     static syslog_symbol_t _symbols[] = {
-                                            { syslog_symbol(LOG_AUTHPRIV) },
-                                            { syslog_symbol(LOG_DAEMON) },
-                                            { syslog_symbol(LOG_LOCAL0) },
-                                            { syslog_symbol(LOG_LOCAL1) },
-                                            { syslog_symbol(LOG_LOCAL2) },
-                                            { syslog_symbol(LOG_LOCAL3) },
-                                            { syslog_symbol(LOG_LOCAL4) },
-                                            { syslog_symbol(LOG_LOCAL5) },
-                                            { syslog_symbol(LOG_LOCAL6) },
-                                            { syslog_symbol(LOG_LOCAL7) },
-                                            { syslog_symbol(LOG_USER) },
-                                            { syslog_symbol(LOG_ERR) },
-                                            { syslog_symbol(LOG_WARNING) },
-                                            { syslog_symbol(LOG_NOTICE) },
-                                            { syslog_symbol(LOG_INFO) },
-                                            { syslog_symbol(LOG_DEBUG) },
-                                            { NULL, 0 }
-                                        };
+        { syslog_symbol(LOG_AUTHPRIV) },
+        { syslog_symbol(LOG_DAEMON) },
+        { syslog_symbol(LOG_LOCAL0) },
+        { syslog_symbol(LOG_LOCAL1) },
+        { syslog_symbol(LOG_LOCAL2) },
+        { syslog_symbol(LOG_LOCAL3) },
+        { syslog_symbol(LOG_LOCAL4) },
+        { syslog_symbol(LOG_LOCAL5) },
+        { syslog_symbol(LOG_LOCAL6) },
+        { syslog_symbol(LOG_LOCAL7) },
+        { syslog_symbol(LOG_USER) },
+        { syslog_symbol(LOG_ERR) },
+        { syslog_symbol(LOG_WARNING) },
+        { syslog_symbol(LOG_NOTICE) },
+        { syslog_symbol(LOG_INFO) },
+        { syslog_symbol(LOG_DEBUG) },
+        { NULL, 0 }
+    };
 
     for (syslog_symbol_t* p = _symbols; p->name != NULL; ++p)
         if (!strcmp(s, p->name) || !strcasecmp(s, p->name+4))
@@ -104,8 +103,8 @@ logfileOpen(const char *path, size_t bufsz, int fatal_flag)
             path += 7;
             char* delim = strchr(path, '.');
 
-	    if (!delim)
-		delim = strchr(path, '|');
+            if (!delim)
+                delim = strchr(path, '|');
 
             if (delim != NULL)
                 *delim = '\0';
diff --git a/src/main.cc b/src/main.cc
index 47b6e3fb26..4adf37e170 100644
--- a/src/main.cc
+++ b/src/main.cc
@@ -20,12 +20,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -147,8 +147,7 @@ class StoreRootEngine : public AsyncEngine
 {
 
 public:
-    int checkEvents(int timeout)
-    {
+    int checkEvents(int timeout) {
         Store::Root().callback();
         return EVENT_IDLE;
     };
@@ -162,8 +161,7 @@ public:
     virtual int checkEvents(int timeout);
 
 private:
-    static void StopEventLoop(void * data)
-    {
+    static void StopEventLoop(void * data) {
         static_cast(data)->loop.stop();
     }
 
@@ -186,7 +184,7 @@ SignalEngine::checkEvents(int timeout)
     } else if (do_shutdown) {
         doShutdown(do_shutdown > 0 ? (int) Config.shutdownLifetime : 0);
         do_shutdown = 0;
-	}
+    }
 
     PROF_stop(SignalEngine_checkEvents);
     return EVENT_IDLE;
@@ -274,8 +272,7 @@ mainParseOptions(int argc, char *argv[])
 #endif
     {
 
-        switch (c)
-        {
+        switch (c) {
 
         case 'C':
             /** \par C
@@ -698,11 +695,12 @@ mainReconfigureStart(void)
     refererCloseLog();
 
     eventAdd("mainReconfigureFinish", &mainReconfigureFinish, NULL, 0, 1,
-        false);
+             false);
 }
 
 static void
-mainReconfigureFinish(void *) {
+mainReconfigureFinish(void *)
+{
     debugs(1, 3, "finishing reconfiguring");
 
     errorClean();
@@ -901,7 +899,7 @@ mainInitialize(void)
         debugs(1, 1, "Windows sockets initialized");
 
     if (WIN32_OS_version > _WIN_OS_WINNT) {
-	WIN32_IpAddrChangeMonitorInit();
+        WIN32_IpAddrChangeMonitorInit();
     }
 
 #endif
@@ -987,9 +985,9 @@ mainInitialize(void)
 
         eventInit();
 
-	// TODO: pconn is a good candidate for new-style registration
+        // TODO: pconn is a good candidate for new-style registration
         // PconnModule::GetInstance()->registerWithCacheManager();
-	//   moved to PconnModule::PconnModule()
+        //   moved to PconnModule::PconnModule()
     }
 
 #if USE_WCCP
@@ -1110,16 +1108,14 @@ SquidMainSafe(int argc, char **argv)
 {
     try {
         return SquidMain(argc, argv);
-	}
-    catch (const std::exception &e) {
+    } catch (const std::exception &e) {
         std::cerr << "dying from an unhandled exception: " << e.what() << std::endl;
-		throw;
-	}
-    catch (...) {
+        throw;
+    } catch (...) {
         std::cerr << "dying from an unhandled exception." << std::endl;
-		throw;
-	}
-	return -1; // not reached
+        throw;
+    }
+    return -1; // not reached
 }
 
 static int
@@ -1188,25 +1184,22 @@ SquidMain(int argc, char **argv)
     mainParseOptions(argc, argv);
 
     if (opt_parse_cfg_only) {
-	Debug::parseOptions("ALL,1");
+        Debug::parseOptions("ALL,1");
     }
 
 #if USE_WIN32_SERVICE
 
-    if (opt_install_service)
-    {
+    if (opt_install_service) {
         WIN32_InstallService();
         return 0;
     }
 
-    if (opt_remove_service)
-    {
+    if (opt_remove_service) {
         WIN32_RemoveService();
         return 0;
     }
 
-    if (opt_command_line)
-    {
+    if (opt_command_line) {
         WIN32_SetServiceCommandLine();
         return 0;
     }
@@ -1239,7 +1232,7 @@ SquidMain(int argc, char **argv)
         parse_err = parseConfigFile(ConfigFile);
 
         Mem::Report();
-        
+
         if (opt_parse_cfg_only)
 
             return parse_err;
@@ -1264,8 +1257,7 @@ SquidMain(int argc, char **argv)
 #endif
 
     /* send signal to running copy and exit */
-    if (opt_send_signal != -1)
-    {
+    if (opt_send_signal != -1) {
         /* chroot if configured to run inside chroot */
 
         if (Config.chroot_dir) {
@@ -1281,8 +1273,7 @@ SquidMain(int argc, char **argv)
         /* NOTREACHED */
     }
 
-    if (opt_create_swap_dirs)
-    {
+    if (opt_create_swap_dirs) {
         /* chroot if configured to run inside chroot */
 
         if (Config.chroot_dir && chroot(Config.chroot_dir)) {
@@ -1306,8 +1297,7 @@ SquidMain(int argc, char **argv)
 
     comm_select_init();
 
-    if (opt_no_daemon)
-    {
+    if (opt_no_daemon) {
         /* we have to init fdstat here. */
         fd_open(0, FD_LOG, "stdin");
         fd_open(1, FD_LOG, "stdout");
@@ -1614,7 +1604,7 @@ watch_child(char *argv[])
 
             case SIGINT:
             case SIGTERM:
-		syslog(LOG_ALERT, "Exiting due to unexpected forced shutdown");
+                syslog(LOG_ALERT, "Exiting due to unexpected forced shutdown");
                 exit(1);
                 break;
 
@@ -1639,7 +1629,7 @@ SquidShutdown()
      * means that no AsyncCalls would be called, including close handlers.
      * TODO: We need to close/shut/free everything that needs calls before
      * exiting the loop.
-     */ 
+     */
 
 #if USE_WIN32_SERVICE
     WIN32_svcstatusupdate(SERVICE_STOP_PENDING, 10000);
diff --git a/src/mem.cc b/src/mem.cc
index 21b748d279..8a9d8c95ce 100644
--- a/src/mem.cc
+++ b/src/mem.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -60,27 +60,25 @@ static double xm_deltat = 0;
 /* string pools */
 #define mem_str_pool_count 3
 
-static const struct
-{
+static const struct {
     const char *name;
     size_t obj_size;
 }
 
 StrPoolsAttrs[mem_str_pool_count] = {
 
-                                        {
-                                            "Short Strings", MemAllocator::RoundedSize(36),
-                                        },				/* to fit rfc1123 and similar */
-                                        {
-                                            "Medium Strings", MemAllocator::RoundedSize(128),
-                                        },				/* to fit most urls */
-                                        {
-                                            "Long Strings", MemAllocator::RoundedSize(512)
-                                        }				/* other */
-                                    };
-
-static struct
-{
+    {
+        "Short Strings", MemAllocator::RoundedSize(36),
+    },				/* to fit rfc1123 and similar */
+    {
+        "Medium Strings", MemAllocator::RoundedSize(128),
+    },				/* to fit most urls */
+    {
+        "Long Strings", MemAllocator::RoundedSize(512)
+    }				/* other */
+};
+
+static struct {
     MemAllocator *pool;
 }
 
@@ -140,17 +138,17 @@ Mem::Stats(StoreEntry * sentry)
     memBufStats(stream);
 #if WITH_VALGRIND
     if (RUNNING_ON_VALGRIND) {
-	long int leaked = 0, dubious = 0, reachable = 0, suppressed = 0;
-	stream << "Valgrind Report:\n";
-	stream << "Type\tAmount\n";
-       debugs(13, 1, "Asking valgrind for memleaks");
-	VALGRIND_DO_LEAK_CHECK;
-       debugs(13, 1, "Getting valgrind statistics");
-	VALGRIND_COUNT_LEAKS(leaked, dubious, reachable, suppressed);
-	stream << "Leaked\t" << leaked << "\n";
-	stream << "Dubious\t" << dubious << "\n";
-	stream << "Reachable\t" << reachable << "\n";
-	stream << "Suppressed\t" << suppressed << "\n";
+        long int leaked = 0, dubious = 0, reachable = 0, suppressed = 0;
+        stream << "Valgrind Report:\n";
+        stream << "Type\tAmount\n";
+        debugs(13, 1, "Asking valgrind for memleaks");
+        VALGRIND_DO_LEAK_CHECK;
+        debugs(13, 1, "Getting valgrind statistics");
+        VALGRIND_COUNT_LEAKS(leaked, dubious, reachable, suppressed);
+        stream << "Leaked\t" << leaked << "\n";
+        stream << "Dubious\t" << dubious << "\n";
+        stream << "Reachable\t" << reachable << "\n";
+        stream << "Suppressed\t" << suppressed << "\n";
     }
 #endif
     stream.flush();
@@ -436,16 +434,16 @@ void
 Mem::Report()
 {
     debugs(13, 3, "Memory pools are '" <<
-        (Config.onoff.mem_pools ? "on" : "off")  << "'; limit: " <<
-        std::setprecision(3) << toMB(MemPools::GetInstance().idleLimit()) <<
-        " MB");
+           (Config.onoff.mem_pools ? "on" : "off")  << "'; limit: " <<
+           std::setprecision(3) << toMB(MemPools::GetInstance().idleLimit()) <<
+           " MB");
 }
 
 void
 Mem::RegisterWithCacheManager(void)
 {
     CacheManager::GetInstance()->registerAction("mem", "Memory Utilization",
-                           Mem::Stats, 0, 1);
+            Mem::Stats, 0, 1);
 }
 
 mem_type &operator++ (mem_type &aMem)
diff --git a/src/mem_node.cc b/src/mem_node.cc
index ce75d99457..179588e058 100644
--- a/src/mem_node.cc
+++ b/src/mem_node.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/src/mem_node.h b/src/mem_node.h
index d596f3573b..e7d27036c0 100644
--- a/src/mem_node.h
+++ b/src/mem_node.h
@@ -19,12 +19,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/src/mime.cc b/src/mime.cc
index 892cae5e12..69b7fdbbfb 100644
--- a/src/mime.cc
+++ b/src/mime.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/src/multicast.cc b/src/multicast.cc
index effe4137bd..8c665e093b 100644
--- a/src/multicast.cc
+++ b/src/multicast.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -69,7 +69,7 @@ mcastJoinGroups(const ipcache_addrs * ia, void *datanotused)
         debugs(7, 10, "Listening for ICP requests on " << ia->in_addrs[i] );
 
 #if USE_IPV6
-        if( ! ia->in_addrs[i].IsIPv4() ) {
+        if ( ! ia->in_addrs[i].IsIPv4() ) {
             debugs(7, 10, "ERROR: IPv6 Multicast Listen has not been implemented!");
             continue;
         }
diff --git a/src/neighbors.cc b/src/neighbors.cc
index cb8bd183ad..537b65d6e1 100644
--- a/src/neighbors.cc
+++ b/src/neighbors.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -103,8 +103,7 @@ whichPeer(const IPAddress &from)
     peer *p = NULL;
     debugs(15, 3, "whichPeer: from " << from);
 
-    for (p = Config.peers; p; p = p->next)
-    {
+    for (p = Config.peers; p; p = p->next) {
         for (j = 0; j < p->n_addresses; j++) {
             if (from == p->addresses[j] && from.GetPort() == p->icp.port) {
                 return p;
@@ -394,7 +393,7 @@ getWeightedRoundRobinParent(HttpRequest * request)
  \param data	unused.
  \todo Make the reset timing a selectable parameter in squid.conf
  */
-static void 
+static void
 peerClearRRLoop(void *data)
 {
     peerClearRR();
@@ -474,7 +473,7 @@ getDefaultParent(HttpRequest * request)
 /*
  * XXX DW thinks this function is equivalent to/redundant with
  * getFirstUpParent().  peerHTTPOkay() only returns true if the
- * peer is UP anyway, so this function would not return a 
+ * peer is UP anyway, so this function would not return a
  * DOWN parent.
  */
 peer *
@@ -541,13 +540,13 @@ neighborsRegisterWithCacheManager()
 {
     CacheManager *manager = CacheManager::GetInstance();
     manager->registerAction("server_list",
-                           "Peer Cache Statistics",
-                           neighborDumpPeers, 0, 1);
+                            "Peer Cache Statistics",
+                            neighborDumpPeers, 0, 1);
 
     if (theInIcpConnection >= 0) {
         manager->registerAction("non_peers",
-                               "List of Unknown sites sending ICP messages",
-                               neighborDumpNonPeers, 0, 1);
+                                "List of Unknown sites sending ICP messages",
+                                neighborDumpNonPeers, 0, 1);
     }
 }
 
@@ -894,9 +893,9 @@ peerNoteDigestLookup(HttpRequest * request, peer * p, lookup_t lookup)
 
     request->hier.cd_lookup = lookup;
 
-    debugs(15, 4, "peerNoteDigestLookup: peer " << 
-                  (p ? p->host : "") << ", lookup: " << 
-                  lookup_t_str[lookup]  );
+    debugs(15, 4, "peerNoteDigestLookup: peer " <<
+           (p ? p->host : "") << ", lookup: " <<
+           lookup_t_str[lookup]  );
 
 #endif
 }
@@ -968,8 +967,7 @@ neighborIgnoreNonPeer(const IPAddress &from, icp_opcode opcode)
 {
     peer *np;
 
-    for (np = non_peers; np; np = np->next)
-    {
+    for (np = non_peers; np; np = np->next) {
         if (np->in_addr != from)
             continue;
 
@@ -979,8 +977,7 @@ neighborIgnoreNonPeer(const IPAddress &from, icp_opcode opcode)
         break;
     }
 
-    if (np == NULL)
-    {
+    if (np == NULL) {
         np = (peer *)xcalloc(1, sizeof(peer));
         np->in_addr = from;
         np->icp.port = from.GetPort();
@@ -998,7 +995,7 @@ neighborIgnoreNonPeer(const IPAddress &from, icp_opcode opcode)
 }
 
 /* ignoreMulticastReply
- * 
+ *
  * * We want to ignore replies from multicast peers if the
  * * cache_host_domain rules would normally prevent the peer
  * * from being used
@@ -1021,7 +1018,7 @@ ignoreMulticastReply(peer * p, MemObject * mem)
 /* I should attach these records to the entry.  We take the first
  * hit we get our wait until everyone misses.  The timeout handler
  * call needs to nip this shopping list or call one of the misses.
- * 
+ *
  * If a hit process is already started, then sobeit
  */
 void
@@ -1052,37 +1049,32 @@ neighborsUdpAck(const cache_key * key, icp_common_t * header, const IPAddress &f
         neighborUpdateRtt(p, mem);
 
     /* Does the entry exist? */
-    if (NULL == entry)
-    {
+    if (NULL == entry) {
         debugs(12, 3, "neighborsUdpAck: Cache key '" << storeKeyText(key) << "' not found");
         neighborCountIgnored(p);
         return;
     }
 
     /* check if someone is already fetching it */
-    if (EBIT_TEST(entry->flags, ENTRY_DISPATCHED))
-    {
+    if (EBIT_TEST(entry->flags, ENTRY_DISPATCHED)) {
         debugs(15, 3, "neighborsUdpAck: '" << storeKeyText(key) << "' already being fetched.");
         neighborCountIgnored(p);
         return;
     }
 
-    if (mem == NULL)
-    {
+    if (mem == NULL) {
         debugs(15, 2, "Ignoring " << opcode_d << " for missing mem_obj: " << storeKeyText(key));
         neighborCountIgnored(p);
         return;
     }
 
-    if (entry->ping_status != PING_WAITING)
-    {
+    if (entry->ping_status != PING_WAITING) {
         debugs(15, 2, "neighborsUdpAck: Late " << opcode_d << " for " << storeKeyText(key));
         neighborCountIgnored(p);
         return;
     }
 
-    if (entry->lock_count == 0)
-    {
+    if (entry->lock_count == 0) {
         debugs(12, 1, "neighborsUdpAck: '" << storeKeyText(key) << "' has no locks");
         neighborCountIgnored(p);
         return;
@@ -1090,31 +1082,26 @@ neighborsUdpAck(const cache_key * key, icp_common_t * header, const IPAddress &f
 
     debugs(15, 3, "neighborsUdpAck: " << opcode_d << " for '" << storeKeyText(key) << "' from " << (p ? p->host : "source") << " ");
 
-    if (p)
-    {
+    if (p) {
         ntype = neighborType(p, mem->request);
     }
 
-    if (ignoreMulticastReply(p, mem))
-    {
+    if (ignoreMulticastReply(p, mem)) {
         neighborCountIgnored(p);
-    } else if (opcode == ICP_MISS)
-    {
+    } else if (opcode == ICP_MISS) {
         if (p == NULL) {
             neighborIgnoreNonPeer(from, opcode);
         } else {
             mem->ping_reply_callback(p, ntype, PROTO_ICP, header, mem->ircb_data);
         }
-    } else if (opcode == ICP_HIT)
-    {
+    } else if (opcode == ICP_HIT) {
         if (p == NULL) {
             neighborIgnoreNonPeer(from, opcode);
         } else {
             header->opcode = ICP_HIT;
             mem->ping_reply_callback(p, ntype, PROTO_ICP, header, mem->ircb_data);
         }
-    } else if (opcode == ICP_DECHO)
-    {
+    } else if (opcode == ICP_DECHO) {
         if (p == NULL) {
             neighborIgnoreNonPeer(from, opcode);
         } else if (ntype == PEER_SIBLING) {
@@ -1123,16 +1110,14 @@ neighborsUdpAck(const cache_key * key, icp_common_t * header, const IPAddress &f
         } else {
             mem->ping_reply_callback(p, ntype, PROTO_ICP, header, mem->ircb_data);
         }
-    } else if (opcode == ICP_SECHO)
-    {
+    } else if (opcode == ICP_SECHO) {
         if (p) {
             debugs(15, 1, "Ignoring SECHO from neighbor " << p->host);
             neighborCountIgnored(p);
         } else {
             debugs(15, 1, "Unsolicited SECHO from " << from);
         }
-    } else if (opcode == ICP_DENIED)
-    {
+    } else if (opcode == ICP_DENIED) {
         if (p == NULL) {
             neighborIgnoreNonPeer(from, opcode);
         } else if (p->stats.pings_acked > 100) {
@@ -1145,11 +1130,9 @@ neighborsUdpAck(const cache_key * key, icp_common_t * header, const IPAddress &f
                 neighborCountIgnored(p);
             }
         }
-    } else if (opcode == ICP_MISS_NOFETCH)
-    {
+    } else if (opcode == ICP_MISS_NOFETCH) {
         mem->ping_reply_callback(p, ntype, PROTO_ICP, header, mem->ircb_data);
-    } else
-    {
+    } else {
         debugs(15, 0, "neighborsUdpAck: Unexpected ICP reply: " << opcode_d);
     }
 }
@@ -1197,7 +1180,7 @@ neighborUp(const peer * p)
 
     /*
      * The peer can not be UP if we don't have any IP addresses
-     * for it. 
+     * for it.
      */
     if (0 == p->n_addresses) {
         debugs(15, 8, "neighborUp: DOWN (no-ip): " << p->host << " (" << p->in_addr << ")");
@@ -1354,10 +1337,9 @@ peerConnectSucceded(peer * p)
         debugs(15, 2, "TCP connection to " << p->host << "/" << p->http_port << " succeded");
         p->tcp_up = PEER_TCP_MAGIC_COUNT; // NP: so peerAlive(p) works properly.
         peerAlive(p);
-	if (!p->n_addresses)
-	    ipcache_nbgethostbyname(p->host, peerDNSConfigure, p);
-    }
-    else
+        if (!p->n_addresses)
+            ipcache_nbgethostbyname(p->host, peerDNSConfigure, p);
+    } else
         p->tcp_up = PEER_TCP_MAGIC_COUNT;
 }
 
@@ -1382,7 +1364,7 @@ peerProbeConnectTimeout(int fd, void *data)
 }
 
 /*
-* peerProbeConnect will be called on dead peers by neighborUp 
+* peerProbeConnect will be called on dead peers by neighborUp
 */
 static int
 peerProbeConnect(peer * p)
@@ -1605,14 +1587,14 @@ dump_peer_options(StoreEntry * sentry, peer * p)
 #if USE_HTCP
     if (p->options.htcp)
         storeAppendPrintf(sentry, " htcp");
-	if (p->options.htcp_oldsquid)
-	    storeAppendPrintf(sentry, " htcp-oldsquid");
-	if (p->options.htcp_no_clr)
-	    storeAppendPrintf(sentry, " htcp-no-clr");
-	if (p->options.htcp_no_purge_clr)
-	    storeAppendPrintf(sentry, " htcp-no-purge-clr");
-	if (p->options.htcp_only_clr)
-	    storeAppendPrintf(sentry, " htcp-only-clr");
+    if (p->options.htcp_oldsquid)
+        storeAppendPrintf(sentry, " htcp-oldsquid");
+    if (p->options.htcp_no_clr)
+        storeAppendPrintf(sentry, " htcp-no-clr");
+    if (p->options.htcp_no_purge_clr)
+        storeAppendPrintf(sentry, " htcp-no-purge-clr");
+    if (p->options.htcp_only_clr)
+        storeAppendPrintf(sentry, " htcp-only-clr");
 #endif
 
     if (p->options.no_netdb_exchange)
@@ -1653,12 +1635,12 @@ dump_peer_options(StoreEntry * sentry, peer * p)
     if (p->domain)
         storeAppendPrintf(sentry, " forceddomain=%s", p->domain);
 
-    if(p->connection_auth == 0)
-	storeAppendPrintf(sentry, " connection-auth=off");
-    else if(p->connection_auth == 1)
-	storeAppendPrintf(sentry, " connection-auth=on");
-    else if(p->connection_auth == 2)
-	storeAppendPrintf(sentry, " connection-auth=auto");
+    if (p->connection_auth == 0)
+        storeAppendPrintf(sentry, " connection-auth=off");
+    else if (p->connection_auth == 1)
+        storeAppendPrintf(sentry, " connection-auth=on");
+    else if (p->connection_auth == 2)
+        storeAppendPrintf(sentry, " connection-auth=auto");
 
     storeAppendPrintf(sentry, "\n");
 }
@@ -1780,9 +1762,9 @@ neighborsHtcpReply(const cache_key * key, htcpReplyData * htcp, const IPAddress
     MemObject *mem = NULL;
     peer *p;
     peer_t ntype = PEER_NONE;
-    debugs(15, 6, "neighborsHtcpReply: " << 
-                  (htcp->hit ? "HIT" : "MISS") << " " << 
-                  storeKeyText(key)  );
+    debugs(15, 6, "neighborsHtcpReply: " <<
+           (htcp->hit ? "HIT" : "MISS") << " " <<
+           storeKeyText(key)  );
 
     if (NULL != e)
         mem = e->mem_obj;
@@ -1791,50 +1773,43 @@ neighborsHtcpReply(const cache_key * key, htcpReplyData * htcp, const IPAddress
         neighborAliveHtcp(p, mem, htcp);
 
     /* Does the entry exist? */
-    if (NULL == e)
-    {
+    if (NULL == e) {
         debugs(12, 3, "neighyborsHtcpReply: Cache key '" << storeKeyText(key) << "' not found");
         neighborCountIgnored(p);
         return;
     }
 
     /* check if someone is already fetching it */
-    if (EBIT_TEST(e->flags, ENTRY_DISPATCHED))
-    {
+    if (EBIT_TEST(e->flags, ENTRY_DISPATCHED)) {
         debugs(15, 3, "neighborsUdpAck: '" << storeKeyText(key) << "' already being fetched.");
         neighborCountIgnored(p);
         return;
     }
 
-    if (mem == NULL)
-    {
+    if (mem == NULL) {
         debugs(15, 2, "Ignoring reply for missing mem_obj: " << storeKeyText(key));
         neighborCountIgnored(p);
         return;
     }
 
-    if (e->ping_status != PING_WAITING)
-    {
+    if (e->ping_status != PING_WAITING) {
         debugs(15, 2, "neighborsUdpAck: Entry " << storeKeyText(key) << " is not PING_WAITING");
         neighborCountIgnored(p);
         return;
     }
 
-    if (e->lock_count == 0)
-    {
+    if (e->lock_count == 0) {
         debugs(12, 1, "neighborsUdpAck: '" << storeKeyText(key) << "' has no locks");
         neighborCountIgnored(p);
         return;
     }
 
-    if (p)
-    {
+    if (p) {
         ntype = neighborType(p, mem->request);
         neighborUpdateRtt(p, mem);
     }
 
-    if (ignoreMulticastReply(p, mem))
-    {
+    if (ignoreMulticastReply(p, mem)) {
         neighborCountIgnored(p);
         return;
     }
diff --git a/src/net_db.cc b/src/net_db.cc
index 8fbedae2c1..1cf2f8715c 100644
--- a/src/net_db.cc
+++ b/src/net_db.cc
@@ -20,12 +20,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -67,8 +67,7 @@ typedef enum {
     STATE_BODY
 } netdb_conn_state_t;
 
-typedef struct
-{
+typedef struct {
     peer *p;
     StoreEntry *e;
     store_client *sc;
@@ -264,8 +263,7 @@ netdbAdd(IPAddress &addr)
     if (memInUse(MEM_NETDBENTRY) > Config.Netdb.high)
         netdbPurgeLRU();
 
-    if ((n = netdbLookupAddr(addr)) == NULL)
-    {
+    if ((n = netdbLookupAddr(addr)) == NULL) {
         n = (netdbEntry *)memAllocate(MEM_NETDBENTRY);
         netdbHashInsert(n, addr);
     }
@@ -351,8 +349,7 @@ networkFromInaddr(const IPAddress &in)
 
     /* in IPv6 the 'network' should be the routing section. */
 
-    if( in.IsIPv6() )
-    {
+    if ( in.IsIPv6() ) {
         out.ApplyMask(64, AF_INET6);
         debugs(14, 5, "networkFromInaddr : Masked IPv6 Address to " << in << "/64 routing part.");
         return out;
@@ -465,7 +462,7 @@ static void
 netdbSaveState(void *foo)
 {
     if (strcmp(Config.netdbFilename, "none") == 0)
-	return;
+        return;
 
     Logfile *lf;
     netdbEntry *n;
@@ -519,8 +516,8 @@ netdbSaveState(void *foo)
     logfileClose(lf);
     getCurrentTime();
     debugs(38, 1, "NETDB state saved; " <<
-                 count << " entries, " <<
-                 tvSubMsec(start, current_time) << " msec" );
+           count << " entries, " <<
+           tvSubMsec(start, current_time) << " msec" );
     eventAddIsh("netdbSaveState", netdbSaveState, NULL, 3600.0, 1);
 }
 
@@ -528,7 +525,7 @@ static void
 netdbReloadState(void)
 {
     if (strcmp(Config.netdbFilename, "none") == 0)
-	return;
+        return;
 
     char *s;
     int fd;
@@ -642,8 +639,8 @@ netdbReloadState(void)
     xfree(buf);
     getCurrentTime();
     debugs(38, 1, "NETDB state reloaded; " <<
-                  count << " entries, " << 
-                  tvSubMsec(start, current_time) << " msec" );
+           count << " entries, " <<
+           tvSubMsec(start, current_time) << " msec" );
 }
 
 static const char *
@@ -888,7 +885,7 @@ static void
 netdbRegisterWithCacheManager(void)
 {
     CacheManager::GetInstance()->
-        registerAction("netdb", "Network Measurement Database", netdbDump, 0, 1);
+    registerAction("netdb", "Network Measurement Database", netdbDump, 0, 1);
 }
 
 #endif /* USE_ICMP */
@@ -933,7 +930,7 @@ netdbPingSite(const char *hostname)
             return;
 
     ipcache_nbgethostbyname(hostname, netdbSendPing,
-			    new generic_cbdata(xstrdup(hostname)));
+                            new generic_cbdata(xstrdup(hostname)));
 
 #endif
 }
@@ -991,8 +988,7 @@ netdbHops(IPAddress &addr)
 #if USE_ICMP
     netdbEntry *n = netdbLookupAddr(addr);
 
-    if (n && n->pings_recv)
-    {
+    if (n && n->pings_recv) {
         n->last_use_time = squid_curtime;
         return (int) (n->hops + 0.5);
     }
@@ -1164,7 +1160,7 @@ netdbExchangeUpdatePeer(IPAddress &addr, peer * e, double rtt, double hops)
            std::setfill('0')<< std::setprecision(2) << hops << " hops, " <<
            rtt << " rtt");
 
-    if( !addr.IsIPv4() ) {
+    if ( !addr.IsIPv4() ) {
         debugs(38, 5, "netdbExchangeUpdatePeer: Aborting peer update for '" << addr << "', NetDB cannot handle IPv6.");
         return;
     }
@@ -1251,7 +1247,7 @@ netdbBinaryExchange(StoreEntry * s)
             continue;
 
         /* FIXME INET6 : NetDB cannot yet handle IPv6 addresses. Ensure only IPv4 get sent. */
-        if( !addr.IsIPv4() )
+        if ( !addr.IsIPv4() )
             continue;
 
         buf[i++] = (char) NETDB_EX_NETWORK;
diff --git a/src/peer_digest.cc b/src/peer_digest.cc
index 2a0d23578b..8899e7f505 100644
--- a/src/peer_digest.cc
+++ b/src/peer_digest.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -250,7 +250,7 @@ peerDigestNotePeerGone(PeerDigest * pd)
 }
 
 /* callback for eventAdd() (with peer digest locked)
- * request new digest if our copy is too old or if we lack one; 
+ * request new digest if our copy is too old or if we lack one;
  * schedule next check otherwise */
 static void
 peerDigestCheck(void *data)
@@ -268,8 +268,8 @@ peerDigestCheck(void *data)
     }
 
     debugs(72, 3, "peerDigestCheck: peer " <<  pd->peer->host << ":" << pd->peer->http_port);
-    debugs(72, 3, "peerDigestCheck: time: " << squid_curtime << 
-           ", last received: " << (long int) pd->times.received << "  (" << 
+    debugs(72, 3, "peerDigestCheck: time: " << squid_curtime <<
+           ", last received: " << (long int) pd->times.received << "  (" <<
            std::showpos << (int) (squid_curtime - pd->times.received) << ")");
 
     /* decide when we should send the request:
@@ -544,8 +544,8 @@ peerDigestFetchReply(void *data, char *buf, ssize_t size)
         assert(reply);
         assert (reply->sline.status != 0);
         status = reply->sline.status;
-        debugs(72, 3, "peerDigestFetchReply: " << pd->host.buf() << " status: " << status << 
-               ", expires: " << (long int) reply->expires << " (" << std::showpos << 
+        debugs(72, 3, "peerDigestFetchReply: " << pd->host.buf() << " status: " << status <<
+               ", expires: " << (long int) reply->expires << " (" << std::showpos <<
                (int) (reply->expires - squid_curtime) << ")");
 
         /* this "if" is based on clientHandleIMSReply() */
@@ -1000,9 +1000,9 @@ peerDigestSetCBlock(PeerDigest * pd, const char *buf)
            (int) cblock.ver.current << " (req: " << (int) cblock.ver.required <<
            ")");
 
-    debugs(72, 2, "\t size: " << 
-           cblock.mask_size << " bytes, e-cnt: " << 
-           cblock.count << ", e-util: " << 
+    debugs(72, 2, "\t size: " <<
+           cblock.mask_size << " bytes, e-cnt: " <<
+           cblock.count << ", e-util: " <<
            xpercentInt(cblock.count, cblock.capacity) << "%" );
     /* check version requirements (both ways) */
 
@@ -1058,8 +1058,8 @@ peerDigestSetCBlock(PeerDigest * pd, const char *buf)
     }
 
     if (!pd->cd) {
-        debugs(72, 2, "creating " << host << " digest; size: " << cblock.mask_size << " (" << 
-                std::showpos <<  (int) (cblock.mask_size - freed_size) << ") bytes");
+        debugs(72, 2, "creating " << host << " digest; size: " << cblock.mask_size << " (" <<
+               std::showpos <<  (int) (cblock.mask_size - freed_size) << ") bytes");
         pd->cd = cacheDigestCreate(cblock.capacity, cblock.bits_per_entry);
 
         if (cblock.mask_size >= freed_size)
diff --git a/src/peer_select.cc b/src/peer_select.cc
index b0e5008d9e..2492130eb9 100644
--- a/src/peer_select.cc
+++ b/src/peer_select.cc
@@ -20,12 +20,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -43,45 +43,42 @@
 #include "forward.h"
 #include "SquidTime.h"
 
-const char *hier_strings[] =
-    {
-        "NONE",
-        "DIRECT",
-        "SIBLING_HIT",
-        "PARENT_HIT",
-        "DEFAULT_PARENT",
-        "SINGLE_PARENT",
-        "FIRST_UP_PARENT",
-        "FIRST_PARENT_MISS",
-        "CLOSEST_PARENT_MISS",
-        "CLOSEST_PARENT",
-        "CLOSEST_DIRECT",
-        "NO_DIRECT_FAIL",
-        "SOURCE_FASTEST",
-        "ROUNDROBIN_PARENT",
+const char *hier_strings[] = {
+    "NONE",
+    "DIRECT",
+    "SIBLING_HIT",
+    "PARENT_HIT",
+    "DEFAULT_PARENT",
+    "SINGLE_PARENT",
+    "FIRST_UP_PARENT",
+    "FIRST_PARENT_MISS",
+    "CLOSEST_PARENT_MISS",
+    "CLOSEST_PARENT",
+    "CLOSEST_DIRECT",
+    "NO_DIRECT_FAIL",
+    "SOURCE_FASTEST",
+    "ROUNDROBIN_PARENT",
 #if USE_CACHE_DIGESTS
-        "CD_PARENT_HIT",
-        "CD_SIBLING_HIT",
+    "CD_PARENT_HIT",
+    "CD_SIBLING_HIT",
 #endif
-        "CARP",
-        "ANY_PARENT",
-	"USERHASH",
-	"SOURCEHASH",
-        "INVALID CODE"
-    };
-
-static struct
-{
+    "CARP",
+    "ANY_PARENT",
+    "USERHASH",
+    "SOURCEHASH",
+    "INVALID CODE"
+};
+
+static struct {
     int timeouts;
 } PeerStats;
 
-static const char *DirectStr[] =
-    {
-        "DIRECT_UNKNOWN",
-        "DIRECT_NO",
-        "DIRECT_MAYBE",
-        "DIRECT_YES"
-    };
+static const char *DirectStr[] = {
+    "DIRECT_UNKNOWN",
+    "DIRECT_NO",
+    "DIRECT_MAYBE",
+    "DIRECT_YES"
+};
 
 static void peerSelectFoo(ps_state *);
 static void peerPingTimeout(void *data);
@@ -379,7 +376,7 @@ peerSelectPinned(ps_state * ps)
     if (!request->pinnedConnection())
         return;
     if (request->pinnedConnection()->validatePinnedConnection(request) != -1) {
-	peer = request->pinnedConnection()->pinnedPeer();
+        peer = request->pinnedConnection()->pinnedPeer();
         if (peer && peerAllowedToUse(peer, request)) {
             peerAddFwdServer(&ps->servers, peer, PINNED);
             if (ps->entry)
@@ -394,7 +391,7 @@ peerSelectPinned(ps_state * ps)
 
 /*
  * peerGetSomeNeighbor
- * 
+ *
  * Selects a neighbor (parent or sibling) based on one of the
  * following methods:
  *      Cache Digests
@@ -438,9 +435,9 @@ peerGetSomeNeighbor(ps_state * ps)
 
             if (ps->ping.n_sent == 0)
                 debugs(44, 0, "WARNING: neighborsUdpPing returned 0");
-                debugs(44, 3, "peerSelect: " << ps->ping.n_replies_expected <<
-                       " ICP replies expected, RTT " << ps->ping.timeout <<
-                       " msec");
+            debugs(44, 3, "peerSelect: " << ps->ping.n_replies_expected <<
+                   " ICP replies expected, RTT " << ps->ping.timeout <<
+                   " msec");
 
 
             if (ps->ping.n_replies_expected > 0) {
@@ -465,7 +462,7 @@ peerGetSomeNeighbor(ps_state * ps)
 
 /*
  * peerGetSomeNeighborReplies
- * 
+ *
  * Selects a neighbor (parent or sibling) based on ICP/HTCP replies.
  */
 static void
@@ -486,8 +483,7 @@ peerGetSomeNeighborReplies(ps_state * ps)
 
     if ((p = ps->hit)) {
         code = ps->hit_type == PEER_PARENT ? PARENT_HIT : SIBLING_HIT;
-    } else
-    {
+    } else {
         if (!ps->closest_parent_miss.IsAnyAddr()) {
             p = whichPeer(ps->closest_parent_miss);
             code = CLOSEST_PARENT_MISS;
@@ -505,7 +501,7 @@ peerGetSomeNeighborReplies(ps_state * ps)
 
 /*
  * peerGetSomeDirect
- * 
+ *
  * Simply adds a 'direct' entry to the FwdServers list if this
  * request can be forwarded directly to the origin server
  */
@@ -517,7 +513,7 @@ peerGetSomeDirect(ps_state * ps)
 
     /* WAIS is not implemented natively */
     if (ps->request->protocol == PROTO_WAIS)
-	return;
+        return;
 
     peerAddFwdServer(&ps->servers, NULL, HIER_DIRECT);
 }
@@ -699,9 +695,9 @@ static void
 peerHandleHtcpReply(peer * p, peer_t type, htcpReplyData * htcp, void *data)
 {
     ps_state *psstate = (ps_state *)data;
-    debugs(44, 3, "peerHandleHtcpReply: " << 
-                  (htcp->hit ? "HIT" : "MISS") << " " << 
-                  psstate->entry->url()  );
+    debugs(44, 3, "peerHandleHtcpReply: " <<
+           (htcp->hit ? "HIT" : "MISS") << " " <<
+           psstate->entry->url()  );
     psstate->ping.n_recv++;
 
     if (htcp->hit) {
@@ -781,9 +777,9 @@ static void
 peerAddFwdServer(FwdServer ** FSVR, peer * p, hier_code code)
 {
     FwdServer *fs = (FwdServer *)memAllocate(MEM_FWD_SERVER);
-    debugs(44, 5, "peerAddFwdServer: adding " << 
-                 (p ? p->host : "DIRECT")  << " " << 
-                 hier_strings[code]  );
+    debugs(44, 5, "peerAddFwdServer: adding " <<
+           (p ? p->host : "DIRECT")  << " " <<
+           hier_strings[code]  );
     fs->_peer = cbdataReference(p);
     fs->code = code;
 
diff --git a/src/peer_sourcehash.cc b/src/peer_sourcehash.cc
index 6dd8073d8b..ddc9a6c6c8 100644
--- a/src/peer_sourcehash.cc
+++ b/src/peer_sourcehash.cc
@@ -22,12 +22,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -158,8 +158,8 @@ static void
 peerSourceHashRegisterWithCacheManager(void)
 {
     CacheManager::GetInstance()->
-        registerAction("sourcehash", "peer sourcehash information", 
-	               peerSourceHashCachemgr, 0, 1);
+    registerAction("sourcehash", "peer sourcehash information",
+                   peerSourceHashCachemgr, 0, 1);
 }
 
 peer *
@@ -194,7 +194,7 @@ peerSourceHashSelectParent(HttpRequest * request)
         combined_hash += combined_hash * 0x62531965;
         combined_hash = ROTATE_LEFT(combined_hash, 21);
         score = combined_hash * tp->sourcehash.load_multiplier;
-        debugs(39, 3, "peerSourceHashSelectParent: " << tp->name << " combined_hash " << combined_hash  << 
+        debugs(39, 3, "peerSourceHashSelectParent: " << tp->name << " combined_hash " << combined_hash  <<
                " score " << std::setprecision(0) << score);
 
         if ((score > high_score) && peerHTTPOkay(tp, request)) {
diff --git a/src/peer_userhash.cc b/src/peer_userhash.cc
index e0baa41591..063cbf29e6 100644
--- a/src/peer_userhash.cc
+++ b/src/peer_userhash.cc
@@ -22,12 +22,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -75,7 +75,7 @@ peerUserHashInit(void)
     n_userhash_peers = 0;
     /* find out which peers we have */
 
-    
+
     peerUserHashRegisterWithCacheManager();
 
     for (p = Config.peers; p; p = p->next) {
@@ -160,8 +160,8 @@ static void
 peerUserHashRegisterWithCacheManager(void)
 {
     CacheManager::GetInstance()->
-        registerAction("userhash", "peer userhash information", peerUserHashCachemgr, 
-	0, 1);
+    registerAction("userhash", "peer userhash information", peerUserHashCachemgr,
+                   0, 1);
 }
 
 peer *
@@ -181,10 +181,10 @@ peerUserHashSelectParent(HttpRequest * request)
         return NULL;
 
     if (request->auth_user_request)
-	key = request->auth_user_request->username();
+        key = request->auth_user_request->username();
 
     if (!key)
-	return NULL;
+        return NULL;
 
     /* calculate hash key */
     debugs(39, 2, "peerUserHashSelectParent: Calculating hash for " << key);
@@ -199,7 +199,7 @@ peerUserHashSelectParent(HttpRequest * request)
         combined_hash += combined_hash * 0x62531965;
         combined_hash = ROTATE_LEFT(combined_hash, 21);
         score = combined_hash * tp->userhash.load_multiplier;
-        debugs(39, 3, "peerUserHashSelectParent: " << tp->name << " combined_hash " << combined_hash  << 
+        debugs(39, 3, "peerUserHashSelectParent: " << tp->name << " combined_hash " << combined_hash  <<
                " score " << std::setprecision(0) << score);
 
         if ((score > high_score) && peerHTTPOkay(tp, request)) {
diff --git a/src/pinger.cc b/src/pinger.cc
index 5aa9a78622..41690482ff 100644
--- a/src/pinger.cc
+++ b/src/pinger.cc
@@ -20,12 +20,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -155,23 +155,23 @@ main(int argc, char *argv[])
     debugs(42, 0, "pinger: Initialising ICMP pinger ...");
 
     icmp4_worker = icmp4.Open();
-    if(icmp4_worker < 0) {
+    if (icmp4_worker < 0) {
         debugs(42, 0, "pinger: Unable to start ICMP pinger.");
     }
     max_fd = max(max_fd, icmp4_worker);
 
 #if USE_IPV6
     icmp6_worker = icmp6.Open();
-    if(icmp6_worker <0 ) {
+    if (icmp6_worker <0 ) {
         debugs(42, 0, "pinger: Unable to start ICMPv6 pinger.");
     }
     max_fd = max(max_fd, icmp6_worker);
 #endif
 
     /** abort if neither worker could open a socket. */
-    if(icmp4_worker == -1) {
+    if (icmp4_worker == -1) {
 #if USE_IPV6
-        if(icmp6_worker == -1)
+        if (icmp6_worker == -1)
 #endif
         {
             debugs(42, 0, "FATAL: pinger: Unable to open any ICMP sockets.");
@@ -179,7 +179,7 @@ main(int argc, char *argv[])
         }
     }
 
-    if( (squid_link = control.Open()) < 0) {
+    if ( (squid_link = control.Open()) < 0) {
         debugs(42, 0, "FATAL: pinger: Unable to setup Pinger control sockets.");
         icmp4.Close();
 #if USE_IPV6
@@ -196,12 +196,12 @@ main(int argc, char *argv[])
         tv.tv_sec = PINGER_TIMEOUT;
         tv.tv_usec = 0;
         FD_ZERO(&R);
-        if(icmp4_worker >= 0) {
+        if (icmp4_worker >= 0) {
             FD_SET(icmp4_worker, &R);
         }
 #if USE_IPV6
 
-        if(icmp6_worker >= 0) {
+        if (icmp6_worker >= 0) {
             FD_SET(icmp6_worker, &R);
         }
 #endif
diff --git a/src/protos.h b/src/protos.h
index 2d38c82ee8..94379bfb8f 100644
--- a/src/protos.h
+++ b/src/protos.h
@@ -18,12 +18,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -761,7 +761,7 @@ SQUIDCEXTERN void logfilePrintf(va_alist);
 SQUIDCEXTERN int getrusage(int, struct rusage *);
 SQUIDCEXTERN int getpagesize(void);
 #if !defined(_XPG4_2) && !(defined(__EXTENSIONS__) || \
-        (!defined(_POSIX_C_SOURCE) && !defined(_XOPEN_SOURCE)))
+(!defined(_POSIX_C_SOURCE) && !defined(_XOPEN_SOURCE)))
 SQUIDCEXTERN int gethostname(char *, int);
 #endif
 #endif
@@ -791,51 +791,51 @@ SQUIDCEXTERN int SquidMain(int, char **);
 SQUIDCEXTERN int WIN32_pipe(int[2]);
 
 SQUIDCEXTERN int WIN32_getrusage(int, struct rusage *);
-SQUIDCEXTERN void WIN32_ExceptionHandlerInit(void);
+            SQUIDCEXTERN void WIN32_ExceptionHandlerInit(void);
 
-SQUIDCEXTERN int Win32__WSAFDIsSet(int fd, fd_set* set);
-SQUIDCEXTERN DWORD WIN32_IpAddrChangeMonitorInit();
+            SQUIDCEXTERN int Win32__WSAFDIsSet(int fd, fd_set* set);
+            SQUIDCEXTERN DWORD WIN32_IpAddrChangeMonitorInit();
 
 #endif
 
-/* external_acl.c */
-class external_acl;
-SQUIDCEXTERN void parse_externalAclHelper(external_acl **);
+            /* external_acl.c */
+            class external_acl;
+            SQUIDCEXTERN void parse_externalAclHelper(external_acl **);
 
-SQUIDCEXTERN void dump_externalAclHelper(StoreEntry * sentry, const char *name, const external_acl *);
+            SQUIDCEXTERN void dump_externalAclHelper(StoreEntry * sentry, const char *name, const external_acl *);
 
-SQUIDCEXTERN void free_externalAclHelper(external_acl **);
+            SQUIDCEXTERN void free_externalAclHelper(external_acl **);
 
-typedef void EAH(void *data, void *result);
-class ACLChecklist;
-SQUIDCEXTERN void externalAclLookup(ACLChecklist * ch, void *acl_data, EAH * handler, void *data);
+            typedef void EAH(void *data, void *result);
+            class ACLChecklist;
+            SQUIDCEXTERN void externalAclLookup(ACLChecklist * ch, void *acl_data, EAH * handler, void *data);
 
-SQUIDCEXTERN void externalAclInit(void);
+            SQUIDCEXTERN void externalAclInit(void);
 
-SQUIDCEXTERN void externalAclShutdown(void);
+            SQUIDCEXTERN void externalAclShutdown(void);
 
-SQUIDCEXTERN char *strtokFile(void);
+            SQUIDCEXTERN char *strtokFile(void);
 
 #if USE_WCCPv2
 
-SQUIDCEXTERN void parse_wccp2_method(int *v);
-SQUIDCEXTERN void free_wccp2_method(int *v);
-SQUIDCEXTERN void dump_wccp2_method(StoreEntry * e, const char *label, int v);
-SQUIDCEXTERN void parse_wccp2_amethod(int *v);
-SQUIDCEXTERN void free_wccp2_amethod(int *v);
-SQUIDCEXTERN void dump_wccp2_amethod(StoreEntry * e, const char *label, int v);
+            SQUIDCEXTERN void parse_wccp2_method(int *v);
+            SQUIDCEXTERN void free_wccp2_method(int *v);
+            SQUIDCEXTERN void dump_wccp2_method(StoreEntry * e, const char *label, int v);
+            SQUIDCEXTERN void parse_wccp2_amethod(int *v);
+            SQUIDCEXTERN void free_wccp2_amethod(int *v);
+            SQUIDCEXTERN void dump_wccp2_amethod(StoreEntry * e, const char *label, int v);
 
-SQUIDCEXTERN void parse_wccp2_service(void *v);
-SQUIDCEXTERN void free_wccp2_service(void *v);
-SQUIDCEXTERN void dump_wccp2_service(StoreEntry * e, const char *label, void *v);
+            SQUIDCEXTERN void parse_wccp2_service(void *v);
+            SQUIDCEXTERN void free_wccp2_service(void *v);
+            SQUIDCEXTERN void dump_wccp2_service(StoreEntry * e, const char *label, void *v);
 
-SQUIDCEXTERN int check_null_wccp2_service(void *v);
+            SQUIDCEXTERN int check_null_wccp2_service(void *v);
 
-SQUIDCEXTERN void parse_wccp2_service_info(void *v);
+            SQUIDCEXTERN void parse_wccp2_service_info(void *v);
 
-SQUIDCEXTERN void free_wccp2_service_info(void *v);
+            SQUIDCEXTERN void free_wccp2_service_info(void *v);
 
-SQUIDCEXTERN void dump_wccp2_service_info(StoreEntry * e, const char *label, void *v);
+            SQUIDCEXTERN void dump_wccp2_service_info(StoreEntry * e, const char *label, void *v);
 
 #endif
 
diff --git a/src/recv-announce.cc b/src/recv-announce.cc
index 9e7d18b748..e8bf07784e 100644
--- a/src/recv-announce.cc
+++ b/src/recv-announce.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -52,18 +52,18 @@
 /*
  * This program must be run from inetd.  First add something like this
  * to /etc/services:
- * 
+ *
  * cached_announce 3131/udp             # cache announcements
- * 
+ *
  * And then add something like this to /etc/inetd/conf:
- * 
+ *
  * cached_announce dgram udp       wait cached /tmp/recv-announce recv-announce /tmp/recv-announce.log
- * 
- * 
+ *
+ *
  * A single instance of this process will continue to handle incoming
  * requests.  If it dies, or is killed, inetd should restart it when the
  * next message arrives.
- * 
+ *
  */
 
 /*
diff --git a/src/redirect.cc b/src/redirect.cc
index 45c923c8cd..db2c006ced 100644
--- a/src/redirect.cc
+++ b/src/redirect.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -44,8 +44,7 @@
 #include "client_side.h"
 #include "helper.h"
 
-typedef struct
-{
+typedef struct {
     void *data;
     char *orig_url;
 
@@ -130,7 +129,7 @@ redirectStart(ClientHttpRequest * http, RH * handler, void *data)
 
     r = cbdataAlloc(redirectStateData);
     r->orig_url = xstrdup(http->uri);
-    if(conn != NULL)
+    if (conn != NULL)
         r->client_addr = conn->log_addr;
     else
         r->client_addr.SetNoAddr();
@@ -180,7 +179,7 @@ static void
 redirectRegisterWithCacheManager(void)
 {
     CacheManager::GetInstance()->
-        registerAction("redirector", "URL Redirector Stats", redirectStats, 0, 1);
+    registerAction("redirector", "URL Redirector Stats", redirectStats, 0, 1);
 }
 
 void
diff --git a/src/referer.cc b/src/referer.cc
index d582d0170a..9da286c51f 100644
--- a/src/referer.cc
+++ b/src/referer.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/src/refresh.cc b/src/refresh.cc
index e19b3da8e7..2fd40fba25 100644
--- a/src/refresh.cc
+++ b/src/refresh.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -58,8 +58,7 @@ typedef enum {
     rcCount
 } refreshCountsEnum;
 
-typedef struct
-{
+typedef struct {
     bool expires;
     bool min;
     bool lmfactor;
@@ -90,8 +89,7 @@ enum {
     STALE_DEFAULT = 299
 };
 
-static struct RefreshCounts
-{
+static struct RefreshCounts {
     const char *proto;
     int total;
     int status[STALE_DEFAULT + 1];
@@ -344,14 +342,14 @@ refreshCheck(const StoreEntry * entry, HttpRequest * request, time_t delta)
         if (sf.expires) {
             debugs(22, 3, "refreshCheck: returning FRESH_EXPIRES");
             return FRESH_EXPIRES;
-	}
+        }
 
         assert(!sf.max);
 
         if (sf.lmfactor) {
             debugs(22, 3, "refreshCheck: returning FRESH_LMFACTOR_RULE");
             return FRESH_LMFACTOR_RULE;
-	}
+        }
 
         assert(sf.min);
 
@@ -400,8 +398,8 @@ refreshIsCachable(const StoreEntry * entry)
     /*
      * Don't look at the request to avoid no-cache and other nuisances.
      * the object should have a mem_obj so the URL will be found there.
-     * minimum_expiry_time seconds delta (defaults to 60 seconds), to 
-     * avoid objects which expire almost immediately, and which can't 
+     * minimum_expiry_time seconds delta (defaults to 60 seconds), to
+     * avoid objects which expire almost immediately, and which can't
      * be refreshed.
      */
     int reason = refreshCheck(entry, NULL, Config.minimum_expiry_time);
@@ -578,7 +576,7 @@ static void
 refreshRegisterWithCacheManager(void)
 {
     CacheManager::GetInstance()->
-        registerAction("refresh", "Refresh Algorithm Statistics", refreshStats, 0, 1);
+    registerAction("refresh", "Refresh Algorithm Statistics", refreshStats, 0, 1);
 }
 
 void
diff --git a/src/repl/heap/store_heap_replacement.cc b/src/repl/heap/store_heap_replacement.cc
index 08fb4e98dc..cbbb634d5d 100644
--- a/src/repl/heap/store_heap_replacement.cc
+++ b/src/repl/heap/store_heap_replacement.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -35,7 +35,7 @@
 
 /*
  * The code in this file is Copyrighted (C) 1999 by Hewlett Packard.
- * 
+ *
  *
  * For a description of these cache replacement policies see --
  *  http://www.hpl.hp.com/techreports/1999/HPL-1999-69.html
@@ -56,7 +56,7 @@
  * in cache regardless of size.  Achieves lower hit rate than GDS
  * because there are more large objects in cache (so less room for
  * smaller popular objects).
- * 
+ *
  * This version implements a tie-breaker based upon recency
  * (e->lastref): for objects that have the same reference count
  * the most recent object wins (gets a higher key value).
@@ -102,7 +102,7 @@ HeapKeyGen_StoreEntry_LFUDA(void *entry, double heap_age)
  * keeping more small, popular objects in cache.  Achieves lower
  * byte hit rate than LFUDA because there are fewer large objects
  * in cache.
- * 
+ *
  * This version implements a tie-breaker based upon recency
  * (e->lastref): for objects that have the same reference count
  * the most recent object wins (gets a higher key value).
@@ -144,9 +144,9 @@ heap_key
 HeapKeyGen_StoreEntry_LRU(void *entry, double heap_age)
 {
     StoreEntry *e = (StoreEntry *)entry;
-    debugs(81, 3, "HeapKeyGen_StoreEntry_LRU: " << 
-                  e->getMD5Text() << " heap_age=" << heap_age << 
-                  " lastref=" << (double) e->lastref  );
+    debugs(81, 3, "HeapKeyGen_StoreEntry_LRU: " <<
+           e->getMD5Text() << " heap_age=" << heap_age <<
+           " lastref=" << (double) e->lastref  );
 
     if (e->mem_obj && e->mem_obj->url)
         debugs(81, 3, "HeapKeyGen_StoreEntry_LRU: url=" << e->mem_obj->url);
diff --git a/src/repl/heap/store_repl_heap.cc b/src/repl/heap/store_repl_heap.cc
index 81e48ab493..74ba7c35e3 100644
--- a/src/repl/heap/store_repl_heap.cc
+++ b/src/repl/heap/store_repl_heap.cc
@@ -12,7 +12,7 @@
  * For details on the original heap policy work and the thinking behind see
  * http://www.hpl.hp.com/techreports/1999/HPL-1999-69.html
  *
- * 
+ *
  * SQUID Web Proxy Cache          http://www.squid-cache.org/
  * ----------------------------------------------------------
  *
@@ -29,12 +29,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -52,8 +52,7 @@ REMOVALPOLICYCREATE createRemovalPolicy_heap;
 
 static int nr_heap_policies = 0;
 
-struct HeapPolicyData
-{
+struct HeapPolicyData {
     void setPolicyNode (StoreEntry *, void *) const;
     RemovalPolicy *policy;
     heap *theHeap;
@@ -154,8 +153,7 @@ heap_referenced(RemovalPolicy * policy, const StoreEntry * entry,
 
 typedef struct _HeapWalkData HeapWalkData;
 
-struct _HeapWalkData
-{
+struct _HeapWalkData {
     size_t current;
 };
 
@@ -208,8 +206,7 @@ heap_walkInit(RemovalPolicy * policy)
 
 typedef struct _HeapPurgeData HeapPurgeData;
 
-struct _HeapPurgeData
-{
+struct _HeapPurgeData {
     link_list *locked_entries;
     heap_key min_age;
 };
diff --git a/src/repl/lru/store_repl_lru.cc b/src/repl/lru/store_repl_lru.cc
index 853eb58bc6..90e845313e 100644
--- a/src/repl/lru/store_repl_lru.cc
+++ b/src/repl/lru/store_repl_lru.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -40,8 +40,7 @@
 
 REMOVALPOLICYCREATE createRemovalPolicy_lru;
 
-struct LruPolicyData
-{
+struct LruPolicyData {
     void setPolicyNode (StoreEntry *, void *) const;
     RemovalPolicy *policy;
     dlink_list list;
@@ -89,8 +88,7 @@ LruPolicyData::setPolicyNode (StoreEntry *entry, void *value) const
 
 typedef struct _LruNode LruNode;
 
-struct _LruNode
-{
+struct _LruNode {
     /* Note: the dlink_node MUST be the first member of the LruNode
      * structure. This member is later pointer typecasted to LruNode *.
      */
@@ -161,8 +159,7 @@ lru_referenced(RemovalPolicy * policy, const StoreEntry * entry,
 
 typedef struct _LruWalkData LruWalkData;
 
-struct _LruWalkData
-{
+struct _LruWalkData {
     LruNode *current;
 };
 
@@ -213,8 +210,7 @@ lru_walkInit(RemovalPolicy * policy)
 
 typedef struct _LruPurgeData LruPurgeData;
 
-struct _LruPurgeData
-{
+struct _LruPurgeData {
     LruNode *current;
     LruNode *start;
 };
diff --git a/src/send-announce.cc b/src/send-announce.cc
index 4d94c3b296..8f11c92950 100644
--- a/src/send-announce.cc
+++ b/src/send-announce.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/src/snmp_agent.cc b/src/snmp_agent.cc
index 200b742a67..d77edb6b0e 100644
--- a/src/snmp_agent.cc
+++ b/src/snmp_agent.cc
@@ -20,12 +20,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -39,13 +39,13 @@
 #include "SquidTime.h"
 
 /************************************************************************
- 
+
  SQUID MIB Implementation
- 
+
  ************************************************************************/
 
-/* 
- * cacheSystem group 
+/*
+ * cacheSystem group
  */
 
 variable_list *
@@ -84,8 +84,8 @@ snmp_sysFn(variable_list * Var, snint * ErrP)
     return Answer;
 }
 
-/* 
- * cacheConfig group 
+/*
+ * cacheConfig group
  */
 variable_list *
 snmp_confFn(variable_list * Var, snint * ErrP)
@@ -190,7 +190,7 @@ snmp_confFn(variable_list * Var, snint * ErrP)
 }
 
 
-/* 
+/*
  * cacheMesh group
  *   - cachePeerTable
  */
@@ -206,29 +206,26 @@ snmp_meshPtblFn(variable_list * Var, snint * ErrP)
     debugs(49, 5, "snmp_meshPtblFn: peer " << Var->name[LEN_SQ_MESH + 3] << " requested!");
     *ErrP = SNMP_ERR_NOERROR;
 
-    u_int index = Var->name[LEN_SQ_MESH + 3] ; 
-    for (p = Config.peers; p != NULL; p = p->next, cnt++)
-      {
-        if (p->index == index)
-	  {
-	    laddr = p->in_addr ;
-	    break;
-	  }
-      }
+    u_int index = Var->name[LEN_SQ_MESH + 3] ;
+    for (p = Config.peers; p != NULL; p = p->next, cnt++) {
+        if (p->index == index) {
+            laddr = p->in_addr ;
+            break;
+        }
+    }
 
     if (p == NULL) {
-      *ErrP = SNMP_ERR_NOSUCHNAME;
-      return NULL;
+        *ErrP = SNMP_ERR_NOSUCHNAME;
+        return NULL;
     }
 
 
     switch (Var->name[LEN_SQ_MESH + 2]) {
-    case MESH_PTBL_INDEX: // FIXME INET6: Should be visible?
-        {
-            Answer = snmp_var_new_integer(Var->name, Var->name_length,
-                                          (snint)p->index, SMI_INTEGER);
-        }
-        break;
+    case MESH_PTBL_INDEX: { // FIXME INET6: Should be visible?
+        Answer = snmp_var_new_integer(Var->name, Var->name_length,
+                                      (snint)p->index, SMI_INTEGER);
+    }
+    break;
 
 
     case MESH_PTBL_NAME:
@@ -240,27 +237,25 @@ snmp_meshPtblFn(variable_list * Var, snint * ErrP)
 
         break;
 
-    case MESH_PTBL_ADDR_TYPE:
-        {
-            int ival;
-            ival = laddr.IsIPv4() ? INETADDRESSTYPE_IPV4 : INETADDRESSTYPE_IPV6 ;
-            Answer = snmp_var_new_integer(Var->name, Var->name_length,
-                                          ival, SMI_INTEGER);
-        }
-        break;
-    case MESH_PTBL_ADDR:
-        {
-            Answer = snmp_var_new(Var->name, Var->name_length);
-            // InetAddress doesn't have its own ASN.1 type,
-            // like IpAddr does (SMI_IPADDRESS)
-            // See: rfc4001.txt
-            Answer->type = ASN_OCTET_STR;
-	    char host[MAX_IPSTRLEN];
-	    laddr.NtoA(host,MAX_IPSTRLEN);
-	    Answer->val_len = strlen(host);
-	    Answer->val.string =  (u_char *) xstrdup(host);
-        }
-        break;
+    case MESH_PTBL_ADDR_TYPE: {
+        int ival;
+        ival = laddr.IsIPv4() ? INETADDRESSTYPE_IPV4 : INETADDRESSTYPE_IPV6 ;
+        Answer = snmp_var_new_integer(Var->name, Var->name_length,
+                                      ival, SMI_INTEGER);
+    }
+    break;
+    case MESH_PTBL_ADDR: {
+        Answer = snmp_var_new(Var->name, Var->name_length);
+        // InetAddress doesn't have its own ASN.1 type,
+        // like IpAddr does (SMI_IPADDRESS)
+        // See: rfc4001.txt
+        Answer->type = ASN_OCTET_STR;
+        char host[MAX_IPSTRLEN];
+        laddr.NtoA(host,MAX_IPSTRLEN);
+        Answer->val_len = strlen(host);
+        Answer->val.string =  (u_char *) xstrdup(host);
+    }
+    break;
 
     case MESH_PTBL_HTTP:
         Answer = snmp_var_new_integer(Var->name, Var->name_length,
@@ -413,16 +408,16 @@ snmp_prfSysFn(variable_list * Var, snint * ErrP)
         break;
 
     case PERF_SYS_CURUSED_FD:
-	Answer = snmp_var_new_integer(Var->name, Var->name_length,
-				      (snint) Number_FD,
-				      SMI_GAUGE32);
-	break;
+        Answer = snmp_var_new_integer(Var->name, Var->name_length,
+                                      (snint) Number_FD,
+                                      SMI_GAUGE32);
+        break;
 
     case PERF_SYS_CURMAX_FD:
-	Answer = snmp_var_new_integer(Var->name, Var->name_length,
-				      (snint) Biggest_FD,
-				      SMI_GAUGE32);
-	break;
+        Answer = snmp_var_new_integer(Var->name, Var->name_length,
+                                      (snint) Biggest_FD,
+                                      SMI_GAUGE32);
+        break;
 
     case PERF_SYS_NUMOBJCNT:
         Answer = snmp_var_new_integer(Var->name, Var->name_length,
@@ -615,10 +610,10 @@ snmp_prfProtoFn(variable_list * Var, snint * ErrP)
             x = statByteHitRatio(minutes);
             break;
 
-	case PERF_MEDIAN_HTTP_NH:
-	    x = statHistDeltaMedian(&l->client_http.nh_svc_time,
-				    &f->client_http.nh_svc_time);
-	    break;
+        case PERF_MEDIAN_HTTP_NH:
+            x = statHistDeltaMedian(&l->client_http.nh_svc_time,
+                                    &f->client_http.nh_svc_time);
+            break;
 
         default:
             *ErrP = SNMP_ERR_NOSUCHNAME;
diff --git a/src/snmp_core.cc b/src/snmp_core.cc
index 5a57973f5d..05f4aa8992 100644
--- a/src/snmp_core.cc
+++ b/src/snmp_core.cc
@@ -20,12 +20,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -45,8 +45,7 @@ IPAddress theOutSNMPAddr;
 typedef struct _mib_tree_entry mib_tree_entry;
 typedef oid *(instance_Fn) (oid * name, snint * len, mib_tree_entry * current, oid_ParseFn ** Fn);
 
-struct _mib_tree_entry
-{
+struct _mib_tree_entry {
     oid *name;
     int len;
     oid_ParseFn *parsefunction;
@@ -173,10 +172,10 @@ snmpInit(void)
                                                                                                                                                         LEN_SQ_PRF + 2, snmp_prfSysFn, static_Inst, 0),
                                                                                                                                             snmpAddNode(snmpCreateOid(LEN_SQ_PRF + 2, SQ_PRF, PERF_SYS, PERF_SYS_CURRESERVED_FD),
                                                                                                                                                         LEN_SQ_PRF + 2, snmp_prfSysFn, static_Inst, 0),
-																	    snmpAddNode(snmpCreateOid(LEN_SQ_PRF + 2, SQ_PRF, PERF_SYS, PERF_SYS_CURUSED_FD),
-																			LEN_SQ_PRF + 2, snmp_prfSysFn, static_Inst, 0),
-																	    snmpAddNode(snmpCreateOid(LEN_SQ_PRF + 2, SQ_PRF, PERF_SYS, PERF_SYS_CURMAX_FD),
-																			LEN_SQ_PRF + 2, snmp_prfSysFn, static_Inst, 0)),
+                                                                                                                                            snmpAddNode(snmpCreateOid(LEN_SQ_PRF + 2, SQ_PRF, PERF_SYS, PERF_SYS_CURUSED_FD),
+                                                                                                                                                        LEN_SQ_PRF + 2, snmp_prfSysFn, static_Inst, 0),
+                                                                                                                                            snmpAddNode(snmpCreateOid(LEN_SQ_PRF + 2, SQ_PRF, PERF_SYS, PERF_SYS_CURMAX_FD),
+                                                                                                                                                        LEN_SQ_PRF + 2, snmp_prfSysFn, static_Inst, 0)),
                                                                                                                                 snmpAddNode(snmpCreateOid(LEN_SQ_PRF + 1, SQ_PRF, PERF_PROTO),
                                                                                                                                             LEN_SQ_PRF + 1, NULL, NULL, 2,
                                                                                                                                             snmpAddNode(snmpCreateOid(LEN_SQ_PRF + 2, SQ_PRF, PERF_PROTO, PERF_PROTOSTAT_AGGR),
@@ -423,7 +422,7 @@ snmpConnectionOpen(void)
         if (x < 0)
             debugs(51, 1, "theOutSnmpConnection FD " << theOutSnmpConnection << ": getsockname: " << xstrerror());
         else
-	    theOutSNMPAddr = *xaddr;
+            theOutSNMPAddr = *xaddr;
 
         theOutSNMPAddr.FreeAddrInfo(xaddr);
     }
@@ -585,20 +584,18 @@ snmpConstructReponse(snmp_request_t * rq)
 
 static struct snmp_pdu *
 
-            snmpAgentResponse(struct snmp_pdu *PDU)
-{
+            snmpAgentResponse(struct snmp_pdu *PDU) {
 
     struct snmp_pdu *Answer = NULL;
 
     debugs(49, 5, "snmpAgentResponse: Called.");
 
-    if ((Answer = snmp_pdu_create(SNMP_PDU_RESPONSE)))
-    {
+    if ((Answer = snmp_pdu_create(SNMP_PDU_RESPONSE))) {
         Answer->reqid = PDU->reqid;
         Answer->errindex = 0;
 
         if (PDU->command == SNMP_PDU_GET || PDU->command == SNMP_PDU_GETNEXT) {
-	  /* Indirect way */
+            /* Indirect way */
             int get_next = (PDU->command == SNMP_PDU_GETNEXT);
             variable_list *VarPtr_;
             variable_list **RespVars = &(Answer->variables);
@@ -661,8 +658,8 @@ static struct snmp_pdu *
                 *RespVars = VarNew;
 
                 RespVars = &(VarNew->next_variable);
-            } 
-        } 
+            }
+        }
     }
 
     return (Answer);
@@ -719,7 +716,7 @@ snmpTreeNext(oid * Current, snint CurrentLen, oid ** Next, snint * NextLen)
         while ((mibTreeEntry) && (count < CurrentLen) && (!mibTreeEntry->parsefunction)) {
             mib_tree_entry *nextmibTreeEntry = snmpTreeEntry(Current[count], count, mibTreeEntry);
 
-            if (!nextmibTreeEntry)  
+            if (!nextmibTreeEntry)
                 break;
             else
                 mibTreeEntry = nextmibTreeEntry;
@@ -736,21 +733,20 @@ snmpTreeNext(oid * Current, snint CurrentLen, oid ** Next, snint * NextLen)
 
 
     if ((mibTreeEntry) && (mibTreeEntry->parsefunction)) {
-      *NextLen = CurrentLen;  
-      *Next = (*mibTreeEntry->instancefunction) (Current, NextLen, mibTreeEntry, &Fn);
-      if (*Next)
-	{
-	  debugs(49, 6, "snmpTreeNext: Next : ");
-	  snmpDebugOid(6, *Next, *NextLen);
-	  return (Fn);
-	}
+        *NextLen = CurrentLen;
+        *Next = (*mibTreeEntry->instancefunction) (Current, NextLen, mibTreeEntry, &Fn);
+        if (*Next) {
+            debugs(49, 6, "snmpTreeNext: Next : ");
+            snmpDebugOid(6, *Next, *NextLen);
+            return (Fn);
+        }
     }
 
     if ((mibTreeEntry) && (mibTreeEntry->parsefunction)) {
         count--;
         nextoid = snmpTreeSiblingEntry(Current[count], count, mibTreeEntry->parent);
         if (nextoid) {
-	  debugs(49, 5, "snmpTreeNext: Next OID found for sibling" << nextoid );
+            debugs(49, 5, "snmpTreeNext: Next OID found for sibling" << nextoid );
             mibTreeEntry = nextoid;
             count++;
         } else {
@@ -783,13 +779,11 @@ snmpTreeNext(oid * Current, snint CurrentLen, oid ** Next, snint * NextLen)
         *Next = (*mibTreeEntry->instancefunction) (mibTreeEntry->name, NextLen, mibTreeEntry, &Fn);
     }
 
-    if (*Next)
-	{
-	  debugs(49, 6, "snmpTreeNext: Next : ");
-	  snmpDebugOid(6, *Next, *NextLen);
-	  return (Fn);
-	}
-    else
+    if (*Next) {
+        debugs(49, 6, "snmpTreeNext: Next : ");
+        snmpDebugOid(6, *Next, *NextLen);
+        return (Fn);
+    } else
         return NULL;
 }
 
@@ -825,7 +819,7 @@ time_Inst(oid * name, snint * len, mib_tree_entry * current, oid_ParseFn ** Fn)
         while ((loop < TIME_INDEX_LEN) && (identifier != index[loop]))
             loop++;
 
-        if (loop < (TIME_INDEX_LEN - 1)) { 
+        if (loop < (TIME_INDEX_LEN - 1)) {
             instance = (oid *)xmalloc(sizeof(name) * (*len));
             xmemcpy(instance, name, (sizeof(name) * *len));
             instance[*len - 1] = index[++loop];
@@ -849,24 +843,24 @@ peer_Inst(oid * name, snint * len, mib_tree_entry * current, oid_ParseFn ** Fn)
             current = current->leaves[0];
 
         instance = client_Inst(current->name, len, current, Fn);
-    } else if (*len <= current->len) { 
-      instance = (oid *)xmalloc(sizeof(name) * ( *len + 1));
-      xmemcpy(instance, name, (sizeof(name) * *len));
-      instance[*len] = 1 ;
-      *len += 1;  
+    } else if (*len <= current->len) {
+        instance = (oid *)xmalloc(sizeof(name) * ( *len + 1));
+        xmemcpy(instance, name, (sizeof(name) * *len));
+        instance[*len] = 1 ;
+        *len += 1;
     } else {
-      int no = name[current->len] ;
-      int i ; // Note: This works because the Confifg.peers 
-              // keep its index acording to its position.
-      for ( i=0 ; peers && (i < no) ; peers = peers->next , i++ ) ;
-      
-      if (peers) {
-	  instance = (oid *)xmalloc(sizeof(name) * (current->len + 1 ));
-	  xmemcpy(instance, name, (sizeof(name) * current->len ));
-	  instance[current->len] = no + 1 ; // i.e. the next index on cache_peeer table.
-      } else {
-	return (instance);
-      }
+        int no = name[current->len] ;
+        int i ; // Note: This works because the Confifg.peers
+        // keep its index acording to its position.
+        for ( i=0 ; peers && (i < no) ; peers = peers->next , i++ ) ;
+
+        if (peers) {
+            instance = (oid *)xmalloc(sizeof(name) * (current->len + 1 ));
+            xmemcpy(instance, name, (sizeof(name) * current->len ));
+            instance[current->len] = no + 1 ; // i.e. the next index on cache_peeer table.
+        } else {
+            return (instance);
+        }
     }
     *Fn = current->parsefunction;
     return (instance);
@@ -881,14 +875,14 @@ client_Inst(oid * name, snint * len, mib_tree_entry * current, oid_ParseFn ** Fn
     int size = 0;
     int newshift = 0;
 
-    if(*len <= current->len) {
-        aux  = client_entry(NULL);  
-        if(aux)
+    if (*len <= current->len) {
+        aux  = client_entry(NULL);
+        if (aux)
             laddr = *aux;
         else
             laddr.SetAnyAddr();
 
-        if(laddr.IsIPv4())
+        if (laddr.IsIPv4())
             size = sizeof(in_addr);
 #if USE_IPV6
         else
@@ -903,16 +897,16 @@ client_Inst(oid * name, snint * len, mib_tree_entry * current, oid_ParseFn ** Fn
             *len += size ;
         }
     } else {
-        int shift = *len - current->len ; // i.e 4 or 16 
-        oid2addr(&name[*len - shift], laddr,shift); 
-        aux = client_entry(&laddr);  
-        if(aux)
+        int shift = *len - current->len ; // i.e 4 or 16
+        oid2addr(&name[*len - shift], laddr,shift);
+        aux = client_entry(&laddr);
+        if (aux)
             laddr = *aux;
         else
             laddr.SetAnyAddr();
-      
-        if(!laddr.IsAnyAddr()) {
-            if(laddr.IsIPv4())
+
+        if (!laddr.IsAnyAddr()) {
+            if (laddr.IsIPv4())
                 newshift = sizeof(in_addr);
 #if USE_IPV6
             else
@@ -924,7 +918,7 @@ client_Inst(oid * name, snint * len, mib_tree_entry * current, oid_ParseFn ** Fn
             *len = current->len + newshift ;
         }
     }
-    
+
     *Fn = current->parsefunction;
     return (instance);
 }
@@ -935,7 +929,7 @@ client_Inst(oid * name, snint * len, mib_tree_entry * current, oid_ParseFn ** Fn
  */
 
 /*
- * Tree utility functions. 
+ * Tree utility functions.
  */
 
 /*
@@ -1029,8 +1023,7 @@ va_dcl
     entry->instancefunction = instancefunction;
     entry->children = children;
 
-    if (children > 0)
-    {
+    if (children > 0) {
         entry->leaves = (mib_tree_entry **)xmalloc(sizeof(mib_tree_entry *) * children);
 
         for (loop = 0; loop < children; loop++) {
@@ -1070,8 +1063,7 @@ va_dcl
 
     new_oid = (oid *)xmalloc(sizeof(oid) * length);
 
-    if (length > 0)
-    {
+    if (length > 0) {
         for (loop = 0; loop < length; loop++) {
             new_oid[loop] = va_arg(args, int);
         }
@@ -1106,82 +1098,79 @@ snmpSnmplibDebug(int lvl, char *buf)
 
 
 
-/* 
+/*
    IPv4 address: 10.10.0.9  ==>
-   oid == 10.10.0.9 
-   IPv6 adress : 20:01:32:ef:a2:21:fb:32:00:00:00:00:00:00:00:00:OO:01 ==> 
-   oid == 32.1.50.239.162.33.251.20.50.0.0.0.0.0.0.0.0.0.1 
+   oid == 10.10.0.9
+   IPv6 adress : 20:01:32:ef:a2:21:fb:32:00:00:00:00:00:00:00:00:OO:01 ==>
+   oid == 32.1.50.239.162.33.251.20.50.0.0.0.0.0.0.0.0.0.1
 */
 void
 addr2oid(IPAddress &addr, oid * Dest)
 {
-  u_int i ;
-  u_char *cp = NULL;
-  struct in_addr iaddr;
+    u_int i ;
+    u_char *cp = NULL;
+    struct in_addr iaddr;
 #if USE_IPV6
-  struct in6_addr i6addr;
-  oid code = addr.IsIPv4()? INETADDRESSTYPE_IPV4  : INETADDRESSTYPE_IPV6 ;
-  u_int size = (code == INETADDRESSTYPE_IPV4) ? sizeof(struct in_addr):sizeof(struct in6_addr);
+    struct in6_addr i6addr;
+    oid code = addr.IsIPv4()? INETADDRESSTYPE_IPV4  : INETADDRESSTYPE_IPV6 ;
+    u_int size = (code == INETADDRESSTYPE_IPV4) ? sizeof(struct in_addr):sizeof(struct in6_addr);
 #else
-  oid code = INETADDRESSTYPE_IPV4 ;
-  u_int size = sizeof(struct in_addr) ;
+    oid code = INETADDRESSTYPE_IPV4 ;
+    u_int size = sizeof(struct in_addr) ;
 #endif /* USE_IPV6 */
-  //  Dest[0] = code ;
-  if ( code == INETADDRESSTYPE_IPV4 ) {
-    addr.GetInAddr(iaddr);
-    cp = (u_char *) &(iaddr.s_addr);
-  }
+    //  Dest[0] = code ;
+    if ( code == INETADDRESSTYPE_IPV4 ) {
+        addr.GetInAddr(iaddr);
+        cp = (u_char *) &(iaddr.s_addr);
+    }
 #if USE_IPV6
-  else 
-   {
-    addr.GetInAddr(i6addr);
-    cp = (u_char *) &i6addr;
-   }
+    else {
+        addr.GetInAddr(i6addr);
+        cp = (u_char *) &i6addr;
+    }
 #endif
-  for ( i=0 ; i < size ; i++)
-    {
-      // OID's are in network order
-      Dest[i] = *cp++;  
+    for ( i=0 ; i < size ; i++) {
+        // OID's are in network order
+        Dest[i] = *cp++;
     }
-  debugs(49, 7, "addr2oid: Dest : ");
-  snmpDebugOid(7, Dest, size );
+    debugs(49, 7, "addr2oid: Dest : ");
+    snmpDebugOid(7, Dest, size );
 
 }
 
-/* 
+/*
    oid == 10.10.0.9 ==>
    IPv4 address: 10.10.0.9
-   oid == 32.1.50.239.162.33.251.20.50.0.0.0.0.0.0.0.0.0.1 ==> 
+   oid == 32.1.50.239.162.33.251.20.50.0.0.0.0.0.0.0.0.0.1 ==>
    IPv6 adress : 20:01:32:ef:a2:21:fb:32:00:00:00:00:00:00:00:00:OO:01
 */
 void
 oid2addr(oid * id, IPAddress &addr, u_int size)
 {
-  struct in_addr iaddr;
-  u_int i;
-  u_char *cp;
+    struct in_addr iaddr;
+    u_int i;
+    u_char *cp;
 #if USE_IPV6
-  struct in6_addr i6addr;
-  if ( size == sizeof(struct in_addr) )
+    struct in6_addr i6addr;
+    if ( size == sizeof(struct in_addr) )
 #endif /* USE_IPV6 */
-  cp = (u_char *) &(iaddr.s_addr);
+        cp = (u_char *) &(iaddr.s_addr);
 #if USE_IPV6
-  else 
-  cp = (u_char *) &(i6addr);
+    else
+        cp = (u_char *) &(i6addr);
 #endif /* USE_IPV6 */
-  debugs(49, 7, "oid2addr: id : ");
-  snmpDebugOid(7, id, size  );
-  for(i=0 ; i(ptr); // may be NULL
 }
 
@@ -733,7 +733,7 @@ sslCreateServerContext(const char *certfile, const char *keyfile, int version, c
 
     if (!SSL_CTX_check_private_key(sslContext)) {
         ssl_error = ERR_get_error();
-        debugs(83, 0, "SSL private key '" << 
+        debugs(83, 0, "SSL private key '" <<
                certfile << "' does not match public key '" <<
                keyfile << "': " << ERR_error_string(ssl_error, NULL)  );
         goto error;
@@ -763,7 +763,7 @@ sslCreateServerContext(const char *certfile, const char *keyfile, int version, c
         cert_names = SSL_load_client_CA_file(clientCA);
 
         if (cert_names == NULL) {
-            debugs(83, 1, "Error loading the client CA certificates from '" << clientCA << "\': " << ERR_error_string(ERR_get_error(),NULL)  ); 
+            debugs(83, 1, "Error loading the client CA certificates from '" << clientCA << "\': " << ERR_error_string(ERR_get_error(),NULL)  );
             goto error;
         }
 
diff --git a/src/ssl_support.h b/src/ssl_support.h
index 8ce898677e..c28a6a8d1d 100644
--- a/src/ssl_support.h
+++ b/src/ssl_support.h
@@ -20,12 +20,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -100,7 +100,8 @@ const char *sslFindErrorString(ssl_error_t value);
 #ifdef __cplusplus
 
 /** \cond AUTODOCS-IGNORE */
-namespace Squid {
+namespace Squid
+{
 /** \endcond */
 
 /// \ingroup ServerProtocolSSLAPI
diff --git a/src/stat.cc b/src/stat.cc
index 1b0a085487..4f1e4ffa03 100644
--- a/src/stat.cc
+++ b/src/stat.cc
@@ -20,12 +20,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -538,7 +538,7 @@ info_get(StoreEntry * sentry)
                       store_swap_size);
 
     storeAppendPrintf(sentry, "\tStorage Swap capacity:\t%4.1f%% used, %4.1f%% free\n",
-                      dpercent(store_swap_size, Store::Root().maxSize()),  
+                      dpercent(store_swap_size, Store::Root().maxSize()),
                       dpercent((Store::Root().maxSize() - store_swap_size), Store::Root().maxSize()));
 
 
@@ -763,46 +763,46 @@ service_times(StoreEntry * sentry)
     int p;
     storeAppendPrintf(sentry, "Service Time Percentiles            5 min    60 min:\n");
     for (p = 5; p < 100; p += 5) {
-       storeAppendPrintf(sentry, "\tHTTP Requests (All):  %2d%%  %8.5f %8.5f\n",
-	p,
-	statPctileSvc((double) p / 100.0, 5, PCTILE_HTTP) / 1000.0,
-	statPctileSvc((double) p / 100.0, 60, PCTILE_HTTP) / 1000.0);
+        storeAppendPrintf(sentry, "\tHTTP Requests (All):  %2d%%  %8.5f %8.5f\n",
+                          p,
+                          statPctileSvc((double) p / 100.0, 5, PCTILE_HTTP) / 1000.0,
+                          statPctileSvc((double) p / 100.0, 60, PCTILE_HTTP) / 1000.0);
     }
     for (p = 5; p < 100; p += 5) {
-       storeAppendPrintf(sentry, "\tCache Misses:         %2d%%  %8.5f %8.5f\n",
-	p,
-	statPctileSvc((double) p / 100.0, 5, PCTILE_MISS) / 1000.0,
-	statPctileSvc((double) p / 100.0, 60, PCTILE_MISS) / 1000.0);
+        storeAppendPrintf(sentry, "\tCache Misses:         %2d%%  %8.5f %8.5f\n",
+                          p,
+                          statPctileSvc((double) p / 100.0, 5, PCTILE_MISS) / 1000.0,
+                          statPctileSvc((double) p / 100.0, 60, PCTILE_MISS) / 1000.0);
     }
     for (p = 5; p < 100; p += 5) {
-       storeAppendPrintf(sentry, "\tCache Hits:           %2d%%  %8.5f %8.5f\n",
-	p,
-	statPctileSvc((double) p / 100.0, 5, PCTILE_HIT) / 1000.0,
-	statPctileSvc((double) p / 100.0, 60, PCTILE_HIT) / 1000.0);
+        storeAppendPrintf(sentry, "\tCache Hits:           %2d%%  %8.5f %8.5f\n",
+                          p,
+                          statPctileSvc((double) p / 100.0, 5, PCTILE_HIT) / 1000.0,
+                          statPctileSvc((double) p / 100.0, 60, PCTILE_HIT) / 1000.0);
     }
     for (p = 5; p < 100; p += 5) {
-       storeAppendPrintf(sentry, "\tNear Hits:            %2d%%  %8.5f %8.5f\n",
-	p,
-	statPctileSvc((double) p / 100.0, 5, PCTILE_NH) / 1000.0,
-	statPctileSvc((double) p / 100.0, 60, PCTILE_NH) / 1000.0);
+        storeAppendPrintf(sentry, "\tNear Hits:            %2d%%  %8.5f %8.5f\n",
+                          p,
+                          statPctileSvc((double) p / 100.0, 5, PCTILE_NH) / 1000.0,
+                          statPctileSvc((double) p / 100.0, 60, PCTILE_NH) / 1000.0);
     }
     for (p = 5; p < 100; p += 5) {
-       storeAppendPrintf(sentry, "\tNot-Modified Replies: %2d%%  %8.5f %8.5f\n",
-	p,
-	statPctileSvc((double) p / 100.0, 5, PCTILE_NM) / 1000.0,
-	statPctileSvc((double) p / 100.0, 60, PCTILE_NM) / 1000.0);
+        storeAppendPrintf(sentry, "\tNot-Modified Replies: %2d%%  %8.5f %8.5f\n",
+                          p,
+                          statPctileSvc((double) p / 100.0, 5, PCTILE_NM) / 1000.0,
+                          statPctileSvc((double) p / 100.0, 60, PCTILE_NM) / 1000.0);
     }
     for (p = 5; p < 100; p += 5) {
-       storeAppendPrintf(sentry, "\tDNS Lookups:          %2d%%  %8.5f %8.5f\n",
-	p,
-	statPctileSvc((double) p / 100.0, 5, PCTILE_DNS) / 1000.0,
-	statPctileSvc((double) p / 100.0, 60, PCTILE_DNS) / 1000.0);
+        storeAppendPrintf(sentry, "\tDNS Lookups:          %2d%%  %8.5f %8.5f\n",
+                          p,
+                          statPctileSvc((double) p / 100.0, 5, PCTILE_DNS) / 1000.0,
+                          statPctileSvc((double) p / 100.0, 60, PCTILE_DNS) / 1000.0);
     }
     for (p = 5; p < 100; p += 5) {
-       storeAppendPrintf(sentry, "\tICP Queries:          %2d%%  %8.5f %8.5f\n",
-	p,
-	statPctileSvc((double) p / 100.0, 5, PCTILE_ICP_QUERY) / 1000000.0,
-	statPctileSvc((double) p / 100.0, 60, PCTILE_ICP_QUERY) / 1000000.0);
+        storeAppendPrintf(sentry, "\tICP Queries:          %2d%%  %8.5f %8.5f\n",
+                          p,
+                          statPctileSvc((double) p / 100.0, 5, PCTILE_ICP_QUERY) / 1000000.0,
+                          statPctileSvc((double) p / 100.0, 60, PCTILE_ICP_QUERY) / 1000000.0);
     }
 }
 
@@ -1013,38 +1013,38 @@ statRegisterWithCacheManager(void)
     manager->registerAction("info", "General Runtime Information",
                             info_get, 0, 1);
     manager->registerAction("service_times", "Service Times (Percentiles)",
-                           service_times, 0, 1);
+                            service_times, 0, 1);
     manager->registerAction("filedescriptors", "Process Filedescriptor Allocation",
-                           fde::DumpStats, 0, 1);
+                            fde::DumpStats, 0, 1);
     manager->registerAction("objects", "All Cache Objects", stat_objects_get, 0, 0);
     manager->registerAction("vm_objects", "In-Memory and In-Transit Objects",
-                           stat_vmobjects_get, 0, 0);
+                            stat_vmobjects_get, 0, 0);
     manager->registerAction("io", "Server-side network read() size histograms",
-                           stat_io_get, 0, 1);
+                            stat_io_get, 0, 1);
     manager->registerAction("counters", "Traffic and Resource Counters",
-                           statCountersDump, 0, 1);
+                            statCountersDump, 0, 1);
     manager->registerAction("peer_select", "Peer Selection Algorithms",
-                           statPeerSelect, 0, 1);
+                            statPeerSelect, 0, 1);
     manager->registerAction("digest_stats", "Cache Digest and ICP blob",
-                           statDigestBlob, 0, 1);
+                            statDigestBlob, 0, 1);
     manager->registerAction("5min", "5 Minute Average of Counters",
-                           statAvg5min, 0, 1);
+                            statAvg5min, 0, 1);
     manager->registerAction("60min", "60 Minute Average of Counters",
-                           statAvg60min, 0, 1);
+                            statAvg60min, 0, 1);
     manager->registerAction("utilization", "Cache Utilization",
-                           statUtilization, 0, 1);
+                            statUtilization, 0, 1);
     manager->registerAction("histograms", "Full Histogram Counts",
-                           statCountersHistograms, 0, 1);
+                            statCountersHistograms, 0, 1);
     manager->registerAction("active_requests",
-                           "Client-side Active Requests",
-                           statClientRequests, 0, 1);
+                            "Client-side Active Requests",
+                            statClientRequests, 0, 1);
 #if DEBUG_OPENFD
     manager->registerAction("openfd_objects", "Objects with Swapout files open",
-                           statOpenfdObj, 0, 0);
+                            statOpenfdObj, 0, 0);
 #endif
 #if STAT_GRAPHS
     manager->registerAction("graph_variables", "Display cache metrics graphically",
-                           statGraphDump, 0, 1);
+                            statGraphDump, 0, 1);
 #endif
 }
 
diff --git a/src/stmem.cc b/src/stmem.cc
index d94a16cddc..5e574320b6 100644
--- a/src/stmem.cc
+++ b/src/stmem.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -235,7 +235,7 @@ mem_hdr::debugDump() const
 
 /* FIXME: how do we deal with sparse results -
  * where we have (say)
- * 0-500 and 1000-1500, but are asked for 
+ * 0-500 and 1000-1500, but are asked for
  * 0-2000
  * Partial answer:
  * we supply 0-500 and stop.
diff --git a/src/stmem.h b/src/stmem.h
index c4e30ce757..30d1f8f7e7 100644
--- a/src/stmem.h
+++ b/src/stmem.h
@@ -19,12 +19,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -62,7 +62,7 @@ public:
     mem_node const *start() const;
     mem_node *getBlockContainingLocation (int64_t location) const;
     /* access the contained nodes - easier than punning
-     * as a contianer ourselves 
+     * as a contianer ourselves
      */
     const Splay &getNodes() const;
     char * NodeGet(mem_node * aNode);
diff --git a/src/store.cc b/src/store.cc
index 33a5aaea96..c3e6fc156d 100644
--- a/src/store.cc
+++ b/src/store.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -57,31 +57,27 @@ static STMCB storeWriteComplete;
 
 #define STORE_IN_MEM_BUCKETS            (229)
 
-const char *memStatusStr[] =
-    {
-        "NOT_IN_MEMORY",
-        "IN_MEMORY"
-    };
-
-const char *pingStatusStr[] =
-    {
-        "PING_NONE",
-        "PING_WAITING",
-        "PING_DONE"
-    };
-
-const char *storeStatusStr[] =
-    {
-        "STORE_OK",
-        "STORE_PENDING"
-    };
-
-const char *swapStatusStr[] =
-    {
-        "SWAPOUT_NONE",
-        "SWAPOUT_WRITING",
-        "SWAPOUT_DONE"
-    };
+const char *memStatusStr[] = {
+    "NOT_IN_MEMORY",
+    "IN_MEMORY"
+};
+
+const char *pingStatusStr[] = {
+    "PING_NONE",
+    "PING_WAITING",
+    "PING_DONE"
+};
+
+const char *storeStatusStr[] = {
+    "STORE_OK",
+    "STORE_PENDING"
+};
+
+const char *swapStatusStr[] = {
+    "SWAPOUT_NONE",
+    "SWAPOUT_WRITING",
+    "SWAPOUT_DONE"
+};
 
 extern OBJH storeIOStats;
 
@@ -92,8 +88,7 @@ extern OBJH storeIOStats;
 
 typedef struct _storerepl_entry storerepl_entry_t;
 
-struct _storerepl_entry
-{
+struct _storerepl_entry {
     const char *typestr;
     REMOVALPOLICYCREATE *create;
 };
@@ -815,8 +810,7 @@ StoreEntry::write (StoreIOBuffer writeBuffer)
     PROF_start(StoreEntry_write);
     assert(store_status == STORE_PENDING);
 
-    if (!writeBuffer.length)
-      {
+    if (!writeBuffer.length) {
         /* the headers are received already, but we have not received
          * any body data. There are BROKEN abuses of HTTP which require
          * the headers to be passed along before any body data - see
@@ -828,7 +822,7 @@ StoreEntry::write (StoreIOBuffer writeBuffer)
         PROF_stop(StoreEntry_write);
         invokeHandlers();
         return;
-      }
+    }
 
     debugs(20, 5, "storeWrite: writing " << writeBuffer.length << " bytes for '" << getMD5Text() << "'");
     PROF_stop(StoreEntry_write);
@@ -891,11 +885,9 @@ storeAppendVPrintf(StoreEntry * e, const char *fmt, va_list vargs)
     e->append(buf, strlen(buf));
 }
 
-struct _store_check_cachable_hist
-{
+struct _store_check_cachable_hist {
 
-    struct
-    {
+    struct {
         int non_get;
         int not_entry_cachable;
         int wrong_content_length;
@@ -907,8 +899,7 @@ struct _store_check_cachable_hist
         int too_many_open_fds;
     } no;
 
-    struct
-    {
+    struct {
         int Default;
     } yes;
 } store_check_cachable_hist;
@@ -933,7 +924,7 @@ StoreEntry::checkTooSmall()
 
     if (STORE_OK == store_status)
         if (mem_obj->object_sz < 0 ||
-	    mem_obj->object_sz < Config.Store.minObjectSize)
+                mem_obj->object_sz < Config.Store.minObjectSize)
             return 1;
     if (getReply()->content_length > -1)
         if (getReply()->content_length < Config.Store.minObjectSize)
@@ -1114,18 +1105,18 @@ StoreEntry::abort()
      * Should we check abort.data for validity?
      */
     if (mem_obj->abort.callback) {
-	if (!cbdataReferenceValid(mem_obj->abort.data))
-	    debugs(20,1,HERE << "queueing event when abort.data is not valid");
+        if (!cbdataReferenceValid(mem_obj->abort.data))
+            debugs(20,1,HERE << "queueing event when abort.data is not valid");
         eventAdd("mem_obj->abort.callback",
                  mem_obj->abort.callback,
                  mem_obj->abort.data,
                  0.0,
                  true);
-	unregisterAbort();
+        unregisterAbort();
     }
 
     /* XXX Should we reverse these two, so that there is no
-     * unneeded disk swapping triggered? 
+     * unneeded disk swapping triggered?
      */
     /* Notify the client side */
     invokeHandlers();
@@ -1184,8 +1175,8 @@ storeGetMemSpace(int size)
 
 
 /* thunk through to Store::Root().maintain(). Note that this would be better still
- * if registered against the root store itself, but that requires more complex 
- * update logic - bigger fish to fry first. Long term each store when 
+ * if registered against the root store itself, but that requires more complex
+ * update logic - bigger fish to fry first. Long term each store when
  * it becomes active will self register
  */
 void
@@ -1394,7 +1385,7 @@ storeRegisterWithCacheManager(void)
     manager->registerAction("storedir", "Store Directory Stats", Store::Stats, 0, 1);
     manager->registerAction("store_io", "Store IO Interface Stats", storeIOStats, 0, 1);
     manager->registerAction("store_check_cachable_stats", "storeCheckCachable() Stats",
-                           storeCheckCachableStats, 0, 1);
+                            storeCheckCachableStats, 0, 1);
 }
 
 void
@@ -1457,7 +1448,7 @@ StoreEntry::checkNegativeHit() const
 void
 StoreEntry::negativeCache()
 {
-    if(expires == 0)
+    if (expires == 0)
 #if HTTP_VIOLATIONS
         expires = squid_curtime + Config.negativeTtl;
 #else
@@ -1535,9 +1526,9 @@ StoreEntry::timestampsSet()
             served_date = squid_curtime - age;
 
     if (reply->expires > 0 && reply->date > -1)
-	expires = served_date + (reply->expires - reply->date);
+        expires = served_date + (reply->expires - reply->date);
     else
-	expires = reply->expires;
+        expires = reply->expires;
 
     lastmod = reply->last_modified;
 
@@ -1558,8 +1549,8 @@ StoreEntry::unregisterAbort()
 {
     assert(mem_obj);
     if (mem_obj->abort.callback) {
-	mem_obj->abort.callback = NULL;
-	cbdataReferenceDone(mem_obj->abort.data);
+        mem_obj->abort.callback = NULL;
+        cbdataReferenceDone(mem_obj->abort.data);
     }
 }
 
@@ -1847,7 +1838,7 @@ StoreEntry::trimMemory()
      * objects.  We have to wait until the mem_status changes.
      */
     if (mem_status == IN_MEMORY)
-	return;
+        return;
 
     if (mem_obj->policyLowestOffsetToKeep() == 0)
         /* Nothing to do */
diff --git a/src/store_client.cc b/src/store_client.cc
index 7f74b5125b..0757cfa35d 100644
--- a/src/store_client.cc
+++ b/src/store_client.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -343,7 +343,7 @@ store_client::doCopy(StoreEntry *anEntry)
 
     if (storeClientNoMoreToSend(entry, this)) {
         /* There is no more to send! */
-	debugs(33, 3, HERE << "There is no more to send!");
+        debugs(33, 3, HERE << "There is no more to send!");
         callback(0);
         flags.store_copying = 0;
         return;
@@ -496,7 +496,7 @@ store_client::fail()
     /* synchronous open failures callback from the store,
      * before startSwapin detects the failure.
      * TODO: fix this inconsistent behaviour - probably by
-     * having storeSwapInStart become a callback functions, 
+     * having storeSwapInStart become a callback functions,
      * not synchronous
      */
 
@@ -647,7 +647,7 @@ storeUnregister(store_client * sc, StoreEntry * e, void *data)
     if (mem == NULL)
         return 0;
 
-        debugs(90, 3, "storeUnregister: called for '" << e->getMD5Text() << "'");
+    debugs(90, 3, "storeUnregister: called for '" << e->getMD5Text() << "'");
 
     if (sc == NULL) {
         debugs(90, 3, "storeUnregister: No matching client for '" << e->getMD5Text() << "'");
diff --git a/src/store_digest.cc b/src/store_digest.cc
index ad10563c2f..74475c08d8 100644
--- a/src/store_digest.cc
+++ b/src/store_digest.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -71,8 +71,7 @@ public:
 };
 
 
-typedef struct
-{
+typedef struct {
     int del_count;		/* #store entries deleted from store_digest */
     int del_lost_count;		/* #store entries not found in store_digest on delete */
     int add_count;		/* #store entries accepted to store_digest */
@@ -105,7 +104,7 @@ static void
 storeDigestRegisterWithCacheManager(void)
 {
     CacheManager::GetInstance()->
-        registerAction("store_digest", "Store Digest", storeDigestReport, 0, 1);
+    registerAction("store_digest", "Store Digest", storeDigestReport, 0, 1);
 }
 
 /*
@@ -425,7 +424,7 @@ storeDigestRewriteResume(void)
     rep->setHeaders(version, HTTP_OK, "Cache Digest OK",
                     "application/cache-digest", store_digest->mask_size + sizeof(sd_state.cblock),
                     squid_curtime, squid_curtime + Config.digest.rewrite_period);
-    debugs(71, 3, "storeDigestRewrite: entry expires on " << rep->expires << 
+    debugs(71, 3, "storeDigestRewrite: entry expires on " << rep->expires <<
            " (" << std::showpos << (int) (rep->expires - squid_curtime) << ")");
     e->buffer();
     e->replaceHttpReply(rep);
@@ -441,7 +440,7 @@ storeDigestRewriteFinish(StoreEntry * e)
     assert(e == sd_state.rewrite_lock);
     e->complete();
     e->timestampsSet();
-    debugs(71, 2, "storeDigestRewriteFinish: digest expires at " << e->expires << 
+    debugs(71, 2, "storeDigestRewriteFinish: digest expires at " << e->expires <<
            " (" << std::showpos << (int) (e->expires - squid_curtime) << ")");
     /* is this the write order? @?@ */
     e->mem_obj->unlinkRequest();
@@ -506,13 +505,13 @@ storeDigestCalcCap(void)
 {
     /*
      * To-Do: Bloom proved that the optimal filter utilization is 50% (half of
-     * the bits are off). However, we do not have a formula to calculate the 
+     * the bits are off). However, we do not have a formula to calculate the
      * number of _entries_ we want to pre-allocate for.
      */
     const int hi_cap = Store::Root().maxSize() / Config.Store.avgObjectSize;
     const int lo_cap = 1 + store_swap_size / Config.Store.avgObjectSize;
     const int e_count = StoreEntry::inUseCount();
-    int cap = e_count ? e_count : hi_cap;
+    int cap = e_count ? e_count :hi_cap;
     debugs(71, 2, "storeDigestCalcCap: have: " << e_count << ", want " << cap <<
            " entries; limits: [" << lo_cap << ", " << hi_cap << "]");
 
@@ -521,7 +520,7 @@ storeDigestCalcCap(void)
 
     /* do not enforce hi_cap limit, average-based estimation may be wrong
      *if (cap > hi_cap)
-     *  cap = hi_cap; 
+     *  cap = hi_cap;
      */
     return cap;
 }
@@ -534,8 +533,8 @@ storeDigestResize(void)
     int diff;
     assert(store_digest);
     diff = abs(cap - store_digest->capacity);
-    debugs(71, 2, "storeDigestResize: " << 
-           store_digest->capacity << " -> " << cap << "; change: " << 
+    debugs(71, 2, "storeDigestResize: " <<
+           store_digest->capacity << " -> " << cap << "; change: " <<
            diff << " (" << xpercentInt(diff, store_digest->capacity) << "%)" );
     /* avoid minor adjustments */
 
diff --git a/src/store_dir.cc b/src/store_dir.cc
index aadc5a9300..e3349748e1 100644
--- a/src/store_dir.cc
+++ b/src/store_dir.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -222,7 +222,7 @@ storeDirSelectSwapDirRoundRobin(const StoreEntry * e)
  *
  * Note: We should modify this later on to prefer sticking objects
  * in the *tightest fit* swapdir to conserve space, along with the
- * actual swapdir usage. But for now, this hack will do while  
+ * actual swapdir usage. But for now, this hack will do while
  * testing, so you should order your swapdirs in the config file
  * from smallest maxobjsize to unlimited (-1) maxobjsize.
  *
@@ -320,10 +320,10 @@ storeDirSwapLog(const StoreEntry * e, int op)
 
     assert(op > SWAP_LOG_NOP && op < SWAP_LOG_MAX);
 
-    debugs(20, 3, "storeDirSwapLog: " << 
-           swap_log_op_str[op] << " " <<  
-           e->getMD5Text() << " " <<  
-           e->swap_dirn << " " << 
+    debugs(20, 3, "storeDirSwapLog: " <<
+           swap_log_op_str[op] << " " <<
+           e->getMD5Text() << " " <<
+           e->swap_dirn << " " <<
            std::hex << std::uppercase << std::setfill('0') << std::setw(8) << e->swap_filen);
 
     dynamic_cast(INDEXSD(e->swap_dirn))->logEntry(*e, op);
@@ -410,7 +410,7 @@ storeDirCloseSwapLogs(void)
 
 /*
  *  storeDirWriteCleanLogs
- * 
+ *
  *  Writes a "clean" swap log file from in-memory metadata.
  *  This is a rewrite of the original function to troll each
  *  StoreDir and write the logs, and flush at the end of
@@ -522,7 +522,7 @@ StoreController::sync(void)
 }
 
 /*
- * handle callbacks all avaliable fs'es 
+ * handle callbacks all avaliable fs'es
  */
 int
 StoreController::callback()
@@ -641,7 +641,7 @@ free_cachedir(SquidConfig::_cacheSwap * swap)
     for (i = 0; i < swap->n_configured; i++) {
         /* TODO XXX this lets the swapdir free resources asynchronously
         * swap->swapDirs[i]->deactivate();
-        * but there may be such a means already. 
+        * but there may be such a means already.
         * RBC 20041225
         */
         swap->swapDirs[i] = NULL;
@@ -690,7 +690,7 @@ StoreController::dereference(StoreEntry & e)
 StoreEntry *
 
 StoreController::get
-    (const cache_key *key)
+(const cache_key *key)
 {
 
     return swapDir->get
@@ -700,7 +700,7 @@ StoreController::get
 void
 
 StoreController::get
-    (String const key, STOREGETCLIENT callback, void *cbdata)
+(String const key, STOREGETCLIENT callback, void *cbdata)
 {
     fatal("not implemented");
 }
@@ -708,7 +708,7 @@ StoreController::get
 StoreHashIndex::StoreHashIndex()
 {
     if (store_table)
-	abort();
+        abort();
     assert (store_table == NULL);
 }
 
@@ -765,7 +765,7 @@ StoreHashIndex::create()
 StoreEntry *
 
 StoreHashIndex::get
-    (const cache_key *key)
+(const cache_key *key)
 {
     PROF_start(storeGet);
     debugs(20, 3, "storeGet: looking up " << storeKeyText(key));
@@ -777,7 +777,7 @@ StoreHashIndex::get
 void
 
 StoreHashIndex::get
-    (String const key, STOREGETCLIENT callback, void *cbdata)
+(String const key, STOREGETCLIENT callback, void *cbdata)
 {
     fatal("not implemented");
 }
@@ -809,7 +809,7 @@ StoreHashIndex::init()
          * driven by the StoreHashIndex, not by each store.
         *
         * That is, the HashIndex should perform a search of each dir it is
-        * indexing to do the hash insertions. The search is then able to 
+        * indexing to do the hash insertions. The search is then able to
         * decide 'from-memory', or 'from-clean-log' or 'from-dirty-log' or
         * 'from-no-log'.
         *
diff --git a/src/store_io.cc b/src/store_io.cc
index db0cfc0e17..4f95df662c 100644
--- a/src/store_io.cc
+++ b/src/store_io.cc
@@ -3,11 +3,9 @@
 #include "MemObject.h"
 #include "SwapDir.h"
 
-static struct
-{
+static struct {
 
-    struct
-    {
+    struct {
         int calls;
         int select_fail;
         int create_fail;
@@ -78,7 +76,7 @@ void
 storeClose(StoreIOState::Pointer sio)
 {
     if (sio->flags.closing) {
-	debugs(20,3,HERE << "storeClose: flags.closing already set, bailing");
+        debugs(20,3,HERE << "storeClose: flags.closing already set, bailing");
         return;
     }
 
diff --git a/src/store_key_md5.cc b/src/store_key_md5.cc
index 0c33306177..85c6670a70 100644
--- a/src/store_key_md5.cc
+++ b/src/store_key_md5.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/src/store_log.cc b/src/store_log.cc
index 8c0c484cb0..637f0b5522 100644
--- a/src/store_log.cc
+++ b/src/store_log.cc
@@ -20,12 +20,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -39,14 +39,13 @@
 #include "CacheManager.h"
 #include "SquidTime.h"
 
-static const char *storeLogTags[] =
-    {
-        "CREATE",
-        "SWAPIN",
-        "SWAPOUT",
-        "RELEASE",
-        "SO_FAIL",
-    };
+static const char *storeLogTags[] = {
+    "CREATE",
+    "SWAPIN",
+    "SWAPOUT",
+    "RELEASE",
+    "SO_FAIL",
+};
 
 static int storeLogTagsCounts[STORE_LOG_SWAPOUTFAIL+1];
 static OBJH storeLogTagsHist;
@@ -128,15 +127,15 @@ static void
 storeLogRegisterWithCacheManager(void)
 {
     CacheManager::GetInstance()->
-        registerAction("store_log_tags", "Histogram of store.log tags",
-                       storeLogTagsHist, 0, 1);
+    registerAction("store_log_tags", "Histogram of store.log tags",
+                   storeLogTagsHist, 0, 1);
 }
 
 void
 storeLogOpen(void)
 {
     storeLogRegisterWithCacheManager();
- 
+
     if (Config.Log.store == NULL || strcmp(Config.Log.store, "none") == 0) {
         debugs(20, 1, "Store logging disabled");
         return;
@@ -150,8 +149,8 @@ storeLogTagsHist(StoreEntry *e)
 {
     int tag;
     for (tag = 0; tag <= STORE_LOG_SWAPOUTFAIL; tag++) {
-	storeAppendPrintf(e, "%s %d\n",
-	    storeLogTags[tag],
-	    storeLogTagsCounts[tag]);
+        storeAppendPrintf(e, "%s %d\n",
+                          storeLogTags[tag],
+                          storeLogTagsCounts[tag]);
     }
 }
diff --git a/src/store_rebuild.cc b/src/store_rebuild.cc
index 0778cc7482..232880ab4e 100644
--- a/src/store_rebuild.cc
+++ b/src/store_rebuild.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -45,8 +45,7 @@ static struct _store_rebuild_data counts;
 static struct timeval rebuild_start;
 static void storeCleanup(void *);
 
-typedef struct
-{
+typedef struct {
     /* total number of "swap.state" entries that will be read */
     int total;
     /* number of entries read so far */
@@ -111,7 +110,7 @@ storeCleanup(void *datanotused)
         debugs(20, 1, "  Completed Validation Procedure");
         debugs(20, 1, "  Validated " << validated << " Entries");
         debugs(20, 1, "  store_swap_size = " << store_swap_size);
-	StoreController::store_dirs_rebuilding--;
+        StoreController::store_dirs_rebuilding--;
         assert(0 == StoreController::store_dirs_rebuilding);
 
         if (opt_store_doublecheck)
@@ -184,8 +183,8 @@ storeRebuildStart(void)
     rebuild_start = current_time;
     /*
      * Note: store_dirs_rebuilding is initialized to 1.
-     *  
-     * When we parse the configuration and construct each swap dir, 
+     *
+     * When we parse the configuration and construct each swap dir,
      * the construction of that raises the rebuild count.
      *
      * This prevents us from trying to write clean logs until we
diff --git a/src/store_swapin.cc b/src/store_swapin.cc
index ccd47a9cf4..8e4e325c61 100644
--- a/src/store_swapin.cc
+++ b/src/store_swapin.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -51,8 +51,8 @@ storeSwapInStart(store_client * sc)
         return;
     }
 
-    debugs(20, 3, "storeSwapInStart: called for : " << e->swap_dirn << " " <<  
-           std::hex << std::setw(8) << std::setfill('0') << std::uppercase << 
+    debugs(20, 3, "storeSwapInStart: called for : " << e->swap_dirn << " " <<
+           std::hex << std::setw(8) << std::setfill('0') << std::uppercase <<
            e->swap_filen << " " <<  e->getMD5Text());
 
     if (e->swap_status != SWAPOUT_WRITING && e->swap_status != SWAPOUT_DONE) {
diff --git a/src/store_swapmeta.cc b/src/store_swapmeta.cc
index a38a9aa582..e0742ac706 100644
--- a/src/store_swapmeta.cc
+++ b/src/store_swapmeta.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/src/store_swapout.cc b/src/store_swapout.cc
index cc596dd356..a36daed40b 100644
--- a/src/store_swapout.cc
+++ b/src/store_swapout.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -56,8 +56,8 @@ storeSwapOutStart(StoreEntry * e)
     /* Build the swap metadata, so the filesystem will know how much
      * metadata there is to store
      */
-    debugs(20, 5, "storeSwapOutStart: Begin SwapOut '" << e->url() << "' to dirno " <<  
-           e->swap_dirn << ", fileno " << std::hex << std::setw(8) << std::setfill('0') << 
+    debugs(20, 5, "storeSwapOutStart: Begin SwapOut '" << e->url() << "' to dirno " <<
+           e->swap_dirn << ", fileno " << std::hex << std::setw(8) << std::setfill('0') <<
            std::uppercase << e->swap_filen);
     e->swap_status = SWAPOUT_WRITING;
     /* If we start swapping out objects with OutOfBand Metadata,
@@ -192,7 +192,7 @@ StoreEntry::swapOut()
     debugs(20, 7, HERE << "storeSwapOut: swapout.queue_offset = " << mem_obj->swapout.queue_offset);
 
     if (mem_obj->swapout.sio != NULL)
-    debugs(20, 7, "storeSwapOut: storeOffset() = " << mem_obj->swapout.sio->offset()  );
+        debugs(20, 7, "storeSwapOut: storeOffset() = " << mem_obj->swapout.sio->offset()  );
 
     int64_t swapout_maxsize = mem_obj->endOffset() - mem_obj->swapout.queue_offset;
 
@@ -317,8 +317,8 @@ storeSwapOutFileClosed(void *data, int errflag, StoreIOState::Pointer self)
     cbdataFree(c);
 
     if (errflag) {
-        debugs(20, 1, "storeSwapOutFileClosed: dirno " << e->swap_dirn << ", swapfile " << 
-               std::hex << std::setw(8) << std::setfill('0') << std::uppercase << 
+        debugs(20, 1, "storeSwapOutFileClosed: dirno " << e->swap_dirn << ", swapfile " <<
+               std::hex << std::setw(8) << std::setfill('0') << std::uppercase <<
                e->swap_filen << ", errflag=" << errflag);
         debugs(20, 1, "\t" << xstrerror());
 
@@ -342,8 +342,8 @@ storeSwapOutFileClosed(void *data, int errflag, StoreIOState::Pointer self)
         e->releaseRequest();
     } else {
         /* swapping complete */
-        debugs(20, 3, "storeSwapOutFileClosed: SwapOut complete: '" << e->url() << "' to " << 
-               e->swap_dirn  << ", " << std::hex << std::setw(8) << std::setfill('0') << 
+        debugs(20, 3, "storeSwapOutFileClosed: SwapOut complete: '" << e->url() << "' to " <<
+               e->swap_dirn  << ", " << std::hex << std::setw(8) << std::setfill('0') <<
                std::uppercase << e->swap_filen);
         e->swap_file_sz = e->objectLen() + mem->swap_hdr_sz;
         e->swap_status = SWAPOUT_DONE;
diff --git a/src/test_cache_digest.cc b/src/test_cache_digest.cc
index b51301f041..8a2accef70 100644
--- a/src/test_cache_digest.cc
+++ b/src/test_cache_digest.cc
@@ -20,12 +20,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -38,8 +38,7 @@
 
 #include "squid.h"
 
-typedef struct
-{
+typedef struct {
     int query_count;
     int true_hit_count;
     int true_miss_count;
@@ -49,8 +48,7 @@ typedef struct
 
 typedef struct _Cache Cache;
 
-struct _Cache
-{
+struct _Cache {
     const char *name;
     hash_table *hash;
     CacheDigest *digest;
@@ -63,8 +61,7 @@ struct _Cache
 };
 
 
-typedef struct _CacheEntry
-{
+typedef struct _CacheEntry {
     const cache_key *key;
 
     struct _CacheEntry *next;
@@ -74,8 +71,7 @@ typedef struct _CacheEntry
 
 /* parsed access log entry */
 
-typedef struct
-{
+typedef struct {
     cache_key key[SQUID_MD5_DIGEST_LENGTH];
     time_t timestamp;
     short int use_icp;		/* true/false */
@@ -88,8 +84,7 @@ typedef enum {
 typedef struct _FileIterator FileIterator;
 typedef fr_result(*FI_READER) (FileIterator * fi);
 
-struct _FileIterator
-{
+struct _FileIterator {
     const char *fname;
     FILE *file;
     time_t inner_time;		/* timestamp of the current entry */
@@ -105,17 +100,16 @@ struct _FileIterator
 static time_t cur_time = -1;	/* timestamp of the current log entry */
 
 /* copied from url.c */
-const char *RequestMethodStr[] =
-    {
-        "NONE",
-        "GET",
-        "POST",
-        "PUT",
-        "HEAD",
-        "CONNECT",
-        "TRACE",
-        "PURGE"
-    };
+const char *RequestMethodStr[] = {
+    "NONE",
+    "GET",
+    "POST",
+    "PUT",
+    "HEAD",
+    "CONNECT",
+    "TRACE",
+    "PURGE"
+};
 
 /* copied from url.c */
 static HttpRequestMethod
diff --git a/src/tests/CapturingStoreEntry.h b/src/tests/CapturingStoreEntry.h
index b992020482..b6d534a35e 100644
--- a/src/tests/CapturingStoreEntry.h
+++ b/src/tests/CapturingStoreEntry.h
@@ -18,18 +18,15 @@ public:
     int _buffer_calls;
     int _flush_calls;
 
-    virtual void buffer()
-    {
+    virtual void buffer() {
         _buffer_calls += 1;
     }
 
-    virtual void flush()
-    {
+    virtual void flush() {
         _flush_calls += 1;
     }
 
-    virtual void append(char const * buf, int len)
-    {
+    virtual void append(char const * buf, int len) {
         _appended_text.append(buf, len);
     }
 };
diff --git a/src/tests/stub_DelayId.cc b/src/tests/stub_DelayId.cc
index 34a2785495..99c5fb17cc 100644
--- a/src/tests/stub_DelayId.cc
+++ b/src/tests/stub_DelayId.cc
@@ -20,12 +20,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/src/tests/stub_HttpReply.cc b/src/tests/stub_HttpReply.cc
index 8c3b955226..2a98b3837e 100644
--- a/src/tests/stub_HttpReply.cc
+++ b/src/tests/stub_HttpReply.cc
@@ -20,12 +20,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/src/tests/stub_HttpRequest.cc b/src/tests/stub_HttpRequest.cc
index f4bc033c9d..dc69e76797 100644
--- a/src/tests/stub_HttpRequest.cc
+++ b/src/tests/stub_HttpRequest.cc
@@ -20,12 +20,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/src/tests/stub_MemObject.cc b/src/tests/stub_MemObject.cc
index e1513b93aa..2c0aec2d28 100644
--- a/src/tests/stub_MemObject.cc
+++ b/src/tests/stub_MemObject.cc
@@ -20,12 +20,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -139,7 +139,7 @@ MemObject::write(StoreIOBuffer writeBuffer, STMCB *callback, void *callbackData)
     writeBuffer.offset += (_reply ? _reply->hdr_sz : 0);
 
     /* We don't separate out mime headers yet, so ensure that the first
-     * write is at offset 0 - where they start 
+     * write is at offset 0 - where they start
      */
     assert (data_hdr.endOffset() || writeBuffer.offset == 0);
 
diff --git a/src/tests/stub_access_log.cc b/src/tests/stub_access_log.cc
index 3743681b2e..d793b7b1a0 100644
--- a/src/tests/stub_access_log.cc
+++ b/src/tests/stub_access_log.cc
@@ -20,12 +20,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/src/tests/stub_acl.cc b/src/tests/stub_acl.cc
index d20bb9b4aa..2b33eeafca 100644
--- a/src/tests/stub_acl.cc
+++ b/src/tests/stub_acl.cc
@@ -20,12 +20,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/src/tests/stub_cache_cf.cc b/src/tests/stub_cache_cf.cc
index c88bcb3025..8d76a1d64f 100644
--- a/src/tests/stub_cache_cf.cc
+++ b/src/tests/stub_cache_cf.cc
@@ -20,12 +20,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/src/tests/stub_cache_manager.cc b/src/tests/stub_cache_manager.cc
index e9ec9261c7..b67584e549 100644
--- a/src/tests/stub_cache_manager.cc
+++ b/src/tests/stub_cache_manager.cc
@@ -17,12 +17,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/src/tests/stub_client_side_request.cc b/src/tests/stub_client_side_request.cc
index 2795e81213..b5904c1ba5 100644
--- a/src/tests/stub_client_side_request.cc
+++ b/src/tests/stub_client_side_request.cc
@@ -19,12 +19,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/src/tests/stub_comm.cc b/src/tests/stub_comm.cc
index bf88f01fc1..e9f4fdb70e 100644
--- a/src/tests/stub_comm.cc
+++ b/src/tests/stub_comm.cc
@@ -20,12 +20,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/src/tests/stub_errorpage.cc b/src/tests/stub_errorpage.cc
index ddb5fb424c..797ee854dd 100644
--- a/src/tests/stub_errorpage.cc
+++ b/src/tests/stub_errorpage.cc
@@ -20,12 +20,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/src/tests/stub_fd.cc b/src/tests/stub_fd.cc
index 46ec376a0a..08ba3b6bcb 100644
--- a/src/tests/stub_fd.cc
+++ b/src/tests/stub_fd.cc
@@ -20,12 +20,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/src/tests/stub_helper.cc b/src/tests/stub_helper.cc
index 46f71d7cd1..14f6a26913 100644
--- a/src/tests/stub_helper.cc
+++ b/src/tests/stub_helper.cc
@@ -20,12 +20,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/src/tests/stub_http.cc b/src/tests/stub_http.cc
index 39137d5c3c..2b86c8f502 100644
--- a/src/tests/stub_http.cc
+++ b/src/tests/stub_http.cc
@@ -20,12 +20,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/src/tests/stub_internal.cc b/src/tests/stub_internal.cc
index f3372a0830..afa3369512 100644
--- a/src/tests/stub_internal.cc
+++ b/src/tests/stub_internal.cc
@@ -20,12 +20,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/src/tests/stub_mem_node.cc b/src/tests/stub_mem_node.cc
index 7947136b07..b832192aa3 100644
--- a/src/tests/stub_mem_node.cc
+++ b/src/tests/stub_mem_node.cc
@@ -20,12 +20,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/src/tests/stub_mime.cc b/src/tests/stub_mime.cc
index 635685b3f6..db6c973998 100644
--- a/src/tests/stub_mime.cc
+++ b/src/tests/stub_mime.cc
@@ -20,12 +20,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/src/tests/stub_stat.cc b/src/tests/stub_stat.cc
index 7b75e7e9ac..3f36b10251 100644
--- a/src/tests/stub_stat.cc
+++ b/src/tests/stub_stat.cc
@@ -20,12 +20,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/src/tests/stub_stmem.cc b/src/tests/stub_stmem.cc
index 443607b2cf..8c7b00ec75 100644
--- a/src/tests/stub_stmem.cc
+++ b/src/tests/stub_stmem.cc
@@ -20,12 +20,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/src/tests/stub_store.cc b/src/tests/stub_store.cc
index fd28bcb1bf..bbd46407d5 100644
--- a/src/tests/stub_store.cc
+++ b/src/tests/stub_store.cc
@@ -20,12 +20,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/src/tests/stub_store_client.cc b/src/tests/stub_store_client.cc
index 3482655db5..6c5539b46e 100644
--- a/src/tests/stub_store_client.cc
+++ b/src/tests/stub_store_client.cc
@@ -20,12 +20,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/src/tests/stub_store_rebuild.cc b/src/tests/stub_store_rebuild.cc
index 10ac8440ec..05adc3a2ca 100644
--- a/src/tests/stub_store_rebuild.cc
+++ b/src/tests/stub_store_rebuild.cc
@@ -20,12 +20,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/src/tests/stub_store_swapout.cc b/src/tests/stub_store_swapout.cc
index 549ba9f149..bc29345384 100644
--- a/src/tests/stub_store_swapout.cc
+++ b/src/tests/stub_store_swapout.cc
@@ -20,12 +20,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/src/tests/stub_tools.cc b/src/tests/stub_tools.cc
index 4ed74a8941..c91e638029 100644
--- a/src/tests/stub_tools.cc
+++ b/src/tests/stub_tools.cc
@@ -19,12 +19,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/src/tests/testAuth.cc b/src/tests/testAuth.cc
index 28de16f94a..9cfd4fbd2a 100644
--- a/src/tests/testAuth.cc
+++ b/src/tests/testAuth.cc
@@ -34,10 +34,10 @@ find_proxy_auth(char const *type)
 {
     char const * proxy_auths[][2]= { {"basic","Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="},
 
-                                     {"digest", "Digest username=\"robertdig\", realm=\"Squid proxy-caching web server\", nonce=\"yy8rQXjEWwixXVBj\", uri=\"/images/bg8.gif\", response=\"f75a7d3edd48d93c681c75dc4fb58700\", qop=auth, nc=00000012, cnonce=\"e2216641961e228e\" "},
-                                     {"ntlm", "NTLM "},
-                                     {"negotiate", "Negotiate "}
-                                   };
+        {"digest", "Digest username=\"robertdig\", realm=\"Squid proxy-caching web server\", nonce=\"yy8rQXjEWwixXVBj\", uri=\"/images/bg8.gif\", response=\"f75a7d3edd48d93c681c75dc4fb58700\", qop=auth, nc=00000012, cnonce=\"e2216641961e228e\" "},
+        {"ntlm", "NTLM "},
+        {"negotiate", "Negotiate "}
+    };
 
     for (unsigned count = 0; count < 4 ; count++) {
         if (strcasecmp(type, proxy_auths[count][0]) == 0)
@@ -116,10 +116,10 @@ fake_auth_setup()
     }
 
     params[]={ {"digest", digest_parms, 2},
-               {"basic", basic_parms, 2},
-               {"ntlm", ntlm_parms, 1},
-               {"negotiate", negotiate_parms, 1}
-             };
+        {"basic", basic_parms, 2},
+        {"ntlm", ntlm_parms, 1},
+        {"negotiate", negotiate_parms, 1}
+    };
 
     for (unsigned scheme=0; scheme < 4; scheme++)
         setup_scheme(getConfig(params[scheme].name), params[scheme].params, params[scheme].paramlength);
diff --git a/src/tests/testCoss.cc b/src/tests/testCoss.cc
index f669857716..925bb54997 100644
--- a/src/tests/testCoss.cc
+++ b/src/tests/testCoss.cc
@@ -180,7 +180,7 @@ testCoss::testCossSearch()
     loop.run();
 
     /* cannot use loop.run(); as the loop will never idle: the store-dir
-     * clean() scheduled event prevents it 
+     * clean() scheduled event prevents it
      */
 
     /* nothing left to rebuild */
@@ -268,7 +268,7 @@ testCoss::testCossSearch()
         throw std::runtime_error("Failed to clean test work directory");
 }
 
-/* The COSS store should always configure an IO engine even if none is 
+/* The COSS store should always configure an IO engine even if none is
  * supplied on the configuration line.
  */
 void
diff --git a/src/tests/testDiskIO.cc b/src/tests/testDiskIO.cc
index 7881fe148f..c997d36afd 100644
--- a/src/tests/testDiskIO.cc
+++ b/src/tests/testDiskIO.cc
@@ -1,4 +1,4 @@
-#define SQUID_UNIT_TEST 1 
+#define SQUID_UNIT_TEST 1
 
 #include "squid.h"
 #include 
diff --git a/src/tests/testEvent.cc b/src/tests/testEvent.cc
index e2d233525b..f59994dbe1 100644
--- a/src/tests/testEvent.cc
+++ b/src/tests/testEvent.cc
@@ -43,12 +43,10 @@ testEvent::testCreate()
 
 /* Helper for tests - an event which records the number of calls it received. */
 
-struct CalledEvent
-{
+struct CalledEvent {
     CalledEvent() : calls(0) {}
 
-    static void Handler(void *data)
-    {
+    static void Handler(void *data) {
         static_cast(data)->calls++;
     }
 
@@ -99,15 +97,15 @@ testEvent::testDump()
     /* loop over the strings, showing exactly where they differ (if at all) */
     printf("Actual Text:\n");
     /* TODO: these should really be just [] lookups, but String doesn't have those here yet. */
-    for( int i = 0; i < anEntry->_appended_text.size(); i++) {
+    for ( int i = 0; i < anEntry->_appended_text.size(); i++) {
         CPPUNIT_ASSERT( expect.buf()[i] );
         CPPUNIT_ASSERT( anEntry->_appended_text.buf()[i] );
 
         /* slight hack to make special chars visible */
-        switch(anEntry->_appended_text.buf()[i])
-        {
+        switch (anEntry->_appended_text.buf()[i]) {
         case '\t':
-            printf("\\t"); break;
+            printf("\\t");
+            break;
         default:
             printf("%c", anEntry->_appended_text.buf()[i] );
         }
@@ -142,7 +140,7 @@ testEvent::testCheckEvents()
     CalledEvent event;
     /* with no events, its an idle engine */
     CPPUNIT_ASSERT_EQUAL(int(AsyncEngine::EVENT_IDLE), scheduler.checkEvents(0));
-    /* event running now gets will get sent to the dispatcher and the 
+    /* event running now gets will get sent to the dispatcher and the
      * engine becomes idle.
      */
     scheduler.schedule("test event", CalledEvent::Handler, &event, 0, 0, false);
diff --git a/src/tests/testEventLoop.cc b/src/tests/testEventLoop.cc
index bd9a028f53..37c87e94da 100644
--- a/src/tests/testEventLoop.cc
+++ b/src/tests/testEventLoop.cc
@@ -46,7 +46,7 @@ testEventLoop::testCreate()
 #if POLISHED_MAIN_LOOP
 
 /*
- * Running the loop once is useful for integration with other loops, such as 
+ * Running the loop once is useful for integration with other loops, such as
  * migrating to it in incrementally.
  *
  * This test works by having a custom dispatcher and engine which record how
@@ -58,11 +58,9 @@ class RecordDispatcher : public CompletionDispatcher
 
 public:
     int calls;
-    RecordDispatcher(): calls(0)
-    {}
+    RecordDispatcher(): calls(0) {}
 
-    bool dispatch()
-    {
+    bool dispatch() {
         ++calls;
         /* claim we dispatched calls to be useful for the testStopOnIdle test.
          */
@@ -80,16 +78,14 @@ public:
     int lasttimeout;
     int return_timeout;
     RecordingEngine(int return_timeout=0): calls(0), lasttimeout(0),
-            return_timeout(return_timeout)
-          {}
+            return_timeout(return_timeout) {}
 
-          virtual int checkEvents(int timeout)
-          {
-              ++calls;
-              lasttimeout = timeout;
-              return return_timeout;
-          }
-      };
+    virtual int checkEvents(int timeout) {
+        ++calls;
+        lasttimeout = timeout;
+        return return_timeout;
+    }
+};
 
 #if POLISHED_MAIN_LOOP
 
@@ -123,11 +119,9 @@ class ShutdownDispatcher : public CompletionDispatcher
 public:
     EventLoop &theLoop;
     int calls;
-    ShutdownDispatcher(EventLoop & theLoop):theLoop(theLoop), calls(0)
-    {}
+    ShutdownDispatcher(EventLoop & theLoop):theLoop(theLoop), calls(0) {}
 
-    bool dispatch()
-    {
+    bool dispatch() {
         if (++calls == 2)
             theLoop.stop();
 
@@ -245,8 +239,7 @@ public:
     StubTime() : calls(0) {}
 
     int calls;
-    void tick()
-    {
+    void tick() {
         ++calls;
     }
 };
diff --git a/src/tests/testHttpRequest.cc b/src/tests/testHttpRequest.cc
index 624e0b8dab..1e0c2f4556 100644
--- a/src/tests/testHttpRequest.cc
+++ b/src/tests/testHttpRequest.cc
@@ -139,10 +139,10 @@ testHttpRequest::testIPv6HostColonBug()
     CPPUNIT_ASSERT_EQUAL(expected_port, aRequest->port);
     CPPUNIT_ASSERT(aRequest->method == METHOD_GET);
 #if USE_IPV6
-      /* We hasve fixed this in IPv6 build. */
+    /* We hasve fixed this in IPv6 build. */
     CPPUNIT_ASSERT_EQUAL(String("[2000:800::45]"), String(aRequest->GetHost()));
 #else
-      /* NO fix is possible in IPv4-pure build. */
+    /* NO fix is possible in IPv4-pure build. */
     CPPUNIT_ASSERT_EQUAL(String("2000:800::45"), String(aRequest->GetHost()));
 #endif
     CPPUNIT_ASSERT_EQUAL(String("/foo"), aRequest->urlpath);
diff --git a/src/tests/testHttpRequestMethod.cc b/src/tests/testHttpRequestMethod.cc
index bb0aea291b..6c113dabf1 100644
--- a/src/tests/testHttpRequestMethod.cc
+++ b/src/tests/testHttpRequestMethod.cc
@@ -1,4 +1,4 @@
-#define SQUID_UNIT_TEST 1 
+#define SQUID_UNIT_TEST 1
 
 #include "squid.h"
 #include 
@@ -26,7 +26,7 @@ testHttpRequestMethod::testConstructCharStart()
 }
 
 /*
- * We can also parse precise ranges of characters 
+ * We can also parse precise ranges of characters
  */
 void
 testHttpRequestMethod::testConstructCharStartEnd()
diff --git a/src/tests/testICMP.cc b/src/tests/testICMP.cc
index 749a0a37fb..fd2f3def1f 100644
--- a/src/tests/testICMP.cc
+++ b/src/tests/testICMP.cc
@@ -50,7 +50,7 @@ testICMP::testHops()
     // zero
     CPPUNIT_ASSERT_EQUAL(33, icmp.testHops(0));
 
-        /* test each valid case boundary */
+    /* test each valid case boundary */
     // n(1...32)    : 32 >= n >= 1
     CPPUNIT_ASSERT_EQUAL(32, icmp.testHops(1));
     CPPUNIT_ASSERT_EQUAL(1, icmp.testHops(32));
@@ -75,7 +75,7 @@ testICMP::testHops()
     CPPUNIT_ASSERT_EQUAL(63, icmp.testHops(193));
     CPPUNIT_ASSERT_EQUAL(1, icmp.testHops(255));
 
-        /* test invalid (over values) */
+    /* test invalid (over values) */
     // 256 - produces zero
     CPPUNIT_ASSERT_EQUAL(0, icmp.testHops(256));
     // 257 - produces negative hops
diff --git a/src/tests/testICMP.h b/src/tests/testICMP.h
index da50d6722c..6e43b0be01 100644
--- a/src/tests/testICMP.h
+++ b/src/tests/testICMP.h
@@ -21,7 +21,7 @@ public:
     /// Handle ICMP responses.
     virtual void Recv(void) {};
 
-/* methods to relay test data from tester to private methods being tested */
+    /* methods to relay test data from tester to private methods being tested */
     int testChecksum(unsigned short *ptr, int size) { return CheckSum(ptr,size); };
     int testHops(int ttl) { return ipHops(ttl); };
 };
diff --git a/src/tests/testStore.cc b/src/tests/testStore.cc
index ad9dad4899..6be5f03067 100644
--- a/src/tests/testStore.cc
+++ b/src/tests/testStore.cc
@@ -15,7 +15,7 @@ TestStore::callback()
 StoreEntry*
 
 TestStore::get
-    (const cache_key*)
+(const cache_key*)
 {
     return NULL;
 }
@@ -23,7 +23,7 @@ TestStore::get
 void
 
 TestStore::get
-    (String, void (*)(StoreEntry*, void*), void*)
+(String, void (*)(StoreEntry*, void*), void*)
 {}
 
 void
diff --git a/src/tests/testStore.h b/src/tests/testStore.h
index 5d7f0136e4..804a92f44d 100644
--- a/src/tests/testStore.h
+++ b/src/tests/testStore.h
@@ -46,14 +46,14 @@ public:
     virtual int callback();
 
     virtual StoreEntry* get
-        (const cache_key*);
+    (const cache_key*);
 
     virtual void get
-        (String, void (*)(StoreEntry*, void*), void*);
+    (String, void (*)(StoreEntry*, void*), void*);
 
     virtual void init();
 
-virtual void maintain() {};
+    virtual void maintain() {};
 
     virtual size_t maxSize() const;
 
@@ -61,9 +61,9 @@ virtual void maintain() {};
 
     virtual void stat(StoreEntry &) const; /* output stats to the provided store entry */
 
-    virtual void reference(StoreEntry &){}	/* Reference this object */
+    virtual void reference(StoreEntry &) {}	/* Reference this object */
 
-    virtual void dereference(StoreEntry &){}	/* Unreference this object */
+    virtual void dereference(StoreEntry &) {}	/* Unreference this object */
 
     virtual void updateSize(int64_t size, int sign) {}
 
diff --git a/src/tests/testStoreEntryStream.cc b/src/tests/testStoreEntryStream.cc
index aac6034ab1..ed07fabc43 100644
--- a/src/tests/testStoreEntryStream.cc
+++ b/src/tests/testStoreEntryStream.cc
@@ -41,15 +41,15 @@ testStoreEntryStream::testGetStream()
 
         const int preFlushCount = anEntry->_flush_calls;
         // may have already flushed
-        CPPUNIT_ASSERT(preFlushCount >= 0); 
+        CPPUNIT_ASSERT(preFlushCount >= 0);
         stream.flush();
         // flushed at least once more
         CPPUNIT_ASSERT(anEntry->_flush_calls > preFlushCount);
 
         CPPUNIT_ASSERT_EQUAL(1, anEntry->_buffer_calls);
 
-        CPPUNIT_ASSERT_EQUAL(String("12345677.7 some text   !."), 
-anEntry->_appended_text);
+        CPPUNIT_ASSERT_EQUAL(String("12345677.7 some text   !."),
+                             anEntry->_appended_text);
     }
 
     delete anEntry;
diff --git a/src/tests/testStoreEntryStream.h b/src/tests/testStoreEntryStream.h
index 4561fddd6e..dff1170b17 100644
--- a/src/tests/testStoreEntryStream.h
+++ b/src/tests/testStoreEntryStream.h
@@ -5,7 +5,7 @@
 #include 
 
 /*
- * test StoreEntryStream 
+ * test StoreEntryStream
  */
 
 class testStoreEntryStream : public CPPUNIT_NS::TestFixture
diff --git a/src/tests/testStoreSupport.cc b/src/tests/testStoreSupport.cc
index 0a620d90e6..ae485f69b6 100644
--- a/src/tests/testStoreSupport.cc
+++ b/src/tests/testStoreSupport.cc
@@ -19,12 +19,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/src/tests/testStoreSupport.h b/src/tests/testStoreSupport.h
index e8d89f4f91..dfa6025c4f 100644
--- a/src/tests/testStoreSupport.h
+++ b/src/tests/testStoreSupport.h
@@ -19,12 +19,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/src/tests/testURLScheme.cc b/src/tests/testURLScheme.cc
index 391302cab3..c18bfaad52 100644
--- a/src/tests/testURLScheme.cc
+++ b/src/tests/testURLScheme.cc
@@ -26,7 +26,7 @@ testHttpRequestMethod::testConstructCharStart()
 }
 
 /*
- * We can also parse precise ranges of characters 
+ * We can also parse precise ranges of characters
  */
 void
 testHttpRequestMethod::testConstructCharStartEnd()
@@ -113,7 +113,7 @@ testURLScheme::testConst_str()
 }
 
 /*
- * a URLScheme replaces protocol_t, so we should be able to test for equality on 
+ * a URLScheme replaces protocol_t, so we should be able to test for equality on
  * either the left or right hand side seamlessly.
  */
 void
diff --git a/src/tests/testUfs.cc b/src/tests/testUfs.cc
index eaea635650..58ee2e3429 100644
--- a/src/tests/testUfs.cc
+++ b/src/tests/testUfs.cc
@@ -129,7 +129,7 @@ testUfs::testUfsSearch()
         loop.runOnce();
 
     /* cannot use loop.run(); as the loop will never idle: the store-dir
-     * clean() scheduled event prevents it 
+     * clean() scheduled event prevents it
      */
 
     /* nothing left to rebuild */
@@ -216,7 +216,7 @@ testUfs::testUfsSearch()
         throw std::runtime_error("Failed to clean test work directory");
 }
 
-/* The UFS store should always configure an IO engine even if none is 
+/* The UFS store should always configure an IO engine even if none is
  * supplied on the configuration line.
  */
 void
diff --git a/src/tests/test_http_range.cc b/src/tests/test_http_range.cc
index 717dbe522a..16516d34e3 100644
--- a/src/tests/test_http_range.cc
+++ b/src/tests/test_http_range.cc
@@ -20,12 +20,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/src/time.cc b/src/time.cc
index 2b15c5872a..c59f8d22d4 100644
--- a/src/time.cc
+++ b/src/time.cc
@@ -20,12 +20,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/src/tools.cc b/src/tools.cc
index f2cc309fbc..3ab469e3cf 100644
--- a/src/tools.cc
+++ b/src/tools.cc
@@ -20,12 +20,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -151,7 +151,7 @@ mail_warranty(void)
 
     snprintf(command, 256, "%s %s < %s", Config.EmailProgram, Config.adminEmail, filename);
 
-    if(system(command)) {}		/* XXX should avoid system(3) */
+    if (system(command)) {}		/* XXX should avoid system(3) */
 
     unlink(filename);
 }
@@ -502,8 +502,7 @@ fatalf(const char *fmt,...)
 #else
 void
 fatalf(va_alist)
-va_dcl
-{
+va_dcl {
     va_list args;
     const char *fmt = NULL;
     va_start(args);
@@ -620,11 +619,11 @@ getMyHostname(void)
      * If the first http_port address has a specific address, try a
      * reverse DNS lookup on it.
      */
-    if( !sa.IsAnyAddr() ) {
+    if ( !sa.IsAnyAddr() ) {
 
         sa.GetAddrInfo(AI);
         /* we are looking for a name. */
-        if(xgetnameinfo(AI->ai_addr, AI->ai_addrlen, host, SQUIDHOSTNAMELEN, NULL, 0, NI_NAMEREQD ) == 0) {
+        if (xgetnameinfo(AI->ai_addr, AI->ai_addrlen, host, SQUIDHOSTNAMELEN, NULL, 0, NI_NAMEREQD ) == 0) {
             /* DNS lookup successful */
             /* use the official name from DNS lookup */
             debugs(50, 4, "getMyHostname: resolved " << sa << " to '" << host << "'");
@@ -639,25 +638,23 @@ getMyHostname(void)
 
         sa.FreeAddrInfo(AI);
         debugs(50, 1, "WARNING: failed to resolve " << sa << " to a fully qualified hostname");
-    }
-    else {
+    } else {
         if (gethostname(host, SQUIDHOSTNAMELEN) < 0) {
             debugs(50, 1, "WARNING: gethostname failed: " << xstrerror());
-        }
-        else {
+        } else {
             /* Verify that the hostname given resolves properly */
             struct addrinfo hints;
             memset(&hints, 0, sizeof(addrinfo));
             hints.ai_flags = AI_CANONNAME;
 
-            if(xgetaddrinfo(host, NULL, NULL, &AI) == 0) {
+            if (xgetaddrinfo(host, NULL, NULL, &AI) == 0) {
                 /* DNS lookup successful */
                 /* use the official name from DNS lookup */
                 debugs(50, 6, "getMyHostname: '" << host << "' has rDNS.");
                 present = 1;
 
                 /* AYJ: do we want to flag AI_ALL and cache the result anywhere. ie as our local host IPs? */
-                if(AI) {
+                if (AI) {
                     xfreeaddrinfo(AI);
                     AI = NULL;
                 }
@@ -665,7 +662,7 @@ getMyHostname(void)
                 return host;
             }
 
-            if(AI) xfreeaddrinfo(AI);
+            if (AI) xfreeaddrinfo(AI);
             debugs(50, 1, "WARNING: '" << host << "' rDNS test failed: " << xstrerror());
         }
     }
@@ -1216,7 +1213,7 @@ strwordquote(MemBuf * mb, const char *str)
         mb->append(str, l);
         str += l;
 
-        switch(*str) {
+        switch (*str) {
 
         case '\n':
             mb->append("\\n", 2);
@@ -1281,7 +1278,7 @@ restoreCapabilities(int keep)
     cap->inheritable = 0;
     cap->effective = (1 << CAP_NET_BIND_SERVICE);
 
-    if(IPInterceptor.TransparentActive()) {
+    if (IPInterceptor.TransparentActive()) {
         cap->effective |= (1 << CAP_NET_ADMIN);
 #if LINUX_TPROXY2
         cap->effective |= (1 << CAP_NET_BROADCAST);
diff --git a/src/tunnel.cc b/src/tunnel.cc
index 0722fa584b..81844bbe30 100644
--- a/src/tunnel.cc
+++ b/src/tunnel.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -71,7 +71,7 @@ public:
     {
 
     public:
-        Connection() : len (0),buf ((char *)xmalloc(SQUID_TCP_SO_RCVBUF)), size_ptr(NULL), fd_(-1){}
+        Connection() : len (0),buf ((char *)xmalloc(SQUID_TCP_SO_RCVBUF)), size_ptr(NULL), fd_(-1) {}
 
         ~Connection();
         int const & fd() const { return fd_;}
@@ -136,12 +136,12 @@ tunnelServerClosed(int fd, void *data)
 
     if (tunnelState->noConnections()) {
         tunnelStateFree(tunnelState);
-	return;
+        return;
     }
-    
+
     if (!tunnelState->server.len) {
-	comm_close(tunnelState->client.fd());
-	return;
+        comm_close(tunnelState->client.fd());
+        return;
     }
 }
 
@@ -155,12 +155,12 @@ tunnelClientClosed(int fd, void *data)
 
     if (tunnelState->noConnections()) {
         tunnelStateFree(tunnelState);
-	return;
+        return;
     }
-    
+
     if (!tunnelState->client.len) {
-	comm_close(tunnelState->server.fd());
-	return;
+        comm_close(tunnelState->server.fd());
+        return;
     }
 }
 
@@ -235,7 +235,7 @@ TunnelStateData::readServer(char *buf, size_t len, comm_err_t errcode, int xerrn
 {
     /*
      * Bail out early on COMM_ERR_CLOSING
-     * - close handlers will tidy up for us 
+     * - close handlers will tidy up for us
      */
 
     if (errcode == COMM_ERR_CLOSING)
@@ -261,7 +261,7 @@ TunnelStateData::Connection::error(int const xerrno)
     if (xerrno == COMM_ERR_CLOSING)
         return;
 
-    debugs(50, debugLevelForError(xerrno), "tunnelReadServer: FD " << fd() << 
+    debugs(50, debugLevelForError(xerrno), "tunnelReadServer: FD " << fd() <<
            ": read failure: " << xstrerror());
 
     if (!ignoreErrno(xerrno))
@@ -284,7 +284,7 @@ TunnelStateData::readClient(char *buf, size_t len, comm_err_t errcode, int xerrn
 {
     /*
      * Bail out early on COMM_ERR_CLOSING
-     * - close handlers will tidy up for us 
+     * - close handlers will tidy up for us
      */
 
     if (errcode == COMM_ERR_CLOSING)
@@ -304,13 +304,13 @@ void
 TunnelStateData::copy (size_t len, comm_err_t errcode, int xerrno, Connection &from, Connection &to, IOCB *completion)
 {
     /* I think this is to prevent free-while-in-a-callback behaviour
-     * - RBC 20030229 
+     * - RBC 20030229
      */
     cbdataInternalLock(this);	/* ??? should be locked by the caller... */
 
     /* Bump the server connection timeout on any activity */
     if (server.fd() != -1)
-	commSetTimeout(server.fd(), Config.Timeout.read, tunnelTimeout, this);
+        commSetTimeout(server.fd(), Config.Timeout.read, tunnelTimeout, this);
 
     if (len < 0 || errcode)
         from.error (xerrno);
@@ -476,7 +476,7 @@ tunnelConnectTimeout(int fd, void *data)
             hierarchyNote(&tunnelState->request->hier, tunnelState->servers->code,
                           tunnelState->host);
     } else
-       debugs(26, 1, "tunnelConnectTimeout(): tunnelState->servers is NULL");
+        debugs(26, 1, "tunnelConnectTimeout(): tunnelState->servers is NULL");
 
     err = errorCon(ERR_CONNECT_FAIL, HTTP_SERVICE_UNAVAILABLE, request);
 
diff --git a/src/typedefs.h b/src/typedefs.h
index 987208018a..58be0cb216 100644
--- a/src/typedefs.h
+++ b/src/typedefs.h
@@ -19,12 +19,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -42,8 +42,7 @@ typedef unsigned int swap_status_t;
 typedef signed int sfileno;
 typedef signed int sdirno;
 
-typedef struct
-{
+typedef struct {
     size_t bytes;
     size_t kb;
 } kb_t;
diff --git a/src/ufsdump.cc b/src/ufsdump.cc
index f648a82186..3bfd795502 100644
--- a/src/ufsdump.cc
+++ b/src/ufsdump.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -60,32 +60,30 @@ eventAdd(const char *name, EVH * func, void *arg, double when, int, bool cbdata)
 #endif
 /* end stub functions */
 
-struct MetaStd{
+struct MetaStd {
     time_t timestamp;
-     time_t lastref;
-     time_t expires;
-     time_t lastmod;
-     size_t swap_file_sz;
-     u_short refcount;
-     u_short flags;
+    time_t lastref;
+    time_t expires;
+    time_t lastmod;
+    size_t swap_file_sz;
+    u_short refcount;
+    u_short flags;
 };
 
-struct MetaStdLfs{
-     time_t timestamp;
-     time_t lastref;
-     time_t expires;
-     time_t lastmod;
-     uint64_t swap_file_sz;
-     u_short refcount;
-     u_short flags;
+struct MetaStdLfs {
+    time_t timestamp;
+    time_t lastref;
+    time_t expires;
+    time_t lastmod;
+    uint64_t swap_file_sz;
+    u_short refcount;
+    u_short flags;
 };
 
-struct DumpStoreMeta : public unary_function
-{
-    DumpStoreMeta(){}
+struct DumpStoreMeta : public unary_function {
+    DumpStoreMeta() {}
 
-    void operator()(StoreMeta const &x)
-    {
+    void operator()(StoreMeta const &x) {
         switch (x.getType()) {
 
         case STORE_META_KEY:
@@ -93,17 +91,17 @@ struct DumpStoreMeta : public unary_function
             break;
 
         case STORE_META_STD:
-	    std::cout << "STD, Size:" << ((struct MetaStd*)x.value)->swap_file_sz << 
-		 " Flags: 0x" << std::hex << ((struct MetaStd*)x.value)->flags << std::dec <<
-		 " Refcount: " << ((struct MetaStd*)x.value)->refcount <<
-		 std::endl;
+            std::cout << "STD, Size:" << ((struct MetaStd*)x.value)->swap_file_sz <<
+                      " Flags: 0x" << std::hex << ((struct MetaStd*)x.value)->flags << std::dec <<
+                      " Refcount: " << ((struct MetaStd*)x.value)->refcount <<
+                      std::endl;
             break;
 
         case STORE_META_STD_LFS:
-	     std::cout << "STD_LFS, Size: " << ((struct MetaStdLfs*)x.value)->swap_file_sz <<
-		  " Flags: 0x" << std::hex << ((struct MetaStdLfs*)x.value)->flags << std::dec <<
-		  " Refcount: " << ((struct MetaStdLfs*)x.value)->refcount <<
-		  std::endl;
+            std::cout << "STD_LFS, Size: " << ((struct MetaStdLfs*)x.value)->swap_file_sz <<
+                      " Flags: 0x" << std::hex << ((struct MetaStdLfs*)x.value)->flags << std::dec <<
+                      " Refcount: " << ((struct MetaStdLfs*)x.value)->refcount <<
+                      std::endl;
             break;
 
         case STORE_META_URL:
@@ -112,8 +110,8 @@ struct DumpStoreMeta : public unary_function
             break;
 
         default:
-	     std::cout << "Unknown store meta type: " << (int)x.getType() <<
-		  " of length " << x.length << std::endl;
+            std::cout << "Unknown store meta type: " << (int)x.getType() <<
+                      " of length " << x.length << std::endl;
             break;
         }
     }
@@ -125,8 +123,7 @@ main(int argc, char *argv[])
     int fd = -1;
     StoreMeta *metadata = NULL;
 
-    try
-    {
+    try {
         if (argc != 2)
             throw std::runtime_error("No filename provided");
 
@@ -162,8 +159,7 @@ main(int argc, char *argv[])
 
 
         return 0;
-    } catch (std::runtime_error error)
-    {
+    } catch (std::runtime_error error) {
         std::cout << "Failed : " << error.what() << std::endl;
 
         if (fd >= 0)
diff --git a/src/unlinkd.cc b/src/unlinkd.cc
index 61e26baaf4..e5fedb9ef9 100644
--- a/src/unlinkd.cc
+++ b/src/unlinkd.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -70,17 +70,17 @@ unlinkdUnlink(const char *path)
      */
     if (queuelen >= UNLINKD_QUEUE_LIMIT) {
 #if defined(USE_EPOLL) || defined(USE_KQUEUE)
-	/*
-	 * DPW 2007-04-23
-	 * We can't use fd_set when using epoll() or kqueue().  In
-	 * these cases we block for 10 ms.
-	 */
-	xusleep(10000);
+        /*
+         * DPW 2007-04-23
+         * We can't use fd_set when using epoll() or kqueue().  In
+         * these cases we block for 10 ms.
+         */
+        xusleep(10000);
 #else
-	/*
-	 * DPW 2007-04-23
-	 * When we can use select, block for up to 100 ms.
-	 */
+        /*
+         * DPW 2007-04-23
+         * When we can use select, block for up to 100 ms.
+         */
         struct timeval to;
         fd_set R;
         FD_ZERO(&R);
@@ -145,8 +145,7 @@ unlinkdClose(void)
 #ifdef _SQUID_MSWIN_
 {
 
-    if (unlinkd_wfd > -1)
-    {
+    if (unlinkd_wfd > -1) {
         debugs(2, 1, "Closing unlinkd pipe on FD " << unlinkd_wfd);
         shutdown(unlinkd_wfd, SD_BOTH);
         comm_close(unlinkd_wfd);
@@ -160,8 +159,7 @@ unlinkdClose(void)
     } else
         debugs(2, 0, "unlinkdClose: WARNING: unlinkd_wfd is " << unlinkd_wfd);
 
-    if (hIpc)
-    {
+    if (hIpc) {
         if (WaitForSingleObject(hIpc, 5000) != WAIT_OBJECT_0) {
             getCurrentTime();
             debugs(2, 1, "unlinkdClose: WARNING: (unlinkd," << pid << "d) didn't exit in 5 seconds");
@@ -205,11 +203,11 @@ unlinkdInit(void)
               /* pipes and poll() don't get along on DUNIX -DW */
               IPC_STREAM,
 #elif defined(_SQUID_MSWIN_)
-/* select() will fail on a pipe */
-IPC_TCP_SOCKET,
+              /* select() will fail on a pipe */
+              IPC_TCP_SOCKET,
 #else
-/* We currently need to use FIFO.. see below */
-IPC_FIFO,
+              /* We currently need to use FIFO.. see below */
+              IPC_FIFO,
 #endif
               Config.Program.unlinkd,
               args,
diff --git a/src/unlinkd_daemon.cc b/src/unlinkd_daemon.cc
index 2b21975dd2..a29ced5883 100644
--- a/src/unlinkd_daemon.cc
+++ b/src/unlinkd_daemon.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/src/url.cc b/src/url.cc
index 00eabb1178..162fc03e77 100644
--- a/src/url.cc
+++ b/src/url.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -180,7 +180,7 @@ urlDefaultPort(protocol_t p)
  * If the 'request' arg is non-NULL, put parsed values there instead
  * of allocating a new HttpRequest.
  *
- * This abuses HttpRequest as a way of representing the parsed url 
+ * This abuses HttpRequest as a way of representing the parsed url
  * and its components.
  * method is used to switch parsers and to init the HttpRequest.
  * If method is METHOD_CONNECT, then rather than a URL a hostname:port is
@@ -236,7 +236,7 @@ urlParse(const HttpRequestMethod& method, char *url, HttpRequest *request)
             *dst = *src;
         }
         if (i >= l)
-           return NULL;
+            return NULL;
         *dst = '\0';
 
         /* Then its :// */
@@ -252,7 +252,7 @@ urlParse(const HttpRequestMethod& method, char *url, HttpRequest *request)
             *dst = *src;
         }
 
-        /* 
+        /*
          * We can't check for "i >= l" here because we could be at the end of the line
          * and have a perfectly valid URL w/ no trailing '/'. In this case we assume we've
          * been -given- a valid URL and the path is just '/'.
@@ -287,12 +287,13 @@ urlParse(const HttpRequestMethod& method, char *url, HttpRequest *request)
         }
 
         /* Is there any host information? (we should eventually parse it above) */
-        if(*host == '[') {
+        if (*host == '[') {
             /* strip any IPA brackets. valid under IPv6. */
             dst = host;
 #if USE_IPV6
             /* only for IPv6 sadly, pre-IPv6/URL code can't handle the clean result properly anyway. */
-            src = host; src++;
+            src = host;
+            src++;
             l = strlen(host);
             i = 1;
             for (; i < l && *src != ']' && *src != '\0'; i++, src++, dst++) {
@@ -303,16 +304,16 @@ urlParse(const HttpRequestMethod& method, char *url, HttpRequest *request)
             *(dst++) = '\0';
 #else
             /* IPv4-pure needs to skip the whole hostname to ']' inclusive for now */
-            while(*dst != '\0' && *dst != ']') dst++;
+            while (*dst != '\0' && *dst != ']') dst++;
 #endif
 
             /* skip ahead to either start of port, or original EOS */
-            while(*dst != '\0' && *dst != ':') dst++;
+            while (*dst != '\0' && *dst != ':') dst++;
             t = dst;
         } else {
             t = strrchr(host, ':');
 
-            if(t != strchr(host,':') ) {
+            if (t != strchr(host,':') ) {
                 /* RFC 2732 states IPv6 "SHOULD" be bracketed. allowing for times when its not. */
                 /* RFC 3986 'update' simply modifies this to an "is" with no emphasis at all! */
                 /* therefore we MUST accept the case where they are not bracketed at all. */
@@ -321,7 +322,8 @@ urlParse(const HttpRequestMethod& method, char *url, HttpRequest *request)
         }
 
         if (t && *t == ':') {
-            *t = '\0'; t++;
+            *t = '\0';
+            t++;
             port = atoi(t);
         }
     }
@@ -486,7 +488,7 @@ urlCanonicalClean(const HttpRequest * request)
         switch (request->method.id()) {
 
         case METHOD_CONNECT:
-            snprintf(buf, MAX_URL, "%s:%d", 
+            snprintf(buf, MAX_URL, "%s:%d",
                      request->GetHost(),
                      request->port);
             break;
@@ -578,31 +580,31 @@ urlMakeAbsolute(const HttpRequest * req, const char *relUrl)
     if (req->method.id() == METHOD_CONNECT) {
         return (NULL);
     }
-    
+
     char *urlbuf = (char *)xmalloc(MAX_URL * sizeof(char));
-    
+
     if (req->protocol == PROTO_URN) {
         snprintf(urlbuf, MAX_URL, "urn:%s", req->urlpath.buf());
         return (urlbuf);
     }
-        
+
     size_t urllen;
 
     if (req->port != urlDefaultPort(req->protocol)) {
         urllen = snprintf(urlbuf, MAX_URL, "%s://%s%s%s:%d",
-            ProtocolStr[req->protocol],
-            req->login,
-            *req->login ? "@" : null_string,
-            req->GetHost(),
-            req->port
-        );
+                          ProtocolStr[req->protocol],
+                          req->login,
+                          *req->login ? "@" : null_string,
+                          req->GetHost(),
+                          req->port
+                         );
     } else {
         urllen = snprintf(urlbuf, MAX_URL, "%s://%s%s%s",
-            ProtocolStr[req->protocol],
-            req->login,
-            *req->login ? "@" : null_string,
-            req->GetHost()
-        );
+                          ProtocolStr[req->protocol],
+                          req->login,
+                          *req->login ? "@" : null_string,
+                          req->GetHost()
+                         );
     }
 
     if (relUrl[0] == '/') {
@@ -612,7 +614,7 @@ urlMakeAbsolute(const HttpRequest * req, const char *relUrl)
         const char *last_slash = strrchr(path, '/');
 
         if (last_slash == NULL) {
-               urlbuf[urllen++] = '/';
+            urlbuf[urllen++] = '/';
             strncpy(&urlbuf[urllen], relUrl, MAX_URL - urllen - 1);
         } else {
             last_slash++;
@@ -634,7 +636,7 @@ urlMakeAbsolute(const HttpRequest * req, const char *relUrl)
 /*
  * matchDomainName() compares a hostname with a domainname according
  * to the following rules:
- * 
+ *
  *    HOST          DOMAIN        MATCH?
  * ------------- -------------    ------
  *    foo.com       foo.com         YES
diff --git a/src/urn.cc b/src/urn.cc
index e03081030e..53b20f0c35 100644
--- a/src/urn.cc
+++ b/src/urn.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -68,8 +68,7 @@ public:
     HttpRequest *request;
     HttpRequest *urlres_r;
 
-    struct
-    {
+    struct {
         unsigned int force_menu:1;
     } flags;
     char reqbuf[URN_REQBUF_SZ];
@@ -79,14 +78,12 @@ private:
     char *urlres;
 };
 
-typedef struct
-{
+typedef struct {
     char *url;
     char *host;
     int rtt;
 
-    struct
-    {
+    struct {
         int cached;
     } flags;
 } url_entry;
@@ -159,8 +156,8 @@ urnFindMinRtt(url_entry * urls, const HttpRequestMethod& m, int *rtt_ret)
         *rtt_ret = min_rtt;
 
     debugs(52, 1, "urnFindMinRtt: Returning '" <<
-                  (min_u ? min_u->url : "NONE") << "' RTT " << 
-                  min_rtt  );
+           (min_u ? min_u->url : "NONE") << "' RTT " <<
+           min_rtt  );
 
     return min_u;
 }
@@ -171,8 +168,8 @@ UrnState::getHost (String &urlpath)
     char * result;
     char const *t;
 
-/* FIXME: this appears to be parsing the URL. *very* badly. */
-/* FIXME: a proper encapsulated URI/URL type needs to clear this up. */
+    /* FIXME: this appears to be parsing the URL. *very* badly. */
+    /* FIXME: a proper encapsulated URI/URL type needs to clear this up. */
 
     if ((t = urlpath.pos(':')) != NULL) {
         urlpath.set(t, '\0');
diff --git a/src/useragent.cc b/src/useragent.cc
index 17affe7aab..0f6fa100bc 100644
--- a/src/useragent.cc
+++ b/src/useragent.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/src/wccp.cc b/src/wccp.cc
index c99e9f7440..cde240dac7 100644
--- a/src/wccp.cc
+++ b/src/wccp.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -49,8 +49,7 @@
 #define WCCP_I_SEE_YOU 8
 #define WCCP_ASSIGN_BUCKET 9
 
-struct wccp_here_i_am_t
-{
+struct wccp_here_i_am_t {
     int type;
     int version;
     int revision;
@@ -59,16 +58,14 @@ struct wccp_here_i_am_t
     int id;
 };
 
-struct wccp_cache_entry_t
-{
+struct wccp_cache_entry_t {
     IPAddress ip_addr;
     int revision;
     char hash[WCCP_HASH_SIZE];
     int reserved;
 };
 
-struct wccp_i_see_you_t
-{
+struct wccp_i_see_you_t {
     int type;
     int version;
     int change;
@@ -78,8 +75,7 @@ struct wccp_i_see_you_t
     struct wccp_cache_entry_t wccp_cache_entry[WCCP_ACTIVE_CACHES];
 };
 
-struct wccp_assign_bucket_t
-{
+struct wccp_assign_bucket_t {
     int type;
     int id;
     int number;
@@ -222,7 +218,7 @@ wccpHandleUdp(int sock, void *not_used)
                             0,
                             from);
     debugs(80, 3, "wccpHandleUdp: " << len << " bytes WCCP pkt from " << from <<
-            ": type=" <<
+           ": type=" <<
            (unsigned) ntohl(wccp_i_see_you.type) << ", version=" <<
            (unsigned) ntohl(wccp_i_see_you.version) << ", change=" <<
            (unsigned) ntohl(wccp_i_see_you.change) << ", id=" <<
diff --git a/src/wccp2.cc b/src/wccp2.cc
index f70e87d0af..33ec543563 100644
--- a/src/wccp2.cc
+++ b/src/wccp2.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -134,8 +134,7 @@ static EVH wccp2AssignBuckets;
 /* WCCP v2 packet header */
 
 /// \interface WCCPv2_Protocol
-struct wccp2_here_i_am_header_t
-{
+struct wccp2_here_i_am_header_t {
     uint32_t type;
     uint16_t version;
     uint16_t length;
@@ -145,16 +144,14 @@ static struct wccp2_here_i_am_header_t wccp2_here_i_am_header;
 
 /* Security struct for the "no security" option */
 
-struct wccp2_security_none_t
-{
+struct wccp2_security_none_t {
     uint16_t security_type;
     uint16_t security_length;
     uint32_t security_option;
 };
 
 /// \interface WCCPv2_Protocol
-struct wccp2_security_md5_t
-{
+struct wccp2_security_md5_t {
     uint16_t security_type;
     uint16_t security_length;
     uint32_t security_option;
@@ -164,8 +161,7 @@ struct wccp2_security_md5_t
 /* Service info struct */
 
 /// \interface WCCPv2_Protocol
-struct wccp2_service_info_t
-{
+struct wccp2_service_info_t {
     uint16_t service_type;
     uint16_t service_length;
     uint8_t service;
@@ -184,8 +180,7 @@ struct wccp2_service_info_t
 };
 
 /// \interface WCCPv2_Protocol
-struct wccp2_cache_identity_info_t
-{
+struct wccp2_cache_identity_info_t {
     struct in_addr addr;
     uint16_t hash_revision;
     char bits[2];
@@ -197,8 +192,7 @@ struct wccp2_cache_identity_info_t
 /* Web Cache identity info */
 
 /// \interface WCCPv2_Protocol
-struct wccp2_identity_info_t
-{
+struct wccp2_identity_info_t {
     uint16_t cache_identity_type;
     uint16_t cache_identity_length;
 
@@ -208,8 +202,7 @@ struct wccp2_identity_info_t
 static struct wccp2_identity_info_t wccp2_identity_info;
 
 /// \interface WCCPv2_Protocol
-struct wccp2_cache_mask_identity_info_t
-{
+struct wccp2_cache_mask_identity_info_t {
     struct in_addr addr;
     uint32_t num1;
     uint32_t num2;
@@ -224,8 +217,7 @@ struct wccp2_cache_mask_identity_info_t
 /* Web Cache identity info */
 
 /// \interface WCCPv2_Protocol
-struct wccp2_mask_identity_info_t
-{
+struct wccp2_mask_identity_info_t {
     uint16_t cache_identity_type;
     uint16_t cache_identity_length;
 
@@ -237,8 +229,7 @@ static struct wccp2_mask_identity_info_t wccp2_mask_identity_info;
 /* View header */
 
 /// \interface WCCPv2_Protocol
-struct wccp2_cache_view_header_t
-{
+struct wccp2_cache_view_header_t {
     uint16_t cache_view_type;
     uint16_t cache_view_length;
     uint32_t cache_view_version;
@@ -249,8 +240,7 @@ static struct wccp2_cache_view_header_t wccp2_cache_view_header;
 /* View info */
 
 /// \interface WCCPv2_Protocol
-struct wccp2_cache_view_info_t
-{
+struct wccp2_cache_view_info_t {
     uint32_t num_routers;
     uint32_t num_caches;
 };
@@ -260,8 +250,7 @@ static struct wccp2_cache_view_info_t wccp2_cache_view_info;
 /* Router ID element */
 
 /// \interface WCCPv2_Protocol
-struct wccp2_router_id_element_t
-{
+struct wccp2_router_id_element_t {
     struct in_addr router_address;
     uint32_t received_id;
 };
@@ -271,8 +260,7 @@ static struct wccp2_router_id_element_t wccp2_router_id_element;
 /* Capability info header */
 
 /// \interface WCCpv2_Protocol
-struct wccp2_capability_info_header_t
-{
+struct wccp2_capability_info_header_t {
     uint16_t capability_info_type;
     uint16_t capability_info_length;
 };
@@ -282,8 +270,7 @@ static struct wccp2_capability_info_header_t wccp2_capability_info_header;
 /* Capability element header */
 
 /// \interface WCCPv2_Protocol
-struct wccp2_capability_element_header_t
-{
+struct wccp2_capability_element_header_t {
     uint16_t capability_type;
     uint16_t capability_length;
 };
@@ -291,8 +278,7 @@ struct wccp2_capability_element_header_t
 /* Capability element */
 
 /// \interface WCCPv2_Protocol
-struct wccp2_capability_element_t
-{
+struct wccp2_capability_element_t {
     uint16_t capability_type;
     uint16_t capability_length;
     uint32_t capability_value;
@@ -303,8 +289,7 @@ static struct wccp2_capability_element_t wccp2_capability_element;
 /* Mask Element */
 
 /// \interface WCCPv2_Protocol
-struct wccp2_mask_element_t
-{
+struct wccp2_mask_element_t {
     uint32_t source_ip_mask;
     uint32_t dest_ip_mask;
     uint16_t source_port_mask;
@@ -315,8 +300,7 @@ struct wccp2_mask_element_t
 /* Value Element */
 
 /// \interface WCCPv2_Protocol
-struct wccp2_value_element_t
-{
+struct wccp2_value_element_t {
     uint32_t source_ip_value;
     uint32_t dest_ip_value;
     uint16_t source_port_value;
@@ -328,8 +312,7 @@ struct wccp2_value_element_t
 /* RECEIVED PACKET STRUCTURE */
 
 /// \interface WCCPv2_Protocol
-struct wccp2_i_see_you_t
-{
+struct wccp2_i_see_you_t {
     uint32_t type;
     uint16_t version;
     uint16_t length;
@@ -341,8 +324,7 @@ static struct wccp2_i_see_you_t wccp2_i_see_you;
 /* Router ID element */
 
 /// \interface WCCPv2_Protocol
-struct wccp2_router_assign_element_t
-{
+struct wccp2_router_assign_element_t {
     struct in_addr router_address;
     uint32_t received_id;
     uint32_t change_number;
@@ -351,8 +333,7 @@ struct wccp2_router_assign_element_t
 /* Generic header struct */
 
 /// \interface WCCPv2_Protocol
-struct wccp2_item_header_t
-{
+struct wccp2_item_header_t {
     uint16_t type;
     uint16_t length;
 };
@@ -360,8 +341,7 @@ struct wccp2_item_header_t
 /* Router identity struct */
 
 /// \interface WCCPv2_Protocol
-struct router_identity_info_t
-{
+struct router_identity_info_t {
 
     struct wccp2_item_header_t header;
 
@@ -374,8 +354,7 @@ struct router_identity_info_t
 /* The received packet for a mask assignment is unusual */
 
 /// \interface WCCPv2_Protocol
-struct cache_mask_info_t
-{
+struct cache_mask_info_t {
     struct in_addr addr;
     uint32_t num1;
     uint32_t num2;
@@ -385,8 +364,7 @@ struct cache_mask_info_t
 /* assigment key */
 
 /// \interface WCCPv2_Protocol
-struct assignment_key_t
-{
+struct assignment_key_t {
     struct in_addr master_ip;
     uint32_t master_number;
 };
@@ -394,8 +372,7 @@ struct assignment_key_t
 /* Router view of WCCP */
 
 /// \interface WCCPv2_Protocol
-struct router_view_t
-{
+struct router_view_t {
 
     struct wccp2_item_header_t header;
     uint32_t change_number;
@@ -406,8 +383,7 @@ struct router_view_t
 /* Lists used to keep track of caches, routers and services */
 
 /// \interface WCCPv2_Protocol
-struct wccp2_cache_list_t
-{
+struct wccp2_cache_list_t {
 
     struct in_addr cache_ip;
 
@@ -417,8 +393,7 @@ struct wccp2_cache_list_t
 };
 
 /// \interface WCCPv2_Protocol
-struct wccp2_router_list_t
-{
+struct wccp2_router_list_t {
 
     struct wccp2_router_id_element_t *info;
 
@@ -436,8 +411,7 @@ struct wccp2_router_list_t
 static int wccp2_numrouters;
 
 /// \interface WCCPv2_Protocol
-struct wccp2_service_list_t
-{
+struct wccp2_service_list_t {
 
     struct wccp2_service_info_t info;
     uint32_t num_routers;
@@ -461,8 +435,7 @@ struct wccp2_service_list_t
 
 static struct wccp2_service_list_t *wccp2_service_list_head = NULL;
 
-int empty_portlist[WCCP2_NUMPORTS] =
-    {0, 0, 0, 0, 0, 0, 0, 0};
+int empty_portlist[WCCP2_NUMPORTS] = {0, 0, 0, 0, 0, 0, 0, 0};
 
 /* END WCCP V2 */
 void wccp2_add_service_list(int service, int service_id, int service_priority,
@@ -531,15 +504,13 @@ wccp2_add_service_list(int service, int service_id, int service_priority,
 }
 
 static struct wccp2_service_list_t *
-            wccp2_get_service_by_id(int service, int service_id)
-{
+            wccp2_get_service_by_id(int service, int service_id) {
 
     struct wccp2_service_list_t *p;
 
     p = wccp2_service_list_head;
 
-    while (p != NULL)
-    {
+    while (p != NULL) {
         if (p->info.service == service && p->info.service_id == service_id) {
             return p;
         }
@@ -618,19 +589,16 @@ wccp2_check_security(struct wccp2_service_list_t *srv, char *security, char *pac
 
     /* Make sure the security type matches what we expect */
 
-    if (ntohl(ws->security_option) != srv->wccp2_security_type)
-    {
+    if (ntohl(ws->security_option) != srv->wccp2_security_type) {
         debugs(80, 1, "wccp2_check_security: received packet has the wrong security option");
         return 0;
     }
 
-    if (srv->wccp2_security_type == WCCP2_NO_SECURITY)
-    {
+    if (srv->wccp2_security_type == WCCP2_NO_SECURITY) {
         return 1;
     }
 
-    if (srv->wccp2_security_type != WCCP2_MD5_SECURITY)
-    {
+    if (srv->wccp2_security_type != WCCP2_MD5_SECURITY) {
         debugs(80, 1, "wccp2_check_security: invalid security option");
         return 0;
     }
@@ -981,7 +949,7 @@ wccp2ConnectionOpen(void)
         return;
     }
 
-    if( !Config.Wccp2.address.SetIPv4() ) {
+    if ( !Config.Wccp2.address.SetIPv4() ) {
         debugs(80, 0, "WCCPv2 Disabled. " << Config.Wccp2.address << " is not an IPv4 address.");
         return;
     }
@@ -1170,14 +1138,16 @@ wccp2HandleUdp(int sock, void *not_used)
 
     commSetSelect(sock, COMM_SELECT_READ, wccp2HandleUdp, NULL, 0);
 
-/* FIXME INET6 : drop conversion boundary */ IPAddress from_tmp;
+    /* FIXME INET6 : drop conversion boundary */
+    IPAddress from_tmp;
 
     len = comm_udp_recvfrom(sock,
                             &wccp2_i_see_you,
                             WCCP_RESPONSE_SIZE,
                             0,
                             from_tmp);
-/* FIXME INET6 : drop conversion boundary */ from_tmp.GetSockAddr(from);
+    /* FIXME INET6 : drop conversion boundary */
+    from_tmp.GetSockAddr(from);
 
     if (len < 0)
         return;
@@ -1969,7 +1939,8 @@ wccp2AssignBuckets(void *voidnotused)
                 /* send packet */
 
                 if (wccp2_numrouters > 1) {
-/* FIXME INET6 : drop temp conversion */ IPAddress tmp_rtr(router);
+                    /* FIXME INET6 : drop temp conversion */
+                    IPAddress tmp_rtr(router);
                     comm_udp_sendto(theWccp2Connection,
                                     tmp_rtr,
                                     &wccp_packet,
@@ -2022,8 +1993,7 @@ parse_wccp2_method(int *method)
 void
 dump_wccp2_method(StoreEntry * e, const char *label, int v)
 {
-    switch(v)
-    {
+    switch (v) {
     case WCCP2_METHOD_GRE:
         storeAppendPrintf(e, "%s gre\n", label);
         break;
@@ -2070,8 +2040,7 @@ parse_wccp2_amethod(int *method)
 void
 dump_wccp2_amethod(StoreEntry * e, const char *label, int v)
 {
-    switch(v)
-    {
+    switch (v) {
     case WCCP2_ASSIGNMENT_METHOD_HASH:
         storeAppendPrintf(e, "%s hash\n", label);
         break;
@@ -2501,27 +2470,27 @@ wccp2SortCacheList(struct wccp2_cache_list_t *head)
 
     /* Go through each position in the list one at a time */
     for (this_item = head; this_item->next; this_item = this_item->next) {
-	/* Find the item with the lowest IP */
-	next_lowest = this_item;
-
-	for (find_item = this_item; find_item->next; find_item = find_item->next) {
-	    if (find_item->cache_ip.s_addr < next_lowest->cache_ip.s_addr) {
-		next_lowest = find_item;
-	    }
-	}
-	/* Swap if we need to */
-	if (next_lowest != this_item) {
-	    /* First make a copy of the current item */
-	    memcpy(&tmp, this_item, sizeof(struct wccp2_cache_list_t));
-
-	    /* Next update the pointers to maintain the linked list */
-	    tmp.next = next_lowest->next;
-	    next_lowest->next = this_item->next;
-
-	    /* Finally copy the updated items to their correct location */
-	    memcpy(this_item, next_lowest, sizeof(struct wccp2_cache_list_t));
-	    memcpy(next_lowest, &tmp, sizeof(struct wccp2_cache_list_t));
-	}
+        /* Find the item with the lowest IP */
+        next_lowest = this_item;
+
+        for (find_item = this_item; find_item->next; find_item = find_item->next) {
+            if (find_item->cache_ip.s_addr < next_lowest->cache_ip.s_addr) {
+                next_lowest = find_item;
+            }
+        }
+        /* Swap if we need to */
+        if (next_lowest != this_item) {
+            /* First make a copy of the current item */
+            memcpy(&tmp, this_item, sizeof(struct wccp2_cache_list_t));
+
+            /* Next update the pointers to maintain the linked list */
+            tmp.next = next_lowest->next;
+            next_lowest->next = this_item->next;
+
+            /* Finally copy the updated items to their correct location */
+            memcpy(this_item, next_lowest, sizeof(struct wccp2_cache_list_t));
+            memcpy(next_lowest, &tmp, sizeof(struct wccp2_cache_list_t));
+        }
     }
 }
 
diff --git a/src/whois.cc b/src/whois.cc
index 9bbd8ca165..cfab852e56 100644
--- a/src/whois.cc
+++ b/src/whois.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/src/win32.cc b/src/win32.cc
index 309f811f31..9e437f0e5c 100644
--- a/src/win32.cc
+++ b/src/win32.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -119,8 +119,7 @@ int WIN32_getrusage(int who, struct rusage *usage)
 #if HAVE_WIN32_PSAPI
 
     if ((WIN32_OS_version == _WIN_OS_WINNT) || (WIN32_OS_version == _WIN_OS_WIN2K)
-            || (WIN32_OS_version == _WIN_OS_WINXP) || (WIN32_OS_version == _WIN_OS_WINNET))
-    {
+            || (WIN32_OS_version == _WIN_OS_WINXP) || (WIN32_OS_version == _WIN_OS_WINNET)) {
         /* On Windows NT/2000 call PSAPI.DLL for process Memory */
         /* informations -- Guido Serassio                       */
         HANDLE hProcess;
@@ -134,9 +133,9 @@ int WIN32_getrusage(int who, struct rusage *usage)
             FILETIME ftCreate, ftExit, ftKernel, ftUser;
 
             if (GetProcessTimes(hProcess, &ftCreate, &ftExit, &ftKernel, &ftUser)) {
-		int64_t *ptUser = (int64_t *)&ftUser;
+                int64_t *ptUser = (int64_t *)&ftUser;
                 int64_t tUser64 = *ptUser / 10;
-		int64_t *ptKernel = (int64_t *)&ftKernel;
+                int64_t *ptKernel = (int64_t *)&ftKernel;
                 int64_t tKernel64 = *ptKernel / 10;
                 usage->ru_utime.tv_sec =(long)(tUser64 / 1000000);
                 usage->ru_stime.tv_sec =(long)(tKernel64 / 1000000);
@@ -165,7 +164,7 @@ int WIN32_getrusage(int who, struct rusage *usage)
 
 
 int Win32__WSAFDIsSet(int fd, fd_set FAR * set
-                         )
+                     )
 {
     fde *F = &fd_table[fd];
     SOCKET s = F->win32.handle;
diff --git a/src/wordlist.cc b/src/wordlist.cc
index a8d601073c..173f32ba1c 100644
--- a/src/wordlist.cc
+++ b/src/wordlist.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/src/wordlist.h b/src/wordlist.h
index dd40e8b3d9..633a639688 100644
--- a/src/wordlist.h
+++ b/src/wordlist.h
@@ -18,12 +18,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/test-suite/ESIExpressions.cc b/test-suite/ESIExpressions.cc
index 6d2e2bc176..815c2fc39c 100644
--- a/test-suite/ESIExpressions.cc
+++ b/test-suite/ESIExpressions.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -40,25 +40,26 @@ int
 main ()
 {
     char const *expressions[] = {
-                                    "!(1==1)", "!(1!=1)", "1!=1", "!1==1", "1==1",
-                                    "1 <=1","2<=1", "1 < 1", "1 < 2", "-1 < 1","!-1<1",
-                                    "1>2","2>1","2>=2", "2>3", "1==1&1==1","1==1&1==0",
-                                    "!('a'<='c')",
-                                    "(1==1)|('abc'=='def')",
-                                    "(4!=5)&(4==5)",
-                                    "(1==1)|(2==3)&(3==4)",	/* should be true because of precedence */
-                                    "(1 & 4)",
-                                    "(\"abc\" | \"edf\")", "1==1==1",
-                                    "!('')",
-                                    /* End of array */""
-                                };
+        "!(1==1)", "!(1!=1)", "1!=1", "!1==1", "1==1",
+        "1 <=1","2<=1", "1 < 1", "1 < 2", "-1 < 1","!-1<1",
+        "1>2","2>1","2>=2", "2>3", "1==1&1==1","1==1&1==0",
+        "!('a'<='c')",
+        "(1==1)|('abc'=='def')",
+        "(4!=5)&(4==5)",
+        "(1==1)|(2==3)&(3==4)",	/* should be true because of precedence */
+        "(1 & 4)",
+        "(\"abc\" | \"edf\")", "1==1==1",
+        "!('')",
+        /* End of array */""
+    };
 
     int results[] = {0, 1, 0, 0, 1,
                      1, 0, 0, 1, 1,
                      0, 0, 1, 1, 0,
                      1, 0, 0, 1, 0,
                      1, 0, 0, 0, 0,
-                     1, 0};
+                     1, 0
+                    };
 
     int i = 0;
 
diff --git a/test-suite/MemPoolTest.cc b/test-suite/MemPoolTest.cc
index fb9ed20aab..bff7962a0c 100644
--- a/test-suite/MemPoolTest.cc
+++ b/test-suite/MemPoolTest.cc
@@ -19,12 +19,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -44,15 +44,17 @@ xassert(const char *msg, const char *file, int line)
     exit (1);
 }
 
-class MemPoolTest {
+class MemPoolTest
+{
 public:
-	void run();
+    void run();
 private:
-  class SomethingToAlloc {
-	  public:
-		  int aValue;
-  };
-  static MemAllocator *Pool;
+    class SomethingToAlloc
+    {
+    public:
+        int aValue;
+    };
+    static MemAllocator *Pool;
 };
 MemAllocator *MemPoolTest::Pool = NULL;
 
diff --git a/test-suite/StackTest.cc b/test-suite/StackTest.cc
index 03f24fc258..eadf1fb3c6 100644
--- a/test-suite/StackTest.cc
+++ b/test-suite/StackTest.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/test-suite/VirtualDeleteOperator.cc b/test-suite/VirtualDeleteOperator.cc
index 85a7a0f727..c653972fb8 100644
--- a/test-suite/VirtualDeleteOperator.cc
+++ b/test-suite/VirtualDeleteOperator.cc
@@ -20,12 +20,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -36,14 +36,15 @@
 #include "squid.h"
 #include 
 
-class CallCounter {
-  public:
+class CallCounter
+{
+public:
     CallCounter();
     void recordNew();
     void recordDelete();
     size_t news() const;
     size_t deletes() const;
-  private:
+private:
     size_t _news, _deletes;
 };
 
@@ -54,8 +55,9 @@ void CallCounter::recordDelete() { ++_deletes;}
 size_t CallCounter::news() const {return _news;}
 size_t CallCounter::deletes() const {return _deletes;}
 
-class BaseVirtual {
-  public:
+class BaseVirtual
+{
+public:
     void *operator new (size_t);
     void operator delete (void *);
     virtual ~BaseVirtual();
@@ -85,10 +87,11 @@ BaseVirtual::DeleteABase(BaseVirtual *aBase)
     delete aBase;
 }
 
-BaseVirtual::~BaseVirtual(){}
+BaseVirtual::~BaseVirtual() {}
 
-class ChildVirtual : public BaseVirtual {
-  public:
+class ChildVirtual : public BaseVirtual
+{
+public:
     void *operator new (size_t);
     void operator delete (void *);
     virtual ~ChildVirtual();
@@ -111,7 +114,7 @@ ChildVirtual::operator delete(void *address)
     ::operator delete (address);
 }
 
-ChildVirtual::~ChildVirtual(){}
+ChildVirtual::~ChildVirtual() {}
 
 int
 main(int argc, char **argv)
diff --git a/test-suite/debug.cc b/test-suite/debug.cc
index 832c24c13e..e30eda6e4e 100644
--- a/test-suite/debug.cc
+++ b/test-suite/debug.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -39,8 +39,9 @@
 #include "mem_node.h"
 #include 
 
-class StreamTest {
-  public:
+class StreamTest
+{
+public:
     std::ostream &serialise(std::ostream &);
     int const getAnInt() const;
     char const *getACString() const;
@@ -79,9 +80,9 @@ main(int argc, char **argv)
     debugs (1,1,"test" << "string");
     debugs (1,1,"test" << "string");
     if (true)
-	debugs(1,9,"this won't compile if the macro is broken.");
+        debugs(1,9,"this won't compile if the macro is broken.");
     else
-	debugs(1,1,"bar");
+        debugs(1,1,"bar");
     StreamTest aStreamObject;
     StreamTest *streamPointer (&aStreamObject);
     debugs(1,1,aStreamObject);
diff --git a/test-suite/hash.c b/test-suite/hash.c
index 01c935d474..a777499009 100644
--- a/test-suite/hash.c
+++ b/test-suite/hash.c
@@ -21,16 +21,16 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
- *  
+ *
  */
 
 #include 
@@ -61,7 +61,7 @@ hash_url(const void *data, unsigned int size)
     unsigned int i, j, n;
     j = strlen(s);
     for (i = j / 2, n = 0; i < j; i++)
-	n ^= 271 * (unsigned) s[i];
+        n ^= 271 * (unsigned) s[i];
     i = n ^ (j * 271);
     return i % size;
 }
@@ -74,8 +74,8 @@ hash_string(const void *data, unsigned int size)
     unsigned int j = 0;
     unsigned int i = 0;
     while (*s) {
-	j++;
-	n ^= 271 * (unsigned) *s++;
+        j++;
+        n ^= 271 * (unsigned) *s++;
     }
     i = n ^ (j * 271);
     return i % size;
@@ -114,30 +114,30 @@ hash4(const void *data, unsigned int size)
     loop = (len + 8 - 1) >> 3;
     switch (len & (8 - 1)) {
     case 0:
-	do {
-	    HASH4;
-	    /* FALLTHROUGH */
-    case 7:
-	    HASH4;
-	    /* FALLTHROUGH */
-    case 6:
-	    HASH4;
-	    /* FALLTHROUGH */
-    case 5:
-	    HASH4;
-	    /* FALLTHROUGH */
-    case 4:
-	    HASH4;
-	    /* FALLTHROUGH */
-    case 3:
-	    HASH4;
-	    /* FALLTHROUGH */
-    case 2:
-	    HASH4;
-	    /* FALLTHROUGH */
-    case 1:
-	    HASH4;
-	} while (--loop);
+        do {
+            HASH4;
+            /* FALLTHROUGH */
+        case 7:
+            HASH4;
+            /* FALLTHROUGH */
+        case 6:
+            HASH4;
+            /* FALLTHROUGH */
+        case 5:
+            HASH4;
+            /* FALLTHROUGH */
+        case 4:
+            HASH4;
+            /* FALLTHROUGH */
+        case 3:
+            HASH4;
+            /* FALLTHROUGH */
+        case 2:
+            HASH4;
+            /* FALLTHROUGH */
+        case 1:
+            HASH4;
+        } while (--loop);
     }
     return h % size;
 }
@@ -152,9 +152,9 @@ hash_create(HASHCMP * cmp_func, int hash_sz, HASHHASH * hash_func)
 {
     hash_table *hid = calloc(1, sizeof(hash_table));
     if (!hash_sz)
-	hid->size = (unsigned int) DEFAULT_HASH_SIZE;
+        hid->size = (unsigned int) DEFAULT_HASH_SIZE;
     else
-	hid->size = (unsigned int) hash_sz;
+        hid->size = (unsigned int) hash_sz;
     /* allocate and null the buckets */
     hid->buckets = calloc(hid->size, sizeof(hash_link *));
     hid->cmp = cmp_func;
@@ -180,9 +180,9 @@ hash_insert(hash_table * hid, const char *k, void *item)
     /* Add to the given hash table 'hid' */
     new = calloc(1, sizeof(hash_link));
     if (!new) {
-	fprintf(stderr, "calloc failed!\n");
-	print_stats();
-	exit(1);
+        fprintf(stderr, "calloc failed!\n");
+        print_stats();
+        exit(1);
     }
     new->item = item;
     new->key = (char *) k;
@@ -193,7 +193,7 @@ hash_insert(hash_table * hid, const char *k, void *item)
 
 /*
  *  hash_join - joins a hash_link under its key lnk->key
- *  into the hash table 'hid'.  
+ *  into the hash table 'hid'.
  *
  *  It does not copy any data into the hash table, only links pointers.
  */
@@ -219,9 +219,9 @@ hash_lookup(hash_table * hid, const void *k)
     assert(k != NULL);
     b = hid->hash(k, hid->size);
     for (walker = hid->buckets[b]; walker != NULL; walker = walker->next) {
-	if ((hid->cmp) (k, walker->key) == 0)
-	    return (walker);
-	assert(walker != walker->next);
+        if ((hid->cmp) (k, walker->key) == 0)
+            return (walker);
+        assert(walker != walker->next);
     }
     return NULL;
 }
@@ -236,16 +236,16 @@ hash_first(hash_table * hid)
     int i;
 
     for (i = 0; i < hid->size; i++) {
-	hid->current_slot = i;
-	if (hid->buckets[i] != NULL)
-	    return (hid->current_ptr = hid->buckets[i]);
+        hid->current_slot = i;
+        if (hid->buckets[i] != NULL)
+            return (hid->current_ptr = hid->buckets[i]);
     }
     return NULL;
 }
 
 /*
  *  hash_next - returns the next item in the hash table 'hid'.
- *  Otherwise, returns NULL on error or end of list.  
+ *  Otherwise, returns NULL on error or end of list.
  *
  *  MUST call hash_first() before hash_next().
  */
@@ -255,15 +255,15 @@ hash_next(hash_table * hid)
     int i;
 
     if (hid->current_ptr != NULL) {
-	hid->current_ptr = hid->current_ptr->next;
-	if (hid->current_ptr != NULL)
-	    return (hid->current_ptr);	/* next item */
+        hid->current_ptr = hid->current_ptr->next;
+        if (hid->current_ptr != NULL)
+            return (hid->current_ptr);	/* next item */
     }
     /* find next bucket */
     for (i = hid->current_slot + 1; i < hid->size; i++) {
-	hid->current_slot = i;
-	if (hid->buckets[i] != NULL)
-	    return (hid->current_ptr = hid->buckets[i]);
+        hid->current_slot = i;
+        if (hid->buckets[i] != NULL)
+            return (hid->current_ptr = hid->buckets[i]);
     }
     return NULL;		/* end of list */
 }
@@ -275,10 +275,10 @@ hash_delete(hash_table * hid, const char *key)
 }
 
 /*
- *  hash_delete_link - deletes the given hash_link node from the 
+ *  hash_delete_link - deletes the given hash_link node from the
  *  hash table 'hid'. If FreeLink then free the given hash_link.
  *
- *  On success, it returns 0 and deletes the link; otherwise, 
+ *  On success, it returns 0 and deletes the link; otherwise,
  *  returns non-zero on error.
  */
 int
@@ -287,26 +287,26 @@ hash_unlink(hash_table * hid, hash_link * hl, int FreeLink)
     hash_link *walker, *prev;
     int i;
     if (hl == NULL)
-	return -1;
+        return -1;
     i = hid->hash(hl->key, hid->size);
     for (prev = NULL, walker = hid->buckets[i];
-	walker != NULL; prev = walker, walker = walker->next) {
-	if (walker == hl) {
-	    if (prev == NULL) {	/* it's the head */
-		hid->buckets[i] = walker->next;
-	    } else {
-		prev->next = walker->next;	/* skip it */
-	    }
-	    /* fix walker state if needed */
-	    if (walker == hid->current_ptr)
-		hid->current_ptr = walker->next;
-	    if (FreeLink) {
-		if (walker) {
-		    free(walker);
-		}
-	    }
-	    return 0;
-	}
+            walker != NULL; prev = walker, walker = walker->next) {
+        if (walker == hl) {
+            if (prev == NULL) {	/* it's the head */
+                hid->buckets[i] = walker->next;
+            } else {
+                prev->next = walker->next;	/* skip it */
+            }
+            /* fix walker state if needed */
+            if (walker == hid->current_ptr)
+                hid->current_ptr = walker->next;
+            if (FreeLink) {
+                if (walker) {
+                    free(walker);
+                }
+            }
+            return 0;
+        }
     }
     return 1;
 }
@@ -326,14 +326,14 @@ hash_remove_link(hash_table * hid, hash_link * hl)
 }
 
 /*
- *  hash_get_bucket - returns the head item of the bucket 
+ *  hash_get_bucket - returns the head item of the bucket
  *  in the hash table 'hid'. Otherwise, returns NULL on error.
  */
 hash_link *
 hash_get_bucket(hash_table * hid, unsigned int bucket)
 {
     if (bucket >= hid->size)
-	return NULL;
+        return NULL;
     return (hid->buckets[bucket]);
 }
 
@@ -344,7 +344,7 @@ hashFreeMemory(hash_table * hid)
     if (hid->buckets);
     free(hid->buckets);
     if (hid)
-	free(hid);
+        free(hid);
 }
 
 
@@ -368,36 +368,36 @@ main(void)
 
     printf("creating hash table\n");
     if ((hid = hash_create(strcmp, 229, hash_string)) < 0) {
-	printf("hash_create error.\n");
-	exit(1);
+        printf("hash_create error.\n");
+        exit(1);
     }
     printf("done creating hash table: %d\n", hid);
 
     while (fgets(buf, BUFSIZ, stdin)) {
-	buf[strlen(buf) - 1] = '\0';
-	printf("Inserting '%s' for item %p to hash table: %d\n",
-	    buf, buf, hid);
-	hash_insert(hid, xstrdup(buf), (void *) 0x12345678);
-	if (random() % 17 == 0)
-	    strcpy(todelete, buf);
+        buf[strlen(buf) - 1] = '\0';
+        printf("Inserting '%s' for item %p to hash table: %d\n",
+               buf, buf, hid);
+        hash_insert(hid, xstrdup(buf), (void *) 0x12345678);
+        if (random() % 17 == 0)
+            strcpy(todelete, buf);
     }
 
     printf("walking hash table...\n");
     for (i = 0, walker = hash_first(hid); walker; walker = hash_next(hid)) {
-	printf("item %5d: key: '%s' item: %p\n", i++, walker->key,
-	    walker->item);
+        printf("item %5d: key: '%s' item: %p\n", i++, walker->key,
+               walker->item);
     }
     printf("done walking hash table...\n");
 
     if (todelete[0]) {
-	printf("deleting %s from %d\n", todelete, hid);
-	if (hash_delete(hid, todelete))
-	    printf("hash_delete error\n");
+        printf("deleting %s from %d\n", todelete, hid);
+        if (hash_delete(hid, todelete))
+            printf("hash_delete error\n");
     }
     printf("walking hash table...\n");
     for (i = 0, walker = hash_first(hid); walker; walker = hash_next(hid)) {
-	printf("item %5d: key: '%s' item: %p\n", i++, walker->key,
-	    walker->item);
+        printf("item %5d: key: '%s' item: %p\n", i++, walker->key,
+               walker->item);
     }
     printf("done walking hash table...\n");
 
diff --git a/test-suite/hash.h b/test-suite/hash.h
index b2c13c42a1..6e048f3110 100644
--- a/test-suite/hash.h
+++ b/test-suite/hash.h
@@ -1,44 +1,45 @@
 #define  DEFAULT_HASH_SIZE 7951
-extern "C" {
-typedef unsigned int HASHHASH(const void *, unsigned int);
-struct _hash_link {
-    char *key;
-    struct _hash_link *next;
-    void *item;
-};
-typedef int HASHCMP(const void *, const void *);
+extern "C"
+{
+    typedef unsigned int HASHHASH(const void *, unsigned int);
+    struct _hash_link {
+        char *key;
+        struct _hash_link *next;
+        void *item;
+    };
+    typedef int HASHCMP(const void *, const void *);
 
-typedef struct _hash_link hash_link;
+    typedef struct _hash_link hash_link;
 
-struct _hash_table {
-    int valid;
-    hash_link **buckets;
-    HASHCMP *cmp;
-    HASHHASH *hash;
-    unsigned int size;
-    unsigned int current_slot;
-    hash_link *current_ptr;
-};
-typedef struct _hash_table hash_table;
+    struct _hash_table {
+        int valid;
+        hash_link **buckets;
+        HASHCMP *cmp;
+        HASHHASH *hash;
+        unsigned int size;
+        unsigned int current_slot;
+        hash_link *current_ptr;
+    };
+    typedef struct _hash_table hash_table;
 
-extern int hash_links_allocated;
-/* AYJ: defined by globals.h */
+    extern int hash_links_allocated;
+    /* AYJ: defined by globals.h */
 //extern int store_hash_buckets;	/* 0 */
 //extern hash_table *store_table;	/* NULL */
-extern hash_table *hash_create(HASHCMP *, int, HASHHASH *);
-extern void hash_insert(hash_table *, const char *, void *);
-extern int hash_delete(hash_table *, const char *);
-int hash_delete_link(hash_table *, hash_link *);
-int hash_unlink(hash_table *, hash_link *, int);
-void hash_join(hash_table *, hash_link *);
-int hash_remove_link(hash_table *, hash_link *);
-hash_link *hash_lookup(hash_table *, const void *);
-hash_link *hash_first(hash_table *);
-hash_link *hash_next(hash_table *);
-hash_link *hash_get_bucket(hash_table *, unsigned int);
-void hashFreeMemory(hash_table *);
-HASHHASH hash_string;
-HASHHASH hash_url;
-HASHHASH hash4;
+    extern hash_table *hash_create(HASHCMP *, int, HASHHASH *);
+    extern void hash_insert(hash_table *, const char *, void *);
+    extern int hash_delete(hash_table *, const char *);
+    int hash_delete_link(hash_table *, hash_link *);
+    int hash_unlink(hash_table *, hash_link *, int);
+    void hash_join(hash_table *, hash_link *);
+    int hash_remove_link(hash_table *, hash_link *);
+    hash_link *hash_lookup(hash_table *, const void *);
+    hash_link *hash_first(hash_table *);
+    hash_link *hash_next(hash_table *);
+    hash_link *hash_get_bucket(hash_table *, unsigned int);
+    void hashFreeMemory(hash_table *);
+    HASHHASH hash_string;
+    HASHHASH hash_url;
+    HASHHASH hash4;
 
 }
diff --git a/test-suite/mem_hdr_test.cc b/test-suite/mem_hdr_test.cc
index d742ba8de9..a3d46ffbbd 100644
--- a/test-suite/mem_hdr_test.cc
+++ b/test-suite/mem_hdr_test.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/test-suite/mem_node_test.cc b/test-suite/mem_node_test.cc
index d5daf728d5..6ae283a8db 100644
--- a/test-suite/mem_node_test.cc
+++ b/test-suite/mem_node_test.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
diff --git a/test-suite/membanger.c b/test-suite/membanger.c
index e11d82615c..9c032e7f76 100644
--- a/test-suite/membanger.c
+++ b/test-suite/membanger.c
@@ -86,41 +86,41 @@ main(int argc, char **argv)
     malloc_options = "A";
     a = 0;
     while ((c = getopt(argc, argv, "f:i:M:l:m:r:N")) != -1) {
-	switch (c) {
-	case 'N':
-	    mem_pools_on = 0;
-	    break;
-	case 'r':
-	    run_stats = atoi(optarg);
-	    break;
-	case 'f':
-	    fn = strdup(optarg);
-	    fp = fopen(fn, "r");
-	    break;
-	case 'i':
-	    initsiz = atoi(optarg);
-	    break;
-	case 'l':
-	    mem_max_size = atoi(optarg) * 1024 * 1024;
-	    break;
-	case 'M':
-	    maxsiz = atoi(optarg);
-	    break;
-	case 'm':
-	    minchunk = atoi(optarg);
-	    break;
-	default:
-	    fprintf(stderr,
-		"Usage: %s -f file -M maxsiz -i initsiz -m minchunk", argv[0]);
-	    exit(1);
-	}
+        switch (c) {
+        case 'N':
+            mem_pools_on = 0;
+            break;
+        case 'r':
+            run_stats = atoi(optarg);
+            break;
+        case 'f':
+            fn = strdup(optarg);
+            fp = fopen(fn, "r");
+            break;
+        case 'i':
+            initsiz = atoi(optarg);
+            break;
+        case 'l':
+            mem_max_size = atoi(optarg) * 1024 * 1024;
+            break;
+        case 'M':
+            maxsiz = atoi(optarg);
+            break;
+        case 'm':
+            minchunk = atoi(optarg);
+            break;
+        default:
+            fprintf(stderr,
+                    "Usage: %s -f file -M maxsiz -i initsiz -m minchunk", argv[0]);
+            exit(1);
+        }
 
     }
     if (!fp) {
-	fprintf(stderr,
-	    "%s pummels %s\n%s . o O ( You't supply a valid tracefile.)\n",
-	    argv[0], getenv("USER"), argv[0]);
-	exit(1);
+        fprintf(stderr,
+                "%s pummels %s\n%s . o O ( You't supply a valid tracefile.)\n",
+                argv[0], getenv("USER"), argv[0]);
+        exit(1);
     }
 #ifdef WITH_LIB
     sizeToPoolInit();
@@ -128,94 +128,94 @@ main(int argc, char **argv)
     mem_table = hash_create(ptrcmp, 229, hash4);	/* small hash table */
     init_stats();
     while (fgets(mbuf, 256, fp) != NULL) {
-	if (run_stats > 0 && (++a) % run_stats == 0)
-	    print_stats();
-	p = NULL;
-	switch (mbuf[0]) {
-	case 'm':		/* malloc */
-	    p = strtok(&mbuf[2], ":");
-	    if (!p)
-		badformat();
-	    size = atoi(p);
-	    p = strtok(NULL, "\n");
-	    if (!p)
-		badformat();
-	    mi = malloc(sizeof(memitem));
-	    strcpy(mi->orig_ptr, p);
-	    mi->size = size;
-	    size2id(size, mi);
-	    mi->my_ptr = xmemAlloc(mi);		/* (void *)xmalloc(size); */
-	    assert(mi->my_ptr);
-	    my_hash_insert(mem_table, mi->orig_ptr, mi);
-	    mstat.mallocs++;
-	    break;
-	case 'c':		/* calloc */
-	    p = strtok(&mbuf[2], ":");
-	    if (!p)
-		badformat();
-	    amt = atoi(p);
-	    p = strtok(NULL, ":");
-	    if (!p)
-		badformat();
-	    size = atoi(p);
-	    p = strtok(NULL, "\n");
-	    if (!p)
-		badformat();
-	    mi = malloc(sizeof(memitem));
-	    strcpy(mi->orig_ptr, p);
-	    size2id(size, mi);
-	    mi->size = amt * size;
-	    mi->my_ptr = xmemAlloc(mi);		/*(void *)xmalloc(amt*size); */
-	    assert(mi->my_ptr);
-	    my_hash_insert(mem_table, mi->orig_ptr, mi);
-	    mstat.callocs++;
-	    break;
-	case 'r':
-	    p = strtok(&mbuf[2], ":");
-	    if (!p)
-		badformat();
-	    strcpy(abuf, p);
-	    p = strtok(NULL, ":");
-	    if (!p)
-		badformat();
-	    mem_entry = hash_lookup(mem_table, p);
-	    if (mem_entry == NULL) {
-		fprintf(stderr, "invalid realloc (%s)!\n", p);
-		break;
-	    }
-	    mi = (memitem *) (mem_entry->item);
-	    assert(mi->pool);
-	    assert(mi->my_ptr);
-	    xmemFree(mi);	/* xfree(mi->my_ptr); */
-	    size2id(atoi(p), mi);	/* we don't need it here I guess? */
-	    strcpy(mi->orig_ptr, abuf);
-	    p = strtok(NULL, "\n");
-	    if (!p)
-		badformat();
-	    mi->my_ptr = xmemAlloc(mi);		/* (char *)xmalloc(atoi(p)); */
-	    assert(mi->my_ptr);
-	    mstat.reallocs++;
-	    break;
-	case 'f':
-	    p = strtok(&mbuf[2], "\n");
-	    mem_entry = hash_lookup(mem_table, p);
-	    if (mem_entry == NULL) {
-		if (p[0] != '0')
-		    fprintf(stderr, "invalid free (%s) at line %d!\n", p, a);
-		break;
-	    }
-	    mi = (memitem *) (mem_entry->item);
-	    assert(mi->pool);
-	    assert(mi->my_ptr);
-	    xmemFree(mi);	/* xfree(mi->my_ptr); */
-	    hash_unlink(mem_table, mem_entry, 1);
-	    free(mi);
-	    mstat.frees++;
-	    break;
-	default:
-	    fprintf(stderr, "%s pummels %s.bad.format\n", argv[0], fn);
-	    exit(1);
-	}
+        if (run_stats > 0 && (++a) % run_stats == 0)
+            print_stats();
+        p = NULL;
+        switch (mbuf[0]) {
+        case 'm':		/* malloc */
+            p = strtok(&mbuf[2], ":");
+            if (!p)
+                badformat();
+            size = atoi(p);
+            p = strtok(NULL, "\n");
+            if (!p)
+                badformat();
+            mi = malloc(sizeof(memitem));
+            strcpy(mi->orig_ptr, p);
+            mi->size = size;
+            size2id(size, mi);
+            mi->my_ptr = xmemAlloc(mi);		/* (void *)xmalloc(size); */
+            assert(mi->my_ptr);
+            my_hash_insert(mem_table, mi->orig_ptr, mi);
+            mstat.mallocs++;
+            break;
+        case 'c':		/* calloc */
+            p = strtok(&mbuf[2], ":");
+            if (!p)
+                badformat();
+            amt = atoi(p);
+            p = strtok(NULL, ":");
+            if (!p)
+                badformat();
+            size = atoi(p);
+            p = strtok(NULL, "\n");
+            if (!p)
+                badformat();
+            mi = malloc(sizeof(memitem));
+            strcpy(mi->orig_ptr, p);
+            size2id(size, mi);
+            mi->size = amt * size;
+            mi->my_ptr = xmemAlloc(mi);		/*(void *)xmalloc(amt*size); */
+            assert(mi->my_ptr);
+            my_hash_insert(mem_table, mi->orig_ptr, mi);
+            mstat.callocs++;
+            break;
+        case 'r':
+            p = strtok(&mbuf[2], ":");
+            if (!p)
+                badformat();
+            strcpy(abuf, p);
+            p = strtok(NULL, ":");
+            if (!p)
+                badformat();
+            mem_entry = hash_lookup(mem_table, p);
+            if (mem_entry == NULL) {
+                fprintf(stderr, "invalid realloc (%s)!\n", p);
+                break;
+            }
+            mi = (memitem *) (mem_entry->item);
+            assert(mi->pool);
+            assert(mi->my_ptr);
+            xmemFree(mi);	/* xfree(mi->my_ptr); */
+            size2id(atoi(p), mi);	/* we don't need it here I guess? */
+            strcpy(mi->orig_ptr, abuf);
+            p = strtok(NULL, "\n");
+            if (!p)
+                badformat();
+            mi->my_ptr = xmemAlloc(mi);		/* (char *)xmalloc(atoi(p)); */
+            assert(mi->my_ptr);
+            mstat.reallocs++;
+            break;
+        case 'f':
+            p = strtok(&mbuf[2], "\n");
+            mem_entry = hash_lookup(mem_table, p);
+            if (mem_entry == NULL) {
+                if (p[0] != '0')
+                    fprintf(stderr, "invalid free (%s) at line %d!\n", p, a);
+                break;
+            }
+            mi = (memitem *) (mem_entry->item);
+            assert(mi->pool);
+            assert(mi->my_ptr);
+            xmemFree(mi);	/* xfree(mi->my_ptr); */
+            hash_unlink(mem_table, mem_entry, 1);
+            free(mi);
+            mstat.frees++;
+            break;
+        default:
+            fprintf(stderr, "%s pummels %s.bad.format\n", argv[0], fn);
+            exit(1);
+        }
 
     }
     fclose(fp);
@@ -253,14 +253,14 @@ print_stats()
 #endif
     getrusage(RUSAGE_SELF, &myusage);
     printf("m/c/f/r=%d/%d/%d/%d\n", mstat.mallocs, mstat.callocs,
-	mstat.frees, mstat.reallocs);
+           mstat.frees, mstat.reallocs);
 #if 0
     printf("types                 : %d\n", size2id_len);
 #endif
     printf("user time used        : %d.%d\n", (int) myusage.ru_utime.tv_sec,
-	(int) myusage.ru_utime.tv_usec);
+           (int) myusage.ru_utime.tv_usec);
     printf("system time used      : %d.%d\n", (int) myusage.ru_stime.tv_sec,
-	(int) myusage.ru_stime.tv_usec);
+           (int) myusage.ru_stime.tv_usec);
     printf("max resident set size : %d\n", (int) myusage.ru_maxrss);
     printf("page faults           : %d\n", (int) myusage.ru_majflt);
 }
@@ -306,9 +306,9 @@ xmemAlloc(memitem * item)
     extern MemPool *StringPool;
     assert(item && item->pool);
     if (StringPool == item->pool)
-	return memStringAlloc(item->pool, item->size);
+        return memStringAlloc(item->pool, item->size);
     else
-	return memAlloc(item->pool);
+        return memAlloc(item->pool);
 }
 
 static void
@@ -317,12 +317,12 @@ xmemFree(memitem * item)
     extern MemPool *StringPool;
     assert(item && item->pool);
     if (StringPool == item->pool)
-	return memStringFree(item->pool, item->my_ptr, item->size);
+        return memStringFree(item->pool, item->my_ptr, item->size);
     else
-	return memFree(item->pool, item->my_ptr);
+        return memFree(item->pool, item->my_ptr);
 }
 
-void 
+void
 my_free(char *file, int line, void *ptr)
 {
 #if 0
diff --git a/test-suite/pconn-banger.c b/test-suite/pconn-banger.c
index 14578088f6..ca9a72274a 100644
--- a/test-suite/pconn-banger.c
+++ b/test-suite/pconn-banger.c
@@ -131,7 +131,7 @@ static struct _r *Requests;
 
 char *
 mkrfc850(t)
-     time_t *t;
+time_t *t;
 {
     static char buf[128];
     struct tm *gmt = gmtime(t);
@@ -151,11 +151,11 @@ mime_headers_end(const char *mime)
     p2 = strstr(mime, "\n\n");
 
     if (p1 && p2)
-	end = p1 < p2 ? p1 : p2;
+        end = p1 < p2 ? p1 : p2;
     else
-	end = p1 ? p1 : p2;
+        end = p1 ? p1 : p2;
     if (end)
-	end += (end == p1 ? 3 : 2);
+        end += (end == p1 ? 3 : 2);
 
     return (char *) end;
 }
@@ -183,16 +183,16 @@ open_http_socket(void)
     xgetaddrinfo(proxy_addr, proxy_port, &hints, AI);
 
     if ((s = socket(AI->ai_family, AI->ai_socktype, AI->ai_protocol)) < 0) {
-	perror("socket");
+        perror("socket");
         xfreeaddrinfo(AI);
-	return -1;
+        return -1;
     }
 
     if (connect(s, AI->ai_addr, AI->ai_addrlen) < 0) {
-	close(s);
-	perror("connect");
+        close(s);
+        perror("connect");
         xfreeaddrinfo(AI);
-	return -1;
+        return -1;
     }
 
     xfreeaddrinfo(AI);
@@ -217,73 +217,73 @@ send_request(int fd, const char *data)
     size = strtok(NULL, " ");
     checksum = strtok(NULL, " ");
     if (!url) {
-	url = method;
-	method = "GET";
+        url = method;
+        method = "GET";
     }
     if (file && strcmp(file, "-") == 0)
-	file = NULL;
+        file = NULL;
     if (size && strcmp(size, "-") == 0)
-	size = NULL;
+        size = NULL;
     if (checksum && strcmp(checksum, "-") == 0)
-	checksum = NULL;
+        checksum = NULL;
     msg[0] = '\0';
     sprintf(buf, "%s %s HTTP/1.0\r\n", method, url);
     strcat(msg, buf);
     strcat(msg, "Accept: */*\r\n");
     strcat(msg, "Proxy-Connection: Keep-Alive\r\n");
     if (opt_ims && (lrand48() & 0x03) == 0) {
-	w = time(NULL) - (lrand48() & 0x3FFFF);
-	sprintf(buf, "If-Modified-Since: %s\r\n", mkrfc850(&w));
-	strcat(msg, buf);
+        w = time(NULL) - (lrand48() & 0x3FFFF);
+        sprintf(buf, "If-Modified-Since: %s\r\n", mkrfc850(&w));
+        strcat(msg, buf);
     }
     if (file) {
-	if ((file_fd = open(file, O_RDONLY)) < 0) {
-	    perror("open");
-	    return -1;
-	}
-	if (fstat(file_fd, &st)) {
-	    perror("fstat");
-	    close(file_fd);
-	    return -1;
-	}
-	sprintf(buf, "Content-length: %d\r\n", st.st_size);
-	strcat(msg, buf);
+        if ((file_fd = open(file, O_RDONLY)) < 0) {
+            perror("open");
+            return -1;
+        }
+        if (fstat(file_fd, &st)) {
+            perror("fstat");
+            close(file_fd);
+            return -1;
+        }
+        sprintf(buf, "Content-length: %d\r\n", st.st_size);
+        strcat(msg, buf);
     }
     strcat(msg, "\r\n");
     len = strlen(msg);
     if (write(fd, msg, len) < 0) {
-	close(fd);
-	perror("request write");
-	close(file_fd);
-	return -1;
+        close(fd);
+        perror("request write");
+        close(file_fd);
+        return -1;
     }
     if (file) {
-	while ((len = read(file_fd, buf, sizeof buf)) > 0) {
-	    if (write(fd, buf, len) < 0) {
-		close(fd);
-		perror("body write");
-		close(file_fd);
-		return -1;
-	    }
-	}
-	if (len < 0) {
-	    perror("file read");
-	    close(file_fd);
-	    return -1;
-	}
-	close(file_fd);
+        while ((len = read(file_fd, buf, sizeof buf)) > 0) {
+            if (write(fd, buf, len) < 0) {
+                close(fd);
+                perror("body write");
+                close(file_fd);
+                return -1;
+            }
+        }
+        if (len < 0) {
+            perror("file read");
+            close(file_fd);
+            return -1;
+        }
+        close(file_fd);
     }
     r = calloc(1, sizeof(struct _r));
     strcpy(r->url, url);
     if (size)
-	r->validsize = atoi(size);
+        r->validsize = atoi(size);
     else
-	r->validsize = -1;
+        r->validsize = -1;
     if (checksum)
-	r->validsum = atoi(checksum);
+        r->validsum = atoi(checksum);
     for (R = &Requests; *R; R = &(*R)->next);
     *R = r;
-/*    fprintf(stderr, "REQUESTED %s\n", url); */
+    /*    fprintf(stderr, "REQUESTED %s\n", url); */
     noutstanding++;
     return 0;
 }
@@ -293,12 +293,12 @@ get_header_int_value(const char *hdr, const char *buf, const char *end)
 {
     const char *t;
     for (t = buf; t < end; t += strcspn(t, crlf), t += strspn(t, crlf)) {
-	if (strncasecmp(t, hdr, strlen(hdr)) == 0) {
-	    t += strlen(hdr);
-	    while (xisspace(*t))
-		t++;
-	    return atoi(t);
-	}
+        if (strncasecmp(t, hdr, strlen(hdr)) == 0) {
+            t += strlen(hdr);
+            while (xisspace(*t))
+                t++;
+            return atoi(t);
+        }
     }
     return -1;
 }
@@ -309,14 +309,14 @@ get_header_string_value(const char *hdr, const char *buf, const char *end)
     const char *t;
     static char result[8192];
     for (t = buf; t < end; t += strcspn(t, crlf), t += strspn(t, crlf)) {
-	if (strncasecmp(t, hdr, strlen(hdr)) == 0) {
-	    t += strlen(hdr);
-	    while (xisspace(*t))
-		t++;
-	    strcpy(result, "");
-	    strncat(result, t, strcspn(t, crlf));
-	    return result;
-	}
+        if (strncasecmp(t, hdr, strlen(hdr)) == 0) {
+            t += strlen(hdr);
+            while (xisspace(*t))
+                t++;
+            strcpy(result, "");
+            strncat(result, t, strcspn(t, crlf));
+            return result;
+        }
     }
     return NULL;
 }
@@ -326,20 +326,20 @@ request_done(struct _r *r)
 {
 #if 0
     fprintf(stderr, "DONE: %s, (%d+%d)\n",
-	r->url,
-	r->hdr_length,
-	r->content_length);
+            r->url,
+            r->hdr_length,
+            r->content_length);
 #endif
     if (r->content_length != r->bytes_read)
-	fprintf(stderr, "ERROR! Short reply, expected %d bytes got %d\n",
-	    r->content_length, r->bytes_read);
+        fprintf(stderr, "ERROR! Short reply, expected %d bytes got %d\n",
+                r->content_length, r->bytes_read);
     else if (r->validsize >= 0) {
-	if (r->validsize != r->bytes_read)
-	    fprintf(stderr, "WARNING: %s Object size mismatch, expected %d got %d\n",
-		r->url, r->validsize, r->bytes_read);
-	else if (opt_checksum && r->sum != r->validsum)
-	    fprintf(stderr, "WARNING: %s Checksum error. Expected %d got %d\n",
-		r->url, r->validsum, r->sum);
+        if (r->validsize != r->bytes_read)
+            fprintf(stderr, "WARNING: %s Object size mismatch, expected %d got %d\n",
+                    r->url, r->validsize, r->bytes_read);
+        else if (opt_checksum && r->sum != r->validsum)
+            fprintf(stderr, "WARNING: %s Checksum error. Expected %d got %d\n",
+                    r->url, r->validsum, r->sum);
     }
 }
 int
@@ -351,104 +351,104 @@ handle_read(char *inbuf, int len)
     static char buf[READ_BUF_SZ];
     int hlen, blen;
     if (len < 0) {
-	perror("read");
-	Requests = r->next;
-	request_done(r);
-	free(r);
-	noutstanding--;
-	if (trace_fd >= 0)
-	    write(trace_fd, "\n[CLOSED]\n", 10);
-	return -1;
+        perror("read");
+        Requests = r->next;
+        request_done(r);
+        free(r);
+        noutstanding--;
+        if (trace_fd >= 0)
+            write(trace_fd, "\n[CLOSED]\n", 10);
+        return -1;
     }
     total_bytes_read += len;
     xmemcpy(buf, inbuf, len);
     if (len == 0) {
-	fprintf(stderr, "WARNING: %s, server closed socket after %d+%d bytes\n", r->url, r->hdr_offset, r->bytes_read);
-	/* XXX, If no data was received and it isn't the first request on this
-	 * connection then the request should be restarted rather than aborted
-	 * but this is a simple test program an not a full blown HTTP client.
-	 */
-	request_done(r);
-	Requests = r->next;
-	free(r);
-	noutstanding--;
-	return -1;
+        fprintf(stderr, "WARNING: %s, server closed socket after %d+%d bytes\n", r->url, r->hdr_offset, r->bytes_read);
+        /* XXX, If no data was received and it isn't the first request on this
+         * connection then the request should be restarted rather than aborted
+         * but this is a simple test program an not a full blown HTTP client.
+         */
+        request_done(r);
+        Requests = r->next;
+        free(r);
+        noutstanding--;
+        return -1;
     }
     if (trace_fd > 0)
-	write(trace_fd, buf, len);
+        write(trace_fd, buf, len);
     while (len > 0) {
-	/* Build headers */
-	if (r->hdr_length == 0) {
-	    hlen = min(len, REPLY_HDR_SZ - r->hdr_offset - 1);
-	    xmemcpy(r->reply_hdrs + r->hdr_offset, buf, hlen);
-	    r->hdr_offset += hlen;
-	    r->reply_hdrs[r->hdr_offset] = '\0';
-	    len -= hlen;
-	    /* Save any remaining read data */
-	    xmemmove(buf, buf + hlen, len);
-	}
-	/* Process headers */
-	if (r->hdr_length == 0 && (end = mime_headers_end(r->reply_hdrs)) != NULL) {
+        /* Build headers */
+        if (r->hdr_length == 0) {
+            hlen = min(len, REPLY_HDR_SZ - r->hdr_offset - 1);
+            xmemcpy(r->reply_hdrs + r->hdr_offset, buf, hlen);
+            r->hdr_offset += hlen;
+            r->reply_hdrs[r->hdr_offset] = '\0';
+            len -= hlen;
+            /* Save any remaining read data */
+            xmemmove(buf, buf + hlen, len);
+        }
+        /* Process headers */
+        if (r->hdr_length == 0 && (end = mime_headers_end(r->reply_hdrs)) != NULL) {
 #if 0
-	    fprintf(stderr, "FOUND EOH FOR %s\n", r->url);
-	    */
+            fprintf(stderr, "FOUND EOH FOR %s\n", r->url);
+            */
 #endif
-		r->hdr_length = end - r->reply_hdrs;
+            r->hdr_length = end - r->reply_hdrs;
 #if 0
-	    fprintf(stderr, "HDR_LENGTH = %d\n", r->hdr_length);
+            fprintf(stderr, "HDR_LENGTH = %d\n", r->hdr_length);
 #endif
-	    /* "unread" any body contents received */
-	    blen = r->hdr_offset - r->hdr_length;
-	    assert(blen >= 0);
-	    if (blen > 0) {
-		xmemmove(buf + blen, buf, len);
-		xmemcpy(buf, r->reply_hdrs + r->hdr_length, blen);
-		len += blen;
-	    }
-	    r->reply_hdrs[r->hdr_length] = '\0';	/* Null terminate headers */
-	    /* Parse headers */
-	    r->content_length = get_header_int_value("content-length:", r->reply_hdrs, end);
-/*          fprintf(stderr, "CONTENT_LENGTH = %d\n", r->content_length); */
-	    url = get_header_string_value("X-Request-URI:", r->reply_hdrs, end);
-	    if (url != NULL && strcmp(r->url, url) != 0)
-		fprintf(stderr, "WARNING: %s got reply %s\n", r->url, url);
+            /* "unread" any body contents received */
+            blen = r->hdr_offset - r->hdr_length;
+            assert(blen >= 0);
+            if (blen > 0) {
+                xmemmove(buf + blen, buf, len);
+                xmemcpy(buf, r->reply_hdrs + r->hdr_length, blen);
+                len += blen;
+            }
+            r->reply_hdrs[r->hdr_length] = '\0';	/* Null terminate headers */
+            /* Parse headers */
+            r->content_length = get_header_int_value("content-length:", r->reply_hdrs, end);
+            /*          fprintf(stderr, "CONTENT_LENGTH = %d\n", r->content_length); */
+            url = get_header_string_value("X-Request-URI:", r->reply_hdrs, end);
+            if (url != NULL && strcmp(r->url, url) != 0)
+                fprintf(stderr, "WARNING: %s got reply %s\n", r->url, url);
 #if XREQUESTURI || 0
-	    fprintf(stderr, "LOCATION = %s\n", get_header_string_value("X-Request-URI:", r->reply_hdrs, end));
+            fprintf(stderr, "LOCATION = %s\n", get_header_string_value("X-Request-URI:", r->reply_hdrs, end));
 #endif
-	}
-	if (!(len == 0 || r->hdr_length > 0)) {
-	    fprintf(stderr, "ERROR!!!\n");
-	    assert((len == 0 || r->hdr_length > 0));
-	}
-	/* Process body */
-	if (r->hdr_length != 0) {
-	    int i;
-	    int bytes_left, bytes_used;
-	    if (r->content_length >= 0) {
-		bytes_left = r->content_length - r->bytes_read;
-		assert(bytes_left >= 0);
-		bytes_used = len < bytes_left ? len : bytes_left;
-	    } else {
-		bytes_left = len + 1;	/* Unknown end... */
-		bytes_used = len;
-	    }
-	    if (opt_checksum) {
-		for (i = 0; i < bytes_used; i++)
-		    r->sum += (int) buf[i] & 0xFF;
-	    }
-	    r->bytes_read += bytes_used;
-	    len -= bytes_used;
-	    if (bytes_left == bytes_used) {
-		request_done(r);
-		Requests = r->next;
-		free(r);
-		noutstanding--;
-		r = Requests;
-	    } else if (r->content_length > -1) {
-		assert(r->bytes_read < r->content_length);
-	    }
-	    xmemmove(buf, buf + bytes_used, len);
-	}
+        }
+        if (!(len == 0 || r->hdr_length > 0)) {
+            fprintf(stderr, "ERROR!!!\n");
+            assert((len == 0 || r->hdr_length > 0));
+        }
+        /* Process body */
+        if (r->hdr_length != 0) {
+            int i;
+            int bytes_left, bytes_used;
+            if (r->content_length >= 0) {
+                bytes_left = r->content_length - r->bytes_read;
+                assert(bytes_left >= 0);
+                bytes_used = len < bytes_left ? len : bytes_left;
+            } else {
+                bytes_left = len + 1;	/* Unknown end... */
+                bytes_used = len;
+            }
+            if (opt_checksum) {
+                for (i = 0; i < bytes_used; i++)
+                    r->sum += (int) buf[i] & 0xFF;
+            }
+            r->bytes_read += bytes_used;
+            len -= bytes_used;
+            if (bytes_left == bytes_used) {
+                request_done(r);
+                Requests = r->next;
+                free(r);
+                noutstanding--;
+                r = Requests;
+            } else if (r->content_length > -1) {
+                assert(r->bytes_read < r->content_length);
+            }
+            xmemmove(buf, buf + bytes_used, len);
+        }
     }
     return 0;
 }
@@ -462,8 +462,8 @@ read_reply(int fd)
     len = read(fd, buf, READ_BUF_SZ);
     x = handle_read(buf, len);
     if (x < 0) {
-	perror("read reply");
-	close(fd);
+        perror("read reply");
+        close(fd);
     }
     return x;
 }
@@ -487,109 +487,109 @@ main_loop(void)
 
     pconn_fd = open_http_socket();
     if (pconn_fd < 0) {
-	perror("socket");
-	exit(1);
+        perror("socket");
+        exit(1);
     }
     while (!done_reading_urls || noutstanding) {
-	if (!opt_reopen && pconn_fd < 0) {
-	    fprintf(stderr, "TERMINATED: Connection closed\n");
-	    break;
-	}
-	if (pconn_fd < 0) {
-	    pconn_fd = open_http_socket();
-	    if (pconn_fd < 0) {
-		perror("socket");
-		exit(1);
-	    }
-	    nextr = Requests;
-	    Requests = NULL;
-	    noutstanding = 0;
-	    while ((r = nextr) != NULL) {
-		nextr = r->next;
-		if (send_request(pconn_fd, r->url) != 0) {
-		    close(pconn_fd);
-		    pconn_fd = -1;
-		    nextr = r;
-		    for (r = Requests; r != NULL && r->next; r = r->next);
-		    if (r != NULL)
-			r->next = nextr;
-		    else
-			Requests = nextr;
-		    break;
-		}
-		free(r);
-	    }
-	    timeouts = 0;
-	    if (pconn_fd < 0)
-		continue;
-	}
-	if (timeouts == 200) {
-	    close(pconn_fd);
-	    pconn_fd = -1;
-	    r = Requests;
-	    Requests = Requests->next;
-	    fprintf(stderr, "ABORT %s\n", Requests->url);
-	    free(r);
-	    noutstanding--;
-	}
-	if (pconn_fd >= 0 && noutstanding < max_outstanding && !done_reading_urls) {
-	    char *t;
-	    if (fgets(buf, 8191, stdin) == NULL) {
-		fprintf(stderr, "Done Reading URLS\n");
-		done_reading_urls = 1;
-		continue;
-	    }
-	    rrequests++;
-	    if ((t = strchr(buf, '\n')))
-		*t = '\0';
-	    if (send_request(pconn_fd, buf) != 0) {
-		close(pconn_fd);
-		pconn_fd = -1;
-		continue;
-	    }
-	    nrequests++;
-	    reqpersec++;
-	    timeouts = 0;
-	}
-	FD_ZERO(&R);
-	to.tv_sec = 1;
-	to.tv_usec = 0;
-	FD_SET(pconn_fd, &R);
-	x = select(pconn_fd + 1, &R, NULL, NULL, &to);
-	if (x < 0) {
-	    if (errno != EINTR)
-		perror("select");
-	    continue;
-	} else if (x == 0) {
-	    assert(Requests != NULL);
-	    fprintf(stderr, "TIMEOUT %s; %d, %d\n", Requests->url,
-		++timeouts, noutstanding);
-	    continue;
-	}
-	if (FD_ISSET(pconn_fd, &R)) {
-	    timeouts = 0;
-	    if (read_reply(pconn_fd) != 0)
-		pconn_fd = -1;
-	}
-	gettimeofday(&now, NULL);
-	if (now.tv_sec > last.tv_sec) {
-	    int dt;
-	    int nreq;
-	    last = now;
-	    dt = (int) (now.tv_sec - start.tv_sec);
-	    nreq = 0;
-	    for (r = Requests; r; r = r->next)
-		nreq++;
-	    printf("T+ %6d: %9d req (%+4d), %4d pend, %3d/sec avg, %dmb, %dkb/sec avg\n",
-		dt,
-		nrequests,
-		reqpersec,
-		nreq,
-		(int) (nrequests / dt),
-		(int) total_bytes_read / 1024 / 1024,
-		(int) total_bytes_read / 1024 / dt);
-	    reqpersec = 0;
-	}
+        if (!opt_reopen && pconn_fd < 0) {
+            fprintf(stderr, "TERMINATED: Connection closed\n");
+            break;
+        }
+        if (pconn_fd < 0) {
+            pconn_fd = open_http_socket();
+            if (pconn_fd < 0) {
+                perror("socket");
+                exit(1);
+            }
+            nextr = Requests;
+            Requests = NULL;
+            noutstanding = 0;
+            while ((r = nextr) != NULL) {
+                nextr = r->next;
+                if (send_request(pconn_fd, r->url) != 0) {
+                    close(pconn_fd);
+                    pconn_fd = -1;
+                    nextr = r;
+                    for (r = Requests; r != NULL && r->next; r = r->next);
+                    if (r != NULL)
+                        r->next = nextr;
+                    else
+                        Requests = nextr;
+                    break;
+                }
+                free(r);
+            }
+            timeouts = 0;
+            if (pconn_fd < 0)
+                continue;
+        }
+        if (timeouts == 200) {
+            close(pconn_fd);
+            pconn_fd = -1;
+            r = Requests;
+            Requests = Requests->next;
+            fprintf(stderr, "ABORT %s\n", Requests->url);
+            free(r);
+            noutstanding--;
+        }
+        if (pconn_fd >= 0 && noutstanding < max_outstanding && !done_reading_urls) {
+            char *t;
+            if (fgets(buf, 8191, stdin) == NULL) {
+                fprintf(stderr, "Done Reading URLS\n");
+                done_reading_urls = 1;
+                continue;
+            }
+            rrequests++;
+            if ((t = strchr(buf, '\n')))
+                *t = '\0';
+            if (send_request(pconn_fd, buf) != 0) {
+                close(pconn_fd);
+                pconn_fd = -1;
+                continue;
+            }
+            nrequests++;
+            reqpersec++;
+            timeouts = 0;
+        }
+        FD_ZERO(&R);
+        to.tv_sec = 1;
+        to.tv_usec = 0;
+        FD_SET(pconn_fd, &R);
+        x = select(pconn_fd + 1, &R, NULL, NULL, &to);
+        if (x < 0) {
+            if (errno != EINTR)
+                perror("select");
+            continue;
+        } else if (x == 0) {
+            assert(Requests != NULL);
+            fprintf(stderr, "TIMEOUT %s; %d, %d\n", Requests->url,
+                    ++timeouts, noutstanding);
+            continue;
+        }
+        if (FD_ISSET(pconn_fd, &R)) {
+            timeouts = 0;
+            if (read_reply(pconn_fd) != 0)
+                pconn_fd = -1;
+        }
+        gettimeofday(&now, NULL);
+        if (now.tv_sec > last.tv_sec) {
+            int dt;
+            int nreq;
+            last = now;
+            dt = (int) (now.tv_sec - start.tv_sec);
+            nreq = 0;
+            for (r = Requests; r; r = r->next)
+                nreq++;
+            printf("T+ %6d: %9d req (%+4d), %4d pend, %3d/sec avg, %dmb, %dkb/sec avg\n",
+                   dt,
+                   nrequests,
+                   reqpersec,
+                   nreq,
+                   (int) (nrequests / dt),
+                   (int) total_bytes_read / 1024 / 1024,
+                   (int) total_bytes_read / 1024 / dt);
+            reqpersec = 0;
+        }
     }
 }
 
@@ -601,43 +601,43 @@ usage(void)
 
 int
 main(argc, argv)
-     int argc;
-     char *argv[];
+int argc;
+char *argv[];
 {
     int c;
     setbuf(stdout, NULL);
     setbuf(stderr, NULL);
     progname = strdup(argv[0]);
     while ((c = getopt(argc, argv, "p:h:n:t:icl:r")) != -1) {
-	switch (c) {
-	case 'p':
-	    proxy_port = atoi(optarg);
-	    break;
-	case 'h':
-	    proxy_addr = strdup(optarg);
-	    break;
-	case 'n':
-	    max_outstanding = atoi(optarg);
-	    break;
-	case 'i':
-	    opt_ims = 1;
-	    break;
-	case 'c':
-	    opt_checksum = 1;
-	    break;
-	case 'l':
-	    lifetime = (time_t) atoi(optarg);
-	    break;
-	case 't':
-	    trace_fd = open(optarg, O_WRONLY | O_CREAT | O_TRUNC, 0666);
-	    break;
-	case 'r':
-	    opt_reopen = !opt_reopen;
-	    break;
-	default:
-	    usage();
-	    return 1;
-	}
+        switch (c) {
+        case 'p':
+            proxy_port = atoi(optarg);
+            break;
+        case 'h':
+            proxy_addr = strdup(optarg);
+            break;
+        case 'n':
+            max_outstanding = atoi(optarg);
+            break;
+        case 'i':
+            opt_ims = 1;
+            break;
+        case 'c':
+            opt_checksum = 1;
+            break;
+        case 'l':
+            lifetime = (time_t) atoi(optarg);
+            break;
+        case 't':
+            trace_fd = open(optarg, O_WRONLY | O_CREAT | O_TRUNC, 0666);
+            break;
+        case 'r':
+            opt_reopen = !opt_reopen;
+            break;
+        default:
+            usage();
+            return 1;
+        }
     }
     signal(SIGINT, sig_intr);
     signal(SIGPIPE, SIG_IGN);
diff --git a/test-suite/refcount.cc b/test-suite/refcount.cc
index b948e5edec..708b39c408 100644
--- a/test-suite/refcount.cc
+++ b/test-suite/refcount.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -44,8 +44,7 @@ public:
 
     ~_ToRefCount() {--Instances;}
 
-    int someMethod()
-    {
+    int someMethod() {
         if (!this)
             exit(1);
 
@@ -68,8 +67,11 @@ class AlsoRefCountable : public RefCountable, public _ToRefCount
 public:
     typedef RefCount Pointer;
 
-    int doSomething() { if (!this)
-            exit (1); return 1;}
+    int doSomething() {
+        if (!this)
+            exit (1);
+        return 1;
+    }
 };
 
 int
diff --git a/test-suite/rfc1738.cc b/test-suite/rfc1738.cc
index 8598a8c554..a8b366a682 100644
--- a/test-suite/rfc1738.cc
+++ b/test-suite/rfc1738.cc
@@ -21,12 +21,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -36,7 +36,7 @@
 
 #include "squid.h"
 #include "util.h"
-/* testing: 
+/* testing:
 SQUIDCEXTERN char *rfc1738_escape(const char *);
 SQUIDCEXTERN char *rfc1738_escape_unescaped(const char *);
 SQUIDCEXTERN char *rfc1738_escape_part(const char *);
@@ -59,7 +59,7 @@ testAString(char const *aString, char const *aResult)
     escapedString = xstrdup (aString);
     rfc1738_unescape(escapedString);
     if (strcmp(escapedString, aResult))
-	exit (1);
+        exit (1);
     safe_free (escapedString);
 }
 
diff --git a/test-suite/splay.cc b/test-suite/splay.cc
index 3286f729de..3dd1df875f 100644
--- a/test-suite/splay.cc
+++ b/test-suite/splay.cc
@@ -31,7 +31,7 @@ class intnode
 {
 
 public:
-    intnode() : i(0){}
+    intnode() : i(0) {}
 
     intnode (int anInt) : i (anInt) {}
 
@@ -164,8 +164,7 @@ main(int argc, char *argv[])
         /* intnode* */
         SplayNode *safeTop = NULL;
 
-        for ( int i = 0; i < 100; i++)
-        {
+        for ( int i = 0; i < 100; i++) {
             intnode *I;
             I = new intnode;
             I->i = squid_random();
@@ -184,8 +183,7 @@ main(int argc, char *argv[])
         /* intnode */
         SplayNode *safeTop = NULL;
 
-        for (int i = 0; i < 100; i++)
-        {
+        for (int i = 0; i < 100; i++) {
             intnode I;
             I.i = squid_random();
             safeTop = safeTop->insert(I, compareintref);
diff --git a/test-suite/syntheticoperators.cc b/test-suite/syntheticoperators.cc
index 4ce31630bc..39ba305f0f 100644
--- a/test-suite/syntheticoperators.cc
+++ b/test-suite/syntheticoperators.cc
@@ -20,12 +20,12 @@
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
@@ -38,8 +38,9 @@
 #include "mem_node.h"
 #include 
 
-class HasExplicit {
-  public:
+class HasExplicit
+{
+public:
     HasExplicit();
     ~HasExplicit();
     HasExplicit(HasExplicit const &);
@@ -47,7 +48,7 @@ class HasExplicit {
     static int const &Instances();
     static int const &Assignments();
     static void Assignments(int const &);
-  private:
+private:
     static void AddInstance();
     static void RemoveInstance();
     static void Assignment();
@@ -58,20 +59,24 @@ class HasExplicit {
 int HasExplicit::Instances_(0);
 int HasExplicit::Assignments_(0);
 
-HasExplicit::HasExplicit() {
+HasExplicit::HasExplicit()
+{
     AddInstance();
 }
 
-HasExplicit::~HasExplicit() {
+HasExplicit::~HasExplicit()
+{
     RemoveInstance();
 }
 
-HasExplicit::HasExplicit(HasExplicit const &) {
+HasExplicit::HasExplicit(HasExplicit const &)
+{
     AddInstance();
 }
 
 HasExplicit &
-HasExplicit::operator= (HasExplicit const &) {
+HasExplicit::operator= (HasExplicit const &)
+{
     Assignment();
     return *this;
 }
@@ -138,8 +143,9 @@ CheckHasExplicitWorks()
     assert (HasExplicit::Assignments() == 0);
 }
 
-class SyntheticOwnsExplicit {
-  public:
+class SyntheticOwnsExplicit
+{
+public:
     HasExplicit aMember;
 };
 
diff --git a/test-suite/tcp-banger2.c b/test-suite/tcp-banger2.c
index 32f9dcd219..3de4cc673e 100644
--- a/test-suite/tcp-banger2.c
+++ b/test-suite/tcp-banger2.c
@@ -143,14 +143,14 @@ static void
 free_request(struct _request *r)
 {
     if (r->url)
-	free(r->url);
+        free(r->url);
     free(r);
 }
 
 #define RFC1123_STRFTIME "%a, %d %b %Y %H:%M:%S GMT"
 char *
 mkrfc1123(t)
-     time_t *t;
+time_t *t;
 {
     static char buf[128];
     struct tm *gmt = gmtime(t);
@@ -164,15 +164,15 @@ fd_close(int fd)
 {
     close(fd);
     if (FD[fd].ccb)
-	FD[fd].ccb(fd, FD[fd].data);
+        FD[fd].ccb(fd, FD[fd].data);
     FD[fd].ccb = NULL;
     FD[fd].cb = NULL;
     FD[fd].data = NULL;
     nfds--;
     if (fd == maxfd) {
-	while (fd > 0 && FD[fd].cb == NULL)
-	    fd--;
-	maxfd = fd;
+        while (fd > 0 && FD[fd].cb == NULL)
+            fd--;
+        maxfd = fd;
     }
 }
 
@@ -185,7 +185,7 @@ fd_open(int fd, CB * cb, void *data, CB * ccb)
     FD[fd].data = data;
     FD[fd].start = now.tv_sec;
     if (fd > maxfd)
-	maxfd = fd;
+        maxfd = fd;
     nfds++;
 }
 
@@ -206,62 +206,62 @@ read_reply(int fd, void *data)
     int len;
     int used = 0;
     if ((len = read(fd, buf, READ_BUF_SZ)) <= 0) {
-	fd_close(fd);
-	reqpersec++;
-	nrequests++;
-	return;
+        fd_close(fd);
+        reqpersec++;
+        nrequests++;
+        return;
     }
     total_bytes_read += len;
     if (r->headfound < 2) {
-	char *p, *header = NULL;
-	int oldlen = strlen(r->buf);
-	int newlen = oldlen + len;
-	assert(oldlen <= READ_BUF_SZ);
-	memcpy(r->buf + oldlen, buf, len);
-	r->buf[newlen + 1] = '\0';
-	for (p = r->buf; r->headfound < 2 && used < newlen; p++, used++) {
-	    switch (*p) {
-	    case '\n':
-		r->headfound++;
-		if (!header)
-		    break;
-		/* Decode header */
-		if (strncmp(header, "HTTP", 4) == 0)
-		    r->status = atoi(header + 8);
-		else if (strncasecmp(header, "Content-Length:", 15) == 0)
-		    r->content_length = atoi(header + 15);
-		else if (strncasecmp(header, "X-Request-URI:", 14) == 0) {
-		    /* Check URI */
-		    if (strncmp(r->url, header + 15, strcspn(header + 15, "\r\n"))) {
-			char url[8192];
-			strncpy(url, header + 15, strcspn(header + 15, "\r\n"));
-			url[strcspn(header + 15, "\r\n")] = '\n';
-			fprintf(stderr, "ERROR: Sent %s received %s\n",
-			    r->url, url);
-		    }
-		}
-		header = NULL;
-		break;
-	    case '\r':
-		break;
-	    default:
-		r->headfound = 0;
-		if (!header)
-		    header = p;
-		break;
-	    }
-	}
-	if (header) {
-	    memmove(r->buf, header, newlen - (header - r->buf) + 1);
-	}
-	assert(used >= oldlen);
-	used -= oldlen;
+        char *p, *header = NULL;
+        int oldlen = strlen(r->buf);
+        int newlen = oldlen + len;
+        assert(oldlen <= READ_BUF_SZ);
+        memcpy(r->buf + oldlen, buf, len);
+        r->buf[newlen + 1] = '\0';
+        for (p = r->buf; r->headfound < 2 && used < newlen; p++, used++) {
+            switch (*p) {
+            case '\n':
+                r->headfound++;
+                if (!header)
+                    break;
+                /* Decode header */
+                if (strncmp(header, "HTTP", 4) == 0)
+                    r->status = atoi(header + 8);
+                else if (strncasecmp(header, "Content-Length:", 15) == 0)
+                    r->content_length = atoi(header + 15);
+                else if (strncasecmp(header, "X-Request-URI:", 14) == 0) {
+                    /* Check URI */
+                    if (strncmp(r->url, header + 15, strcspn(header + 15, "\r\n"))) {
+                        char url[8192];
+                        strncpy(url, header + 15, strcspn(header + 15, "\r\n"));
+                        url[strcspn(header + 15, "\r\n")] = '\n';
+                        fprintf(stderr, "ERROR: Sent %s received %s\n",
+                                r->url, url);
+                    }
+                }
+                header = NULL;
+                break;
+            case '\r':
+                break;
+            default:
+                r->headfound = 0;
+                if (!header)
+                    header = p;
+                break;
+            }
+        }
+        if (header) {
+            memmove(r->buf, header, newlen - (header - r->buf) + 1);
+        }
+        assert(used >= oldlen);
+        used -= oldlen;
     }
     r->bodysize += len - used;
     if (opt_checksum) {
-	for (; used < len; used++) {
-	    r->sum += buf[used];
-	}
+        for (; used < len; used++) {
+            r->sum += buf[used];
+        }
     }
 }
 
@@ -272,34 +272,33 @@ reply_done(int fd, void *data)
     if (opt_range);		/* skip size checks for now */
     else if (strcmp(r->method, "HEAD") == 0);
     else if (r->bodysize != r->content_length && r->content_length >= 0)
-	fprintf(stderr, "ERROR: %s got %d of %d bytes\n",
-	    r->url, r->bodysize, r->content_length);
+        fprintf(stderr, "ERROR: %s got %d of %d bytes\n",
+                r->url, r->bodysize, r->content_length);
     else if (r->validsize >= 0) {
-	if (r->validsize != r->bodysize)
-	    fprintf(stderr, "WARNING: %s size mismatch wanted %d bytes got %d\n",
-		r->url, r->validsize, r->bodysize);
-	else if (opt_checksum && r->validsum != r->sum)
-	    fprintf(stderr, "WARNING: %s invalid checksum wanted 0x%lx got 0x%lx\n",
-		r->url, r->validsum, r->sum);
+        if (r->validsize != r->bodysize)
+            fprintf(stderr, "WARNING: %s size mismatch wanted %d bytes got %d\n",
+                    r->url, r->validsize, r->bodysize);
+        else if (opt_checksum && r->validsum != r->sum)
+            fprintf(stderr, "WARNING: %s invalid checksum wanted 0x%lx got 0x%lx\n",
+                    r->url, r->validsum, r->sum);
     }
     if (r->validstatus && r->status != r->validstatus) {
-	    fprintf(stderr, "WARNING: %s status mismatch wanted %d got %d\n",
-		r->url, r->validstatus, r->status);
+        fprintf(stderr, "WARNING: %s status mismatch wanted %d got %d\n",
+                r->url, r->validstatus, r->status);
     }
     if (trace_file) {
-	if (opt_checksum)
-	    fprintf(trace_file, "%s %s %d %s %d 0x%lx\n",
-		r->method, r->url, r->status, r->requestbodyfile, r->bodysize, r->sum);
-	else
-	    fprintf(trace_file, "%s %s %d %s %d\n",
-		r->method, r->url, r->status, r->requestbodyfile, r->bodysize);
+        if (opt_checksum)
+            fprintf(trace_file, "%s %s %d %s %d 0x%lx\n",
+                    r->method, r->url, r->status, r->requestbodyfile, r->bodysize, r->sum);
+        else
+            fprintf(trace_file, "%s %s %d %s %d\n",
+                    r->method, r->url, r->status, r->requestbodyfile, r->bodysize);
     }
     free_request(r);
 }
 
 struct _request *
-request(char *urlin)
-{
+            request(char *urlin) {
     int s = -1, f = -1;
     char buf[4096];
     char msg[8192];
@@ -312,19 +311,19 @@ request(char *urlin)
     struct sockaddr_in S;
     struct _request *r;
     if (*urlin == '\0')
-	return NULL;
+        return NULL;
     if ((s = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
-	perror("socket");
-	return NULL;
+        perror("socket");
+        return NULL;
     }
     memset(&S, '\0', sizeof(struct sockaddr_in));
     S.sin_family = AF_INET;
     S.sin_port = htons(proxy_port);
     S.sin_addr.s_addr = inet_addr(proxy_addr);
     if (connect(s, (struct sockaddr *) &S, sizeof(S)) < 0) {
-	close(s);
-	perror("connect");
-	return NULL;
+        close(s);
+        perror("connect");
+        return NULL;
     }
     strcpy(urlbuf, urlin);
     method = strtok(urlbuf, " ");
@@ -334,15 +333,15 @@ request(char *urlin)
     size = strtok(NULL, " ");
     checksum = strtok(NULL, " ");
     if (!url) {
-	url = method;
-	method = "GET";
+        url = method;
+        method = "GET";
     }
     if (!file)
-	file = "-";
+        file = "-";
     if (!size)
-	size = "-";
+        size = "-";
     if (!checksum)
-	checksum = "-";
+        checksum = "-";
     r = calloc(1, sizeof *r);
     assert(r != NULL);
     r->url = strdup(url);
@@ -351,95 +350,95 @@ request(char *urlin)
     strcpy(r->requestbodyfile, file);
     r->fd = s;
     if (size && strcmp(size, "-") != 0)
-	r->validsize = atoi(size);
+        r->validsize = atoi(size);
     else
-	r->validsize = -1;	/* Unknown */
+        r->validsize = -1;	/* Unknown */
     if (checksum && strcmp(checksum, "-") != 0)
-	r->validsum = strtoul(checksum, NULL, 0);
+        r->validsum = strtoul(checksum, NULL, 0);
     if (status)
-	r->validstatus = atoi(status);
+        r->validstatus = atoi(status);
     r->content_length = -1;	/* Unknown */
     if (opt_accel) {
-	host = strchr(url, '/') + 2;
-	url = strchr(host, '/');
+        host = strchr(url, '/') + 2;
+        url = strchr(host, '/');
     } else {
-	host = NULL;
+        host = NULL;
     }
     sprintf(msg, "%s %s HTTP/1.0\r\n", method, url);
     if (host) {
-	url[0] = '\0';
-	sprintf(buf, "Host: %s\r\n", host);
-	strcat(msg, buf);
-	url[0] = '/';
+        url[0] = '\0';
+        sprintf(buf, "Host: %s\r\n", host);
+        strcat(msg, buf);
+        url[0] = '/';
     }
     strcat(msg, "Accept: */*\r\n");
     if (opt_ims && (lrand48() & 0x03) == 0) {
-	w = time(NULL) - (lrand48() & 0x3FFFF);
-	sprintf(buf, "If-Modified-Since: %s\r\n", mkrfc850(&w));
-	strcat(msg, buf);
+        w = time(NULL) - (lrand48() & 0x3FFFF);
+        sprintf(buf, "If-Modified-Since: %s\r\n", mkrfc850(&w));
+        strcat(msg, buf);
     }
     if (file && strcmp(file, "-") != 0) {
-	f = open(file, O_RDONLY);
-	if (f < 0) {
-	    perror("open file");
-	    exit(1);
-	}
-	fstat(f, &st);
-	sprintf(buf, "Content-Length: %d\r\n", (int) st.st_size);
-	strcat(msg, buf);
+        f = open(file, O_RDONLY);
+        if (f < 0) {
+            perror("open file");
+            exit(1);
+        }
+        fstat(f, &st);
+        sprintf(buf, "Content-Length: %d\r\n", (int) st.st_size);
+        strcat(msg, buf);
     }
     if (opt_range && (lrand48() & 0x03) == 0) {
-	int len;
-	int count = 0;
-	strcat(msg, "Range: bytes=");
-	while (((len = (int) lrand48()) & 0x03) == 0 || !count) {
-	    const int offset = (int) lrand48();
-	    if (count)
-		strcat(msg, ",");
-	    switch (lrand48() & 0x03) {
-	    case 0:
-		sprintf(buf, "-%d", len);
-		break;
-	    case 1:
-		sprintf(buf, "%d-", offset);
-		break;
-	    default:
-		sprintf(buf, "%d-%d", offset, offset + len);
-		break;
-	    }
-	    strcat(msg, buf);
-	    count++;
-	}
-	strcat(msg, "\r\n");
+        int len;
+        int count = 0;
+        strcat(msg, "Range: bytes=");
+        while (((len = (int) lrand48()) & 0x03) == 0 || !count) {
+            const int offset = (int) lrand48();
+            if (count)
+                strcat(msg, ",");
+            switch (lrand48() & 0x03) {
+            case 0:
+                sprintf(buf, "-%d", len);
+                break;
+            case 1:
+                sprintf(buf, "%d-", offset);
+                break;
+            default:
+                sprintf(buf, "%d-%d", offset, offset + len);
+                break;
+            }
+            strcat(msg, buf);
+            count++;
+        }
+        strcat(msg, "\r\n");
     }
     strcat(msg, custom_header);
     strcat(msg, "\r\n");
     len = strlen(msg);
     if ((len2 = write(s, msg, len)) != len) {
-	close(s);
-	perror("write request");
-	free_request(r);
-	return NULL;
+        close(s);
+        perror("write request");
+        free_request(r);
+        return NULL;
     } else
-	total_bytes_written += len2;
+        total_bytes_written += len2;
     if (f >= 0) {
-	while ((len = read(f, buf, sizeof(buf))) > 0) {
-	    len2 = write(s, buf, len);
-	    if (len2 < 0) {
-		perror("write body");
-		close(s);
-		free_request(r);
-	    }
-	}
-	if (len < 0) {
-	    perror("read body");
-	    exit(1);
-	}
+        while ((len = read(f, buf, sizeof(buf))) > 0) {
+            len2 = write(s, buf, len);
+            if (len2 < 0) {
+                perror("write body");
+                close(s);
+                free_request(r);
+            }
+        }
+        if (len < 0) {
+            perror("read body");
+            exit(1);
+        }
     }
-/*
- * if (fcntl(s, F_SETFL, O_NDELAY) < 0)
- * perror("fcntl O_NDELAY");
- */
+    /*
+     * if (fcntl(s, F_SETFL, O_NDELAY) < 0)
+     * perror("fcntl O_NDELAY");
+     */
     return r;
 }
 
@@ -451,21 +450,21 @@ read_url(int fd, void *junk)
     char *t;
     buf[0] = '\0';
     if (fgets(buf, 8191, stdin) == NULL) {
-	printf("Done Reading URLS\n");
-	fd_close(0);
-	nfds++;
-	return;
+        printf("Done Reading URLS\n");
+        fd_close(0);
+        nfds++;
+        return;
     }
     if (buf[0] == '\0')
-	return;
+        return;
     if ((t = strchr(buf, '\n')))
-	*t = '\0';
+        *t = '\0';
     r = request(buf);
     if (!r) {
-	max_connections = nfds - 1;
-	printf("NOTE: max_connections set at %d\n", max_connections);
+        max_connections = nfds - 1;
+        printf("NOTE: max_connections set at %d\n", max_connections);
     } else {
-	fd_open(r->fd, read_reply, r, reply_done);
+        fd_open(r->fd, read_reply, r, reply_done);
     }
 }
 
@@ -483,8 +482,8 @@ usage(void)
 
 int
 main(argc, argv)
-     int argc;
-     char *argv[];
+int argc;
+char *argv[];
 {
     int i;
     int c;
@@ -501,48 +500,48 @@ main(argc, argv)
     start = last = now;
     custom_header = strdup("");
     while ((c = getopt(argc, argv, "ap:h:H:n:icrl:L:t:")) != -1) {
-	switch (c) {
-	case 'a':
-	    opt_accel = 1;
-	    break;
-	case 'p':
-	    proxy_port = atoi(optarg);
-	    break;
-	case 'h':
-	    proxy_addr = strdup(optarg);
-	    break;
-	case 'n':
-	    max_connections = atoi(optarg);
-	    break;
-	case 'i':
-	    opt_ims = 1;
-	    break;
-	case 'l':
-	    lifetime = (time_t) atoi(optarg);
-	    break;
-	case 'L':
-	    process_lifetime = (time_t) atoi(optarg);
-	    break;
-	case 'c':
-	    opt_checksum = 1;
-	    break;
-	case 't':
-	    trace_file = fopen(optarg, "a");
-	    assert(trace_file);
-	    setbuf(trace_file, NULL);
-	    break;
-	case 'r':
-	    opt_range = 1;
-	    break;
-	case 'H':
-	    custom_header = realloc(custom_header, strlen(custom_header) + strlen(optarg) + 2 + 1);
-	    strcat(custom_header, optarg);
-	    strcat(custom_header, "\r\n");
-	    break;
-	default:
-	    usage();
-	    return 1;
-	}
+        switch (c) {
+        case 'a':
+            opt_accel = 1;
+            break;
+        case 'p':
+            proxy_port = atoi(optarg);
+            break;
+        case 'h':
+            proxy_addr = strdup(optarg);
+            break;
+        case 'n':
+            max_connections = atoi(optarg);
+            break;
+        case 'i':
+            opt_ims = 1;
+            break;
+        case 'l':
+            lifetime = (time_t) atoi(optarg);
+            break;
+        case 'L':
+            process_lifetime = (time_t) atoi(optarg);
+            break;
+        case 'c':
+            opt_checksum = 1;
+            break;
+        case 't':
+            trace_file = fopen(optarg, "a");
+            assert(trace_file);
+            setbuf(trace_file, NULL);
+            break;
+        case 'r':
+            opt_range = 1;
+            break;
+        case 'H':
+            custom_header = realloc(custom_header, strlen(custom_header) + strlen(optarg) + 2 + 1);
+            strcat(custom_header, optarg);
+            strcat(custom_header, "\r\n");
+            break;
+        default:
+            usage();
+            return 1;
+        }
     }
     fd_open(0, read_url, NULL, NULL);
     nfds--;
@@ -550,58 +549,58 @@ main(argc, argv)
     signal(SIGPIPE, SIG_IGN);
     FD_ZERO(&R2);
     while (nfds || FD[0].cb) {
-	FD_ZERO(&R);
-	to.tv_sec = 0;
-	to.tv_usec = 100000;
-	if (nfds < max_connections && FD[0].cb)
-	    FD_SET(0, &R);
-	for (i = 1; i <= maxfd; i++) {
-	    if (FD[i].cb == NULL)
-		continue;
-	    if (now.tv_sec - FD[i].start > lifetime) {
-		fprintf(stderr, "WARNING: fd %d lifetime timeout\n", i);
-		fd_close(i);
-		continue;
-	    }
-	    FD_SET(i, &R);
-	}
-	if (select(maxfd + 1, &R, NULL, NULL, &to) < 0) {
-	    fprintf(stderr, "maxfd=%d\n", maxfd);
-	    if (errno != EINTR)
-		perror("select");
-	    continue;
-	}
-	gettimeofday(&now, NULL);
-	for (i = 0; i <= maxfd; i++) {
-	    if (!FD_ISSET(i, &R))
-		continue;
-	    FD[i].cb(i, FD[i].data);
-	    if (nfds < max_connections && FD[0].cb) {
-		j = 0;
-		FD_SET(0, &R2);
-		to.tv_sec = 0;
-		to.tv_usec = 0;
-		if (select(1, &R2, NULL, NULL, &to) == 1)
-		    FD[0].cb(0, FD[0].data);
-	    }
-	}
-	if (now.tv_sec > last.tv_sec) {
-	    last = now;
-	    dt = (int) (now.tv_sec - start.tv_sec);
-	    printf("T+ %6d: %9d req (%+4d), %4d conn, %3d/sec avg, %dmb, %dkb/sec avg\n",
-		dt,
-		nrequests,
-		reqpersec,
-		nfds,
-		(int) (nrequests / dt),
-		(int) (total_bytes_read / 1024 / 1024),
-		(int) (total_bytes_read / 1024 / dt));
-	    reqpersec = 0;
-	    /*
-	     * if (dt > process_lifetime)
-	     *     exit(0);
-	     */
-	}
+        FD_ZERO(&R);
+        to.tv_sec = 0;
+        to.tv_usec = 100000;
+        if (nfds < max_connections && FD[0].cb)
+            FD_SET(0, &R);
+        for (i = 1; i <= maxfd; i++) {
+            if (FD[i].cb == NULL)
+                continue;
+            if (now.tv_sec - FD[i].start > lifetime) {
+                fprintf(stderr, "WARNING: fd %d lifetime timeout\n", i);
+                fd_close(i);
+                continue;
+            }
+            FD_SET(i, &R);
+        }
+        if (select(maxfd + 1, &R, NULL, NULL, &to) < 0) {
+            fprintf(stderr, "maxfd=%d\n", maxfd);
+            if (errno != EINTR)
+                perror("select");
+            continue;
+        }
+        gettimeofday(&now, NULL);
+        for (i = 0; i <= maxfd; i++) {
+            if (!FD_ISSET(i, &R))
+                continue;
+            FD[i].cb(i, FD[i].data);
+            if (nfds < max_connections && FD[0].cb) {
+                j = 0;
+                FD_SET(0, &R2);
+                to.tv_sec = 0;
+                to.tv_usec = 0;
+                if (select(1, &R2, NULL, NULL, &to) == 1)
+                    FD[0].cb(0, FD[0].data);
+            }
+        }
+        if (now.tv_sec > last.tv_sec) {
+            last = now;
+            dt = (int) (now.tv_sec - start.tv_sec);
+            printf("T+ %6d: %9d req (%+4d), %4d conn, %3d/sec avg, %dmb, %dkb/sec avg\n",
+                   dt,
+                   nrequests,
+                   reqpersec,
+                   nfds,
+                   (int) (nrequests / dt),
+                   (int) (total_bytes_read / 1024 / 1024),
+                   (int) (total_bytes_read / 1024 / dt));
+            reqpersec = 0;
+            /*
+             * if (dt > process_lifetime)
+             *     exit(0);
+             */
+        }
     }
     printf("Exiting normally\n");
     return 0;
diff --git a/test-suite/tcp-banger3.c b/test-suite/tcp-banger3.c
index 9e299eb7f7..72b8d8fd55 100644
--- a/test-suite/tcp-banger3.c
+++ b/test-suite/tcp-banger3.c
@@ -131,53 +131,53 @@ get_url(const char *url)
     assert(!strncmp(url, "http://", 7));
     strncpy(host, url + 7, URL_BUF_SZ);
     if ((t = strchr(host, '/')))
-	*t = '\0';
+        *t = '\0';
     if ((t = strchr(host, ':'))) {
-	*t = '\0';
-	port = (unsigned short) atoi(t + 1);
+        *t = '\0';
+        port = (unsigned short) atoi(t + 1);
     }
 #if 0
     if ((int) port != 80)
-	return 0;
+        return 0;
 #endif
     t = strchr(url + 7, '/');
     strncpy(path, (t ? t : "/"), URL_BUF_SZ);
     memset(&S, '\0', sizeof(S));
     h = gethostbyname(host);
     if (!h)
-	return 0;
+        return 0;
     memcpy(&S.sin_addr.s_addr, h->h_addr_list[0], sizeof(S.sin_addr.s_addr));
     S.sin_port = htons(port);
     S.sin_family = AF_INET;
     if (debug)
-	fprintf(stderr, "%s (%s) %d %s\n", host, inet_ntoa(S.sin_addr), (int) port, path);
+        fprintf(stderr, "%s (%s) %d %s\n", host, inet_ntoa(S.sin_addr), (int) port, path);
     s = socket(PF_INET, SOCK_STREAM, 0);
     if (s < 0) {
-	perror("socket");
-	return -errno;
+        perror("socket");
+        return -errno;
     }
     x = connect(s, (struct sockaddr *) &S, sizeof(S));
     if (x < 0) {
-	perror(host);
-	return -errno;
+        perror(host);
+        return -errno;
     }
     snprintf(request, URL_BUF_SZ,
-	"GET %s HTTP/1.1\r\n"
-	"Accept: */*\r\n"
-	"Host: %s\r\n"
-	"Connection: close\r\n"
-	"\r\n",
-	path,
-	host);
+             "GET %s HTTP/1.1\r\n"
+             "Accept: */*\r\n"
+             "Host: %s\r\n"
+             "Connection: close\r\n"
+             "\r\n",
+             path,
+             host);
     x = write(s, request, strlen(request));
     if (x < 0) {
-	perror("write");
-	return -errno;
+        perror("write");
+        return -errno;
     }
     do {
-	x = read(s, reply, READ_BUF_SZ);
-	if (x > 0)
-	    nr += x;
+        x = read(s, reply, READ_BUF_SZ);
+        if (x > 0)
+            nr += x;
     } while (x > 0);
     close(s);
     return nr;
@@ -192,21 +192,21 @@ child_main_loop(void)
     struct timeval t1;
     struct timeval t2;
     if (debug)
-	fprintf(stderr, "Child PID %d entering child_main_loop\n", (int) getpid());
+        fprintf(stderr, "Child PID %d entering child_main_loop\n", (int) getpid());
     setbuf(stdin, NULL);
     setbuf(stdout, NULL);
     setbuf(stderr, NULL);
     while (fgets(buf, URL_BUF_SZ, stdin)) {
-	t = strchr(buf, '\n');
-	if (t == NULL)
-	    continue;
-	*t = '\0';
-	if (strncmp(buf, "http://", 7))
-	    continue;
-	gettimeofday(&t1, NULL);
-	n = get_url(buf);
-	gettimeofday(&t2, NULL);
-	printf("%d %d\n", n, tvSubMsec(t1, t2));
+        t = strchr(buf, '\n');
+        if (t == NULL)
+            continue;
+        *t = '\0';
+        if (strncmp(buf, "http://", 7))
+            continue;
+        gettimeofday(&t1, NULL);
+        n = get_url(buf);
+        gettimeofday(&t2, NULL);
+        printf("%d %d\n", n, tvSubMsec(t1, t2));
     }
 }
 
@@ -219,28 +219,28 @@ create_a_thing(char *argv[])
     pid_t pid;
     thing *t;
     if (pipe(p2c) < 0)
-	abort();
+        abort();
     if (pipe(c2p) < 0)
-	abort();
+        abort();
     prfd = p2c[0];
     cwfd = p2c[1];
     crfd = c2p[0];
     pwfd = c2p[1];
     if ((pid = fork()) < 0)
-	abort();
+        abort();
     if (pid > 0) {		/* parent */
-	/* close shared socket with child */
-	close(crfd);
-	close(cwfd);
-	t = calloc(1, sizeof(*t));
-	t->wfd = pwfd;
-	t->rfd = prfd;
-	if (pwfd > maxfd)
-	    maxfd = pwfd;
-	if (prfd > maxfd)
-	    maxfd = prfd;
-	t->pid = pid;
-	return t;
+        /* close shared socket with child */
+        close(crfd);
+        close(cwfd);
+        t = calloc(1, sizeof(*t));
+        t->wfd = pwfd;
+        t->rfd = prfd;
+        if (pwfd > maxfd)
+            maxfd = pwfd;
+        if (prfd > maxfd)
+            maxfd = prfd;
+        t->pid = pid;
+        return t;
     }
     /* child */
     close(prfd);
@@ -260,13 +260,13 @@ create_children(char *argv[])
     thing **T = &things;
     int i;
     for (i = 0; i < 20; i++) {
-	t = create_a_thing(argv);
-	assert(t);
-	if (debug)
-	    fprintf(stderr, "Thing #%d on FD %d/%d\n",
-		i, t->rfd, t->wfd);
-	*T = t;
-	T = &t->next;
+        t = create_a_thing(argv);
+        assert(t);
+        if (debug)
+            fprintf(stderr, "Thing #%d on FD %d/%d\n",
+                    i, t->rfd, t->wfd);
+        *T = t;
+        T = &t->next;
     }
 }
 
@@ -275,9 +275,9 @@ parent_read_url(void)
 {
     static char buf[URL_BUF_SZ];
     while (fgets(buf, URL_BUF_SZ, stdin)) {
-	if (strncmp(buf, "http://", 7))
-	    continue;
-	return buf;
+        if (strncmp(buf, "http://", 7))
+            continue;
+        return buf;
     }
     return NULL;
 }
@@ -288,9 +288,9 @@ get_idle_thing(void)
     thing *t;
     thing *n = things;
     while ((t = n)) {
-	n = t->next;
-	if (t->state == 0)
-	    break;
+        n = t->next;
+        if (t->state == 0)
+            break;
     }
     return t;
 }
@@ -303,12 +303,12 @@ dispatch(thing * t, char *url)
     assert(t->state == 0);
     x = write(t->wfd, url, strlen(url));
     if (x < 0)
-	perror("write");
+        perror("write");
     if (debug)
-	fprintf(stderr, "dispatched URL to thing PID %d, %d bytes\n", (int) t->pid, x);
+        fprintf(stderr, "dispatched URL to thing PID %d, %d bytes\n", (int) t->pid, x);
     strncpy(t->url, url, URL_BUF_SZ);
     if ((s = strchr(t->url, '\n')))
-	*s = '\0';
+        *s = '\0';
     t->state = 1;
     FD_SET(t->rfd, &R1);
 }
@@ -322,10 +322,10 @@ read_reply(thing * t)
     int j;
     x = read(t->rfd, buf, 128);
     if (x < 0) {
-	perror("read");
+        perror("read");
     } else if (2 == sscanf(buf, "%d %d", &i, &j)) {
-	gettimeofday(&now, NULL);
-	printf("%d.%06d %9d %9d %s\n", (int) now.tv_sec, (int) now.tv_usec, i, j, t->url);
+        gettimeofday(&now, NULL);
+        printf("%d.%06d %9d %9d %s\n", (int) now.tv_sec, (int) now.tv_usec, i, j, t->url);
     }
     t->state = 0;
     FD_CLR(t->rfd, &R1);
@@ -341,25 +341,25 @@ parent_main_loop(void)
     struct timeval to;
     FD_ZERO(&R1);
     for (;;) {
-	while ((t = get_idle_thing()) && (url = parent_read_url()))
-	    dispatch(t, url);
-	R2 = R1;
-	to.tv_sec = 60;
-	to.tv_usec = 0;
-	x = select(maxfd + 1, &R2, NULL, NULL, &to);
-	if (x < 0) {
-	    perror("select");
-	    continue;
-	} else if (x == 0) {
-	    return;
-	}
-	for (t = things; t; t = t->next) {
-	    if (t->state != 1)
-		continue;
-	    if (!FD_ISSET(t->rfd, &R2))
-		continue;
-	    read_reply(t);
-	}
+        while ((t = get_idle_thing()) && (url = parent_read_url()))
+            dispatch(t, url);
+        R2 = R1;
+        to.tv_sec = 60;
+        to.tv_usec = 0;
+        x = select(maxfd + 1, &R2, NULL, NULL, &to);
+        if (x < 0) {
+            perror("select");
+            continue;
+        } else if (x == 0) {
+            return;
+        }
+        for (t = things; t; t = t->next) {
+            if (t->state != 1)
+                continue;
+            if (!FD_ISSET(t->rfd, &R2))
+                continue;
+            read_reply(t);
+        }
     }
 }
 
@@ -369,7 +369,7 @@ sig_child(int sig)
     int status;
     pid_t pid;
     do {
-	pid = waitpid(-1, &status, WNOHANG);
+        pid = waitpid(-1, &status, WNOHANG);
     } while (pid > 0 || (pid < 0 && errno == EINTR));
     signal(sig, sig_child);
 }
@@ -383,6 +383,6 @@ main(int argc, char *argv[])
     create_children(argv);
     parent_main_loop();
     for (i = 3; i <= maxfd; i++)
-	close(i);
+        close(i);
     sleep(1);
 }
diff --git a/test-suite/test_tools.cc b/test-suite/test_tools.cc
index b77cca54e4..6e10b651a1 100644
--- a/test-suite/test_tools.cc
+++ b/test-suite/test_tools.cc
@@ -29,8 +29,7 @@ _db_print(const char *format,...)
 {
 #else
 _db_print(va_alist)
-va_dcl
-{
+va_dcl {
     const char *format = NULL;
 #endif
 
@@ -116,8 +115,7 @@ fatalf(const char *fmt,...) {
 #else
 void
 fatalf(va_alist)
-va_dcl
-{
+va_dcl {
     va_list args;
     const char *fmt = NULL;
     va_start(args);
@@ -169,10 +167,10 @@ Debug::finishDebug() {
 
 void
 Debug::xassert(const char *msg, const char *file, int line) {
-	
+
     if (CurrentDebug) {
         *CurrentDebug << "assertion failed: " << file << ":" << line <<
-            ": \"" << msg << "\"";
+        ": \"" << msg << "\"";
     }
     abort();
 }
diff --git a/test-suite/waiter.c b/test-suite/waiter.c
index 9a6a54e73b..5a3b39e630 100644
--- a/test-suite/waiter.c
+++ b/test-suite/waiter.c
@@ -16,8 +16,8 @@ main(int argc, char *argv[])
     to.tv_sec = alarm.tv_sec - now.tv_sec;
     to.tv_usec = alarm.tv_usec - now.tv_usec;
     if (to.tv_usec < 0) {
-	to.tv_usec += 1000000;
-	to.tv_sec -= 1;
+        to.tv_usec += 1000000;
+        to.tv_sec -= 1;
     }
     select(1, NULL, NULL, NULL, &to);
     return 0;