tags
test-suite/Makefile
testHeaders
+testHeaders.c
tmp
tools/Makefile
tools/cachemgr.cgi
* 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 <Richard.Huveneers@hekkihek.hacom.nl>)
*/
/* 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;
/*
* 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:
* - Added support for ldap URI via the -H option
* (requires OpenLDAP)
* 2001-12-12: Michael Cunningham <m.cunningham@xpedite.com>
- * - Added TLS support and partial ldap version 3 support.
+ * - Added TLS support and partial ldap version 3 support.
* 2001-10-04: Henrik Nordstrom <hno@squid-cache.org>
* - Be consistent with the other helpers in how
* spaces are managed. If there is space characters
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
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)
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
/* 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;
}
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 <userattr>=user,basedn\n\twill be used (same as specifying a search filter of '<userattr>=',\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 <userattr>=user,basedn\n\twill be used (same as specifying a search filter of '<userattr>=',\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;
}
{
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;
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;
}
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;
* 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.
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
-/*
+/*
* 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.
#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
* 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)))
* 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.
*/
/* 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);
}
/*
* 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;
/* 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);
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);
{
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;
}
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.
* 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.
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
{
/* 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);
}
Check_user(char *ConnectingUser)
{
if (Check_ifuserdenied(ConnectingUser) == 1)
- return 1;
+ return 1;
if (Check_ifuserallowed(ConnectingUser) == 0)
- return 1;
+ return 1;
return 0;
}
/* 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;
}
}
-/*
+/*
* 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.
#include <string.h>
#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
*/
uint32 X[16];
for (j = 0; j < 16; j++)
- X[j] = M[j];
+ X[j] = M[j];
AA = A;
BB = B;
D &= 0xFFFFFFFF;
for (j = 0; j < 16; j++)
- X[j] = 0;
+ X[j] = 0;
}
static void
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
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);
* 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.
/* Read configuration file. Abort wildly if error. */
if (OpenConfigFile() == 1)
- return 1;
+ return 1;
/*
* Read denied and allowed user files.
* 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.
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;
/* UNIX RFCNB (RFC1001/RFC1002) NetBIOS implementation
- *
+ *
* Version 1.0
* RFCNB Common Structures etc Defines
- *
+ *
* Copyright (C) Richard Sharpe 1996
- *
+ *
*/
/*
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You 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.
/* UNIX RFCNB (RFC1001/RFC1002) NetBIOS implementation
- *
+ *
* Version 1.0
* RFCNB Error Response Defines
- *
+ *
* Copyright (C) Richard Sharpe 1996
- *
+ *
*/
/*
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You 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.
/* UNIX RFCNB (RFC1001/RFC1002) NEtBIOS implementation
- *
+ *
* Version 1.0
* RFCNB IO Routines ...
- *
+ *
* Copyright (C) Richard Sharpe 1996
- *
+ *
*/
/*
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You 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.
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;
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;
}
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;
}
/* 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
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;
}
/* 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
}
-/* 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
+ *
*/
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;
+ }
}
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 */
/* 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;
}
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));
}
/* UNIX RFCNB (RFC1001/RFC1002) NetBIOS implementation
- *
+ *
* Version 1.0
* RFCNB IO Routines Defines
- *
+ *
* Copyright (C) Richard Sharpe 1996
- *
+ *
*/
/*
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You 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.
/* UNIX RFCNB (RFC1001/RFC1002) NetBIOS implementation
- *
+ *
* Version 1.0
* RFCNB Defines
- *
+ *
* Copyright (C) Richard Sharpe 1996
- *
+ *
*/
/*
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You 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.
} 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 */
#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;
* 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 */
/* UNIX RFCNB (RFC1001/RFC1002) NetBIOS implementation
- *
+ *
* Version 1.0
* RFCNB Utility Routines ...
- *
+ *
* Copyright (C) Richard Sharpe 1996
- *
+ *
*/
/*
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You 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 <arpa/inet.h>
#include <string.h>
-const char *RFCNB_Error_Strings[] =
-{
+const char *RFCNB_Error_Strings[] = {
"RFCNBE_OK: Routine completed successfully.",
"RFCNBE_NoSpace: No space available for a malloc call.",
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;
}
/* 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
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 */
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;
}
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;
}
if (j > 0) {
- outbuf1[j] = 0;
- fprintf(fd, " %s\n", outbuf1);
+ outbuf1[j] = 0;
+ fprintf(fd, " %s\n", outbuf1);
}
fprintf(fd, "\n");
/* 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);
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;
}
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;
}
}
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;
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));
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;
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 */
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
if ((len = RFCNB_Get_Pkt(con, &res_pkt, sizeof(resp))) < 0) {
- return (RFCNBE_Bad);
+ return (RFCNBE_Bad);
}
/* Now analyze the packet ... */
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;
}
}
/* UNIX RFCNB (RFC1001/RFC1002) NetBIOS implementation
- *
+ *
* Version 1.0
* RFCNB Utility Defines
- *
+ *
* Copyright (C) Richard Sharpe 1996
- *
+ *
*/
/*
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You 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.
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);
/* UNIX RFCNB (RFC1001/RFC1002) NetBIOS implementation
- *
+ *
* Version 1.0
* RFCNB Defines
- *
+ *
* Copyright (C) Richard Sharpe 1996
- *
+ *
*/
/*
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You 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.
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);
/* UNIX RFCNB (RFC1001/RFC1002) NetBIOS implementation
- *
+ *
* Version 1.0
* Session Routines ...
- *
+ *
* Copyright (C) Richard Sharpe 1996
- *
+ *
*/
/*
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You 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.
/* 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;
/* 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 */
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 */
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 ... */
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 */
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 */
}
-/* 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
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 */
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 */
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 */
{
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;
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));
}
}
-/*
+/*
* 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
#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
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
{
int i;
for (i = 0; i < n; i++)
- out[i] = in1[i] ^ in2[i];
+ out[i] = in1[i] ^ in2[i];
}
static void
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);
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);
}
}
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);
}
-/*
+/*
* 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.
/*
* 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)
{
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.
*/
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.
*/
/* 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 */
{
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;
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++;
+ }
}
}
/* UNIX SMBlib NetBIOS implementation
- *
+ *
* Version 1.0
* SMBlib Common Defines
- *
+ *
* Copyright (C) Richard Sharpe 1996
- *
+ *
*/
/*
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You 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.
/* UNIX SMBlib NetBIOS implementation
- *
+ *
* Version 1.0
* SMBlib private Defines
- *
+ *
* Copyright (C) Richard Sharpe 1996
- *
+ *
*/
/*
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You 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.
#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 */
#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 */
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;
/* UNIX SMBlib NetBIOS implementation
- *
+ *
* Version 1.0
* SMBlib Utility Routines
- *
+ *
* Copyright (C) Richard Sharpe 1996
- *
+ *
*/
/*
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You 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 <string.h>
#include <unistd.h>
-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 */
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);
}
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 */
}
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;
}
if (pkt == NULL) {
- SMBlib_errno = SMBlibE_NoSpace;
- return (SMBlibE_BAD);
+ SMBlib_errno = SMBlibE_NoSpace;
+ return (SMBlibE_BAD);
}
/* Now plug in the bits we need */
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 */
}
#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 ... */
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 */
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
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
}
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;
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 ... */
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;
}
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 ... */
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 ... */
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);
#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;
}
/* 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.",
"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)
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));
- }
+ }
}
}
/* UNIX SMBlib NetBIOS implementation
- *
+ *
* Version 1.0
* SMBlib Routines
- *
+ *
* Copyright (C) Richard Sharpe 1996
- *
+ *
*/
/*
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You 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.
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();
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;
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 ... */
* 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);
/* 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;
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 ... */
* 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);
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;
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;
}
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 ... */
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 ... */
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 ... */
RFCNB_Hangup(Con_Handle->Trans_Connect);
if (!KeepHandle)
- free(Con_Handle);
+ free(Con_Handle);
return (0);
/* UNIX SMBlib NetBIOS implementation
- *
+ *
* Version 1.0
* SMBlib Defines
- *
+ *
* Copyright (C) Richard Sharpe 1996
- *
+ *
*/
/*
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You 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.
/* 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 */
/* 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 ... */
/* 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 */
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);
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);
/* RFCNB Standard includes ... */
/*
- *
+ *
* SMBlib Standard Includes
- *
+ *
* Copyright (C) 1996, Richard Sharpe
*/
/* One day we will conditionalize these on OS types ... */
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You 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.
/* RFCNB Standard includes ... */
/*
- *
+ *
* RFCNB Standard Includes
- *
+ *
* Copyright (C) 1996, Richard Sharpe
*/
/* One day we will conditionalize these on OS types ... */
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You 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.
* 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.
{
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;
}
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;
/* 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;
}
/* 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.
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);
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;
}
}
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 */
/* 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;
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));
* 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);
/* Created by Ramon de Carvalho <ramondecarvalho@yahoo.com.br>
Refined by Rodrigo Rubira Branco <rodrigo@kernelhacking.com>
*/
-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;
}
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);
}
user_data *u;
setbuf(stdout, NULL);
if (argc != 2) {
- fprintf(stderr, "Usage: ncsa_auth <passwordfile>\n");
- exit(1);
+ fprintf(stderr, "Usage: ncsa_auth <passwordfile>\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);
}
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;
return ((*resp)[0].resp ? PAM_SUCCESS : PAM_CONV_ERR);
}
-static struct pam_conv conv =
-{
+static struct pam_conv conv = {
&password_conversation,
NULL
};
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;
}
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;
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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);
}
}
/* 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;
/* Free last entry */
if (val) {
- free(val);
- val = NULL;
+ free(val);
+ val = NULL;
}
/* Get NIS entry */
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;
}
}
-extern char * get_nis_password(char *user, char *nisdomain, char *nismap);
+extern char * get_nis_password(char *user, char *nisdomain, char *nismap);\r
setbuf(stdout, NULL);
if (argc != 3) {
- fprintf(stderr, "Usage: yp_auth <domainname> <nis map for password>\n");
- fprintf(stderr, "\n");
- fprintf(stderr, "Example yp_auth mydomain.com passwd.byname\n");
- exit(1);
+ fprintf(stderr, "Usage: yp_auth <domainname> <nis map for password>\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);
}
*
* 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
* + can handle PAM request
*
* 2006-07: Giancarlo Razzolini <linux-fan@onda.com.br>
- *
+ *
* Added functionality for doing shadow authentication too,
* using the getspnam() function on systems that support it.
*
#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
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);
}
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
-
+
* You should have received a copy of the GNU General 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 <stdio.h>
-#include <getopt.h>
+#include <stdio.h>
+#include <getopt.h>
#include "util.h"
/* Check if we try to compile on a Windows Platform */
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
{
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);
}
}
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;
}
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
-
+
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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;
}
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;
}
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
-
+
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
#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 */
* 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
*/
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"
*/
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);
+ }
}
/*
*/
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);
}
/*
*/
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);
}
* 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
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
* 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
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);
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;
}
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);
}
}
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;
}
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';
}
*ptr++ = PW_USER_NAME;
length = strlen(username);
if (length > MAXPWNAM) {
- length = MAXPWNAM;
+ length = MAXPWNAM;
}
*ptr++ = length + 2;
memcpy(ptr, username, length);
*/
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;
/* 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;
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 <kw@w-m-p.com> changed this
* 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);
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
/*
*/
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;
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);
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)
*/
* - 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
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;
}
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);
}
RequestData requestData;
ParseBuffer(buf, &requestData);
if (!requestData.parsed) {
- printf("ERR\n");
- return;
+ printf("ERR\n");
+ return;
}
OutputHHA1(&requestData);
}
int i;
i = LDAPArguments(argc, argv);
if (i)
- exit(i);
+ exit(i);
}
int
setbuf(stdout, NULL);
ProcessArguments(argc, argv);
while (fgets(buf, 256, stdin) != NULL)
- DoOneRequest(buf);
+ DoOneRequest(buf);
exit(0);
}
-/*
+/*
* 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
* 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"
**********************************************************************/
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;
}
/**********************************************************************
**********************************************************************/
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;
}
/**********************************************************************
**********************************************************************/
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;
}
/**********************************************************************
**********************************************************************/
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;
}
/**********************************************************************
**********************************************************************/
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;
}
**********************************************************************/
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;
}
/**********************************************************************
*********************************************************************/
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;
}
-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);\r
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
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)
{
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;
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;
}
{
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
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;
}
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);
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;
}
}
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)
*/
* - 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
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;
}
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);
}
RequestData requestData;
ParseBuffer(buf, &requestData);
if (!requestData.parsed) {
- printf("ERR\n");
- return;
+ printf("ERR\n");
+ return;
}
OutputHHA1(&requestData);
}
int i;
i = LDAPArguments(argc, argv);
if (i)
- exit(i);
+ exit(i);
}
int
setbuf(stdout, NULL);
ProcessArguments(argc, argv);
while (fgets(buf, 256, stdin) != NULL)
- DoOneRequest(buf);
+ DoOneRequest(buf);
exit(0);
}
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
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)
{
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;
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;
}
{
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
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;
}
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);
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;
}
}
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)
*/
* - 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
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;
}
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);
}
RequestData requestData;
ParseBuffer(buf, &requestData);
if (!requestData.parsed) {
- printf("ERR\n");
- return;
+ printf("ERR\n");
+ return;
}
OutputHHA1(&requestData);
}
setbuf(stdout, NULL);
ProcessArguments(argc, argv);
while (fgets(buf, 256, stdin) != NULL)
- DoOneRequest(buf);
+ DoOneRequest(buf);
exit(0);
}
* - 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
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);
}
{
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] <passwordfile>\n");
- fprintf(stderr, " -c accept digest hashed passwords rather than plaintext in passwordfile\n");
- exit(1);
+ fprintf(stderr, "Usage: digest_pw_auth [OPTIONS] <passwordfile>\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);
}
}
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;
}
{
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);
}
}
* - 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
-/* $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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#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
* 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
*/
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 */
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
-*
+*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
-*
+*
* You 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 *);
-/* $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"
static void
usage (char *program_name)
{
- fprintf (stderr, "Usage:\n%s -f <configuration file>\n",
- program_name);
+ fprintf (stderr, "Usage:\n%s -f <configuration file>\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;
}
-/* $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 <stdio.h>
#include <string.h>
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 */
* 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 <flavio@marasystems.com>
* Henrik Nordstrom <hno@marasystems.com>
*
* 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.
*/
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
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)
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;
}
{
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;
{
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;
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;
{
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);
}
}
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);
* 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.
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;
}
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;
}
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;
}
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);
/* 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;
}
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
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;
}
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();
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;
}
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
-
+
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
#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 */
* 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.
* 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.
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);
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;
}
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;
}
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);
/* 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;
}
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
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;
}
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();
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;
}
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
-
+
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
#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 */
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
{
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);
}
}
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;
}
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);
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;
*
* 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:
*
#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
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;
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;
}
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");
}
/* 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;
}
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
-
+
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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 = '.';
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);
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
-
+
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
#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__ */
{
char *p = string, c;
while ((c = *p)) {
- *p = xtoupper(c);
- p++;
+ *p = xtoupper(c);
+ p++;
}
}
{
char *p = string, c;
while ((c = *p)) {
- *p = xtolower(c);
- p++;
+ *p = xtolower(c);
+ p++;
}
}
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);
}
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
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) {
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);
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);
}
} 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(),
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
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");
setbuf(stderr, NULL);
while (manage_request()) {
- /* everything is done within manage_request */
+ /* everything is done within manage_request */
}
exit(0);
}
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;
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;
}
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;
}
// 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
};
/////////////////////////////////////////////////////////////////////////////
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;
}
// [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:
////////////////////////////////////////////////////////////////////////////
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;
}
/////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
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;
}
/////////////////////////////////////////////////////////////////////////////
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;
+ }
}
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;
}
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;
}
/////////////////////////////////////////////////////////////////////////////
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;
}
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;
}
/////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
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;
}
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;
}
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;
}
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;
}
{
#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 */
#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 */
// 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
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;
}
/////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
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;
}
/////////////////////////////////////////////////////////////////////////////
//
////////////////////////////////////////////////////////////////////////////
-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;
}
/////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
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;;
}
/////////////////////////////////////////////////////////////////////////////
void spnegoFreeData( SPNEGO_TOKEN_HANDLE hSpnegoToken )
{
- FreeSpnegoToken( (SPNEGO_TOKEN*) hSpnegoToken);
- return;
+ FreeSpnegoToken( (SPNEGO_TOKEN*) hSpnegoToken);
+ return;
}
/////////////////////////////////////////////////////////////////////////////
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;
}
/////////////////////////////////////////////////////////////////////////////
// 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;;
}
/////////////////////////////////////////////////////////////////////////////
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;;
}
/////////////////////////////////////////////////////////////////////////////
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;;
}
/////////////////////////////////////////////////////////////////////////////
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;;
}
/////////////////////////////////////////////////////////////////////////////
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;;
}
/////////////////////////////////////////////////////////////////////////////
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;;
}
// 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
// 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
// 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)
#endif
#ifdef DEBUG
#include <stdio.h>
- #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
/* Check arguments. */\r
\r
if (!kerberosToken ||\r
- !negTokenTarg ||\r
- !negTokenTargLength)\r
+ !negTokenTarg ||\r
+ !negTokenTargLength)\r
return 10;\r
\r
/* Does IIS reply with 1.2.840.48018.1.2.2 or 1.2.840.113554.1.2.2? */\r
0,\r
&hSpnegoToken);\r
\r
- if (rc2 != SPNEGO_E_SUCCESS)\r
- {\r
+ if (rc2 != SPNEGO_E_SUCCESS) {\r
rc1 = abs(rc2)+100;\r
goto cleanup;\r
}\r
NULL,\r
(unsigned long*) negTokenTargLength);\r
\r
- if (rc2 != SPNEGO_E_BUFFER_TOO_SMALL)\r
- {\r
+ if (rc2 != SPNEGO_E_BUFFER_TOO_SMALL) {\r
rc1 = abs(rc2)+200;\r
goto cleanup;\r
}\r
\r
*negTokenTarg = malloc (*negTokenTargLength);\r
\r
- if (!*negTokenTarg)\r
- {\r
+ if (!*negTokenTarg) {\r
rc1 = abs(rc2)+300;\r
goto cleanup;\r
}\r
/* Get NegTokenTarg data. */\r
\r
rc2 = spnegoTokenGetBinary (hSpnegoToken,\r
- (unsigned char *) *negTokenTarg,\r
- (unsigned long*) negTokenTargLength);\r
+ (unsigned char *) *negTokenTarg,\r
+ (unsigned long*) negTokenTargLength);\r
\r
\r
- if (rc2 != SPNEGO_E_SUCCESS)\r
- {\r
+ if (rc2 != SPNEGO_E_SUCCESS) {\r
rc1 = abs(rc2)+400;\r
goto error;\r
}\r
\r
error:\r
\r
- if (*negTokenTarg)\r
- {\r
+ if (*negTokenTarg) {\r
free ((unsigned char *) *negTokenTarg);\r
*negTokenTarg = NULL;\r
*negTokenTargLength = 0;\r
/* Check arguments. */\r
\r
if (!negTokenInit ||\r
- !kerberosToken ||\r
- !kerberosTokenLength)\r
+ !kerberosToken ||\r
+ !kerberosTokenLength)\r
return 10;\r
\r
/* Decode SPNEGO token. */\r
negTokenInitLength,\r
&hSpnegoToken);\r
\r
- if (rc2 != SPNEGO_E_SUCCESS)\r
- {\r
+ if (rc2 != SPNEGO_E_SUCCESS) {\r
rc1 = abs(rc2)+100;\r
goto cleanup;\r
}\r
rc2 = spnegoGetTokenType (hSpnegoToken,\r
&tokenType);\r
\r
- if (rc2 != SPNEGO_E_SUCCESS)\r
- {\r
+ if (rc2 != SPNEGO_E_SUCCESS) {\r
rc1 = abs(rc2)+200;\r
goto cleanup;\r
}\r
\r
- if (tokenType != SPNEGO_TOKEN_INIT)\r
- {\r
+ if (tokenType != SPNEGO_TOKEN_INIT) {\r
rc1 = abs(rc2)+300;\r
goto cleanup;\r
}\r
\r
- /*\r
- Check that first mechType is 1.2.840.113554.1.2.2 or 1.2.840.48018.1.2.2.\r
- */\r
+ /*\r
+ Check that first mechType is 1.2.840.113554.1.2.2 or 1.2.840.48018.1.2.2.\r
+ */\r
\r
- /*\r
- IE seems to reply with 1.2.840.48018.1.2.2 and then 1.2.840.113554.1.2.2.\r
- */\r
+ /*\r
+ IE seems to reply with 1.2.840.48018.1.2.2 and then 1.2.840.113554.1.2.2.\r
+ */\r
\r
rc2 = spnegoIsMechTypeAvailable (hSpnegoToken,\r
spnego_mech_oid_Kerberos_V5_Legacy,\r
&pindex);\r
\r
if (rc2 != SPNEGO_E_SUCCESS ||\r
- pindex != 0)\r
- {\r
+ pindex != 0) {\r
rc2 = spnegoIsMechTypeAvailable (hSpnegoToken,\r
spnego_mech_oid_Kerberos_V5,\r
&pindex);\r
\r
if (rc2 != SPNEGO_E_SUCCESS ||\r
- pindex != 0)\r
- {\r
+ pindex != 0) {\r
rc1 = abs(rc2)+400;\r
goto cleanup;\r
}\r
rc2 = spnegoGetContextFlags (hSpnegoToken,\r
&reqFlags);\r
\r
- if (rc2 == SPNEGO_E_SUCCESS)\r
- {\r
+ if (rc2 == SPNEGO_E_SUCCESS) {\r
rc1 = abs(rc2)+500;\r
goto cleanup;\r
}\r
NULL,\r
(unsigned long*) kerberosTokenLength);\r
\r
- if (rc2 != SPNEGO_E_BUFFER_TOO_SMALL)\r
- {\r
+ if (rc2 != SPNEGO_E_BUFFER_TOO_SMALL) {\r
rc1 = abs(rc2)+600;\r
goto cleanup;\r
}\r
\r
*kerberosToken = malloc (*kerberosTokenLength);\r
\r
- if (!*kerberosToken)\r
- {\r
+ if (!*kerberosToken) {\r
rc1 = abs(rc2)+700;\r
goto cleanup;\r
}\r
(unsigned char *) *kerberosToken,\r
(unsigned long*) kerberosTokenLength);\r
\r
- if (rc2 != SPNEGO_E_SUCCESS)\r
- {\r
+ if (rc2 != SPNEGO_E_SUCCESS) {\r
rc1 = abs(rc2)+800;\r
goto error;\r
}\r
\r
error:\r
\r
- if (*kerberosToken)\r
- {\r
+ if (*kerberosToken) {\r
free ((unsigned char *) *kerberosToken);\r
*kerberosToken = NULL;\r
*kerberosTokenLength = 0;\r
*/\r
\r
#ifndef SPNEGOHELP_H\r
-#define SPNEGOHELP_H\r
+\r#define SPNEGOHELP_H\r
\r
#ifdef __cplusplus\r
-extern "C" {\r
+\rextern "C"\r
+{\r
#endif\r
-\r
+\r\r
#include <stddef.h>\r
\r
-/* -----------------------------------------------------------------------------\r
- * makeNegTokenTarg makes an RFC 2478 SPNEGO NegTokenTarg (token) from an\r
- * RFC 1964 Kerberos GSS-API token.\r
- *\r
- * If makeNegTokenTarg is successful, call free (*negTokenTarg) to free the\r
- * memory allocated by parseNegTokenInit.\r
- *\r
- * Returns 0 if successful, 1 otherwise.\r
- * -----------------------------------------------------------------------------\r
- */\r
-\r
-int makeNegTokenTarg (const unsigned char * kerberosToken,\r
- size_t kerberosTokenLength,\r
- const unsigned char ** negTokenTarg,\r
- size_t * negTokenTargLength);\r
-\r
-/* -----------------------------------------------------------------------------\r
- * parseNegTokenInit parses an RFC 2478 SPNEGO NegTokenInit (token) to extract\r
- * an RFC 1964 Kerberos GSS-API token.\r
- *\r
- * If the NegTokenInit does cotain a Kerberos GSS-API token, parseNegTokenInit\r
- * returns an error.\r
- *\r
- * If parseNegTokenInit is successful, call free (*kerberosToken) to\r
- * free the memory allocated by parseNegTokenInit.\r
- *\r
- * Returns 0 if successful, 1 otherwise.\r
- * -----------------------------------------------------------------------------\r
- */\r
-\r
-int parseNegTokenInit (const unsigned char * negTokenInit,\r
- size_t negTokenInitLength,\r
- const unsigned char ** kerberosToken,\r
- size_t * kerberosTokenLength);\r
+ /* -----------------------------------------------------------------------------\r
+ * makeNegTokenTarg makes an RFC 2478 SPNEGO NegTokenTarg (token) from an\r
+ * RFC 1964 Kerberos GSS-API token.\r
+ *\r
+ * If makeNegTokenTarg is successful, call free (*negTokenTarg) to free the\r
+ * memory allocated by parseNegTokenInit.\r
+ *\r
+ * Returns 0 if successful, 1 otherwise.\r
+ * -----------------------------------------------------------------------------\r
+ */\r
+\r
+ int makeNegTokenTarg (const unsigned char * kerberosToken,\r
+ size_t kerberosTokenLength,\r
+ const unsigned char ** negTokenTarg,\r
+ size_t * negTokenTargLength);\r
+\r
+ /* -----------------------------------------------------------------------------\r
+ * parseNegTokenInit parses an RFC 2478 SPNEGO NegTokenInit (token) to extract\r
+ * an RFC 1964 Kerberos GSS-API token.\r
+ *\r
+ * If the NegTokenInit does cotain a Kerberos GSS-API token, parseNegTokenInit\r
+ * returns an error.\r
+ *\r
+ * If parseNegTokenInit is successful, call free (*kerberosToken) to\r
+ * free the memory allocated by parseNegTokenInit.\r
+ *\r
+ * Returns 0 if successful, 1 otherwise.\r
+ * -----------------------------------------------------------------------------\r
+ */\r
+\r
+ int parseNegTokenInit (const unsigned char * negTokenInit,\r
+ size_t negTokenInitLength,\r
+ const unsigned char ** kerberosToken,\r
+ size_t * kerberosTokenLength);\r
\r
#ifdef __cplusplus\r
-}\r
+\r}\r
#endif\r
-\r
+\r\r
#endif /* SPNEGOHELP_H */\r
+\r
\ No newline at end of file
////////////////////////////////////////////////////////////////////////////
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;
}
////////////////////////////////////////////////////////////////////////////
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;
}
////////////////////////////////////////////////////////////////////////////
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;
}
////////////////////////////////////////////////////////////////////////////
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;
}
////////////////////////////////////////////////////////////////////////////
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;
}
/////////////////////////////////////////////////////////////////////////////
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 );
+ }
}
/////////////////////////////////////////////////////////////////////////////
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;
+ }
+
}
/////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
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;
}
////////////////////////////////////////////////////////////////////////////
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;
}
/////////////////////////////////////////////////////////////////////////////
//
// 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;
}
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;
}
////////////////////////////////////////////////////////////////////////////
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;
}
////////////////////////////////////////////////////////////////////////////
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;
}
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;
}
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 );
}
/////////////////////////////////////////////////////////////////////////////
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 );
}
/////////////////////////////////////////////////////////////////////////////
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 );
}
/////////////////////////////////////////////////////////////////////////////
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;
}
/////////////////////////////////////////////////////////////////////////////
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;
}
/////////////////////////////////////////////////////////////////////////////
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;
}
/////////////////////////////////////////////////////////////////////////////
// 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;
}
// 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.
//
// 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)
// 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)
// 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
#undef VERSION
#endif
/*
- * Reset varibles
+ * Reset varibles
*/
#include "config.h"
#endif
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;
+ }
}
- }
}
#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);
}
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
-
+
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
/* 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);
#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
dc_disconnect()
{
if (handle != NULL)
- SMB_Discon(handle, 0);
+ SMB_Discon(handle, 0);
handle = NULL;
}
{
SMB_Handle_Type h = SMB_Connect_Server(NULL, domain_controller, domain);
if (h == NULL)
- return 0;
+ return 0;
SMB_Discon(h, 0);
return 1;
}
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);
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;
}
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);
}
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;
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);
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. */
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
-
+
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
-
+
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
{
char *p = string, c;
while ((c = *p)) {
- *p = xtoupper(c);
- p++;
+ *p = xtoupper(c);
+ p++;
}
}
{
char *p = string, c;
while ((c = *p)) {
- *p = xtolower(c);
- p++;
+ *p = xtolower(c);
+ p++;
}
}
#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
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;
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 */
}
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;
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 ********/
}
/* 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;
}
-/*
+/*
* 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
* 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)))
-/*
+/*
* 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 <string.h>
uint32 X[16];
for (j = 0; j < 16; j++)
- X[j] = M[j];
+ X[j] = M[j];
AA = A;
BB = B;
D &= 0xFFFFFFFF;
for (j = 0; j < 16; j++)
- X[j] = 0;
+ X[j] = 0;
}
static void
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
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);
-void mdfour(unsigned char *out, unsigned char *in, int n);
+void mdfour(unsigned char *out, unsigned char *in, int n);\r
/* UNIX RFCNB (RFC1001/RFC1002) NetBIOS implementation
- *
+ *
* Version 1.0
* RFCNB Common Structures etc Defines
- *
+ *
* Copyright (C) Richard Sharpe 1996
- *
+ *
*/
/*
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You 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.
/* UNIX RFCNB (RFC1001/RFC1002) NetBIOS implementation
- *
+ *
* Version 1.0
* RFCNB Error Response Defines
- *
+ *
* Copyright (C) Richard Sharpe 1996
- *
+ *
*/
/*
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You 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.
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.",
* "RFCNBE_CallRejUnSpec: Call rejected. Unspecified error.",
* "RFCNBE_BadParam: Bad parameters passed to a routine.",
* "RFCNBE_Timeout: IO Operation timed out ..."
- *
+ *
* };
*/
/* UNIX RFCNB (RFC1001/RFC1002) NEtBIOS implementation
- *
+ *
* Version 1.0
* RFCNB IO Routines ...
- *
+ *
* Copyright (C) Richard Sharpe 1996
- *
+ *
*/
/*
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You 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.
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
}
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;
}
/* 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
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;
}
/* 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
}
-/* 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
+ *
*/
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;
+ }
}
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 */
/* 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;
}
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));
}
/* UNIX RFCNB (RFC1001/RFC1002) NetBIOS implementation
- *
+ *
* Version 1.0
* RFCNB IO Routines Defines
- *
+ *
* Copyright (C) Richard Sharpe 1996
- *
+ *
*/
/*
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You 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.
#define __RFCNB_H__
/* UNIX RFCNB (RFC1001/RFC1002) NetBIOS implementation
- *
+ *
* Version 1.0
* RFCNB Defines
- *
+ *
* Copyright (C) Richard Sharpe 1996
- *
+ *
*/
/*
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You 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.
} 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 */
#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;
* 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 */
/* UNIX RFCNB (RFC1001/RFC1002) NetBIOS implementation
- *
+ *
* Version 1.0
* RFCNB Utility Routines ...
- *
+ *
* Copyright (C) Richard Sharpe 1996
- *
+ *
*/
/*
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You 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.
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;
}
/* 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
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 */
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;
}
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;
}
if (j > 0) {
- outbuf1[j] = 0;
- fprintf(fd, " %s\n", outbuf1);
+ outbuf1[j] = 0;
+ fprintf(fd, " %s\n", outbuf1);
}
fprintf(fd, "\n");
/* 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);
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;
}
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;
}
}
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;
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));
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;
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 */
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
if ((len = RFCNB_Get_Pkt(con, &res_pkt, sizeof(resp))) < 0) {
- return (RFCNBE_Bad);
+ return (RFCNBE_Bad);
}
/* Now analyze the packet ... */
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;
}
}
/* UNIX RFCNB (RFC1001/RFC1002) NetBIOS implementation
- *
+ *
* Version 1.0
* RFCNB Utility Defines
- *
+ *
* Copyright (C) Richard Sharpe 1996
- *
+ *
*/
/*
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You 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.
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);
/* UNIX RFCNB (RFC1001/RFC1002) NetBIOS implementation
- *
+ *
* Version 1.0
* RFCNB Defines
- *
+ *
* Copyright (C) Richard Sharpe 1996
- *
+ *
*/
/*
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You 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.
/* 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);
/* UNIX RFCNB (RFC1001/RFC1002) NetBIOS implementation
- *
+ *
* Version 1.0
* Session Routines ...
- *
+ *
* Copyright (C) Richard Sharpe 1996
- *
+ *
*/
/*
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You 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.
/* 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.",
/* 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;
/* 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 */
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 */
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 ... */
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 */
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 */
}
-/* 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
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 */
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 */
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 */
{
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;
{
return (setsockopt(con_Handle->fd, IPPROTO_TCP, TCP_NODELAY,
- (char *) &yn, sizeof(yn)));
+ (char *) &yn, sizeof(yn)));
}
{
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));
}
}
-/*
+/*
* 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
-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
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
{
int i;
for (i = 0; i < n; i++)
- out[i] = in1[i] ^ in2[i];
+ out[i] = in1[i] ^ in2[i];
}
static void
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);
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);
}
}
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);
}
-/*
+/*
* 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.
/*
* 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)
{
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.
*/
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.
*/
/* 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 */
{
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;
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++;
+ }
}
}
#define __SMBLIB_COMMON_H__
/* UNIX SMBlib NetBIOS implementation
- *
+ *
* Version 1.0
* SMBlib Common Defines
- *
+ *
* Copyright (C) Richard Sharpe 1996
- *
+ *
*/
/*
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You 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.
#define __SMBLIB_PRIV_H__
/* UNIX SMBlib NetBIOS implementation
- *
+ *
* Version 1.0
* SMBlib private Defines
- *
+ *
* Copyright (C) Richard Sharpe 1996
- *
+ *
*/
/*
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You 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.
#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 */
#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 */
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",
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;
#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);
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);
/* UNIX SMBlib NetBIOS implementation
- *
+ *
* Version 1.0
* SMBlib Utility Routines
- *
+ *
* Copyright (C) Richard Sharpe 1996
- *
+ *
*/
/*
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You 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.
/* 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 ... */
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 *
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);
SMB_Get_Tree_MBS(SMB_Tree_Handle tree)
{
if (tree != NULL) {
- return (tree->mbs);
+ return (tree->mbs);
} else {
- return (SMBlibE_BAD);
+ return (SMBlibE_BAD);
}
}
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);
}
}
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 */
}
}
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 */
}
}
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);
}
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 */
}
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;
}
if (pkt == NULL) {
- SMBlib_errno = SMBlibE_NoSpace;
- return (SMBlibE_BAD);
+ SMBlib_errno = SMBlibE_NoSpace;
+ return (SMBlibE_BAD);
}
/* Now plug in the bits we need */
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 */
}
#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 ... */
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 */
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
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
}
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;
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 ... */
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;
}
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 ... */
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 ... */
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);
#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;
}
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 ... */
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 ... */
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 ... */
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 */
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);
/* 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.",
"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)
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;
}
/* UNIX SMBlib NetBIOS implementation
- *
+ *
* Version 1.0
* SMBlib Routines
- *
+ *
* Copyright (C) Richard Sharpe 1996
- *
+ *
*/
/*
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You 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.
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();
#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);
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;
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 ... */
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 '.' */
+ }
}
* 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);
/* 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;
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 ... */
* 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);
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;
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;
}
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 ... */
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 ... */
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 ... */
/* 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);
/* UNIX SMBlib NetBIOS implementation
- *
+ *
* Version 1.0
* SMBlib Defines
- *
+ *
* Copyright (C) Richard Sharpe 1996
- *
+ *
*/
/*
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You 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.
/* 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 */
/* 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 ... */
/* 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 */
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);
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"
/* RFCNB Standard includes ... */
/*
- *
+ *
* SMBlib Standard Includes
- *
+ *
* Copyright (C) 1996, Richard Sharpe
- *
+ *
* One day we will conditionalize these on OS types ... */
/*
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You 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.
/* RFCNB Standard includes ... */
/*
- *
+ *
* RFCNB Standard Includes
- *
+ *
* Copyright (C) 1996, Richard Sharpe
- *
+ *
* One day we will conditionalize these on OS types ... */
/*
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You 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.
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);
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);
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);
}
*/
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);
+ }
}
}
{
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
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);
i = 0;
if (authenticate_ntlm_domain != NULL)
- while (authenticate_ntlm_domain[i++]);
+ while (authenticate_ntlm_domain[i++]);
chal->target.offset = htole32(48);
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;
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);
}
/* 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);
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);
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;
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);
}
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);
}
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);
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General 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_
#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__ */
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
-
+
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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;
}
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 );
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;
}
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 */
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 */
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';
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);
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;
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 = '.';
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);
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
-
+
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
#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__ */
{
char *p = string, c;
while ((c = *p)) {
- *p = xtoupper(c);
- p++;
+ *p = xtoupper(c);
+ p++;
}
}
{
char *p = string, c;
while ((c = *p)) {
- *p = xtolower(c);
- p++;
+ *p = xtolower(c);
+ p++;
}
}
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);
}
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);
}
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;
}
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);
} 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
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");
setbuf(stderr, NULL);
while (manage_request()) {
- /* everything is done within manage_request */
+ /* everything is done within manage_request */
}
exit(0);
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* 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. */
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;
* 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. */
* 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. */
* 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. */
#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;
#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;
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');
}
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");
}
void
print_compiled_pattern(bufp)
- struct re_pattern_buffer *bufp;
+struct re_pattern_buffer *bufp;
{
unsigned char *buffer = bufp->buffer;
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);
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]);
}
}
/* 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 */
+ };
\f
/* 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'). */
\f
/* `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;
* `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. */
#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;
#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 <jump count> <upper bound>
- * set_number_at <succeed_n count> <lower bound>
- * succeed_n <after jump addr> <succed_n count>
- * <body of loop>
- * jump_n <succeed_n addr> <jump count>
- * (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 <jump count> <upper bound>
+ * set_number_at <succeed_n count> <lower bound>
+ * succeed_n <after jump addr> <succed_n count>
+ * <body of loop>
+ * jump_n <succeed_n addr> <jump count>
+ * (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);
#ifdef DEBUG
if (debug) {
- DEBUG_PRINT1("\nCompiled pattern: ");
- print_compiled_pattern(bufp);
+ DEBUG_PRINT1("\nCompiled pattern: ");
+ print_compiled_pattern(bufp);
}
#endif /* DEBUG */
register unsigned char *pto = end + 3;
while (pfrom != loc)
- *--pto = *--pfrom;
+ *--pto = *--pfrom;
store_op1(op, loc, arg);
}
register unsigned char *pto = end + 5;
while (pfrom != loc)
- *--pto = *--pfrom;
+ *--pto = *--pfrom;
store_op2(op, loc, arg1, arg2);
}
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));
}
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
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;
}
* 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. */
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];
/* 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;
/* 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) \
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) \
/* 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) \
/* 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'. */
* 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;
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
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;
/* 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 */
* 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
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);
* 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;
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;
* 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: ");
* 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;
-
-
- /* \<digit> has been turned into a `duplicate' command which is
- * followed by the numeric value of <digit> 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;
+
+
+ /* \<digit> has been turned into a `duplicate' command which is
+ * followed by the numeric value of <digit> 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();
/* 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
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;
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;
/* 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
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;
{
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;
}
/* 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
* `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;
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;
}
/* 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;
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;
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;
}
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;
}
\f
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
/* return IPv4 CIDR for any Mapped address */
/* Thus only check the mapped bit */
- if( !IsIPv6() ) {
+ if ( !IsIPv6() ) {
shift = 12;
}
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];
#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
clearbits = (uint8_t)( (mtype==AF_INET6?128:32) -cidr);
// short-cut
- if(clearbits == 0)
+ if (clearbits == 0)
return true;
#if USE_IPV6
#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 {
!( 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
#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.
{
#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);
/* 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) );
}
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
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
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;
}
{
#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);
void IPAddress::check4Mapped()
{
- // obsolete.
+ // obsolete.
// TODO use this NOW to set the sin6_family properly on exporting. not on import.
}
IPAddress& IPAddress::operator =(IPAddress *s)
{
IPAddress *tmp = NULL;
- if(!s) return *this;
+ if (!s) return *this;
tmp = dynamic_cast<IPAddress*>(s);
- if(!tmp) return *this;
+ if (!tmp) return *this;
return operator=(*tmp);
}
// 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]);
break;
default:
- IASSERT("false",false);
- return false;
+ IASSERT("false",false);
+ return false;
}
return true;
// 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);
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;
}
void IPAddress::GetAddrInfo(struct addrinfo *&dst, int force) const
{
- if(dst == NULL)
- {
+ if (dst == NULL) {
dst = new addrinfo;
}
// 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));
} 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;
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));
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;
// 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;
}
bool IPAddress::operator <=(const IPAddress &rhs) const
{
- if(IsAnyAddr() && !rhs.IsAnyAddr())
+ if (IsAnyAddr() && !rhs.IsAnyAddr())
return true;
return (matchIPAddr(rhs) <= 0);
bool IPAddress::operator >=(const IPAddress &rhs) const
{
- if(IsNoAddr() && !rhs.IsNoAddr())
+ if (IsNoAddr() && !rhs.IsNoAddr())
return true;
return ( matchIPAddr(rhs) >= 0);
bool IPAddress::operator >(const IPAddress &rhs) const
{
- if(IsNoAddr() && !rhs.IsNoAddr())
+ if (IsNoAddr() && !rhs.IsNoAddr())
return true;
return ( matchIPAddr(rhs) > 0);
bool IPAddress::operator <(const IPAddress &rhs) const
{
- if(IsNoAddr() && !rhs.IsNoAddr())
+ if (IsNoAddr() && !rhs.IsNoAddr())
return true;
return ( matchIPAddr(rhs) < 0);
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
/* 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);
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));
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++;
}
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() );
}
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
#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;
/* 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));
memcpy(&buf, &m_SocketAddr, sizeof(struct sockaddr_in));
- if(buf.sin_family == 0)
- {
+ if (buf.sin_family == 0) {
buf.sin_family = AF_INET;
}
#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;
#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;
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));
}
}
-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 */
#if IPV6_SPECIAL_LOCALHOST
/* LOCALHOST */
- if( IsLocalhost() )
- {
+ if ( IsLocalhost() ) {
out.s_addr = htonl(0x7F000001);
}
#endif
#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;
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* 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
* 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,
* 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 <robertc@squid-cache.org>
*/
* if we are called during static initialisations.
*/
if (!Instance)
- Instance = new MemPools;
+ Instance = new MemPools;
return *Instance;
}
pool = iter->pool;
if (!pool)
- return NULL;
+ return NULL;
iter->pool = pool->next;
return pool;
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
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;
/* 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;
}
/* 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;
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;
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;
* 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
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 */
{
++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
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. */
/* 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;
}
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;
}
}
}
void
-MemPoolMeter::flush()
+MemPoolMeter::flush()
{
alloc.level = 0;
inuse.level = 0;
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);
}
MemImplementingAllocator::alloc()
{
if (++alloc_calls == FLUSH_LIMIT)
- flushMeters();
+ flushMeters();
return allocate();
}
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<MemChunk *>(*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<MemChunk *>(*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;
}
}
time_t age;
if (!this)
- return;
+ return;
if (!Chunks)
- return;
+ return;
flushMetersFull();
convertFreeCacheToChunkFreeCache();
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 */
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
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);
}
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 */
/* 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;
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();
int
MemMalloc::getInUseCount()
{
- return inuse;
+ return inuse;
}
/*
/* 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);
MemAllocatorProxy::getAllocator() const
{
if (!theAllocator)
- theAllocator = MemPools::GetInstance().create(objectType(), size);
+ theAllocator = MemPools::GetInstance().create(objectType(), size);
return theAllocator;
}
MemAllocatorProxy::inUseCount() const
{
if (!theAllocator)
- return 0;
+ return 0;
else
- return memPoolInUseCount(theAllocator);
+ return memPoolInUseCount(theAllocator);
}
size_t
}
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 &
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
/*
* 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
* 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
* 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"
#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];
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++;
}
xprof_InitLib(void)
{
if (xprof_inited)
- return;
+ return;
xprof_Timers = calloc(XPROF_LAST + 2, sizeof(xprof_stats_node));
{
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 */
/* 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;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General 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 "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();
}
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;
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;
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;
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;
/*
* $Id: charset.c,v 1.1 2008/07/07 11:04:47 hno Exp $
*
- * DEBUG:
+ * DEBUG:
* AUTHOR: Henrik Nordstrom <henrik@henriknordstrom.net>
- *
+ *
* Copyright (C) 2008 Henrik Nordstrom
*
* SQUID Web Proxy Cache http://www.squid-cache.org/
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
{
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;
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* 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 <jeremy@hksys.com>
* Significantly revised and rewinddir, seekdir and telldir added by Colin
* Peters <colin@fu.is.saga-u.ac.jp>
- *
+ *
*/
#include "util.h"
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);
/* 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);
* 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;
}
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);
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;
errno = 0;
if (!dirp) {
- errno = EFAULT;
- return -1;
+ errno = EFAULT;
+ return -1;
}
return dirp->dd_stat;
}
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_ */
#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);
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]);
}
/* 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. */
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,
};
-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,
};
-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,
};
-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,
};
-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,
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,
};
-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;
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
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);
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;
}
}
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;
}
#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 */
/*
* $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/
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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;
}
#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 <numeric-addr><delim><zoneid> */
- 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 <numeric-addr><delim><zoneid> */
+ 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
#include <string.h>
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)'?'
*/
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 */
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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;
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;
}
{
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;
/*
* 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.
*/
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;
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];
}
/*
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().
*/
{
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;
}
}
/*
- * 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.
*
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]);
}
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);
}
{
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,
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;
}
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");
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
#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);
assert(hp != NULL);
if (initSize <= 0)
- initSize = MinSize;
+ initSize = MinSize;
hp->nodes = xcalloc(initSize, sizeof(heap_node *));
assert(hp->nodes != NULL);
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);
elm->data = dat;
if (_heap_should_grow(hp))
- _heap_grow(hp);
+ _heap_grow(hp);
hp->nodes[hp->last] = elm;
elm->id = hp->last;
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.
*/
#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.
*/
heap_t data;
if (hp->last <= 0)
- return NULL;
+ return NULL;
mutex_lock(hp->lock);
}
-/*
+/*
* Remove the last node in HP. Frees the heap internal structure and
* returns the data pointes to by the last node.
*/
}
-/*
+/*
* The semantics of this routine is the same as the followings:
* heap_delete(hp, elm);
* heap_insert(hp, 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 *
}
-/*
+/*
* The KEY of the root node.
*/
heap_key
}
-/*
+/*
* Same as heap_peep except that this return the KEY of the node.
* Only meant for iteration.
*/
}
-/*
+/*
* 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++)
#ifndef heap_nodes
-/*
+/*
* Current number of nodes in HP.
*/
int
#ifndef heap_empty
-/*
+/*
* Determine if the heap is empty. Returns 1 if HP has no elements and 0
* otherwise.
*/
/****************** 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.
*/
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
{
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)
#ifdef NOTDEF
-/*
+/*
* Copy KEY and DATA fields of SRC to DEST. ID field is NOT copied.
*/
static void
#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
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
}
-/*
+/*
* 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;
}
* 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++;
}
}
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;
}
heap_node **bn = (heap_node **) b;
float cmp = (*an)->key - (*bn)->key;
if (cmp < 0)
- return -1;
+ return -1;
else
- return 1;
+ return 1;
}
/*
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.
*/
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
*/
norm = skew * 2.56 / (max * max);
- /*
+ /*
* Free the nodes array; note this is just an array of pointers, not data!
*/
xfree(nodes);
/*
* $Id: html_quote.c,v 1.6 2007/12/06 02:37:15 amosjeffries Exp $
- *
+ *
* DEBUG:
* AUTHOR: Robert Collins
*
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General 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 "util.h"
-/*
+/*
* HTML defines these characters as special entities that should be quoted.
*/
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 *
* 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';
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);
}
*/
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 *
*/
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 *
*/
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 */
#include "config.h"
-#ifndef HAVE_INET_PTON
+#ifndef HAVE_INET_PTON
/*
* Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
*/
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
*/
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
*/
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 */
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();
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]);
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
#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++.
*/
*/
bool add
- (char const *, size_t, void *);
+ (char const *, size_t, void *);
private:
TrieNode *head;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
#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
*/
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
#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
*/
*/
bool add
- (char const *, size_t, void *, TrieCharTransform *);
+ (char const *, size_t, void *, TrieCharTransform *);
private:
/* 256-way Trie */
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
bool
Trie::add
- (char const *aString, size_t theLength, void *privatedata)
+(char const *aString, size_t theLength, void *privatedata)
{
if (!privatedata)
return false;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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 */
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
{
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;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
{
unsigned int i;
for (i = 0; i < 16; i++)
- printf("%02x", digest[i]);
+ printf("%02x", digest[i]);
}
int
MDString("message digest");
MDString("abcdefghijklmnopqrstuvwxyz");
MDString
- ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");
+ ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");
MDString
- ("1234567890123456789012345678901234567890\
+ ("1234567890123456789012345678901234567890\
1234567890123456789012345678901234567890");
return 0;
}
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
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);
/* 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. */
}
/*
- * 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
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);
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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
/* 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;
*/
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);
*/
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;
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);
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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 */
* 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
*/
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;
}
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;
}
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;
* 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
* 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;
* 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;
}
#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);
}
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);
* 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;
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.
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);
}
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;
* 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
* 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;
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.
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);
*/
/* 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 */
}
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);
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);
}
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
/*
* KNOWN BUGS:
- *
+ *
* UDP replies with TC set should be retried via TCP
*/
/*
* rfc1035HeaderPack()
- *
+ *
* Packs a rfc1035_header structure into a buffer.
* Returns number of octets packed (should always be 12)
*/
/*
* 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.
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++;
/*
* 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.
* 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);
/*
* 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;
/*
* rfc1035HeaderUnpack()
- *
+ *
* Unpacks a RFC1035 message header buffer into the header fields
* of the rfc1035_message structure.
*
* is less than that.
*/
if (sz < 12)
- return 1;
+ return 1;
memcpy(&s, buf + (*off), sizeof(s));
(*off) += sizeof(s);
h->id = ntohs(s);
/*
* 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'
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;
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;
/*
* rfc1035RRUnpack()
- *
+ *
* Unpacks a RFC1035 Resource Record into 'RR' from a message buffer.
* The caller must free RR->rdata!
*
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);
(*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) {
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);
{
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;
}
}
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;
/*
* rfc1035QueryUnpack()
- *
+ *
* Unpacks a RFC1035 Query Record into 'query' from a message buffer.
*
* Updates the new message buffer offset.
{
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;
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)
{
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);
}
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;
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
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;
/*
* 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
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;
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;
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;
}
/*
* $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/
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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"
};
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
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;
}
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;
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);
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_)
#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
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);
/*
* $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/
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General 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 "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, /* " */
(char) 0x20 /* space */
};
-static char rfc1738_reserved_chars[] =
-{
+static char rfc1738_reserved_chars[] = {
(char) 0x3b, /* ; */
(char) 0x2f, /* / */
(char) 0x3f, /* ? */
};
/*
- * 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 *
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);
}
/*
- * 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
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';
}
-/* 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
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';
}
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';
}
}
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);
}
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);
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);
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
/*
* 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.
/* 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 );
}
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]);
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
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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);
}
-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 */
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;
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;
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;
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;
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
#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
#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);
#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};
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;
}
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);
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;
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;
}
{
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);
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;
{
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;
/*
* $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/
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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 */
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;
}
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;
}
{
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;
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;
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;
}
void testArray::all()
{
- CPPUNIT_ASSERT( 1 == 1 );
+ CPPUNIT_ASSERT( 1 == 1 );
Vector<int> aArray;
CPPUNIT_ASSERT (aArray.size() == 0);
aArray.push_back(2);
#include <cppunit/extensions/HelperMacros.h>
-/*
+/*
* A test case that is designed to produce
* example errors and failures
*
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();
};
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 ) );
}
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);
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() );
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() );
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)
IPAddress anIPA = "192.168.100.12";
- /* test stored values */
+ /* test stored values */
CPPUNIT_ASSERT( !anIPA.IsAnyAddr() );
CPPUNIT_ASSERT( !anIPA.IsNoAddr() );
CPPUNIT_ASSERT( anIPA.IsIPv4() );
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() );
- /* 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() );
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() );
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;
}
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;
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);
/*
* $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/
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
/*
* 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 *
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();
}
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,
/* 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.
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;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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;
#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;
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;
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];
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;
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;
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;
} _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."
}
};
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;
}
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
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},
#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
#
# 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";
+#!/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
/***************************************************************************
*
* 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
* 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
* 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"
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));
*/
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}*
/* 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++;
/* 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;
*/
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}*
/* 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++;
/* 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;
*/
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}*
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;
/* 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);
}
*/
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}*
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.
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);
}
*/
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
*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;
/*
* 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.
*
*/
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
*/
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;
*/
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;
/* 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);
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)--;
*/
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);
*/
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 */
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);
*/
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}*
*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;
}
/*
*/
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);
*/
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}*
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;
*/
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
*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);
*/
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
*/
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}*
*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;
*/
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;
#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.
*/
* 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
*/
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));
}
/**********************************************************************
*
* 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
* 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
* 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 <ryan+@andrew.cmu.edu>
- *
+ *
**********************************************************************/
#include "config.h"
* 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)
*
*/
#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);
}
}
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
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;
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;
}
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;
}
* 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);
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;
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;
}
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
int x;
for (x = 0; x < len; x++)
- printf(".%u", O[x]);
+ printf(".%u", O[x]);
}
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
};
-struct tok tokens[] =
-{
+struct tok tokens[] = {
{"obsolete", sizeof("obsolete") - 1, OBSOLETE},
{"Opaque", sizeof("Opaque") - 1, SNMP_OPAQUE},
{"recommended", sizeof("recommended") - 1, RECOMMENDED},
{"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},
{"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}
};
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;
}
}
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;
}
}
{
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 */
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;
+ }
}
}
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;
#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;
}
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
* 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;
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;
ep = np->enums;
while (ep) {
- tep = ep;
- ep = ep->next;
- xfree((char *) tep);
+ tep = ep;
+ ep = ep->next;
+ xfree((char *) tep);
}
xfree((char *) 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;
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;
}
}
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;
* 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;
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;
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:
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:
*
*/
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;
}
static
#endif
struct node *
-parse(FILE *fp)
-{
+ parse(FILE *fp) {
char token[64];
char name[64];
int type = 1;
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;
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);
/**********************************************************************
*
* 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
* 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
* 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"
*/
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);
}
*/
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;
/* 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';
/***************************************************************************
*
* 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
* 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
* 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 <ryan+@andrew.cmu.edu>
- *
+ *
***************************************************************************/
#ifdef HAVE_CONFIG_H
int snmp_errno = 0;
-static const char *api_errors[17] =
-{
+static const char *api_errors[17] = {
"Unknown Error",
"Generic Error",
"Invalid local port",
{
int foo = (err * -1);
if ((foo < SNMPERR_GENERR) ||
- (foo > SNMPERR_LAST))
- foo = 0;
+ (foo > SNMPERR_LAST))
+ foo = 0;
return (api_errors[foo]);
}
/**********************************************************************
*
* 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
* 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
* 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"
#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.",
"This variable is read only",
"A general failure occured",
- /* SNMPv2 Errors */
+ /* SNMPv2 Errors */
"NOACCESS",
"WRONGTYPE",
"WRONGLENGTH",
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";
}
}
/**********************************************************************
*
* 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
* 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
* 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 <ryan+@andrew.cmu.edu>
- *
+ *
**********************************************************************/
#include "config.h"
#include "snmp_msg.h"
-/*
+/*
* RFC 1901: Introduction to Community-based SNMPv2
*
* Message ::=
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;
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;
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;
}
/**********************************************************************
*
* 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
* 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
* 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 <ryan+@andrew.cmu.edu>
- *
+ *
**********************************************************************/
#include "config.h"
*/
struct snmp_pdu *
-snmp_pdu_create(int command)
-{
+ snmp_pdu_create(int command) {
struct snmp_pdu *pdu;
#ifdef DEBUG_PDU
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));
/* 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
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));
* 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;
#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;
/* 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);
}
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);
}
/*
* RFC 1902: Structure of Management Information for SNMPv2
*
- * PDU ::=
+ * PDU ::=
* SEQUENCE {
* request-id INTEGER32
* error-status INTEGER
/*
* RFC 1157: A Simple Network Management Protocol (SNMP)
*
- * PDU ::=
+ * PDU ::=
* SEQUENCE {
* request-id INTEGER
* error-status INTEGER
u_char *
snmp_pdu_encode(u_char * DestBuf, int *DestBufLen,
- struct snmp_pdu *PDU)
+ struct snmp_pdu *PDU)
{
u_char *bufp;
/* 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);
*/
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;
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);
#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);
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;
/**********************************************************************
*
* 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
* 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
* 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 <ryan+@andrew.cmu.edu>
- *
+ *
**********************************************************************/
#include "config.h"
*/
struct variable_list *
-snmp_var_new(oid * Name, int Len)
-{
+ snmp_var_new(oid * Name, int Len) {
struct variable_list *New;
#ifdef DEBUG_VARS
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; */
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);
/* 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));
*/
struct variable_list *
-snmp_var_clone(struct variable_list *Src)
-{
+ snmp_var_clone(struct variable_list *Src) {
struct variable_list *Dest;
#ifdef DEBUG_VARS
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);
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);
}
*
* RFC 1905: Protocol Operations for SNMPv2
*
- * VarBind ::=
+ * VarBind ::=
* SEQUENCE {
* name ObjectName
* CHOICE {
*/
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;
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);
}
/* 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;
/* 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);
/* 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
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;
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);
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
#ifdef _SQUID_WIN32_
-struct arpreq
-{
+struct arpreq {
IPAddress arp_pa; /* protocol address */
* 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 <name> arp <Ethernet address> ...
- *
+ *
* For example,
- *
+ *
* acl students arp 00:00:21:55:ed:22 00:00:21:ff:55:38
*
* NOTE: Linux code by David Luyer <luyer@ucs.uwa.edu.au>.
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;
}
/*
* 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
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General 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 "splay.h"
/// \ingroup ACLAPI
-struct acl_arp_data
-{
+struct acl_arp_data {
char eth[6];
};
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
private:
static ACLCertificateStrategy Instance_;
- ACLCertificateStrategy(){}
+ ACLCertificateStrategy() {}
ACLCertificateStrategy&operator=(ACLCertificateStrategy const &);
};
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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) {
currentAnswer(ACCESS_DENIED);
if (callerGone()) {
- checkCallback(currentAnswer());
- return;
+ checkCallback(currentAnswer());
+ return;
}
/* NOTE: This holds a cbdata reference to the current access_list
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;
}
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)");
" 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
void
ACLChecklist::NullState::checkForAsync(ACLChecklist *) const
- {}
+{}
ACLChecklist::NullState ACLChecklist::NullState::_instance;
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)
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
void changeState (ACLChecklist *, AsyncState *) const;
};
-class NullState : public AsyncState
+ class NullState : public AsyncState
{
public:
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
private:
static ACLDestinationASNStrategy Instance_;
- ACLDestinationASNStrategy(){}
+ ACLDestinationASNStrategy() {}
ACLDestinationASNStrategy&operator=(ACLDestinationASNStrategy const &);
};
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
public:
virtual int match (ACLData<MatchType> * &, ACLChecklist *);
static ACLDestinationDomainStrategy *Instance();
-
+
/**
* Not implemented to prevent copies of the instance.
\par
private:
static ACLDestinationDomainStrategy Instance_;
- ACLDestinationDomainStrategy(){}
+ ACLDestinationDomainStrategy() {}
ACLDestinationDomainStrategy&operator=(ACLDestinationDomainStrategy const &);
};
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
/* 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)
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General 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 "splay.h"
/// \ingroup ACLAPI
-struct acl_httpstatus_data
-{
+struct acl_httpstatus_data {
int status1, status2;
acl_httpstatus_data(int);
acl_httpstatus_data(int, int);
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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';
}
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 {
/* 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);
}
memset(&hints, 0, sizeof(struct addrinfo));
- if( iptype != AF_UNSPEC ) {
+ if ( iptype != AF_UNSPEC ) {
hints.ai_flags |= AI_NUMERICHOST;
}
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;
}
/* 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 << "'");
#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;
}
/* 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;
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) {}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
void *operator new(size_t);
void operator delete(void *);
- ACLIP() : data(NULL){}
+ ACLIP() : data(NULL) {}
~ACLIP();
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
}
/*
- * 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,
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);
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
char const *class_;
int maximum;
- struct Flags
- {
- Flags() : strict(0){}
+ struct Flags {
+ Flags() : strict(0) {}
unsigned int strict:1;
} flags;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
private:
static ACLMethodStrategy Instance_;
- ACLMethodStrategy(){}
+ ACLMethodStrategy() {}
ACLMethodStrategy&operator=(ACLMethodStrategy const &);
};
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
private:
static ACLMyPortStrategy Instance_;
- ACLMyPortStrategy(){}
+ ACLMyPortStrategy() {}
ACLMyPortStrategy&operator=(ACLMyPortStrategy const &);
};
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
ACLMyPortNameStrategy::match (ACLData<MatchType> * &data, ACLChecklist *checklist)
{
if (checklist->conn() != NULL)
- return data->match (checklist->conn()->port->name);
+ return data->match (checklist->conn()->port->name);
return 0;
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
private:
static ACLMyPortNameStrategy Instance_;
- ACLMyPortNameStrategy(){}
+ ACLMyPortNameStrategy() {}
ACLMyPortNameStrategy&operator=(ACLMyPortNameStrategy const &);
};
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
private:
static ACLProtocolStrategy Instance_;
- ACLProtocolStrategy(){}
+ ACLProtocolStrategy() {}
ACLProtocolStrategy&operator=(ACLProtocolStrategy const &);
};
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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;
}
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
private:
static ACLReplyHeaderStrategy *Instance_;
- ACLReplyHeaderStrategy(){}
+ ACLReplyHeaderStrategy() {}
ACLReplyHeaderStrategy&operator=(ACLReplyHeaderStrategy const &);
};
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
private:
static ACLRequestHeaderStrategy *Instance_;
- ACLRequestHeaderStrategy(){}
+ ACLRequestHeaderStrategy() {}
ACLRequestHeaderStrategy&operator=(ACLRequestHeaderStrategy const &);
};
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
private:
static ACLSourceASNStrategy Instance_;
- ACLSourceASNStrategy(){}
+ ACLSourceASNStrategy() {}
ACLSourceASNStrategy&operator=(ACLSourceASNStrategy const &);
};
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
private:
static ACLSourceDomainStrategy Instance_;
- ACLSourceDomainStrategy(){}
+ ACLSourceDomainStrategy() {}
ACLSourceDomainStrategy&operator=(ACLSourceDomainStrategy const &);
};
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
private:
static ACLSslErrorStrategy Instance_;
- ACLSslErrorStrategy(){}
+ ACLSslErrorStrategy() {}
ACLSslErrorStrategy&operator=(ACLSslErrorStrategy const &);
};
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General 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 "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<HttpHeader*>;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
virtual bool valid() const {return true;}
- virtual ~ACLStrategy(){}
+ virtual ~ACLStrategy() {}
};
#endif /* SQUID_ACLSTRATEGY_H */
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
private:
static ACLTimeStrategy Instance_;
- ACLTimeStrategy(){}
+ ACLTimeStrategy() {}
ACLTimeStrategy&operator=(ACLTimeStrategy const &);
};
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
private:
static ACLUrlStrategy Instance_;
- ACLUrlStrategy(){}
+ ACLUrlStrategy() {}
ACLUrlStrategy&operator=(ACLUrlStrategy const &);
};
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
private:
static ACLUrlPathStrategy Instance_;
- ACLUrlPathStrategy(){}
+ ACLUrlPathStrategy() {}
ACLUrlPathStrategy&operator=(ACLUrlPathStrategy const &);
};
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
private:
static ACLUrlPortStrategy Instance_;
- ACLUrlPortStrategy(){}
+ ACLUrlPortStrategy() {}
ACLUrlPortStrategy&operator=(ACLUrlPortStrategy const &);
};
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
SplayNode<char *> *names;
- struct
- {
+ struct {
unsigned int case_insensitive:1;
unsigned int required:1;
} flags;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
/* 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()
AsyncCall::make()
{
debugs(debugSection, debugLevel, HERE << "make call " << name <<
- " [call"<< id << ']');
+ " [call"<< id << ']');
if (canFire()) {
fire();
return;
isCanceled = "unknown reason";
debugs(debugSection, debugLevel, HERE << "will not call " << name <<
- " [call"<< id << ']' << " because of " << isCanceled);
+ " [call"<< id << ']' << " because of " << isCanceled);
}
bool
{
if (isCanceled)
debugs(debugSection, debugLevel, HERE << "will not call " << name <<
- " [call"<< id << ']' << " also because " << reason);
+ " [call"<< id << ']' << " also because " << reason);
isCanceled = reason;
return false;
}
}
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;
}
* 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.
*/
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:
{
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;
inline
AsyncCall *
asyncCall(int aDebugSection, int aDebugLevel, const char *aName,
- const Dialer &aDialer)
+ const Dialer &aDialer)
{
return new AsyncCallT<Dialer>(aDebugSection, aDebugLevel, aName, aDialer);
}
AsyncCallQueue::Instance()
{
// TODO: how to remove this frequent check while supporting early calls?
- if (!TheInstance)
+ if (!TheInstance)
TheInstance = new AsyncCallQueue();
return *TheInstance;
{
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();
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
/* 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
* 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
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 << "()"; }
Method method;
protected:
- virtual void doDial() { (object->*method)(); }
+ virtual void doDial() { (object->*method)(); }
};
template <class C, class Argument1>
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 << ')'; }
Argument1 arg1;
protected:
- virtual void doDial() { (object->*method)(arg1); }
+ virtual void doDial() { (object->*method)(arg1); }
};
// ... add more as needed
template <class C, class Argument1>
UnaryMemFunT<C, Argument1>
MemFun(C *object, typename UnaryMemFunT<C, Argument1>::Method method,
- Argument1 arg1)
+ Argument1 arg1)
{
return UnaryMemFunT<C, Argument1>(object, method, arg1);
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
typedef Vector<AuthScheme*>::const_iterator const_iterator;
AuthScheme() : initialised (false) {}
- virtual ~AuthScheme(){}
+ virtual ~AuthScheme() {}
/* per scheme methods */
virtual char const *type () const = 0;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
{
auth_user_ip_t *ipdata = (auth_user_ip_t *) ip_list.head;
- while (ipdata)
- {
+ while (ipdata) {
/* walk the ip list */
if (ipdata->ipaddr == 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 */
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
}
/*
- * 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.
* 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!
*/
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 " <<
*/
/* 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;
}
* 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) {
"' to '" << proxy_auth << "' (client " <<
src_addr << ")");
- AUTHUSERREQUESTUNLOCK(conn->auth_user_request, "conn");
+ AUTHUSERREQUESTUNLOCK(conn->auth_user_request, "conn");
conn->auth_type = AUTH_UNKNOWN;
}
}
/* 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;
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;
}
}
- if (!authenticateUserAuthenticated(*auth_user_request))
- {
+ if (!authenticateUserAuthenticated(*auth_user_request)) {
/* User not logged in. Log them in */
authenticateAuthenticateUser(*auth_user_request, request,
conn, headertype);
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 */
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");
}
}
/* 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);
}
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;
}
{
http_hdr_type type;
- switch (rep->sline.status)
- {
+ switch (rep->sline.status) {
case HTTP_PROXY_AUTHENTICATION_REQUIRED:
/* Proxy authorisation needed */
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) {
* 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;
}
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
class AuthScheme;
-struct AuthUserIP
-{
+struct AuthUserIP {
dlink_node node;
/* IP addr this user authenticated from */
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);
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<BodyProducer, BodyPipe::Pointer>
{
public:
- typedef UnaryMemFunT<BodyProducer, BodyPipe::Pointer> Parent;
+ typedef UnaryMemFunT<BodyProducer, BodyPipe::Pointer> 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<BodyConsumer, BodyPipe::Pointer>
{
public:
- typedef UnaryMemFunT<BodyConsumer, BodyPipe::Pointer> Parent;
+ typedef UnaryMemFunT<BodyConsumer, BodyPipe::Pointer> 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;
}
// inform the pipe that we are done and clear the Pointer
void BodyProducer::stopProducingFor(RefCount<BodyPipe> &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;
}
// inform the pipe that we are done and clear the Pointer
void BodyConsumer::stopConsumingFrom(RefCount<BodyPipe> &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<uint64_t>(theBodySize);
+ assert(bodySizeKnown());
+ return static_cast<uint64_t>(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<size_t>(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<size_t>(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
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);
/* 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;
}
// 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<BodyPipe> bp) = 0;
- virtual void noteBodyConsumerAborted(RefCount<BodyPipe> bp) = 0;
+ virtual void noteMoreBodySpaceAvailable(RefCount<BodyPipe> bp) = 0;
+ virtual void noteBodyConsumerAborted(RefCount<BodyPipe> bp) = 0;
- protected:
- void stopProducingFor(RefCount<BodyPipe> &pipe, bool atEof);
+protected:
+ void stopProducingFor(RefCount<BodyPipe> &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<BodyPipe> bp) = 0;
- virtual void noteBodyProductionEnded(RefCount<BodyPipe> bp) = 0;
- virtual void noteBodyProducerAborted(RefCount<BodyPipe> bp) = 0;
-
- protected:
- void stopConsumingFrom(RefCount<BodyPipe> &pipe);
+class BodyConsumer: virtual public AsyncJob
+{
+public:
+ BodyConsumer():AsyncJob("BodyConsumer") {}
+ virtual ~BodyConsumer() {}
+
+ virtual void noteMoreBodyDataAvailable(RefCount<BodyPipe> bp) = 0;
+ virtual void noteBodyProductionEnded(RefCount<BodyPipe> bp) = 0;
+ virtual void noteBodyProducerAborted(RefCount<BodyPipe> bp) = 0;
+
+protected:
+ void stopConsumingFrom(RefCount<BodyPipe> &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<BodyPipe> Pointer;
- typedef BodyProducer Producer;
- typedef BodyConsumer Consumer;
- typedef BodyPipeCheckout Checkout;
+class BodyPipe: public RefCountable
+{
+public:
+ typedef RefCount<BodyPipe> 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 */
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
/* 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 */
{
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++;
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* 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);
};
* 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);
};
// 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;
} cachemgrStateData;
- CacheManager();
+ CacheManager();
cachemgrStateData* ParseUrl(const char *url);
void ParseHeaders(cachemgrStateData * mgr, const HttpRequest * request);
int CheckPassword(cachemgrStateData * mgr);
/*
* $Id: ChunkedCodingParser.h,v 1.1 2007/12/26 22:33:32 hno Exp $
- *
+ *
* SQUID Web Proxy Cache http://www.squid-cache.org/
* ----------------------------------------------------------
*
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
/* 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)
{
}
/* CommAcceptCbParams */
CommAcceptCbParams::CommAcceptCbParams(void *aData): CommCommonCbParams(aData),
- nfd(-1)
+ nfd(-1)
{
}
/* CommConnectCbParams */
CommConnectCbParams::CommConnectCbParams(void *aData):
- CommCommonCbParams(aData)
+ CommCommonCbParams(aData)
{
}
// 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
/* CommIoCbParams */
CommIoCbParams::CommIoCbParams(void *aData): CommCommonCbParams(aData),
- buf(NULL), size(0)
+ buf(NULL), size(0)
{
}
// 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
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)
{
}
/* CommAcceptCbPtrFun */
CommAcceptCbPtrFun::CommAcceptCbPtrFun(IOACB *aHandler,
- const CommAcceptCbParams &aParams):
- CommDialerParamsT<CommAcceptCbParams>(aParams),
- handler(aHandler)
+ const CommAcceptCbParams &aParams):
+ CommDialerParamsT<CommAcceptCbParams>(aParams),
+ handler(aHandler)
{
}
/* CommConnectCbPtrFun */
CommConnectCbPtrFun::CommConnectCbPtrFun(CNCB *aHandler,
- const CommConnectCbParams &aParams):
- CommDialerParamsT<CommConnectCbParams>(aParams),
- handler(aHandler)
+ const CommConnectCbParams &aParams):
+ CommDialerParamsT<CommConnectCbParams>(aParams),
+ handler(aHandler)
{
}
/* CommIoCbPtrFun */
CommIoCbPtrFun::CommIoCbPtrFun(IOCB *aHandler, const CommIoCbParams &aParams):
- CommDialerParamsT<CommIoCbParams>(aParams),
- handler(aHandler)
+ CommDialerParamsT<CommIoCbParams>(aParams),
+ handler(aHandler)
{
}
/* CommCloseCbPtrFun */
CommCloseCbPtrFun::CommCloseCbPtrFun(PF *aHandler,
- const CommCloseCbParams &aParams):
- CommDialerParamsT<CommCloseCbParams>(aParams),
- handler(aHandler)
+ const CommCloseCbParams &aParams):
+ CommDialerParamsT<CommCloseCbParams>(aParams),
+ handler(aHandler)
{
}
/* CommTimeoutCbPtrFun */
CommTimeoutCbPtrFun::CommTimeoutCbPtrFun(PF *aHandler,
- const CommTimeoutCbParams &aParams):
- CommDialerParamsT<CommTimeoutCbParams>(aParams),
- handler(aHandler)
+ const CommTimeoutCbParams &aParams):
+ CommDialerParamsT<CommTimeoutCbParams>(aParams),
+ handler(aHandler)
{
}
* - 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);
/// 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;
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);
};
// connect parameters
-class CommConnectCbParams: public CommCommonCbParams {
+class CommConnectCbParams: public CommCommonCbParams
+{
public:
CommConnectCbParams(void *aData);
};
// read/write (I/O) parameters
-class CommIoCbParams: public CommCommonCbParams {
+class CommIoCbParams: public CommCommonCbParams
+{
public:
CommIoCbParams(void *aData);
};
// 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);
};
// Interface to expose comm callback parameters of all comm dialers.
// GetCommParams() uses this interface to access comm parameters.
template <class Params_>
-class CommDialerParamsT {
+class CommDialerParamsT
+{
public:
typedef Params_ Params;
CommDialerParamsT(const Params &io): params(io) {}
// Get comm params of an async comm call
template <class Params>
-Params &GetCommParams(AsyncCall::Pointer &call) {
- typedef CommDialerParamsT<Params> DialerParams;
+Params &GetCommParams(AsyncCall::Pointer &call)
+{
+ typedef CommDialerParamsT<Params> DialerParams;
DialerParams *dp = dynamic_cast<DialerParams*>(call->getDialer());
assert(dp);
return dp->params;
typedef void (C::*Method)(const Params &io);
CommCbMemFunT(C *obj, Method meth): JobDialer(obj),
- CommDialerParamsT<Params>(obj), object(obj), method(meth) {}
+ CommDialerParamsT<Params>(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:
// accept (IOACB) dialer
class CommAcceptCbPtrFun: public CallDialer,
- public CommDialerParamsT<CommAcceptCbParams>
+ public CommDialerParamsT<CommAcceptCbParams>
{
public:
typedef CommAcceptCbParams Params;
// connect (CNCB) dialer
class CommConnectCbPtrFun: public CallDialer,
- public CommDialerParamsT<CommConnectCbParams>
+ public CommDialerParamsT<CommConnectCbParams>
{
public:
typedef CommConnectCbParams Params;
// read/write (IOCB) dialer
class CommIoCbPtrFun: public CallDialer,
- public CommDialerParamsT<CommIoCbParams>
+ public CommDialerParamsT<CommIoCbParams>
{
public:
typedef CommIoCbParams Params;
// close (PF) dialer
class CommCloseCbPtrFun: public CallDialer,
- public CommDialerParamsT<CommCloseCbParams>
+ public CommDialerParamsT<CommCloseCbParams>
{
public:
typedef CommCloseCbParams Params;
};
class CommTimeoutCbPtrFun:public CallDialer,
- public CommDialerParamsT<CommTimeoutCbParams>
+ public CommDialerParamsT<CommTimeoutCbParams>
{
public:
typedef CommTimeoutCbParams Params;
// TODO: Get rid of this class by moving canFire() to canDial() method
// of dialers.
template <class Dialer>
-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; }
template <class Dialer>
inline
CommCbFunPtrCallT<Dialer> *commCbCall(int debugSection, int debugLevel,
- const char *callName, const Dialer &dialer)
+ const char *callName, const Dialer &dialer)
{
return new CommCbFunPtrCallT<Dialer>(debugSection, debugLevel, callName,
- dialer);
+ dialer);
}
/* inlined implementation of templated methods */
template <class Dialer>
CommCbFunPtrCallT<Dialer>::CommCbFunPtrCallT(int debugSection, int debugLevel,
- const char *callName, const Dialer &aDialer):
+ const char *callName, const Dialer &aDialer):
AsyncCall(debugSection, debugLevel, callName),
dialer(aDialer)
{
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
\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
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
typedef RefCount<CompositePoolNode> 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;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
void
ConfigOptionVector::dump(StoreEntry * e) const
{
- for(Vector<ConfigOption *>::const_iterator i = options.begin();
+ for (Vector<ConfigOption *>::const_iterator i = options.begin();
i != options.end(); ++i)
(*i)->dump(e);
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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);
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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;
/* skip comments */
/* skip blank lines */
- } while( *t == '#' || !*t );
+ } while ( *t == '#' || !*t );
return t;
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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
};
#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);
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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;
}
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)
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
public:
typedef RefCount<DelayIdComposite> Pointer;
- virtual inline ~DelayIdComposite(){}
+ virtual inline ~DelayIdComposite() {}
virtual int bytesWanted (int min, int max) const =0;
virtual void bytesIn(int qty) = 0;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
CommonPool *pool;
CompositePoolNode::Pointer theComposite() {return theComposite_;}
- CompositePoolNode::Pointer const theComposite() const{return theComposite_;}
+ CompositePoolNode::Pointer const theComposite() const {return theComposite_;}
acl_access *access;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
{
public:
- virtual ~Updateable(){}
+ virtual ~Updateable() {}
virtual void update(int) = 0;
};
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
// 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;
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;
~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
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
void
AIODiskIOStrategy::statfs(StoreEntry & sentry)const
- {}
+{}
ConfigOption *
AIODiskIOStrategy::getOptionTree() const
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
/* Allocate an overlapped structure. */
Overlapped = (LPOVERLAPPED) xcalloc(1, sizeof(OVERLAPPED));
- if (!Overlapped)
- {
+ if (!Overlapped) {
errno = ENOMEM;
return -1;
}
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;
}
/* Allocate an overlapped structure. */
Overlapped = (LPOVERLAPPED) xcalloc(1, sizeof(OVERLAPPED));
- if (!Overlapped)
- {
+ if (!Overlapped) {
errno = ENOMEM;
return -1;
}
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;
}
/* Allocate an overlapped structure. */
Overlapped = (LPOVERLAPPED) xcalloc(1, sizeof(OVERLAPPED));
- if (!Overlapped)
- {
+ if (!Overlapped) {
errno = ENOMEM;
return -1;
}
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;
}
/* Allocate an overlapped structure. */
Overlapped = (LPOVERLAPPED) xcalloc(1, sizeof(OVERLAPPED));
- if (!Overlapped)
- {
+ if (!Overlapped) {
errno = ENOMEM;
return -1;
}
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;
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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 */
#endif
-struct aiocb64
-{
+struct aiocb64 {
int aio_fildes; /* file descriptor */
void *aio_buf; /* buffer location */
size_t aio_nbytes; /* length of transfer */
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 */
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;
/* 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 */
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
{
/* 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.
*/
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* - 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;
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
#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;
int recv_count;
int sio_id;
- struct
- {
+ struct {
int ops;
int success;
int fail;
struct RefCountable_;
-struct diomsg
-{
+struct diomsg {
mtyp_t mtype;
int id;
int seq_no;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
typedef struct _file_state file_state;
-struct _file_state
-{
+struct _file_state {
void *key;
file_state *next;
int id;
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) {
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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();
typedef Vector<DiskIOModule*>::iterator iterator;
typedef Vector<DiskIOModule*>::const_iterator const_iterator;
DiskIOModule();
- virtual ~DiskIOModule(){}
+ virtual ~DiskIOModule() {}
virtual void init() = 0;
//virtual void registerWithCacheManager(void);
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
{
public:
- virtual ~DiskIOStrategy(){}
+ virtual ~DiskIOStrategy() {}
/** Can the IO Strategy handle more requests ? */
virtual bool shedLoad() = 0;
{
public:
- SingletonIOStrategy(DiskIOStrategy *anIO) : io(anIO){}
+ SingletonIOStrategy(DiskIOStrategy *anIO) : io(anIO) {}
virtual bool shedLoad() { return io->shedLoad(); }
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;
void *data; /* Available to the caller */
};
-struct squidaio_ctrl_t
-{
+struct squidaio_ctrl_t {
struct squidaio_ctrl_t *next;
int fd;
class DiskThreadsIOStrategy;
-struct AIOCounts
-{
+struct AIOCounts {
int open_start;
int open_finish;
int close_start;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
public:
void * operator new (size_t);
void operator delete (void *);
- IoResult(RefCount<DiskThreadsDiskFile> aFile, RefCount<RT> aRequest) : file(aFile), request(aRequest){}
+ IoResult(RefCount<DiskThreadsDiskFile> aFile, RefCount<RT> aRequest) : file(aFile), request(aRequest) {}
RefCount<DiskThreadsDiskFile> file;
RefCount<RT> request;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* 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
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
};
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;
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;
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;
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
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
};
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;
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;
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 */
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;
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);
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
AIOCounts squidaio_counts;
-typedef struct squidaio_unlinkq_t
-{
+typedef struct squidaio_unlinkq_t {
char *path;
struct squidaio_unlinkq_t *next;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General 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 "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.
*
/* 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.
/* esiComment */
-struct esiComment : public ESIElement
-{
+struct esiComment : public ESIElement {
MEMPROXY_CLASS(esiComment);
~esiComment();
esiComment();
/* esiTry */
-struct esiTry : public ESIElement
-{
+struct esiTry : public ESIElement {
MEMPROXY_CLASS(esiTry);
esiTry(esiTreeParentPtr aParent);
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 */
/* esiChoose */
-struct esiChoose : public ESIElement
-{
+struct esiChoose : public ESIElement {
MEMPROXY_CLASS(esiChoose);
esiChoose(esiTreeParentPtr);
/* esiWhen */
-struct esiWhen : public esiSequence
-{
+struct esiWhen : public esiSequence {
MEMPROXY_CLASS(esiWhen);
esiWhen(esiTreeParentPtr aParent, int attributes, const char **attr, ESIVarState *);
~esiWhen();
/* 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) {}
* 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.
/* 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));
status = tree->process(0);
processing = false;
- switch (status)
- {
+ switch (status) {
case ESI_PROCESS_COMPLETE:
debugs(86, 5, "esiProcess: tree Processed OK");
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
*/
}
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;
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.
*/
}
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;
}
/* 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");
}
}
if (!sctusable || sctusable->content.size() == 0)
/* Nothing generic or targeted at us, or no
- * content processing requested
+ * content processing requested
*/
return 0;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
/* 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) {}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* when it is, so thats ok. */
ClientHttpRequest *http;
- struct
- {
+ struct {
int passthrough:1;
int oktosend:1;
int finished:1;
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 */
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
switch (lastTag) {
case ESITAG: {
- ++openESITags;
- char *tagEnd = strchr(const_cast<char *>(tag), '>');
-
- if (!tagEnd) {
- error = "Could not find end ('>') of tag";
- return false;
- }
+ ++openESITags;
+ char *tagEnd = strchr(const_cast<char *>(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<char *>(tag), w_space);
+ if (*(tagEnd - 1) == '/')
+ --openESITags;
- if (endofName > tagEnd)
- endofName = const_cast<char *>(tagEnd);
+ char * endofName = strpbrk(const_cast<char *>(tag), w_space);
- *endofName = '\0';
+ if (endofName > tagEnd)
+ endofName = const_cast<char *>(tagEnd);
- *tagEnd = '\0';
+ *endofName = '\0';
- Vector<char *>attributes;
+ *tagEnd = '\0';
- char *attribute = const_cast<char *>(endofName + 1);
+ Vector<char *>attributes;
- while (attribute > tag && attribute < tagEnd) {
- /* leading spaces */
+ char *attribute = const_cast<char *>(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<char *>(tag), w_space);
+ char * endofName = strpbrk(const_cast<char *>(tag), w_space);
- if (endofName > tagEnd)
- endofName = const_cast<char *>(tagEnd);
+ if (endofName > tagEnd)
+ endofName = const_cast<char *>(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<char *>(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<char *>(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");
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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<esiTreeParent> esiTreeParentPtr;
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;
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;
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General 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 "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
typedef int evaluate (stackmember * stack, int *depth, int whereAmI,
stackmember * candidate);
-typedef enum
-{
+typedef enum {
ESI_EXPR_INVALID,
ESI_EXPR_LITERAL,
ESI_EXPR_OR,
ESI_EXPR_EXPR /* the result of an expr PRI 1 */
} evaltype;
-typedef enum
-{
+typedef enum {
ESI_LITERAL_STRING,
ESI_LITERAL_FLOAT,
ESI_LITERAL_INT,
ESI_LITERAL_INVALID
} literalhint;
-struct _stackmember
-{
+struct _stackmember {
evaluate *eval;
- union
- {
+ union {
char *string;
double floating;
int integral;
break;
case ESI_LITERAL_INT:
- debug (86,1) ("%d", s.value.integral);
+ debug (86,1) ("%d", s.value.integral);
break;
case ESI_LITERAL_BOOL:
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* 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
/* 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);
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");
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.
*
*/
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());
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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 */
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
class ESIContext;
/* esiLiteral */
-struct esiLiteral : public ESIElement
-{
+struct esiLiteral : public ESIElement {
MEMPROXY_CLASS(esiLiteral);
esiLiteral(ESISegment::Pointer);
/* optimise copies away later */
ESISegment::Pointer buffer;
- struct
- {
+ struct {
int donevars:1;
} flags;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
virtual char const * errorString() const =0;
protected:
- ESIParser(){};
+ ESIParser() {};
class 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;
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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");
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 */
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
ElementList elements; /* unprocessed or rendered nodes */
size_t processedcount;
- struct
- {
+ struct {
int dovars:1; /* for esiVar */
} flags;
void finish();
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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;
}
};
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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
}
struct _query_elem const *
- ESIVariableQuery::queryVector() const
- {
+ ESIVariableQuery::queryVector() const {
return query;
}
/* 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<sp> 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.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
/* Recursive uses are not supported by design */
-struct _query_elem{char *var, *val;};
+struct _query_elem {char *var, *val;};
class ESIVarState
{
ESISegment::Pointer output;
HttpHeader hdr;
- struct
- {
+ struct {
int language:1;
int cookie:1;
int host:1;
public:
Variable () {}
- virtual ~Variable(){}
+ virtual ~Variable() {}
/* prevent synthetics */
Variable (Variable const &) {}
private:
static char const * esiUserOs[];
- enum esiUserOs_t{
+ enum esiUserOs_t {
ESI_OS_WIN,
ESI_OS_MAC,
ESI_OS_UNIX,
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
sawActivity = dispatchCalls();
if (sawActivity)
runOnceResult = false;
- } while (sawActivity);
+ } while (sawActivity);
if (waitingEngine != NULL)
checkEngine(waitingEngine, true);
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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();
* 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);
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General 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 "dlink.h"
template <class _Arg, class _Result>
-struct unary_function
-{
+struct unary_function {
typedef _Arg argument_type;
typedef _Result result_type;
};
/* generic ostream printer */
template <class Pointer>
-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;
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General 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 "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;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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;
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* Range-Spec
*/
-HttpHdrRangeSpec::HttpHdrRangeSpec() : offset(UnknownPosition), length(UnknownPosition){}
+HttpHdrRangeSpec::HttpHdrRangeSpec() : offset(UnknownPosition), length(UnknownPosition) {}
/* parses range-spec and returns new object on success */
HttpHdrRangeSpec *
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();
/* 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();
/*
* 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
/*
* 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
return false;
if (Config.rangeOffsetLimit == 0)
- /* disabled */
- return true;
+ /* disabled */
+ return true;
if (-1 == Config.rangeOffsetLimit)
/* forced */
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General 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 "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;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
/*
* 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.
*/
*/
/*
- * 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;
* 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;
httpHeaderRegisterWithCacheManager(void)
{
CacheManager::GetInstance()->
- registerAction("http_headers",
- "HTTP Header Statistics",
- httpHeaderStoreReport, 0, 1);
+ registerAction("http_headers",
+ "HTTP Header Statistics",
+ httpHeaderStoreReport, 0, 1);
}
void
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;
}
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--;
}
}
/* 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 */
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'));
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;
}
}
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;
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;
}
} 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;
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) {
}
/*
- * 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
*/
}
/*
- * 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)
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);
}
}
return NULL;
String s;
-
+
(void) getList(HDR_SURROGATE_CONTROL, &s);
HttpHdrSc *sc = httpHdrScParseCreate(&s);
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 */
{
/* 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 */
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);
+ }
}
}
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;
/*
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
hoReply
} http_hdr_owner_type;
-struct _HttpHeaderFieldAttrs
-{
+struct _HttpHeaderFieldAttrs {
const char *name;
http_hdr_type id;
field_type type;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
{
size_t len;
static char delim[3][8] = {
- "\"?,",
- "\"\\",
- " ?,\t\r\n"
+ "\"?,",
+ "\"\\",
+ " ?,\t\r\n"
};
int quoted = 0;
assert(str && item && pos);
errno = 0;
int64_t res = strtoll(start, NULL, 10);
if (!res && EINVAL == errno) /* maybe not portable? */
- return 0;
+ return 0;
*value = res;
return 1;
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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;
}
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;
}
}
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
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.)
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.
*
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;
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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;
virtual bool expectingBody(const HttpRequestMethod&, int64_t&) const = 0;
void firstLineBuf(MemBuf&);
-
+
virtual bool inheritProperties(const HttpMsg *aMsg) = 0;
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;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* 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
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();
}
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;
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
bool HttpReply::inheritProperties(const HttpMsg *aMsg)
{
const HttpReply *aRep = dynamic_cast<const HttpReply*>(aMsg);
- if(!aRep)
- return false;
+ if (!aRep)
+ return false;
keep_alive = aRep->keep_alive;
return true;
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
virtual void reset();
// use HTTPMSGLOCK() instead of calling this directly
- virtual HttpRequest *_lock()
- {
+ virtual HttpRequest *_lock() {
return static_cast<HttpRequest*>(HttpMsg::_lock());
};
/* 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);
}
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;
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:
virtual bool sanityCheckStartLine(MemBuf *buf, http_status *error);
virtual void hdrCacheInit();
-
+
virtual bool inheritProperties(const HttpMsg *aMsg);
};
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General 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 "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)
/*
* 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)
*/
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;
#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 {
}
}
-bool
+bool
HttpRequestMethod::isCacheble() const
{
// TODO: optimize the lookup with a precomputed flags array
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:
* 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
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
*/
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
}
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 */
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
{
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;
}
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;
return true;
}
- bool operator!=(const HttpVersion& that) const
- {
+ bool operator!=(const HttpVersion& that) const {
return ((this->major != that.major) || (this->minor != that.minor));
}
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;
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()
// 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;
// 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);
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");
}
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)
}
debugs(inCall->debugSection, inCall->debugLevel,
- typeName << " status out:" << status());
+ typeName << " status out:" << status());
inCall = NULL;
}
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();
}
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);
}
}
-JobDialer::~JobDialer(){
+JobDialer::~JobDialer()
+{
cbdataReferenceDone(lock); // lock may be NULL
}
}
void
-JobDialer::dial(AsyncCall &call)
+JobDialer::dial(AsyncCall &call)
{
Must(lock && cbdataReferenceValid(lock)); // canDial() checks for this
Must(job);
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);
}
- /*
- * $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
* "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
private:
// not implemented and should not be needed
- JobDialer &operator =(const JobDialer &);
+ JobDialer &operator =(const JobDialer &);
};
#include "AsyncJobCalls.h"
template <class Dialer>
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);
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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)
{
}
{
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;
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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 */
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General 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 "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
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);
}
}
- void setHeader(Header *h)
- {
+ void setHeader(Header *h) {
HTTPMSGUNLOCK(header);
header = HTTPMSGLOCK(h);
- body_pipe = header->body_pipe;
+ body_pipe = header->body_pipe;
}
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 ?
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)
{
}
sendAnswer(message);
clearAdaptation(theXaction);
Must(done());
- debugs(93,3, HERE << "ICAPLauncher::noteAdaptationAnswer exiting ");
+ debugs(93,3, HERE << "ICAPLauncher::noteAdaptationAnswer exiting ");
}
void ICAPLauncher::noteInitiatorAborted()
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();
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* 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.
*/
ICAPOptXact::ICAPOptXact(Adaptation::Initiator *anInitiator, ICAPServiceRep::Pointer &aService):
- AsyncJob("ICAPOptXact"),
- ICAPXaction("ICAPOptXact", anInitiator, aService)
+ AsyncJob("ICAPOptXact"),
+ ICAPXaction("ICAPOptXact", anInitiator, aService)
{
}
/* ICAPOptXactLauncher */
ICAPOptXactLauncher::ICAPOptXactLauncher(Adaptation::Initiator *anInitiator, Adaptation::ServicePointer aService):
- AsyncJob("ICAPOptXactLauncher"),
- ICAPLauncher("ICAPOptXactLauncher", anInitiator, aService)
+ AsyncJob("ICAPOptXactLauncher"),
+ ICAPLauncher("ICAPOptXactLauncher", anInitiator, aService)
{
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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
{
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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;
#if USE_ICMP
/* This is a line-data format struct. DO NOT alter. */
-struct pingerEchoData
-{
+struct pingerEchoData {
IPAddress to;
unsigned char opcode;
int psize;
};
/* This is a line-data format struct. DO NOT alter. */
-struct pingerReplyData
-{
+struct pingerReplyData {
IPAddress from;
unsigned char opcode;
int rtt;
char payload[PINGER_PAYLOAD_SZ];
};
-struct icmpEchoData
-{
+struct icmpEchoData {
struct timeval tv;
unsigned char opcode;
char payload[MAX_PAYLOAD];
/**
* 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
* 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:
* 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;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
#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,
#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 );
}
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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.
pecho.psize = len;
- if(len > 0)
+ if (len > 0)
xmemcpy(pecho.payload, payload, len);
slen = sizeof(pingerEchoData) - PINGER_PAYLOAD_SZ + pecho.psize;
IPAddress localhost;
/* User configured disabled. */
- if(!Config.pinger.enable) {
+ if (!Config.pinger.enable) {
Close();
return -1;
}
#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_
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General 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 "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()
* cevans - beware signed/unsigned issues in untrusted data from
* the network!!
*/
- if (len < 0)
- {
+ if (len < 0) {
len = 0;
}
icmp_pktsize += sizeof(struct timeval) + sizeof(char);
- if (payload)
- {
+ if (payload) {
if (len > MAX_PAYLOAD)
len = MAX_PAYLOAD;
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());
}
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;
}
#endif
/* IP Header */
-typedef struct iphdr
-{
+typedef struct iphdr {
u_int8_t ip_vhl:
4; /* Length of the header in dwords */
} 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;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
// 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()
{
icmp6_pktsize += sizeof(struct timeval) + sizeof(char);
- if (payload)
- {
+ if (payload) {
if (len > MAX_PAYLOAD)
len = MAX_PAYLOAD;
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);
struct timeval now;
static pingerReplyData preply;
- if(icmp_sock < 0) {
+ if (icmp_sock < 0) {
debugs(42,0, HERE << "dropping ICMPv6 read. No socket!?");
return;
}
// 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;
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;
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* 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 */
#endif
/// \ingroup ServerProtocolICPAPI
-struct icpUdpData
-{
+struct icpUdpData {
IPAddress address;
void *msg;
size_t len;
/*
* $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
*
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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;
}
/** \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;
}
/* 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;
}
/** \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;
}
{
#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)
peer.GetInAddr(natLookup.nl_outip);
natLookup.nl_flags = IPN_TCP;
- if (natfd < 0)
- {
+ if (natfd < 0) {
int save_errno;
enter_suid();
#ifdef IPNAT_NAME
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;
* 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)");
}
return -1;
- } else
- {
+ } else {
if (me != natLookup.nl_realip) {
client = natLookup.nl_realip;
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.
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;
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;
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)");
}
return -1;
- } else
- {
+ } else {
int natted = (me != nl.rdaddr.v4);
client = nl.rdaddr.v4;
client.SetPort(ntohs(nl.rdport));
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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);
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);
}
}
/* 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 <dlfcn.h>
+#include <dlfcn.h>
#endif
#include "TextException.h"
// 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<lt_dlhandle>(theHandle)) == 0;
+ // we cast to avoid including ltdl.h in LoadableModule.h
+ return lt_dlclose(static_cast<lt_dlhandle>(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
}
#include "SquidString.h"
// wrapper for dlopen(3), libltdl, and friends
-class LoadableModule {
+class LoadableModule
+{
public:
enum LoadMode { lmNow, lmLazy };
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
\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);
*
#else
void
MemBuf::Printf(va_alist)
-va_dcl
-{
+va_dcl {
va_list args;
mb_size_t sz = 0;
va_start(args);
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
/**
\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
*/
\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 */
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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);
_reply = HTTPMSGLOCK(newrep);
}
-struct LowestMemReader : public unary_function<store_client, void>
-{
- LowestMemReader(int64_t seed):current(seed){}
+struct LowestMemReader : public unary_function<store_client, void> {
+ 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;
}
int64_t current;
};
-struct StoreClientStats : public unary_function<store_client, void>
-{
- StoreClientStats(MemBuf *anEntry):where(anEntry),index(0){}
+struct StoreClientStats : public unary_function<store_client, void> {
+ StoreClientStats(MemBuf *anEntry):where(anEntry),index(0) {}
- void operator()(store_client const &x)
- {
+ void operator()(store_client const &x) {
x.dumpStats(where, index++);
}
/*
* 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.
*
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
IRCB *ping_reply_callback;
void *ircb_data;
- struct
- {
+ struct {
STABH *callback;
void *data;
} abort;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
/*
* 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. :)
- *
+ *
*/
#else
void
packerPrintf(va_alist)
-va_dcl
-{
+va_dcl {
va_list args;
Packer *p = NULL;
const char *fmt = NULL;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General 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 "cbdata.h"
-struct _Version
-{
+struct _Version {
short int current; /* current version */
short int required; /* minimal version that can safely handle current version */
};
class StoreDigestCBlock
{
- public:
+public:
Version ver;
int capacity;
int count;
int reserved[32 - 6];
};
-struct _DigestFetchState
-{
+struct _DigestFetchState {
PeerDigest *pd;
StoreEntry *entry;
StoreEntry *old_entry;
time_t resp_time;
time_t expires;
- struct
- {
+ struct {
int msg;
int bytes;
}
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 */
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;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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;
http_port_list::http_port_list(const char *aProtocol)
#if USE_SSL
- : http(*this)
+ :
+ http(*this)
#endif
{
protocol = xstrdup(aProtocol);
//#include "typedefs.h"
#include "cbdata.h"
-struct http_port_list
-{
+struct http_port_list {
http_port_list(const char *aProtocol);
~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;
#if USE_SSL
-struct https_port_list: public http_port_list
-{
+struct https_port_list: public http_port_list {
https_port_list();
};
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
class RemovalPolicy
{
- public:
+public:
const char *_type;
void *_data;
void (*Free) (RemovalPolicy * policy);
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);
};
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
static StringRegistry &Instance();
void add
- (String const *);
+ (String const *);
StringRegistry();
void remove
- (String const *);
+ (String const *);
private:
static OBJH Stat;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
/*
* 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
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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);
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();
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;
};
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<size_t> 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;}
/** 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
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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;
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;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
{
public:
- StoreEntryStreamBuf(StoreEntry *anEntry) : theEntry(anEntry)
- {
+ StoreEntryStreamBuf(StoreEntry *anEntry) : theEntry(anEntry) {
theEntry->lock();
theEntry->buffer();
}
- ~StoreEntryStreamBuf()
- {
+ ~StoreEntryStreamBuf() {
theEntry->unlock();
}
/* 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 ())
}
/* push the buffer to the store */
- virtual int sync()
- {
+ virtual int sync() {
std::streamsize pending(pptr() - pbase());
if (pending)
/* 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);
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
/**
\defgroup FileSystems Storage Filesystems
- *
+ *
\section Introduction Introduction
\par
* Traditionally, Squid has always used the Unix filesystem (\link UFS UFS\endlink)
* 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
* 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
*
\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
typedef Vector<StoreFileSystem*>::const_iterator const_iterator;
StoreFileSystem() : initialised(false) {}
- virtual ~StoreFileSystem(){}
+ virtual ~StoreFileSystem() {}
virtual char const *type () const = 0;
virtual SwapDir *createSwapDir() = 0;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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();
};
class StoreHashIndexEntry : public StoreEntry
-{};
+ {};
class StoreSearchHashIndex : public StoreSearch
{
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 */
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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;
}
StoreIOBuffer(MemBuf *aMemBuf, int64_t anOffset) :
length(aMemBuf->contentSize()),
offset (anOffset),
- data(aMemBuf->content())
- {
+ data(aMemBuf->content()) {
flags.error = 0;
}
- Range<int64_t> range() const
- {
+ Range<int64_t> range() const {
return Range<int64_t>(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;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
}
void
-StoreIOState::operator delete (void *address){assert (0);}
+StoreIOState::operator delete (void *address) {assert (0);}
StoreIOState::StoreIOState()
{
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
STIOCB *callback;
void *callback_data;
- struct
- {
+ struct {
STRCB *callback;
void *callback_data;
} read;
- struct
- {
+ struct {
unsigned int closing:1; /* debugging aid */
} flags;
};
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
/* 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;
}
{
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;
}
}
- bool includes (int anInt) const
- {
+ bool includes (int anInt) const {
if (anInt < _min || anInt > _max)
return false;
result = new StoreMetaSTDLFS;
break;
- case STORE_META_OBJSIZE:
- result = new StoreMetaObjSize;
+ case STORE_META_OBJSIZE:
+ result = new StoreMetaObjSize;
break;
case STORE_META_VARY_HEADERS:
break;
case STORE_META_OBJSIZE:
- break;
+ break;
default:
debugs(20, 1, "WARNING: got unused STORE_META type " << getType());
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
virtual char getType() const = 0;
virtual bool validLength(int) const;
virtual bool checkConsistency(StoreEntry *) const;
- virtual ~StoreMeta(){}
+ virtual ~StoreMeta() {}
int length;
void *value;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
StoreMeta *newNode = StoreMeta::Factory(type, length, &buf[position]);
if (newNode)
- tail = StoreMeta::Add (tail, newNode);
+ tail = StoreMeta::Add (tail, newNode);
position += length;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
void asList(void (*) (CbDataList<StoreEntryPointer), void *cbdata);
*/
/* 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) = 0;
/* return true if a new StoreEntry is immediately available
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
StoreSwapLogHeader::StoreSwapLogHeader():op(SWAP_LOG_VERSION), version(1)
{
- record_size = sizeof(StoreSwapLogData);
+ record_size = sizeof(StoreSwapLogData);
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* takes a StoreEntry as a parameter and returns a tlv linked
* list. Second, storeSwapMetaPack() converts the tlv list
* into a character buffer that we can write.
- *
+ *
\note MemObject has a MemObject::swap_hdr_sz.
* This value is the size of that character buffer; the size of the
* swap file meta data. The StoreEntry has a member
* Thus, the size of the object "content" is
\code StoreEntry->swap_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
/*
* 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
class StoreSwapLogHeader
{
public:
- StoreSwapLogHeader();
- char op;
- int version;
- int record_size;
+ StoreSwapLogHeader();
+ char op;
+ int version;
+ int record_size;
};
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General 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 "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)
{
#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);
}
void
StringRegistry::remove
- (String const *entry)
+(String const *entry)
{
entries.remove(entry, ptrcmp);
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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;
}
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';
}
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';
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
}
void
-SwapDir::create(){}
+SwapDir::create() {}
void
-SwapDir::dump(StoreEntry &)const{}
+SwapDir::dump(StoreEntry &)const {}
bool
SwapDir::doubleCheck(StoreEntry &)
}
void
-SwapDir::unlink(StoreEntry &){}
+SwapDir::unlink(StoreEntry &) {}
void
SwapDir::stat(StoreEntry &output) const
SwapDir::statfs(StoreEntry &)const {}
void
-SwapDir::maintain(){}
+SwapDir::maintain() {}
size_t
SwapDir::minSize() const
}
void
-SwapDir::reference(StoreEntry &){}
+SwapDir::reference(StoreEntry &) {}
void
-SwapDir::dereference(StoreEntry &){}
+SwapDir::dereference(StoreEntry &) {}
int
SwapDir::callback()
}
void
-SwapDir::sync(){}
+SwapDir::sync() {}
/* Move to StoreEntry ? */
bool
}
void
-SwapDir::openLog(){}
+SwapDir::openLog() {}
void
-SwapDir::closeLog(){}
+SwapDir::closeLog() {}
int
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
}
/* NOT performance critical. Really. Don't bother optimising for speed
- * - RBC 20030718
+ * - RBC 20030718
*/
ConfigOption *
SwapDir::getOptionTree() 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);
}
void
SwapDir::get
- (String const key, STOREGETCLIENT callback, void *cbdata)
+(String const key, STOREGETCLIENT callback, void *cbdata)
{
fatal("not implemented");
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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();
{
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;
}
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;
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;
{
public:
- virtual ~CleanLog(){}
+ virtual ~CleanLog() {}
virtual const StoreEntry *nextEntry() = 0;
virtual void write(StoreEntry const &) = 0;
virtual void writeCleanDone();
virtual void parse(int index, char *path) = 0;
- struct
- {
+ struct {
int blksize;
} fs;
};
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
/**
\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;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General 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 "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"
+};
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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
/* ====================================================================== */
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;
}
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
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;
}
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;
}
int main(int argc, char **argv)
{
SERVICE_TABLE_ENTRY DispatchTable[] = {
- {NULL, SquidWinSvcMain},
- {NULL, NULL}
- };
+ {NULL, SquidWinSvcMain},
+ {NULL, NULL}
+ };
char *c;
char stderr_path[256];
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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;
buf = static_cast<char *>(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.
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') {
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},
- /*{ "<a", LFT_SERVER_IP_ADDRESS }, */
- /*{ "<p", LFT_SERVER_PORT }, */
- {"<A", LFT_SERVER_IP_OR_PEER_NAME},
+ /*{ "<a", LFT_SERVER_IP_ADDRESS }, */
+ /*{ "<p", LFT_SERVER_PORT }, */
+ {"<A", LFT_SERVER_IP_OR_PEER_NAME},
- /* {"oa", LFT_OUTGOING_IP}, */
- /* {"ot", LFT_OUTGOING_TOS}, */
+ /* {"oa", LFT_OUTGOING_IP}, */
+ /* {"ot", LFT_OUTGOING_TOS}, */
- {"la", LFT_LOCAL_IP},
- {"lp", LFT_LOCAL_PORT},
- /*{ "lA", LFT_LOCAL_NAME }, */
+ {"la", LFT_LOCAL_IP},
+ {"lp", LFT_LOCAL_PORT},
+ /*{ "lA", LFT_LOCAL_NAME }, */
- {"ts", LFT_TIME_SECONDS_SINCE_EPOCH},
- {"tu", LFT_TIME_SUBSECOND},
- {"tl", LFT_TIME_LOCALTIME},
- {"tg", LFT_TIME_GMT},
- {"tr", LFT_TIME_TO_HANDLE_REQUEST},
+ {"ts", LFT_TIME_SECONDS_SINCE_EPOCH},
+ {"tu", LFT_TIME_SUBSECOND},
+ {"tl", LFT_TIME_LOCALTIME},
+ {"tg", LFT_TIME_GMT},
+ {"tr", LFT_TIME_TO_HANDLE_REQUEST},
- {">h", LFT_REQUEST_HEADER},
- {">h", LFT_REQUEST_ALL_HEADERS},
- {"<h", LFT_REPLY_HEADER},
- {"<h", LFT_REPLY_ALL_HEADERS},
+ {">h", LFT_REQUEST_HEADER},
+ {">h", LFT_REQUEST_ALL_HEADERS},
+ {"<h", LFT_REPLY_HEADER},
+ {"<h", LFT_REPLY_ALL_HEADERS},
- {"un", LFT_USER_NAME},
- {"ul", LFT_USER_LOGIN},
- /*{ "ur", LFT_USER_REALM }, */
- /*{ "us", LFT_USER_SCHEME }, */
- {"ui", LFT_USER_IDENT},
- {"ue", LFT_USER_EXTERNAL},
+ {"un", LFT_USER_NAME},
+ {"ul", LFT_USER_LOGIN},
+ /*{ "ur", LFT_USER_REALM }, */
+ /*{ "us", LFT_USER_SCHEME }, */
+ {"ui", LFT_USER_IDENT},
+ {"ue", LFT_USER_EXTERNAL},
- {"Hs", LFT_HTTP_CODE},
- /*{ "Ht", LFT_HTTP_STATUS }, */
+ {"Hs", LFT_HTTP_CODE},
+ /*{ "Ht", LFT_HTTP_STATUS }, */
- {"Ss", LFT_SQUID_STATUS},
- /*{ "Se", LFT_SQUID_ERROR }, */
- {"Sh", LFT_SQUID_HIERARCHY},
+ {"Ss", LFT_SQUID_STATUS},
+ /*{ "Se", LFT_SQUID_ERROR }, */
+ {"Sh", LFT_SQUID_HIERARCHY},
- {"mt", LFT_MIME_TYPE},
+ {"mt", LFT_MIME_TYPE},
- {"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},
+ {"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 }, */
- {"<st", LFT_REPLY_SIZE_TOTAL},
- {"<sH", LFT_REPLY_HIGHOFFSET},
- {"<sS", LFT_REPLY_OBJECTSIZE},
- /*{ "<sl", LFT_REPLY_SIZE_LINE }, * / / * the reply line (protocol, code, text) */
- /*{ "<sh", LFT_REPLY_SIZE_HEADERS }, */
- /*{ "<sb", LFT_REPLY_SIZE_BODY }, */
- /*{ "<sB", LFT_REPLY_SIZE_BODY_NO_TE }, */
+ {"<st", LFT_REPLY_SIZE_TOTAL},
+ {"<sH", LFT_REPLY_HIGHOFFSET},
+ {"<sS", LFT_REPLY_OBJECTSIZE},
+ /*{ "<sl", LFT_REPLY_SIZE_LINE }, * / / * the reply line (protocol, code, text) */
+ /*{ "<sh", LFT_REPLY_SIZE_HEADERS }, */
+ /*{ "<sb", LFT_REPLY_SIZE_BODY }, */
+ /*{ "<sB", LFT_REPLY_SIZE_BODY_NO_TE }, */
- {"et", LFT_TAG},
- {"st", LFT_IO_SIZE_TOTAL},
- {"ea", LFT_EXT_LOG},
+ {"et", LFT_TAG},
+ {"st", LFT_IO_SIZE_TOTAL},
+ {"ea", LFT_EXT_LOG},
- {"%", LFT_PERCENT},
+ {"%", LFT_PERCENT},
- {NULL, LFT_NONE} /* this must be last */
- };
+ {NULL, LFT_NONE} /* this must be last */
+};
static void
accessLogCustom(AccessLogEntry * al, customlog * log)
break;
case LFT_CLIENT_PORT:
- if (al->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: */
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<int64_t>(current_time.tv_sec);
dooff = 1;
break;
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;
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:
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;
lt->data.string = cp;
while (l > 0) {
- switch(*cur) {
+ switch (*cur) {
case '"':
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) {
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
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
}
/*
- * 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
* 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/
* ----------------------------------------------------------
*
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
/*
* 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.
*/
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
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;
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;
}
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;
}
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();
}
class HttpRequest;
class HttpReply;
-namespace Adaptation {
+namespace Adaptation
+{
class AccessRule;
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
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) {
if (!group()) {
debugs(93,0, "ERROR: Unknown adaptation service or group name: '" <<
- groupId << "'"); // TODO: fail on failures
+ groupId << "'"); // TODO: fail on failures
}
}
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();
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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());
}
}
const Vector<ServiceConfig*> &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
// 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()
{
template <class C>
class RefCount;
-namespace Adaptation {
+namespace Adaptation
+{
class Service;
class ServiceConfig;
const char *
Adaptation::methodStr(Adaptation::Method method)
{
- switch(method) {
+ switch (method) {
case Adaptation::methodReqmod:
return "REQMOD";
const char *
Adaptation::vectPointStr(Adaptation::VectPoint point)
{
- switch(point) {
+ switch (point) {
case Adaptation::pointPreCache:
return "PRECACHE";
#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
typedef UnaryMemFunT<Initiator, HttpMsg*> 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); }
};
/* 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);
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();
}
{
if (theInitiator.isThere()) {
CallJobHere1(93, 5, theInitiator.ptr(),
- Initiator::noteAdaptationQueryAbort, final);
- }
+ Initiator::noteAdaptationQueryAbort, final);
+ }
clearInitiator();
}
return *theService;
}
-const char *Adaptation::Initiate::status() const {
+const char *Adaptation::Initiate::status() const
+{
return AsyncJob::status(); // for now
}
/* InitiatorHolder */
Adaptation::InitiatorHolder::InitiatorHolder(Initiator *anInitiator):
- prime(0), cbdata(0)
+ prime(0), cbdata(0)
{
if (anInitiator) {
cbdata = cbdataReference(anInitiator->toCbdata());
}
Adaptation::InitiatorHolder::InitiatorHolder(const InitiatorHolder &anInitiator):
- prime(0), cbdata(0)
+ prime(0), cbdata(0)
{
if (anInitiator != NULL && cbdataReferenceValid(anInitiator.cbdata)) {
cbdata = cbdataReference(anInitiator.cbdata);
clear();
}
-void Adaptation::InitiatorHolder::clear() {
+void Adaptation::InitiatorHolder::clear()
+{
if (prime) {
prime = NULL;
cbdataReferenceDone(cbdata);
}
bool
-Adaptation::InitiatorHolder::isThere() {
+Adaptation::InitiatorHolder::isThere()
+{
return prime && cbdataReferenceValid(cbdata);
}
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);
/*
* 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.
class HttpMsg;
-namespace Adaptation {
+namespace Adaptation
+{
class Initiator: virtual public AsyncJob
{
class BodyPipe;
typedef RefCount<BodyPipe> 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.
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
/// 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
for (SI i = AllServices().begin(); i != AllServices().end(); ++i) {
if ((*i)->cfg().key == key)
return *i;
- }
+ }
return NULL;
}
class HttpMsg;
class HttpRequest;
-namespace Adaptation {
+namespace Adaptation
+{
// manages adaptation service configuration in squid.conf
// specific adaptation mechanisms extend this class
#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 *
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);
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<int>(p);
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;
}
#include "RefCount.h"
#include "adaptation/Elements.h"
-namespace Adaptation {
+namespace Adaptation
+{
// manages adaptation service configuration in squid.conf
class ServiceConfig
// TODO: fail on failures
if (!FindService(id))
debugs(93,0, "ERROR: Unknown adaptation name: " << id);
- }
+ }
debugs(93,7, HERE << "finalized " << kind << ": " << id);
}
/* SingleService */
Adaptation::SingleService::SingleService(const String &aServiceId):
- ServiceGroup("single-service group")
+ ServiceGroup("single-service group")
{
id = aServiceId;
services.push_back(aServiceId);
#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
// 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;
template <class Item>
class Vector;
-namespace Adaptation {
+namespace Adaptation
+{
class Service;
class ServiceConfig;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
/* 32/128 bits address in memory with length */
-class m_ADDR {
+class m_ADDR
+{
public:
uint8_t len;
IPAddress addr;
/// \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<int> *as_number;
time_t expires; /* NOTUSED */
};
-struct ASState
-{
+struct ASState {
StoreEntry *entry;
store_client *sc;
HttpRequest *request;
};
/** 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;
ACLASN::prepareForUse()
{
for (CbDataList<int> *i = data; i; i = i->
- next)
+ next)
asnCacheStart(i->element);
}
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);
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);
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
currentRequest = auth_user_request;
httpAuthHeader = proxy_auth;
if (decodeCleartext ()) {
- extractUsername();
- extractPassword();
+ extractUsername();
+ extractPassword();
}
currentRequest = NULL;
httpAuthHeader = NULL;
BasicUser::valid() const
{
if (username() == NULL)
- return false;
+ return false;
if (passwd == NULL)
- return false;
+ return false;
return true;
}
/**
* 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 *
AuthBasicConfig::registerWithCacheManager(void)
{
CacheManager::GetInstance()->
- registerAction("basicauthenticator",
- "Basic User Authenticator Stats",
- authenticateBasicStats, 0, 1);
+ registerAction("basicauthenticator",
+ "Basic User Authenticator Stats",
+ authenticateBasicStats, 0, 1);
}
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);
char *passwd;
time_t credentials_checkedtime;
- struct
- {
+ struct {
unsigned int credentials_ok:
2; /*0=unchecked,1=ok,2=failed */
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
public:
static AuthScheme &GetInstance();
basicScheme();
- virtual ~basicScheme(){}
+ virtual ~basicScheme() {}
/* per scheme */
virtual char const *type () const;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* 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
* 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
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));
case Failed:
- /* send new challenge */
- return 1;
+ /* send new challenge */
+ return 1;
}
return -2;
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);
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 */
}
/* this reference to user was not locked because freeeing the user frees
- * the nonce too.
+ * the nonce too.
*/
nonce->user = NULL;
}
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);
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;
/* 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;
/* 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;
DigestUser *user;
/* has this nonce been invalidated ? */
- struct
- {
+ struct {
unsigned int valid:1;
unsigned int incache:1;
} flags;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
public:
static AuthScheme &GetInstance();
digestScheme();
- virtual ~digestScheme(){}
+ virtual ~digestScheme() {}
/* per scheme */
virtual char const *type () const;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
AuthNegotiateConfig::registerWithCacheManager(void)
{
CacheManager::GetInstance()->
- registerAction("negotiateauthenticator",
- "Negotiate User Authenticator Stats",
- authenticateNegotiateStats, 0, 1);
+ registerAction("negotiateauthenticator",
+ "Negotiate User Authenticator Stats",
+ authenticateNegotiateStats, 0, 1);
}
bool
/* Need keep-alive */
if (!request->flags.proxy_keepalive && request->flags.must_keepalive)
- return;
+ return;
/* New request, no user details */
if (auth_user_request == NULL) {
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 */
/* see if this is an existing user with a different proxy_auth
* string */
AuthUserHashPointer *usernamehash = static_cast<AuthUserHashPointer *>(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<AuthUserHashPointer *>(usernamehash->next);
if (usernamehash) {
* 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.) */
}
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);
/* 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;
}
}
/* locate second word */
blob = proxy_auth;
- if(blob) {
+ if (blob) {
while (xisspace(*blob) && *blob)
blob++;
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;
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 */
}
AuthNegotiateUserRequest::AuthNegotiateUserRequest() :
- /*conn(NULL),*/ auth_state(AUTHENTICATE_STATE_NONE),
+ /*conn(NULL),*/ auth_state(AUTHENTICATE_STATE_NONE),
_theUser(NULL)
{
waiting=0;
authserver = NULL;
}
if (request) {
- HTTPMSGUNLOCK(request);
- request = NULL;
+ HTTPMSGUNLOCK(request);
+ request = NULL;
}
}
/* Generic */
/// \ingroup AuthNegotiateAPI
-typedef struct
-{
+typedef struct {
void *data;
AuthUserRequest *auth_user_request;
RH *handler;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
public:
static AuthScheme &GetInstance();
negotiateScheme();
- virtual ~negotiateScheme(){};
+ virtual ~negotiateScheme() {};
/* per scheme */
virtual char const *type () const;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
AuthNTLMConfig::registerWithCacheManager(void)
{
CacheManager::GetInstance()->
- registerAction("ntlmauthenticator",
- "NTLM User Authenticator Stats",
- authenticateNTLMStats, 0, 1);
+ registerAction("ntlmauthenticator",
+ "NTLM User Authenticator Stats",
+ authenticateNTLMStats, 0, 1);
}
bool
/* Need keep-alive */
if (!request->flags.proxy_keepalive && request->flags.must_keepalive)
- return;
+ return;
/* New request, no user details */
if (auth_user_request == NULL) {
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);
/* see if this is an existing user with a different proxy_auth
* string */
auth_user_hash_pointer *usernamehash = static_cast<AuthUserHashPointer *>(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<AuthUserHashPointer *>(usernamehash->next);
if (usernamehash) {
* 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);
}
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);
* 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;
}
}
blob = proxy_auth;
/* if proxy_auth is actually NULL, we'd better not manipulate it. */
- if(blob) {
+ if (blob) {
while (xisspace(*blob) && *blob)
blob++;
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;
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 */
}
AuthNTLMUserRequest::AuthNTLMUserRequest() :
- /*conn(NULL),*/ auth_state(AUTHENTICATE_STATE_NONE),
+ /*conn(NULL),*/ auth_state(AUTHENTICATE_STATE_NONE),
_theUser(NULL)
{
waiting=0;
authserver = NULL;
}
if (request) {
- HTTPMSGUNLOCK(request);
- request = NULL;
+ HTTPMSGUNLOCK(request);
+ request = NULL;
}
}
/* Generic */
-typedef struct
-{
+typedef struct {
void *data;
AuthUserRequest *auth_user_request;
RH *handler;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
public:
static AuthScheme &GetInstance();
ntlmScheme();
- virtual ~ntlmScheme(){};
+ virtual ~ntlmScheme() {};
/* per scheme */
virtual char const *type () const;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
*
\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:
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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;
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;
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;
#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())
requirePathnameExists("Icon Directory", Config.icons.directory);
- if(Config.errorDirectory)
+ if (Config.errorDirectory)
requirePathnameExists("Error Directory", Config.errorDirectory);
#if HTTP_VIOLATIONS
{
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;
break;
}
- for (R = Config.Refresh; R; R = R->next)
- {
+ for (R = Config.Refresh; R; R = R->next) {
if (!R->flags.override_lastmod)
continue;
break;
}
- for (R = Config.Refresh; R; R = R->next)
- {
+ for (R = Config.Refresh; R; R = R->next) {
if (!R->flags.reload_into_ims)
continue;
break;
}
- for (R = Config.Refresh; R; R = R->next)
- {
+ for (R = Config.Refresh; R; R = R->next) {
if (!R->flags.ignore_reload)
continue;
break;
}
- for (R = Config.Refresh; R; R = R->next)
- {
+ for (R = Config.Refresh; R; R = R->next) {
if (!R->flags.ignore_no_cache)
continue;
break;
}
- for (R = Config.Refresh; R; R = R->next)
- {
+ for (R = Config.Refresh; R; R = R->next) {
if (!R->flags.ignore_no_store)
continue;
break;
}
- for (R = Config.Refresh; R; R = R->next)
- {
+ for (R = Config.Refresh; R; R = R->next) {
if (!R->flags.ignore_private)
continue;
break;
}
- for (R = Config.Refresh; R; R = R->next)
- {
+ for (R = Config.Refresh; R; R = R->next) {
if (!R->flags.ignore_auth)
continue;
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();
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;
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;
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;
}
for (i = 0; i < swap.n_configured; i++) {
s = dynamic_cast<SwapDir *>(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");
if ((strcasecmp(path_str, dynamic_cast<SwapDir *>(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.
/** 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);
self_destruct();
p->host = xstrdup(token);
-
+
p->name = xstrdup(token);
if ((token = strtok(NULL, w_space)) == NULL)
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")) {
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")) {
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;
#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) {
#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();
static void
free_IPAddress_list(IPAddress_list ** head)
{
- if(*head) delete *head; *head = NULL;
+ if (*head) delete *head;
+ *head = NULL;
}
#if CURRENTLY_UNUSED
#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);
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();
}
} 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;
#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();
}
#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();
}
} 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);
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();
}
}
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
}
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();
}
parse_icap_access_type()
{
debugs(93, 0, "WARNING: 'icap_access' is depricated. " <<
- "Use 'adaptation_access' instead");
+ "Use 'adaptation_access' instead");
Adaptation::Config::ParseAccess(LegacyParser);
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General 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 "squid.h"
-typedef struct
-{
+typedef struct {
const char *name;
hash_table *hash;
int count; /* #currently cached entries */
} CacheIndex;
-typedef struct _CacheEntry
-{
+typedef struct _CacheEntry {
const cache_key *key;
struct _CacheEntry *next;
/* 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);
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
/**
\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.
*/
/* warn if user specified incorrect password */
if (mgr->passwd)
- debugs(16, DBG_IMPORTANT, "CacheManager: " <<
- (mgr->user_name ? mgr->user_name : "<unknown>") << "@" <<
- fd_table[fd].ipaddr << ": incorrect password for '" <<
+ debugs(16, DBG_IMPORTANT, "CacheManager: " <<
+ (mgr->user_name ? mgr->user_name : "<unknown>") << "@" <<
+ fd_table[fd].ipaddr << ": incorrect password for '" <<
mgr->action << "'" );
else
- debugs(16, DBG_IMPORTANT, "CacheManager: " <<
- (mgr->user_name ? mgr->user_name : "<unknown>") << "@" <<
- fd_table[fd].ipaddr << ": password needed for '" <<
+ debugs(16, DBG_IMPORTANT, "CacheManager: " <<
+ (mgr->user_name ? mgr->user_name : "<unknown>") << "@" <<
+ fd_table[fd].ipaddr << ": password needed for '" <<
mgr->action << "'" );
rep = err->BuildHttpReply();
return;
}
- debugs(16, DBG_IMPORTANT, "CacheManager: " <<
- (mgr->user_name ? mgr->user_name : "<unknown>") << "@" <<
- fd_table[fd].ipaddr << " requesting '" <<
+ debugs(16, DBG_IMPORTANT, "CacheManager: " <<
+ (mgr->user_name ? mgr->user_name : "<unknown>") << "@" <<
+ fd_table[fd].ipaddr << " requesting '" <<
mgr->action << "'" );
/* retrieve object requested */
a = findAction(mgr->action);
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
* 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)
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
carpRegisterWithCacheManager(void)
{
CacheManager::GetInstance()->
- registerAction("carp", "CARP information", carpCachemgr, 0, 1);
+ registerAction("carp", "CARP information", carpCachemgr, 0, 1);
}
void
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)) {
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
{
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;
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;
#endif
/// \ingroup CBDATAInternal
-struct CBDataIndex
-{
+struct CBDataIndex {
MemAllocator *pool;
FREE *free_func;
}
#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
}
#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
#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
'!', p, type, locks, file, line);
}
-struct CBDataDumper : public unary_function<cbdata, void>
-{
- CBDataDumper(StoreEntry *anEntry):where(anEntry){}
+struct CBDataDumper : public unary_function<cbdata, void> {
+ CBDataDumper(StoreEntry *anEntry):where(anEntry) {}
- void operator()(cbdata const &x)
- {
+ void operator()(cbdata const &x) {
x.dump(where);
}
#if CBDATA_DEBUG
-struct CBDataCallDumper : public unary_function<CBDataCall, void>
-{
- CBDataCallDumper (StoreEntry *anEntry):where(anEntry){}
+struct CBDataCallDumper : public unary_function<CBDataCall, void> {
+ 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");
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
/**
\ingroup CBDATAAPI
- *
+ *
* Initializes the cbdatatype. Must be called prior to the first use of cbdataAlloc() for the type.
*
\par
/**
\ingroup CBDATAAPI
- *
+ *
* Initializes the cbdatatype. Must be called prior to the first use of cbdataAlloc() for the type.
*
\par
*/
class generic_cbdata
{
- public:
+public:
generic_cbdata(void * data) : data(data) {}
- template<typename wrapped_type>void unwrap(wrapped_type **output)
- {
- *output = static_cast<wrapped_type *>(data);
- delete this;
- }
+ template<typename wrapped_type>void unwrap(wrapped_type **output) {
+ *output = static_cast<wrapped_type *>(data);
+ delete this;
+ }
/**
* The wrapped data - only public to allow the mild abuse of this facility
\todo CODE: make this a private field.
*/
void *data; /* the wrapped data */
- private:
+private:
CBDATA_CLASS2(generic_cbdata);
};
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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;
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;
{
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);
}
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);
*(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) {
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;
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) {
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) {
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR 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.
\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.
*
* 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
* 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.
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);
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
*
\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.
/**
\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
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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);
}
clientdbRegisterWithCacheManager(void)
{
CacheManager::GetInstance()->
- registerAction("client_list", "Cache Client List", clientdbDump, 0, 1);
+ registerAction("client_list", "Cache Client List", clientdbDump, 0, 1);
}
void
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);
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 *
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,
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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);
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);
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
*/
// 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();
}
}
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;
}
/* 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;
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);
}
}
if (r->method == METHOD_OTHER) {
- // invalidate all cache entries
- purgeAllCached();
+ // invalidate all cache entries
+ purgeAllCached();
}
if (http->onlyIfCached()) {
triggerInitialStoreRead();
return;
} else {
- assert(http->out.offset == 0);
+ assert(http->out.offset == 0);
createStoreEntry(r->method, r->flags);
triggerInitialStoreRead();
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);
}
#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)) {
#endif
}
-void
+void
clientReplyContext::purgeAllCached()
{
- const char *url = urlCanonical(http->request);
+ const char *url = urlCanonical(http->request);
purgeEntriesByUrl(http->request, url);
}
/*
* 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) {
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;
}
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;
}
}
* 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.
*/
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();
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();
||
(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;
- }
+ }
}
}
}
/* 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);
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;
}
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,
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="<<Config.zph_tos_local);
comm_set_tos(http->getConn()->fd,Config.zph_tos_local);
}
/* 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;
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
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;
headers_sz = reply->hdr_sz;
if (!Config.accessList.reply) {
- processReplyAccessResult(1);
- return;
+ processReplyAccessResult(1);
+ return;
}
ACLChecklist *replyChecklist;
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) {
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);
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 " <<
}
#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="<<http->request->hier.code<<", TOS="<<tos);
- }
- else if (Config.onoff.zph_preserve_miss_tos && Config.zph_preserve_miss_tos_mask) {
+ } else if (Config.onoff.zph_preserve_miss_tos && Config.zph_preserve_miss_tos_mask) {
tos = fd_table[fd].upstreamTOS & Config.zph_preserve_miss_tos_mask;
debugs(33, 2, "ZPH: Preserving TOS on miss, TOS="<<tos);
}
comm_set_tos(fd,tos);
}
-#endif
+#endif
/* We've got the final data to start pushing... */
flags.storelogiccomplete = 1;
reqofs << " bytes (" << result.length <<
" new bytes)");
debugs(88, 5, "clientReplyContext::sendMoreData:"
- " FD " << fd <<
- " '" << entry->url() << "'" <<
- " out.offset=" << http->out.offset);
+ " FD " << fd <<
+ " '" << entry->url() << "'" <<
+ " out.offset=" << http->out.offset);
/* update size of the request */
reqsize = reqofs;
/* 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;
/* 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);
/* 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);
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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 */
/*
* $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/
* ----------------------------------------------------------
*
/*
* 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.
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);
* 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
*/
// 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);
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);
#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);
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
* 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
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.
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;
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.
{
#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;
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 = "<null>";
if (http->getConn() != NULL && http->getConn()->auth_user_request != NULL)
clientStreamNode *node = (clientStreamNode *)http->client_stream.tail->prev->data;
clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(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,
}
if (request->method == METHOD_OTHER) {
- no_cache++;
+ no_cache++;
}
#endif
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.
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
* 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());
+ }
+ }
}
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);
// 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;
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
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
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
#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
assert(!virginHeadSource);
assert(!adaptedBodySource);
virginHeadSource = initiateAdaptation(service->makeXactLauncher(
- this, request, NULL));
+ this, request, NULL));
return virginHeadSource != NULL;
}
{
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());
}
void
-ClientHttpRequest::endRequestSatisfaction() {
+ClientHttpRequest::endRequestSatisfaction()
+{
debugs(85,4, HERE << this << " ends request satisfaction");
assert(request_satisfaction_mode);
stopConsumingFrom(adaptedBodySource);
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);
clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(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);
* $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/
* ----------------------------------------------------------
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
ConnStateData *
ClientHttpRequest::getConn()
{
- if(!cbdataReferenceValid(conn_))
- return NULL;
+ if (!cbdataReferenceValid(conn_))
+ return NULL;
return conn_;
}
ConnStateData * const
ClientHttpRequest::getConn() const
{
- if(!cbdataReferenceValid(conn_))
- return NULL;
+ if (!cbdataReferenceValid(conn_))
+ return NULL;
return conn_;
}
{
assert (conn_ == NULL || aConn == NULL);
- if(conn_)
- cbdataReferenceDone(conn_);
+ if (conn_)
+ cbdataReferenceDone(conn_);
conn_ = cbdataReference(aConn);
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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
{
char *uri;
char *log_uri;
- struct
- {
+ struct {
int64_t offset;
int64_t size;
size_t headers_sz;
struct timeval start_time;
AccessLogEntry al;
- struct
- {
+ struct {
unsigned int accel:1;
unsigned int intercepted:1;
unsigned int spoof_client_ip:1;
unsigned int purging:1;
} flags;
- struct
- {
+ struct {
http_status status;
char *location;
} redirect;
#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:
static const char* epolltype_atoi(int x)
{
- switch(x) {
+ switch (x) {
case EPOLL_CTL_ADD:
return "EPOLL_CTL_ADD";
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;
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;
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());
}
}
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
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??
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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;
{
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);
}
}
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);
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* 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
* 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.:
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);
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++;
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())
commCallCloseHandlers(fd);
} else if (F->timeoutHandler != NULL) {
debugs(5, 0, "comm_poll: Calling Timeout Handler");
- ScheduleCallHere(F->timeoutHandler);
+ ScheduleCallHere(F->timeoutHandler);
}
F->closeHandler = NULL;
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
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* 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
* 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.:
(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++;
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
* 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
commCallCloseHandlers(fd);
} else if (F->timeoutHandler != NULL) {
debugs(5, 0, "examine_select: Calling Timeout Handler");
- ScheduleCallHere(F->timeoutHandler);
+ ScheduleCallHere(F->timeoutHandler);
}
F->closeHandler = NULL;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* 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
* 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.:
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
* 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
commCallCloseHandlers(fd);
} else if (F->timeoutHandler != NULL) {
debugs(5, 0, "examine_select: Calling Timeout Handler");
- ScheduleCallHere(F->timeoutHandler);
+ ScheduleCallHere(F->timeoutHandler);
}
F->closeHandler = NULL;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
{
#else
_db_print(va_alist)
-va_dcl
-{
+va_dcl {
const char *format = NULL;
#endif
#ifdef _SQUID_MSWIN_
/* Multiple WIN32 threads may call this simultaneously */
- if (!dbg_mutex)
- {
+ if (!dbg_mutex) {
HMODULE krnl_lib = GetModuleHandle("Kernel32");
PFInitializeCriticalSectionAndSpinCount InitializeCriticalSectionAndSpinCount = NULL;
vfprintf(debug_log, format, args);
//*AYJ:*/ if (!Config.onoff.buffered_logs)
- fflush(debug_log);
+ fflush(debug_log);
}
static void
l = atoi(arg);
assert(s >= -1);
- if(s >= MAX_DEBUG_SECTIONS)
+ if (s >= MAX_DEBUG_SECTIONS)
s = MAX_DEBUG_SECTIONS-1;
if (l < 0)
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
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;
}
#ifdef _SQUID_MSWIN_
remove
- (to);
+ (to);
#endif
#ifdef _SQUID_MSWIN_
remove
- (to);
+ (to);
#endif
*
* 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)
* {
* // exit, clean after yourself
* ctx_exit(ctx);
* }
- *
+ *
* void
* bottom_level_boo(int status, void *data)
* {
* 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
// 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();
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
DelayPools::RegisterWithCacheManager(void)
{
CacheManager::GetInstance()->
- registerAction("delay", "Delay Pool Levels", Stats, 0, 1);
+ registerAction("delay", "Delay Pool Levels", Stats, 0, 1);
}
void
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 */
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 */
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 */
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 */
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* 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)
/* 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)
/*
* 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
#if defined (_SQUID_OS2_) || defined (_SQUID_WIN32_)
remove
- (to);
+ (to);
#endif
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
{
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;
};
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
dnsRegisterWithCacheManager(void)
{
CacheManager::GetInstance->
- registerAction("dns", "Dnsserver Statistics", dnsStats, 0, 1);
+ registerAction("dns", "Dnsserver Statistics", dnsStats, 0, 1);
}
void
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
typedef struct _nsvc nsvc;
-struct _idns_query
-{
+struct _idns_query {
hash_link hash;
rfc1035_query query;
char buf[RESOLV_BUFSZ];
} initial_AAAA;
};
-struct _nsvc
-{
+struct _nsvc {
int ns;
int fd;
unsigned short msglen;
bool busy;
};
-struct _ns
-{
+struct _ns {
IPAddress S;
int nqueries;
int nreplies;
nsvc *vc;
};
-struct _sp
-{
+struct _sp {
char domain[NS_MAXDNAME];
int queries;
};
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);
}
}
if (npc == 0 && (t = getMyHostname())) {
- t = strchr(t, '.');
- if (t)
- idnsAddPathComponent(t+1);
+ t = strchr(t, '.');
+ if (t)
+ idnsAddPathComponent(t+1);
}
fclose(fp);
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);
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);
}
}
debugs(78, 1, "Adding DHCP nameserver " << token << " from Registry");
token = strtok(NULL, ",");
}
- xfree(t);
+ xfree(t);
}
Result =
idnsAddNameserver(token);
token = strtok(NULL, ", ");
}
- xfree(t);
+ xfree(t);
}
RegCloseKey(hndKey);
idnsAddNameserver(token);
token = strtok(NULL, ", ");
}
- xfree(t);
+ xfree(t);
}
Result =
idnsAddNameserver(token);
token = strtok(NULL, ", ");
}
- xfree(t);
+ xfree(t);
}
RegCloseKey(hndKey2);
idnsAddNameserver(token);
token = strtok(NULL, ", ");
}
- xfree(t);
+ xfree(t);
}
RegCloseKey(hndKey);
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);
}
{
int i;
- for (i = 0; i < nns; i++)
- {
+ for (i = 0; i < nns; i++) {
if (nameservers[i].S != from)
continue;
unsigned short id = squid_random() & 0xFFFF;
unsigned short first_id = id;
- while(idnsFindQuery(id)) {
+ while (idnsFindQuery(id)) {
id++;
if (id == first_id) {
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;
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);
}
#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.
* 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;
}
#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;
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);
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);
/* 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)) {
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);
idnsRegisterWithCacheManager(void)
{
CacheManager::GetInstance()->
- registerAction("idns", "Internal DNS Statistics", idnsStats, 0, 1);
+ registerAction("idns", "Internal DNS Statistics", idnsStats, 0, 1);
}
void
}
#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);
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;
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;
/* 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);
}
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;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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)
/* 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
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;
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)
}
}
- 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
}
}
- 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);
"\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
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. */
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');
}
void
-Ecap::Config::finalize() {
- Adaptation::Config::finalize();
- libecap::shared_ptr<Ecap::Host> host(new Ecap::Host);
- libecap::RegisterHost(host);
+Ecap::Config::finalize()
+{
+ Adaptation::Config::finalize();
+ libecap::shared_ptr<Ecap::Host> host(new Ecap::Host);
+ libecap::RegisterHost(host);
}
Adaptation::ServicePointer
#include "adaptation/Config.h"
-namespace Ecap {
+namespace Ecap
+{
class Config: public Adaptation::Config
{
Config();
~Config();
- virtual void finalize();
+ virtual void finalize();
private:
Config(const Config &); // not implemented
void
Ecap::Host::noteService(const libecap::weak_ptr<libecap::adapter::Service> &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<libecap::adapter::Service> shared(weak);
+ libecap::shared_ptr<libecap::adapter::Service> 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<ServiceRep*>(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 *
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();
}
#include <libecap/host/host.h>
-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<libecap::adapter::Service> &s);
+ // Service management
+ virtual void noteService(const libecap::weak_ptr<libecap::adapter::Service> &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;
/* HeaderRep */
Ecap::HeaderRep::HeaderRep(HttpMsg &aMessage): theHeader(aMessage.header),
- theMessage(aMessage)
+ theMessage(aMessage)
{
}
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
{
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());
}
{
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);
}
Ecap::FirstLineRep::version() const
{
return libecap::Version(theMessage.http_ver.major,
- theMessage.http_ver.minor);
+ theMessage.http_ver.minor);
}
void
{
// 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
/* RequestHeaderRep */
Ecap::RequestLineRep::RequestLineRep(HttpRequest &aMessage):
- FirstLineRep(aMessage), theMessage(aMessage)
+ FirstLineRep(aMessage), theMessage(aMessage)
{
}
Ecap::RequestLineRep::uri() const
{
return Area::FromTempBuffer(theMessage.urlpath.buf(),
- theMessage.urlpath.size());
+ theMessage.urlpath.size());
}
void
} else {
const std::string &image = aMethod.image();
theMessage.method = HttpRequestMethod(image.data(),
- image.data() + image.size());
+ image.data() + image.size());
}
}
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());
}
}
/* ReplyHeaderRep */
Ecap::StatusLineRep::StatusLineRep(HttpReply &aMessage):
- FirstLineRep(aMessage), theMessage(aMessage)
+ FirstLineRep(aMessage), theMessage(aMessage)
{
}
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
/* 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<HttpRequest*>(theMessage.header))
theFirstLineRep = new RequestLineRep(*req);
else
- if (HttpReply *rep = dynamic_cast<HttpReply*>(theMessage.header))
- theFirstLineRep = new StatusLineRep(*rep);
- else
- Must(false); // unknown message header type
+ if (HttpReply *rep = dynamic_cast<HttpReply*>(theMessage.header))
+ theFirstLineRep = new StatusLineRep(*rep);
+ else
+ Must(false); // unknown message header type
theHeaderRep = new HeaderRep(*theMessage.header);
#include <libecap/common/header.h>
#include <libecap/common/body.h>
-namespace Ecap {
+namespace Ecap
+{
class XactionRep;
#include "eCAP/XactionRep.h"
Ecap::ServiceRep::ServiceRep(const Adaptation::ServiceConfig &cfg):
- /*AsyncJob("Ecap::ServiceRep"),*/ Adaptation::Service(cfg)
+ /*AsyncJob("Ecap::ServiceRep"),*/ Adaptation::Service(cfg)
{
}
{
}
-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
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;
}
{
assert(false); // move generic stuff from ICAP to Adaptation
// add theService->status()?
- return NULL;
+ return NULL;
}
#include <libecap/common/forward.h>
#include <libecap/common/memory.h>
-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
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);
Ecap::XactionRep::doneAll() const
{
return proxyingVb >= opComplete && proxyingAb >= opComplete &&
- Adaptation::Initiate::doneAll();
+ Adaptation::Initiate::doneAll();
}
// stops receiving virgin and enables auto-consumption
// called from adapter handler so does not inform adapter
}
-void
+void
Ecap::XactionRep::useVirgin()
{
debugs(93,3, HERE << status());
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<libecap::Message> &m)
{
debugs(93,3, HERE << status());
// nsize means no size limit: all content starting from offset
const size_t size = s == libecap::nsize ?
- haveSize - offset : static_cast<size_t>(s);
+ haveSize - offset : static_cast<size_t>(s);
// XXX: optimize by making theBody a shared_ptr (see Area::FromTemp*() src)
return libecap::Area::FromTempBuffer(p->buf().content() + offset,
- min(static_cast<size_t>(haveSize - offset), size));
+ min(static_cast<size_t>(haveSize - offset), size));
}
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?
return !done();
}
-void
+void
Ecap::XactionRep::noteMoreBodySpaceAvailable(RefCount<BodyPipe> bp)
{
Must(proxyingAb == opOn);
moveAbContent();
}
-void
+void
Ecap::XactionRep::noteBodyConsumerAborted(RefCount<BodyPipe> bp)
{
Must(proxyingAb == opOn);
#include <libecap/host/xaction.h>
#include <libecap/adapter/xaction.h>
-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);
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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,
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
ERCB *callback;
void *callback_data;
- struct
- {
+ struct {
unsigned int flag_cbdata:1;
} flags;
- struct
- {
+ struct {
wordlist *server_msg;
char *request;
char *reply;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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
{
};
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);
}
bool
-EventDialer::canDial(AsyncCall &call) {
+EventDialer::canDial(AsyncCall &call)
+{
// TODO: add Parent::canDial() that always returns true
//if (!Parent::canDial())
// return false;
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)
{
}
eventInit(void)
{
CacheManager::GetInstance()->
- registerAction("events", "Event Queue", eventDump, 0, 1);
+ registerAction("events", "Event Queue", eventDump, 0, 1);
}
static void
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
/* 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
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
external_acl *next;
void add
- (ExternalACLEntry *);
+ (ExternalACLEntry *);
void trimCache();
bool require_auth;
- enum
- {
+ enum {
QUOTE_METHOD_SHELL = 1,
QUOTE_METHOD_URL
} quote;
IPAddress local_addr;
};
-struct _external_acl_format
-{
+struct _external_acl_format {
enum format_type {
EXT_ACL_UNKNOWN,
EXT_ACL_LOGIN,
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;
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;
} 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) {
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);
void
external_acl::add
- (ExternalACLEntry *anEntry)
+(ExternalACLEntry *anEntry)
{
trimCache();
assert (anEntry->def == NULL);
* external acl type
*/
-struct _external_acl_data
-{
+struct _external_acl_data {
external_acl *def;
wordlist *arguments;
};
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();
}
typedef struct _externalAclState externalAclState;
-struct _externalAclState
-{
+struct _externalAclState {
EAH *callback;
void *callback_data;
char *key;
*
* 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)
*/
externalAclRegisterWithCacheManager(void)
{
CacheManager::GetInstance()->
- registerAction("external_acl",
- "External ACL stats",
- externalAclStats, 0, 1);
+ registerAction("external_acl",
+ "External ACL stats",
+ externalAclStats, 0, 1);
}
void
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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);
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);
}
}
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;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
/* 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?
}
/*
* 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.
}
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
FwdState::handleUnregisteredServerEnd()
{
debugs(17, 2, "handleUnregisteredServerEnd: self=" << self <<
- " err=" << err << ' ' << entry->url());
+ " err=" << err << ' ' << entry->url());
assert(server_fd < 0);
retryOrBail();
}
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
anErr->xerrno = ETIMEDOUT;
fail(anErr);
/*
- * This marks the peer DOWN ...
+ * This marks the peer DOWN ...
*/
if (servers)
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;
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) {
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;
}
}
* 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 "<<server_fd<<" "<<xstrerror());
- }
- }
- else
- {
- debugs(33, 1, "ZPH: error in setsockopt(IP_RECVTOS) on FD "<<server_fd<<" "<<xstrerror());
+ 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 "<<server_fd<<" "<<xstrerror());
+ }
+ } else {
+ debugs(33, 1, "ZPH: error in setsockopt(IP_RECVTOS) on FD "<<server_fd<<" "<<xstrerror());
}
- }
+ }
#endif
if (servers && (p = servers->_peer)) {
FwdState::RegisterWithCacheManager(void)
{
CacheManager::GetInstance()->
- registerAction("forward", "Request Forwarding Statistics", fwdStats, 0, 1);
+ registerAction("forward", "Request Forwarding Statistics", fwdStats, 0, 1);
}
void
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
IPAddress addr;
- for (l = head; l; l = l->next)
- {
+ for (l = head; l; l = l->next) {
if (ch->matchAclListFast(l->aclList))
return l->addr;
}
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);
http_status last_status;
#endif
- struct
- {
+ struct {
unsigned int dont_retry:1;
unsigned int ftp_pasv_failed:1;
unsigned int forward_completed:1;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* 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;
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;
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);
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 << "'");
fqdncacheRegisterWithCacheManager(void)
{
CacheManager::GetInstance()->
- registerAction("fqdncache", "FQDN Cache Stats and Contents",
- fqdnStats, 0, 1);
+ registerAction("fqdncache", "FQDN Cache Stats and Contents",
+ fqdnStats, 0, 1);
}
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;
FqdncacheStats.misses++;
- if (flags & FQDN_LOOKUP_IF_MISS)
- {
+ if (flags & FQDN_LOOKUP_IF_MISS) {
fqdncache_nbgethostbyaddr(addr, dummy_handler, NULL);
}
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";
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
~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 */
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
void stat(StoreEntry * sentry);
int stripes;
- struct
- {
+ struct {
int alloc;
int realloc;
int collisions;
int open_mem_hits;
int open_mem_misses;
- struct
- {
+ struct {
int ops;
int success;
int fail;
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 *.
size_t requestoffset; /* in blocks */
int64_t reqdiskoffset; /* in blocks */
- struct
- {
+ struct {
unsigned int reading:1;
unsigned int writing:1;
} flags;
/*
* $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
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
typedef struct _RebuildState RebuildState;
-struct _RebuildState
-{
+struct _RebuildState {
CossSwapDir *sd;
int n_read;
FILE *log;
int speed;
- struct
- {
+ struct {
unsigned int clean:1;
} flags;
storeCossRemove(rb->sd, e);
rb->counts.objcount--;
rb->counts.cancelcount++;
- } continue;
+ }
+ continue;
} else {
x = log(static_cast<double>(++rb->counts.bad_log_op)) / log(10.0);
/* 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()
parseOptions(0);
- if (NULL == io)
+ if (NULL == io)
changeIO(DiskIOModule::FindDefault());
/* Enforce maxobjsize being set to something */
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
} 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++;
* 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);
}
}
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' : '.'));
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
\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.
*/
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
/*
* storeUfsDirReconfigure
*
- * This routine is called when the given swapdir needs reconfiguring
+ * This routine is called when the given swapdir needs reconfiguring
*/
void
}
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);
}
/* 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;
fchmod(state->fd, sb.st_mode);
#endif
-
+
cleanLog = state;
return 0;
* 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
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));
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
void
UFSStoreState::writeCompleted(int errflag, size_t len, RefCount<WriteRequest> 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
* 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();
}
}
* drainWriteQueue().
*/
if (flags.write_draining)
- return;
+ return;
if (!theFile->canWrite())
return;
" 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;
}
/*
* $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
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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;
}
-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);
};
int bytes = sizeof(StoreSwapLogData);
assert(log);
-
- if (fread(&swapData, bytes, 1, log) != 1){
+
+ if (fread(&swapData, bytes, 1, log) != 1) {
return false;
}
return true;
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;
FILE *fp = sd->openTmpSwapLog(&clean, &zeroLengthLog);
if (fp && !zeroLengthLog)
- LogParser = UFSSwapLogParser::GetUFSSwapLogParser(fp);
+ LogParser = UFSSwapLogParser::GetUFSSwapLogParser(fp);
if (LogParser == NULL ) {
fromLog = false;
fclose(fp);
} else {
- fromLog = true;
- flags.clean = (unsigned int) clean;
+ fromLog = true;
+ flags.clean = (unsigned int) clean;
}
if (!clean)
sd->closeTmpSwapLog();
if (LogParser)
- delete LogParser;
+ delete LogParser;
}
void
rebuildFromDirectory();
}
-struct InitStoreEntry : public unary_function<StoreMeta, void>
-{
- InitStoreEntry(StoreEntry *anEntry, cache_key *aKey):what(anEntry),index(aKey){}
+struct InitStoreEntry : public unary_function<StoreMeta, void> {
+ 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:
break;
case STORE_META_STD:
- struct old_metahdr{
+ struct old_metahdr {
time_t timestamp;
time_t lastref;
time_t expires;
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;
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++;
* 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.
*/
}
counts.objcount++;
- // tmpe.dump(5);
+ // tmpe.dump(5);
currentEntry(sd->addDiskRestore(key,
filn,
tmpe.swap_file_sz,
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;
}
* 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.
*/
currentEntry()->release();
counts.objcount--;
counts.cancelcount++;
- } continue;
+ }
+ continue;
} else {
x = ::log(static_cast<double>(++counts.bad_log_op)) / ::log(10.0);
} 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
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);
}
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
/** \todo These should be in the IO strategy */
- struct
- {
+ struct {
/**
* DPW 2006-05-24
* the write_draining flag is used to avoid recursion inside
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;
+ }
}
};
/** \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);
RefCount<UFSSwapDir> 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;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
#define MAX_CSO_RESULT 1024
/// \ingroup ServerProtocolGopherInternal
-typedef struct gopher_ds
-{
+typedef struct gopher_ds {
StoreEntry *entry;
enum {
NORMAL,
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, "<IMG border=\"0\" SRC=\"%s\"> <A HREF=\"telnet://%s@%s%s%s/\">%s</A>\n",
- icon_url, escaped_selector, rfc1738_escape_part(host),
- *port ? ":" : "", port, html_quote(name));
- else
- snprintf(tmpbuf, TEMP_BUF_SIZE, "<IMG border=\"0\" SRC=\"%s\"> <A HREF=\"telnet://%s%s%s/\">%s</A>\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, "<IMG border=\"0\" SRC=\"%s\"> <A HREF=\"http://%s/%s\">%s</A>\n",
- icon_url, host, rfc1738_escape_unescaped(selector + 5), html_quote(name));
- } else {
- /* Standard link */
- snprintf(tmpbuf, TEMP_BUF_SIZE, "<IMG border=\"0\" SRC=\"%s\"> <A HREF=\"gopher://%s/%c%s\">%s</A>\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, "<IMG border=\"0\" SRC=\"%s\"> <A HREF=\"telnet://%s@%s%s%s/\">%s</A>\n",
+ icon_url, escaped_selector, rfc1738_escape_part(host),
+ *port ? ":" : "", port, html_quote(name));
+ else
+ snprintf(tmpbuf, TEMP_BUF_SIZE, "<IMG border=\"0\" SRC=\"%s\"> <A HREF=\"telnet://%s%s%s/\">%s</A>\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, "<IMG border=\"0\" SRC=\"%s\"> <A HREF=\"http://%s/%s\">%s</A>\n",
+ icon_url, host, rfc1738_escape_unescaped(selector + 5), html_quote(name));
+ } else {
+ /* Standard link */
+ snprintf(tmpbuf, TEMP_BUF_SIZE, "<IMG border=\"0\" SRC=\"%s\"> <A HREF=\"gopher://%s/%c%s\">%s</A>\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, "</PRE><HR noshade size=\"1px\"><H2>Record# %d<br><i>%s</i></H2>\n<PRE>", 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, "</PRE><HR noshade size=\"1px\"><H2>Record# %d<br><i>%s</i></H2>\n<PRE>", 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, "</PRE><HR noshade size=\"1px\"><H2>%s</H2>\n<PRE>", 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, "</PRE><HR noshade size=\"1px\"><H2>%s</H2>\n<PRE>", html_quote(result));
+ outbuf.append(tmpbuf);
+ break;
+ }
- }
}
+ }
- } /* HTML_CSO_RESULT */
+ } /* HTML_CSO_RESULT */
default:
break; /* do nothing */
if (do_next_read)
comm_read(fd, buf, read_sz, gopherReadReply, gopherState);
-
+
return;
}
/* 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)
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
/*
* DPW 2007-05-08
- *
+ *
* helperStatefulOpenServers: create the stateful child helper processes
*/
void
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.");
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.
StatefulServerEnqueue(lastserver, r);
}
} else {
- helper_stateful_server *srv;
+ helper_stateful_server *srv;
if ((srv = StatefulGetFirstAvailable(hlp))) {
helperStatefulDispatch(srv, r);
} else
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 *
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,
srv->wfd = -1;
srv->flags.closing=1;
comm_close(wfd);
- return;
+ return;
} else
helperKickQueue(hlp);
}
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 */
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)
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;
}
static void
helperStatefulRequestFree(helper_stateful_request * r)
{
- if(r) {
+ if (r) {
cbdataReferenceDone(r->data);
xfree(r->buf);
delete r;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
typedef stateful_helper_callback_t HLPSCB(void *, void *lastserver, char *buf);
-struct _helper
-{
+struct _helper {
wordlist *cmdline;
dlink_list servers;
dlink_list queue;
time_t last_queue_warn;
time_t last_restart;
- struct
- {
+ struct {
int requests;
int replies;
int queue_size;
} stats;
};
-struct _helper_stateful
-{
+struct _helper_stateful {
wordlist *cmdline;
dlink_list servers;
dlink_list queue;
time_t last_queue_warn;
time_t last_restart;
- struct
- {
+ struct {
int requests;
int replies;
int queue_size;
} stats;
};
-struct _helper_server
-{
+struct _helper_server {
int index;
int pid;
IPAddress addr;
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;
class helper_stateful_request;
-struct _helper_stateful_server
-{
+struct _helper_stateful_server {
int index;
int pid;
IPAddress addr;
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;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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
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;
/* RR == 0 --> REQUEST */
/* RR == 1 --> RESPONSE */
-struct _htcpAuthHeader
-{
+struct _htcpAuthHeader {
u_int16_t length;
time_t sig_time;
time_t sig_expire;
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;
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
auth.length = htons(2);
copy_sz += 2;
if (buflen < copy_sz)
- return -1;
+ return -1;
xmemcpy(buf, &auth, copy_sz);
return copy_sz;
}
htcpBuildClrOpData(char *buf, size_t buflen, htcpStuff * stuff)
{
u_short reason;
-
+
switch (stuff->rr) {
case RR_REQUEST:
debugs(31, 3, "htcpBuildClrOpData: RR_REQUEST");
default:
fatal_dump("htcpBuildClrOpData: bad RR value");
}
-
+
return 0;
}
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.
*/
s->request = HttpRequest::CreateFromUrlAndMethod(s->uri, method == METHOD_NONE ? HttpRequestMethod(METHOD_GET) : method);
if (s->request)
- HTTPMSGLOCK(s->request);
+ HTTPMSGLOCK(s->request);
return s;
}
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.
*/
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;
safe_free(stuff.D.entity_hdrs);
safe_free(stuff.D.cache_hdrs);
- if (!pktlen)
- {
+ if (!pktlen) {
debugs(31, 3, "htcpTstReply: htcpBuildPacket() failed");
return;
}
pktlen = htcpBuildPacket(pkt, sizeof(pkt), &stuff);
- if (pktlen == 0)
- {
+ if (pktlen == 0) {
debugs(31, 3, "htcpClrReply: htcpBuildPacket() failed");
return;
}
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;
}
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 '" <<
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;
}
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);
/* buf should be a SPECIFIER */
htcpSpecifier *s;
- if (sz == 0)
- {
+ if (sz == 0) {
debugs(31, 3, "htcpHandleTst: nothing to do");
return;
}
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;
/* 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;
* analog to clientPurgeRequest in client_side.c
*/
- switch (htcpClrStore(s))
- {
+ switch (htcpClrStore(s)) {
case 1:
htcpClrReply(hdr, 1, from); /* hit */
htcpForwardClr(char *buf, int sz)
{
peer *p;
-
+
for (p = Config.peers; p; p = p->next) {
if (!p->options.htcp) {
continue;
if (!p->options.htcp_forward_clr) {
continue;
}
-
+
htcpSend(buf, sz, p->in_addr);
}
}
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;
}
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;
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;
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;
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;
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) {
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;
}
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);
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
u_int32_t msg_id;
double version;
- struct cto_t
- {
+ struct cto_t {
/* cache-to-origin */
double rtt;
int samp;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
ICMP::Close()
{
#if USE_ICMP
- if(icmp_sock > 0)
+ if (icmp_sock > 0)
close(icmp_sock);
icmp_sock = -1;
icmp_ident = 0;
unsigned short oddbyte;
unsigned short answer;
- if(!ptr) return 65535; // bad input.
+ if (!ptr) return 65535; // bad input.
sum = 0;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
/* ICPState */
ICPState::ICPState(icp_common_t &aHeader, HttpRequest *aRequest):
- header(aHeader),
- request(HTTPMSGLOCK(aRequest)),
+ header(aHeader),
+ request(HTTPMSGLOCK(aRequest)),
fd(-1),
url(NULL)
{}
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);
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;
commSetSelect(fd, COMM_SELECT_WRITE, icpUdpSendQueue, NULL, 0);
statCounter.icp.replies_queued++;
- } else
- {
+ } else {
/* don't queue it */
statCounter.icp.replies_dropped++;
}
{
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);
}
}
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;
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);
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;
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;
}
* 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 */
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);
}
}
}
/**
- * icpConnectionShutdown only closes the 'in' socket if it is
+ * icpConnectionShutdown only closes the 'in' socket if it is
* different than the 'out' socket.
*/
void
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
public:
ICP3State(icp_common_t &aHeader, HttpRequest *aRequest) :
- ICPState(aHeader, aRequest)
- {}
+ ICPState(aHeader, aRequest) {}
~ICP3State();
void created (StoreEntry *newEntry);
if (!icp_request)
return;
- if (!icpAccessAllowed(from, icp_request))
- {
+ if (!icpAccessAllowed(from, icp_request)) {
icpDenyAccess (from, url, header.reqnum, fd);
delete icp_request;
return;
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;
}
* 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);
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
#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 */
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;
}
COMM_NONBLOCKING,
"ident");
- if (fd == COMM_ERROR)
- {
+ if (fd == COMM_ERROR) {
/* Failed to get a local socket */
callback(NULL, data);
return;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General 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 "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
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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.
*/
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
#endif
#include <process.h>
-struct ipc_params
-{
+struct ipc_params {
int type;
int crfd;
int cwfd;
char **args;
};
-struct thread_params
-{
+struct thread_params {
int type;
int rfd;
int send_fd;
params.cwfd = cwfd;
params.PS = *aiPS;
-
+
params.local_addr = local_addr;
params.prog = prog;
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;
IPAddress PS = params->PS;
IPAddress local_addr = params->local_addr;
-
+
buf1 = (char *)xcalloc(1, 8192);
strcpy(buf1, params->prog);
prog = strtok(buf1, w_space);
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 (;;) {
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* 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;
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;
static void
ipcacheRelease(ipcache_entry * i, bool dofree)
{
- if(!i) {
+ if (!i) {
debugs(14, 0, "ipcacheRelease: Releasing entry with i=<NULL>");
return;
}
- if(!i || !i->hash.key) {
+ if (!i || !i->hash.key) {
debugs(14, 0, "ipcacheRelease: Releasing entry without hash link!");
return;
}
hash_remove_link(ip_table, (hash_link *) i);
dlinkDelete(&i->lru, &lru_list);
- if(dofree)
+ if (dofree)
ipcacheFreeEntry(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);
}
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);
#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++;
#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) );
}
#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;
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));
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.");
}
}
/* 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 */
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
{
* 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
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);
}
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;
/** \par
* Negative-cached entries have no IPs listed. */
- if(i->flags.negcached) {
+ if (i->flags.negcached) {
storeAppendPrintf(sentry, "\n");
return;
}
* Cached entries have IPs listed with a BNF of: <IP> '-' ('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 ");
#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++;
}
}
// 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++;
}
#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] );
}
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);
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);
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);
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);
}
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);
}
/* 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)) {
return NULL;
}
delete tmp;
- }
- else if (!(ip = name))
+ } else if (!(ip = name))
return NULL;
debugs(14, 4, "ipcacheCheckNumeric: HIT_BYPASS for '" << name << "' == " << ip );
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;
}
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;
}
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);
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;
}
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;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
#define LOG_AUTHPRIV LOG_AUTH
#endif
-struct syslog_symbol_t
-{
+struct syslog_symbol_t {
const char* name;
int value;
};
{
#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))
path += 7;
char* delim = strchr(path, '.');
- if (!delim)
- delim = strchr(path, '|');
+ if (!delim)
+ delim = strchr(path, '|');
if (delim != NULL)
*delim = '\0';
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
{
public:
- int checkEvents(int timeout)
- {
+ int checkEvents(int timeout) {
Store::Root().callback();
return EVENT_IDLE;
};
virtual int checkEvents(int timeout);
private:
- static void StopEventLoop(void * data)
- {
+ static void StopEventLoop(void * data) {
static_cast<SignalEngine *>(data)->loop.stop();
}
} else if (do_shutdown) {
doShutdown(do_shutdown > 0 ? (int) Config.shutdownLifetime : 0);
do_shutdown = 0;
- }
+ }
PROF_stop(SignalEngine_checkEvents);
return EVENT_IDLE;
#endif
{
- switch (c)
- {
+ switch (c) {
case 'C':
/** \par C
refererCloseLog();
eventAdd("mainReconfigureFinish", &mainReconfigureFinish, NULL, 0, 1,
- false);
+ false);
}
static void
-mainReconfigureFinish(void *) {
+mainReconfigureFinish(void *)
+{
debugs(1, 3, "finishing reconfiguring");
errorClean();
debugs(1, 1, "Windows sockets initialized");
if (WIN32_OS_version > _WIN_OS_WINNT) {
- WIN32_IpAddrChangeMonitorInit();
+ WIN32_IpAddrChangeMonitorInit();
}
#endif
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
{
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
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;
}
parse_err = parseConfigFile(ConfigFile);
Mem::Report();
-
+
if (opt_parse_cfg_only)
return parse_err;
#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) {
/* 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)) {
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");
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;
* 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);
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
/* 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;
}
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();
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)
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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;
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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;
\param data unused.
\todo Make the reset timing a selectable parameter in squid.conf
*/
-static void
+static void
peerClearRRLoop(void *data)
{
peerClearRR();
/*
* 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 *
{
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);
}
}
request->hier.cd_lookup = lookup;
- debugs(15, 4, "peerNoteDigestLookup: peer " <<
- (p ? p->host : "<none>") << ", lookup: " <<
- lookup_t_str[lookup] );
+ debugs(15, 4, "peerNoteDigestLookup: peer " <<
+ (p ? p->host : "<none>") << ", lookup: " <<
+ lookup_t_str[lookup] );
#endif
}
{
peer *np;
- for (np = non_peers; np; np = np->next)
- {
+ for (np = non_peers; np; np = np->next) {
if (np->in_addr != from)
continue;
break;
}
- if (np == NULL)
- {
+ if (np == NULL) {
np = (peer *)xcalloc(1, sizeof(peer));
np->in_addr = from;
np->icp.port = from.GetPort();
}
/* ignoreMulticastReply
- *
+ *
* * We want to ignore replies from multicast peers if the
* * cache_host_domain rules would normally prevent the peer
* * from being used
/* 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
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;
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) {
} 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) {
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);
}
}
/*
* 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 << ")");
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;
}
}
/*
-* peerProbeConnect will be called on dead peers by neighborUp
+* peerProbeConnect will be called on dead peers by neighborUp
*/
static int
peerProbeConnect(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)
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");
}
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;
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;
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
STATE_BODY
} netdb_conn_state_t;
-typedef struct
-{
+typedef struct {
peer *p;
StoreEntry *e;
store_client *sc;
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);
}
/* 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;
netdbSaveState(void *foo)
{
if (strcmp(Config.netdbFilename, "none") == 0)
- return;
+ return;
Logfile *lf;
netdbEntry *n;
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);
}
netdbReloadState(void)
{
if (strcmp(Config.netdbFilename, "none") == 0)
- return;
+ return;
char *s;
int fd;
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 *
netdbRegisterWithCacheManager(void)
{
CacheManager::GetInstance()->
- registerAction("netdb", "Network Measurement Database", netdbDump, 0, 1);
+ registerAction("netdb", "Network Measurement Database", netdbDump, 0, 1);
}
#endif /* USE_ICMP */
return;
ipcache_nbgethostbyname(hostname, netdbSendPing,
- new generic_cbdata(xstrdup(hostname)));
+ new generic_cbdata(xstrdup(hostname)));
#endif
}
#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);
}
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;
}
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;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
}
/* 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)
}
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:
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() */
(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) */
}
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)
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General 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 "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);
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)
/*
* peerGetSomeNeighbor
- *
+ *
* Selects a neighbor (parent or sibling) based on one of the
* following methods:
* Cache Digests
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) {
/*
* peerGetSomeNeighborReplies
- *
+ *
* Selects a neighbor (parent or sibling) based on ICP/HTCP replies.
*/
static void
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;
/*
* peerGetSomeDirect
- *
+ *
* Simply adds a 'direct' entry to the FwdServers list if this
* request can be forwarded directly to the origin server
*/
/* WAIS is not implemented natively */
if (ps->request->protocol == PROTO_WAIS)
- return;
+ return;
peerAddFwdServer(&ps->servers, NULL, HIER_DIRECT);
}
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) {
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;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
peerSourceHashRegisterWithCacheManager(void)
{
CacheManager::GetInstance()->
- registerAction("sourcehash", "peer sourcehash information",
- peerSourceHashCachemgr, 0, 1);
+ registerAction("sourcehash", "peer sourcehash information",
+ peerSourceHashCachemgr, 0, 1);
}
peer *
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)) {
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
n_userhash_peers = 0;
/* find out which peers we have */
-
+
peerUserHashRegisterWithCacheManager();
for (p = Config.peers; p; p = p->next) {
peerUserHashRegisterWithCacheManager(void)
{
CacheManager::GetInstance()->
- registerAction("userhash", "peer userhash information", peerUserHashCachemgr,
- 0, 1);
+ registerAction("userhash", "peer userhash information", peerUserHashCachemgr,
+ 0, 1);
}
peer *
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);
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)) {
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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.");
}
}
- 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
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
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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
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
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
/*
* 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.
- *
+ *
*/
/*
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General 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 "client_side.h"
#include "helper.h"
-typedef struct
-{
+typedef struct {
void *data;
char *orig_url;
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();
redirectRegisterWithCacheManager(void)
{
CacheManager::GetInstance()->
- registerAction("redirector", "URL Redirector Stats", redirectStats, 0, 1);
+ registerAction("redirector", "URL Redirector Stats", redirectStats, 0, 1);
}
void
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
rcCount
} refreshCountsEnum;
-typedef struct
-{
+typedef struct {
bool expires;
bool min;
bool lmfactor;
STALE_DEFAULT = 299
};
-static struct RefreshCounts
-{
+static struct RefreshCounts {
const char *proto;
int total;
int status[STALE_DEFAULT + 1];
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);
/*
* 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);
refreshRegisterWithCacheManager(void)
{
CacheManager::GetInstance()->
- registerAction("refresh", "Refresh Algorithm Statistics", refreshStats, 0, 1);
+ registerAction("refresh", "Refresh Algorithm Statistics", refreshStats, 0, 1);
}
void
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
/*
* 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
* 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).
* 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).
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);
* 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/
* ----------------------------------------------------------
*
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
static int nr_heap_policies = 0;
-struct HeapPolicyData
-{
+struct HeapPolicyData {
void setPolicyNode (StoreEntry *, void *) const;
RemovalPolicy *policy;
heap *theHeap;
typedef struct _HeapWalkData HeapWalkData;
-struct _HeapWalkData
-{
+struct _HeapWalkData {
size_t current;
};
typedef struct _HeapPurgeData HeapPurgeData;
-struct _HeapPurgeData
-{
+struct _HeapPurgeData {
link_list *locked_entries;
heap_key min_age;
};
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
REMOVALPOLICYCREATE createRemovalPolicy_lru;
-struct LruPolicyData
-{
+struct LruPolicyData {
void setPolicyNode (StoreEntry *, void *) const;
RemovalPolicy *policy;
dlink_list list;
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 *.
*/
typedef struct _LruWalkData LruWalkData;
-struct _LruWalkData
-{
+struct _LruWalkData {
LruNode *current;
};
typedef struct _LruPurgeData LruPurgeData;
-struct _LruPurgeData
-{
+struct _LruPurgeData {
LruNode *current;
LruNode *start;
};
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General 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 "SquidTime.h"
/************************************************************************
-
+
SQUID MIB Implementation
-
+
************************************************************************/
-/*
- * cacheSystem group
+/*
+ * cacheSystem group
*/
variable_list *
return Answer;
}
-/*
- * cacheConfig group
+/*
+ * cacheConfig group
*/
variable_list *
snmp_confFn(variable_list * Var, snint * ErrP)
}
-/*
+/*
* cacheMesh group
* - cachePeerTable
*/
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:
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,
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,
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;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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;
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),
if (x < 0)
debugs(51, 1, "theOutSnmpConnection FD " << theOutSnmpConnection << ": getsockname: " << xstrerror());
else
- theOutSNMPAddr = *xaddr;
+ theOutSNMPAddr = *xaddr;
theOutSNMPAddr.FreeAddrInfo(xaddr);
}
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);
*RespVars = VarNew;
RespVars = &(VarNew->next_variable);
- }
- }
+ }
+ }
}
return (Answer);
while ((mibTreeEntry) && (count < CurrentLen) && (!mibTreeEntry->parsefunction)) {
mib_tree_entry *nextmibTreeEntry = snmpTreeEntry(Current[count], count, mibTreeEntry);
- if (!nextmibTreeEntry)
+ if (!nextmibTreeEntry)
break;
else
mibTreeEntry = nextmibTreeEntry;
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 {
*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;
}
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];
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);
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
*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
*len = current->len + newshift ;
}
}
-
+
*Fn = current->parsefunction;
return (instance);
}
*/
/*
- * Tree utility functions.
+ * Tree utility functions.
*/
/*
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++) {
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);
}
-/*
+/*
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<size; i++)
- {
- cp[i] = id[i];
+ debugs(49, 7, "oid2addr: id : ");
+ snmpDebugOid(7, id, size );
+ for (i=0 ; i<size; i++) {
+ cp[i] = id[i];
}
#if USE_IPV6
- if ( size == sizeof(struct in_addr) )
+ if ( size == sizeof(struct in_addr) )
#endif
- addr = iaddr;
+ addr = iaddr;
#if USE_IPV6
- else
- addr = i6addr;
+ else
+ addr = i6addr;
#endif
}
private:
static ACLSNMPCommunityStrategy Instance_;
- ACLSNMPCommunityStrategy(){}
+ ACLSNMPCommunityStrategy() {}
ACLSNMPCommunityStrategy&operator=(ACLSNMPCommunityStrategy const &);
};
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* places
*/
-struct rusage
-{
+struct rusage {
struct timeval ru_stime;
#define getpagesize( ) sysconf(_SC_PAGE_SIZE)
#endif
-#if defined(_SQUID_MSWIN_) && !defined(getpagesize)
+#if defined(_SQUID_MSWIN_) && !defined(getpagesize)
/* Windows may lack getpagesize() prototype */
SQUIDCEXTERN size_t getpagesize(void);
#endif /* _SQUID_MSWIN_ */
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
debugs(83, 5, "SSL Certificate has illegal \'not before\' field: " <<
buffer);
-
+
break;
case X509_V_ERR_CERT_HAS_EXPIRED:
}
}
-if (!dont_verify_domain && server) {}
+ if (!dont_verify_domain && server) {}
return ok;
}
/// \ingroup ServerProtocolSSLInternal
-static struct ssl_option
-{
+static struct ssl_option {
const char *name;
long value;
}
ssl_options[] = {
#ifdef SSL_OP_MICROSOFT_SESS_ID_BUG
- {
- "MICROSOFT_SESS_ID_BUG", SSL_OP_MICROSOFT_SESS_ID_BUG
- },
+ {
+ "MICROSOFT_SESS_ID_BUG", SSL_OP_MICROSOFT_SESS_ID_BUG
+ },
#endif
#ifdef SSL_OP_NETSCAPE_CHALLENGE_BUG
- {
- "NETSCAPE_CHALLENGE_BUG", SSL_OP_NETSCAPE_CHALLENGE_BUG
- },
+ {
+ "NETSCAPE_CHALLENGE_BUG", SSL_OP_NETSCAPE_CHALLENGE_BUG
+ },
#endif
#ifdef SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
- {
- "NETSCAPE_REUSE_CIPHER_CHANGE_BUG", SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
- },
+ {
+ "NETSCAPE_REUSE_CIPHER_CHANGE_BUG", SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
+ },
#endif
#ifdef SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
- {
- "SSLREF2_REUSE_CERT_TYPE_BUG", SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
- },
+ {
+ "SSLREF2_REUSE_CERT_TYPE_BUG", SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
+ },
#endif
#ifdef SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
- {
- "MICROSOFT_BIG_SSLV3_BUFFER", SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
- },
+ {
+ "MICROSOFT_BIG_SSLV3_BUFFER", SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
+ },
#endif
#ifdef SSL_OP_MSIE_SSLV2_RSA_PADDING
- {
- "MSIE_SSLV2_RSA_PADDING", SSL_OP_MSIE_SSLV2_RSA_PADDING
- },
+ {
+ "MSIE_SSLV2_RSA_PADDING", SSL_OP_MSIE_SSLV2_RSA_PADDING
+ },
#endif
#ifdef SSL_OP_SSLEAY_080_CLIENT_DH_BUG
- {
- "SSLEAY_080_CLIENT_DH_BUG", SSL_OP_SSLEAY_080_CLIENT_DH_BUG
- },
+ {
+ "SSLEAY_080_CLIENT_DH_BUG", SSL_OP_SSLEAY_080_CLIENT_DH_BUG
+ },
#endif
#ifdef SSL_OP_TLS_D5_BUG
- {
- "TLS_D5_BUG", SSL_OP_TLS_D5_BUG
- },
+ {
+ "TLS_D5_BUG", SSL_OP_TLS_D5_BUG
+ },
#endif
#ifdef SSL_OP_TLS_BLOCK_PADDING_BUG
- {
- "TLS_BLOCK_PADDING_BUG", SSL_OP_TLS_BLOCK_PADDING_BUG
- },
+ {
+ "TLS_BLOCK_PADDING_BUG", SSL_OP_TLS_BLOCK_PADDING_BUG
+ },
#endif
#ifdef SSL_OP_TLS_ROLLBACK_BUG
- {
- "TLS_ROLLBACK_BUG", SSL_OP_TLS_ROLLBACK_BUG
- },
+ {
+ "TLS_ROLLBACK_BUG", SSL_OP_TLS_ROLLBACK_BUG
+ },
#endif
#ifdef SSL_OP_ALL
- {
- "ALL", SSL_OP_ALL
- },
+ {
+ "ALL", SSL_OP_ALL
+ },
#endif
#ifdef SSL_OP_SINGLE_DH_USE
- {
- "SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE
- },
+ {
+ "SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE
+ },
#endif
#ifdef SSL_OP_EPHEMERAL_RSA
- {
- "EPHEMERAL_RSA", SSL_OP_EPHEMERAL_RSA
- },
+ {
+ "EPHEMERAL_RSA", SSL_OP_EPHEMERAL_RSA
+ },
#endif
#ifdef SSL_OP_PKCS1_CHECK_1
- {
- "PKCS1_CHECK_1", SSL_OP_PKCS1_CHECK_1
- },
+ {
+ "PKCS1_CHECK_1", SSL_OP_PKCS1_CHECK_1
+ },
#endif
#ifdef SSL_OP_PKCS1_CHECK_2
- {
- "PKCS1_CHECK_2", SSL_OP_PKCS1_CHECK_2
- },
+ {
+ "PKCS1_CHECK_2", SSL_OP_PKCS1_CHECK_2
+ },
#endif
#ifdef SSL_OP_NETSCAPE_CA_DN_BUG
- {
- "NETSCAPE_CA_DN_BUG", SSL_OP_NETSCAPE_CA_DN_BUG
- },
+ {
+ "NETSCAPE_CA_DN_BUG", SSL_OP_NETSCAPE_CA_DN_BUG
+ },
#endif
#ifdef SSL_OP_NON_EXPORT_FIRST
- {
- "NON_EXPORT_FIRST", SSL_OP_NON_EXPORT_FIRST
- },
+ {
+ "NON_EXPORT_FIRST", SSL_OP_NON_EXPORT_FIRST
+ },
#endif
#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
- {
- "CIPHER_SERVER_PREFERENCE", SSL_OP_CIPHER_SERVER_PREFERENCE
- },
+ {
+ "CIPHER_SERVER_PREFERENCE", SSL_OP_CIPHER_SERVER_PREFERENCE
+ },
#endif
#ifdef SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
- {
- "NETSCAPE_DEMO_CIPHER_CHANGE_BUG", SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
- },
+ {
+ "NETSCAPE_DEMO_CIPHER_CHANGE_BUG", SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
+ },
#endif
#ifdef SSL_OP_NO_SSLv2
- {
- "NO_SSLv2", SSL_OP_NO_SSLv2
- },
+ {
+ "NO_SSLv2", SSL_OP_NO_SSLv2
+ },
#endif
#ifdef SSL_OP_NO_SSLv3
- {
- "NO_SSLv3", SSL_OP_NO_SSLv3
- },
+ {
+ "NO_SSLv3", SSL_OP_NO_SSLv3
+ },
#endif
#ifdef SSL_OP_NO_TLSv1
- {
- "NO_TLSv1", SSL_OP_NO_TLSv1
- },
+ {
+ "NO_TLSv1", SSL_OP_NO_TLSv1
+ },
#endif
- {
- "", 0
- },
- {
- NULL, 0
- }
- };
+ {
+ "", 0
+ },
+ {
+ NULL, 0
+ }
+};
/// \ingroup ServerProtocolSSLInternal
static long
return fl;
}
-struct SslErrorMapEntry
-{
+struct SslErrorMapEntry {
const char *name;
ssl_error_t value;
};
// "dup" function for SSL_get_ex_new_index("cert_err_check")
static int
ssl_dupAclChecklist(CRYPTO_EX_DATA *, CRYPTO_EX_DATA *, void *,
- int, long, void *) {
+ int, long, void *)
+{
// We do not support duplication of ACLCheckLists.
// If duplication is needed, we can count copies with cbdata.
assert(false);
// "free" function for SSL_get_ex_new_index("cert_err_check")
static void
ssl_freeAclChecklist(void *, void *ptr, CRYPTO_EX_DATA *,
- int, long, void *) {
+ int, long, void *)
+{
delete static_cast<ACLChecklist *>(ptr); // may be NULL
}
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;
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;
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
#ifdef __cplusplus
/** \cond AUTODOCS-IGNORE */
-namespace Squid {
+namespace Squid
+{
/** \endcond */
/// \ingroup ServerProtocolSSLAPI
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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()));
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);
}
}
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
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
/* 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.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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<mem_node *> &getNodes() const;
char * NodeGet(mem_node * aNode);
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
#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;
typedef struct _storerepl_entry storerepl_entry_t;
-struct _storerepl_entry
-{
+struct _storerepl_entry {
const char *typestr;
REMOVALPOLICYCREATE *create;
};
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
PROF_stop(StoreEntry_write);
invokeHandlers();
return;
- }
+ }
debugs(20, 5, "storeWrite: writing " << writeBuffer.length << " bytes for '" << getMD5Text() << "'");
PROF_stop(StoreEntry_write);
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;
int too_many_open_fds;
} no;
- struct
- {
+ struct {
int Default;
} yes;
} store_check_cachable_hist;
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)
* 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();
/* 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
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
void
StoreEntry::negativeCache()
{
- if(expires == 0)
+ if (expires == 0)
#if HTTP_VIOLATIONS
expires = squid_curtime + Config.negativeTtl;
#else
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;
{
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);
}
}
* 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 */
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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;
/* 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
*/
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() << "'");
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
};
-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 */
storeDigestRegisterWithCacheManager(void)
{
CacheManager::GetInstance()->
- registerAction("store_digest", "Store Digest", storeDigestReport, 0, 1);
+ registerAction("store_digest", "Store Digest", storeDigestReport, 0, 1);
}
/*
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);
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();
{
/*
* 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 << "]");
/* do not enforce hi_cap limit, average-based estimation may be wrong
*if (cap > hi_cap)
- * cap = hi_cap;
+ * cap = hi_cap;
*/
return cap;
}
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 */
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
*
* 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.
*
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<SwapDir *>(INDEXSD(e->swap_dirn))->logEntry(*e, op);
/*
* 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
}
/*
- * handle callbacks all avaliable fs'es
+ * handle callbacks all avaliable fs'es
*/
int
StoreController::callback()
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;
StoreEntry *
StoreController::get
- (const cache_key *key)
+(const cache_key *key)
{
return swapDir->get
void
StoreController::get
- (String const key, STOREGETCLIENT callback, void *cbdata)
+(String const key, STOREGETCLIENT callback, void *cbdata)
{
fatal("not implemented");
}
StoreHashIndex::StoreHashIndex()
{
if (store_table)
- abort();
+ abort();
assert (store_table == NULL);
}
StoreEntry *
StoreHashIndex::get
- (const cache_key *key)
+(const cache_key *key)
{
PROF_start(storeGet);
debugs(20, 3, "storeGet: looking up " << storeKeyText(key));
void
StoreHashIndex::get
- (String const key, STOREGETCLIENT callback, void *cbdata)
+(String const key, STOREGETCLIENT callback, void *cbdata)
{
fatal("not implemented");
}
* 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'.
*
#include "MemObject.h"
#include "SwapDir.h"
-static struct
-{
+static struct {
- struct
- {
+ struct {
int calls;
int select_fail;
int create_fail;
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;
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General 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 "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;
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;
{
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]);
}
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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 */
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)
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
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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) {
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
/* 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,
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;
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());
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;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General 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 "squid.h"
-typedef struct
-{
+typedef struct {
int query_count;
int true_hit_count;
int true_miss_count;
typedef struct _Cache Cache;
-struct _Cache
-{
+struct _Cache {
const char *name;
hash_table *hash;
CacheDigest *digest;
};
-typedef struct _CacheEntry
-{
+typedef struct _CacheEntry {
const cache_key *key;
struct _CacheEntry *next;
/* parsed access log entry */
-typedef struct
-{
+typedef struct {
cache_key key[SQUID_MD5_DIGEST_LENGTH];
time_t timestamp;
short int use_icp; /* true/false */
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 */
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
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);
}
};
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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);
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
{
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)
}
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);
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 */
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
-#define SQUID_UNIT_TEST 1
+#define SQUID_UNIT_TEST 1
#include "squid.h"
#include <stdexcept>
/* 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<CalledEvent *>(data)->calls++;
}
/* 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] );
}
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);
#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
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.
*/
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
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();
StubTime() : calls(0) {}
int calls;
- void tick()
- {
+ void tick() {
++calls;
}
};
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);
-#define SQUID_UNIT_TEST 1
+#define SQUID_UNIT_TEST 1
#include "squid.h"
#include <sstream>
}
/*
- * We can also parse precise ranges of characters
+ * We can also parse precise ranges of characters
*/
void
testHttpRequestMethod::testConstructCharStartEnd()
// 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));
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
/// 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); };
};
StoreEntry*
TestStore::get
- (const cache_key*)
+(const cache_key*)
{
return NULL;
}
void
TestStore::get
- (String, void (*)(StoreEntry*, void*), void*)
+(String, void (*)(StoreEntry*, void*), void*)
{}
void
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;
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) {}
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;
#include <cppunit/extensions/HelperMacros.h>
/*
- * test StoreEntryStream
+ * test StoreEntryStream
*/
class testStoreEntryStream : public CPPUNIT_NS::TestFixture
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
}
/*
- * We can also parse precise ranges of characters
+ * We can also parse precise ranges of characters
*/
void
testHttpRequestMethod::testConstructCharStartEnd()
}
/*
- * 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
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 */
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
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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);
}
#else
void
fatalf(va_alist)
-va_dcl
-{
+va_dcl {
va_list args;
const char *fmt = NULL;
va_start(args);
* 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 << "'");
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;
}
return host;
}
- if(AI) xfreeaddrinfo(AI);
+ if (AI) xfreeaddrinfo(AI);
debugs(50, 1, "WARNING: '" << host << "' rDNS test failed: " << xstrerror());
}
}
mb->append(str, l);
str += l;
- switch(*str) {
+ switch (*str) {
case '\n':
mb->append("\\n", 2);
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);
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
{
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_;}
if (tunnelState->noConnections()) {
tunnelStateFree(tunnelState);
- return;
+ return;
}
-
+
if (!tunnelState->server.len) {
- comm_close(tunnelState->client.fd());
- return;
+ comm_close(tunnelState->client.fd());
+ return;
}
}
if (tunnelState->noConnections()) {
tunnelStateFree(tunnelState);
- return;
+ return;
}
-
+
if (!tunnelState->client.len) {
- comm_close(tunnelState->server.fd());
- return;
+ comm_close(tunnelState->server.fd());
+ return;
}
}
{
/*
* 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)
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))
{
/*
* 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)
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);
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);
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
typedef signed int sfileno;
typedef signed int sdirno;
-typedef struct
-{
+typedef struct {
size_t bytes;
size_t kb;
} kb_t;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
#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<StoreMeta, void>
-{
- DumpStoreMeta(){}
+struct DumpStoreMeta : public unary_function<StoreMeta, void> {
+ DumpStoreMeta() {}
- void operator()(StoreMeta const &x)
- {
+ void operator()(StoreMeta const &x) {
switch (x.getType()) {
case STORE_META_KEY:
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:
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;
}
}
int fd = -1;
StoreMeta *metadata = NULL;
- try
- {
+ try {
if (argc != 2)
throw std::runtime_error("No filename provided");
return 0;
- } catch (std::runtime_error error)
- {
+ } catch (std::runtime_error error) {
std::cout << "Failed : " << error.what() << std::endl;
if (fd >= 0)
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
*/
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);
#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);
} 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");
/* 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,
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* 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
*dst = *src;
}
if (i >= l)
- return NULL;
+ return NULL;
*dst = '\0';
/* Then its :// */
*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 '/'.
}
/* 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++) {
*(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. */
}
if (t && *t == ':') {
- *t = '\0'; t++;
+ *t = '\0';
+ t++;
port = atoi(t);
}
}
switch (request->method.id()) {
case METHOD_CONNECT:
- snprintf(buf, MAX_URL, "%s:%d",
+ snprintf(buf, MAX_URL, "%s:%d",
request->GetHost(),
request->port);
break;
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] == '/') {
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++;
/*
* matchDomainName() compares a hostname with a domainname according
* to the following rules:
- *
+ *
* HOST DOMAIN MATCH?
* ------------- ------------- ------
* foo.com foo.com YES
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
HttpRequest *request;
HttpRequest *urlres_r;
- struct
- {
+ struct {
unsigned int force_menu:1;
} flags;
char reqbuf[URN_REQBUF_SZ];
char *urlres;
};
-typedef struct
-{
+typedef struct {
char *url;
char *host;
int rtt;
- struct
- {
+ struct {
int cached;
} flags;
} url_entry;
*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;
}
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');
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
#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;
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;
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;
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=" <<
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
/* 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;
/* 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;
/* 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;
};
/// \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];
/* 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;
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;
/* 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;
/* 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;
/* 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;
};
/* 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;
};
/* 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;
};
/* 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;
};
/* 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;
/* 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;
/* 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;
/* 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;
/* 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;
/* Generic header struct */
/// \interface WCCPv2_Protocol
-struct wccp2_item_header_t
-{
+struct wccp2_item_header_t {
uint16_t type;
uint16_t length;
};
/* Router identity struct */
/// \interface WCCPv2_Protocol
-struct router_identity_info_t
-{
+struct router_identity_info_t {
struct wccp2_item_header_t header;
/* 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;
/* assigment key */
/// \interface WCCPv2_Protocol
-struct assignment_key_t
-{
+struct assignment_key_t {
struct in_addr master_ip;
uint32_t master_number;
};
/* 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;
/* 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;
};
/// \interface WCCPv2_Protocol
-struct wccp2_router_list_t
-{
+struct wccp2_router_list_t {
struct wccp2_router_id_element_t *info;
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;
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,
}
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;
}
/* 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;
}
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;
}
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;
/* 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,
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;
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;
/* 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));
+ }
}
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
#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;
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);
int Win32__WSAFDIsSet(int fd, fd_set FAR * set
- )
+ )
{
fde *F = &fd_table[fd];
SOCKET s = F->win32.handle;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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;
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General 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 "squid.h"
#include <iostream>
-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;
};
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();
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();
::operator delete (address);
}
-ChildVirtual::~ChildVirtual(){}
+ChildVirtual::~ChildVirtual() {}
int
main(int argc, char **argv)
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General 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 "mem_node.h"
#include <iostream>
-class StreamTest {
- public:
+class StreamTest
+{
+public:
std::ostream &serialise(std::ostream &);
int const getAnInt() const;
char const *getACString() const;
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);
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General 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 <unistd.h>
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;
}
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;
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;
}
{
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;
/* 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;
/*
* 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.
*/
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;
}
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().
*/
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 */
}
}
/*
- * 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
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;
}
}
/*
- * 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]);
}
if (hid->buckets);
free(hid->buckets);
if (hid)
- free(hid);
+ free(hid);
}
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");
#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;
}
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
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();
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);
#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);
}
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
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
char *
mkrfc850(t)
- time_t *t;
+time_t *t;
{
static char buf[128];
struct tm *gmt = gmtime(t);
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;
}
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);
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;
}
{
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;
}
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;
}
{
#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
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;
}
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;
}
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;
+ }
}
}
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);
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
~_ToRefCount() {--Instances;}
- int someMethod()
- {
+ int someMethod() {
if (!this)
exit(1);
public:
typedef RefCount<AlsoRefCountable> Pointer;
- int doSomething() { if (!this)
- exit (1); return 1;}
+ int doSomething() {
+ if (!this)
+ exit (1);
+ return 1;
+ }
};
int
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General 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 "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 *);
escapedString = xstrdup (aString);
rfc1738_unescape(escapedString);
if (strcmp(escapedString, aResult))
- exit (1);
+ exit (1);
safe_free (escapedString);
}
{
public:
- intnode() : i(0){}
+ intnode() : i(0) {}
intnode (int anInt) : i (anInt) {}
/* intnode* */
SplayNode<intnode *> *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();
/* intnode */
SplayNode<intnode> *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);
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
- *
+ *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General 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 "mem_node.h"
#include <iostream>
-class HasExplicit {
- public:
+class HasExplicit
+{
+public:
HasExplicit();
~HasExplicit();
HasExplicit(HasExplicit const &);
static int const &Instances();
static int const &Assignments();
static void Assignments(int const &);
- private:
+private:
static void AddInstance();
static void RemoveInstance();
static void Assignment();
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;
}
assert (HasExplicit::Assignments() == 0);
}
-class SyntheticOwnsExplicit {
- public:
+class SyntheticOwnsExplicit
+{
+public:
HasExplicit aMember;
};
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);
{
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;
}
}
FD[fd].data = data;
FD[fd].start = now.tv_sec;
if (fd > maxfd)
- maxfd = fd;
+ maxfd = fd;
nfds++;
}
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];
+ }
}
}
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];
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, " ");
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);
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;
}
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);
}
}
int
main(argc, argv)
- int argc;
- char *argv[];
+int argc;
+char *argv[];
{
int i;
int c;
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--;
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;
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;
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));
}
}
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);
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;
}
}
{
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;
}
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;
}
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);
}
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);
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);
+ }
}
}
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);
}
create_children(argv);
parent_main_loop();
for (i = 3; i <= maxfd; i++)
- close(i);
+ close(i);
sleep(1);
}
{
#else
_db_print(va_alist)
-va_dcl
-{
+va_dcl {
const char *format = NULL;
#endif
#else
void
fatalf(va_alist)
-va_dcl
-{
+va_dcl {
va_list args;
const char *fmt = NULL;
va_start(args);
void
Debug::xassert(const char *msg, const char *file, int line) {
-
+
if (CurrentDebug) {
*CurrentDebug << "assertion failed: " << file << ":" << line <<
- ": \"" << msg << "\"";
+ ": \"" << msg << "\"";
}
abort();
}
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;