void netdbExchangeStart(void *data) { #if USE_ICMP peer *p = data; char *uri; netdbExchangeState *ex; method_t *method_get; CBDATA_INIT_TYPE(netdbExchangeState); ex = cbdataAlloc(netdbExchangeState); cbdataLock(p); ex->p = p; uri = internalRemoteUri(p->host, p->http_port, "/squid-internal-dynamic/", "netdb"); debug(38, 3) ("netdbExchangeStart: Requesting '%s'\n", uri); assert(NULL != uri); method_get = urlMethodGetKnownByCode(METHOD_GET); ex->r = urlParse(method_get, uri); if (NULL == ex->r) { debug(38, 1) ("netdbExchangeStart: Bad URI %s\n", uri); return; } requestLink(ex->r); assert(NULL != ex->r); httpBuildVersion(&ex->r->http_ver, 1, 0); ex->e = storeCreateEntry(uri, null_request_flags, method_get); assert(NULL != ex->e); ex->sc = storeClientRegister(ex->e, ex); storeClientRef(ex->sc, ex->e, ex->seen, ex->used, SM_PAGE_SIZE, netdbExchangeHandleReply, ex); ex->r->flags.loopdetect = 1; /* cheat! -- force direct */ if (p->login) xstrncpy(ex->r->login, p->login, MAX_LOGIN_SZ); fwdStart(-1, ex->e, ex->r); #endif }
/* starts swap out sequence for the digest */ static void storeDigestRewriteStart(void *datanotused) { request_flags flags; char *url; StoreEntry *e; assert(store_digest); /* prevent overlapping if rewrite schedule is too tight */ if (sd_state.rewrite_lock) { debug(71, 1) ("storeDigestRewriteStart: overlap detected, consider increasing rewrite period\n"); return; } debug(71, 2) ("storeDigestRewriteStart: start rewrite #%d\n", sd_state.rewrite_count + 1); /* make new store entry */ url = internalStoreUri("/squid-internal-periodic/", StoreDigestFileName); flags = null_request_flags; flags.cachable = 1; e = storeCreateEntry(url, flags, METHOD_GET); assert(e); sd_state.rewrite_lock = cbdataAlloc(generic_cbdata); sd_state.rewrite_lock->data = e; debug(71, 3) ("storeDigestRewriteStart: url: %s key: %s\n", url, storeKeyText(e->hash.key)); e->mem_obj->request = requestLink(urlParse(METHOD_GET, url)); /* wait for rebuild (if any) to finish */ if (sd_state.rebuild_lock) { debug(71, 2) ("storeDigestRewriteStart: waiting for rebuild to finish.\n"); return; } storeDigestRewriteResume(); }
static void asnCacheStart(int as) { LOCAL_ARRAY(char, asres, 4096); StoreEntry *e; request_t *req; ASState *asState; method_t *method_get; method_get = urlMethodGetKnownByCode(METHOD_GET); asState = cbdataAlloc(ASState); debug(53, 3) ("asnCacheStart: AS %d\n", as); snprintf(asres, 4096, "whois://%s/!gAS%d", Config.as_whois_server, as); asState->as_number = as; req = urlParse(method_get, asres); assert(NULL != req); asState->request = requestLink(req); if ((e = storeGetPublic(asres, method_get)) == NULL) { e = storeCreateEntry(asres, null_request_flags, method_get); asState->sc = storeClientRegister(e, asState); fwdStart(-1, e, asState->request); } else { storeLockObject(e); asState->sc = storeClientRegister(e, asState); } asState->entry = e; asState->seen = 0; asState->offset = 0; storeClientRef(asState->sc, e, asState->seen, asState->offset, SM_PAGE_SIZE, asHandleReply, asState); }
int errorMapStart(const errormap * map, request_t * client_req, HttpReply * reply, const char *aclname, ERRMAPCB * callback, void *callback_data) { char squid_error[100]; int len = 0; const char *errorUrl; ErrorMapState *state; const char *tmp; http_status status; request_t *req; HttpHeaderPos hdrpos; HttpHeaderEntry *hdr; if (!client_req || !reply) return 0; status = reply->sline.status; tmp = httpHeaderGetStr(&reply->header, HDR_X_SQUID_ERROR); squid_error[0] = '\0'; if (tmp) { xstrncpy(squid_error, tmp, sizeof(squid_error)); len = strcspn(squid_error, " "); } squid_error[len] = '\0'; errorUrl = getErrorMap(map, status, squid_error, aclname); if (!errorUrl) return 0; req = urlParse(urlMethodGetKnownByCode(METHOD_GET), (char *) errorUrl); if (!req) { debug(0, 0) ("errorMapStart: Invalid error URL '%s'\n", errorUrl); return 0; } req->urlgroup = xstrdup("error"); state = cbdataAlloc(ErrorMapState); state->req = requestLink(req); state->e = storeCreateEntry(errorUrl, req->flags, req->method); state->sc = storeClientRegister(state->e, state); state->callback = callback; state->callback_data = callback_data; cbdataLock(callback_data); hdrpos = HttpHeaderInitPos; while ((hdr = httpHeaderGetEntry(&client_req->header, &hdrpos)) != NULL) { if (CBIT_TEST(client_headers, hdr->id)) httpHeaderAddClone(&req->header, hdr); } hdrpos = HttpHeaderInitPos; while ((hdr = httpHeaderGetEntry(&reply->header, &hdrpos)) != NULL) { if (CBIT_TEST(server_headers, hdr->id)) httpHeaderAddClone(&req->header, hdr); } httpHeaderPutInt(&req->header, HDR_X_ERROR_STATUS, (int) reply->sline.status); httpHeaderPutStr(&req->header, HDR_X_REQUEST_URI, urlCanonical(client_req)); fwdStart(-1, state->e, req); storeClientRef(state->sc, state->e, 0, 0, SM_PAGE_SIZE, errorMapFetchHeaders, state); return 1; }
static void mimeLoadIconFile(const char *icon) { int fd; int n; request_flags flags; struct stat sb; StoreEntry *e; LOCAL_ARRAY(char, path, MAXPATHLEN); LOCAL_ARRAY(char, url, MAX_URL); char *buf; const char *type = mimeGetContentType(icon); HttpReply *reply; if (type == NULL) fatal("Unknown icon format while reading mime.conf\n"); buf = internalLocalUri("/squid-internal-static/icons/", icon); xstrncpy(url, buf, MAX_URL); if (storeGetPublic(url, METHOD_GET)) return; snprintf(path, MAXPATHLEN, "%s/%s", Config.icons.directory, icon); fd = file_open(path, O_RDONLY); if (fd < 0) { debug(25, 0) ("mimeLoadIconFile: %s: %s\n", path, xstrerror()); return; } if (fstat(fd, &sb) < 0) { debug(50, 0) ("mimeLoadIconFile: FD %d: fstat: %s\n", fd, xstrerror()); return; } flags = null_request_flags; flags.cachable = 1; e = storeCreateEntry(url, url, flags, METHOD_GET); assert(e != NULL); storeSetPublicKey(e); storeBuffer(e); e->mem_obj->request = requestLink(urlParse(METHOD_GET, url)); httpReplyReset(reply = e->mem_obj->reply); httpReplySetHeaders(reply, 1.0, HTTP_OK, NULL, type, (int) sb.st_size, sb.st_mtime, -1); reply->cache_control = httpHdrCcCreate(); httpHdrCcSetMaxAge(reply->cache_control, 86400); httpHeaderPutCc(&reply->header, reply->cache_control); httpReplySwapOut(reply, e); reply->hdr_sz = e->mem_obj->inmem_hi; /* yuk */ /* read the file into the buffer and append it to store */ buf = memAllocate(MEM_4K_BUF); while ((n = read(fd, buf, 4096)) > 0) storeAppend(e, buf, n); file_close(fd); EBIT_SET(e->flags, ENTRY_SPECIAL); storeBufferFlush(e); storeComplete(e); storeTimestampsSet(e); debug(25, 3) ("Loaded icon %s\n", url); storeUnlockObject(e); memFree(buf, MEM_4K_BUF); }
void urnStart(request_t * r, StoreEntry * e) { LOCAL_ARRAY(char, urlres, 4096); request_t *urlres_r = NULL; const char *t; char *host; UrnState *urnState; StoreEntry *urlres_e; ErrorState *err; debug(52, 3) ("urnStart: '%s'\n", storeUrl(e)); CBDATA_INIT_TYPE(UrnState); urnState = cbdataAlloc(UrnState); urnState->entry = e; urnState->request = requestLink(r); storeLockObject(urnState->entry); if (strncasecmp(strBuf(r->urlpath), "menu.", 5) == 0) { char *new_path = xstrdup(strBuf(r->urlpath) + 5); urnState->flags.force_menu = 1; stringReset(&r->urlpath, new_path); xfree(new_path); } if ((t = strChr(r->urlpath, ':')) != NULL) { strSet(r->urlpath, t, '\0'); host = xstrdup(strBuf(r->urlpath)); strSet(r->urlpath, t, ':'); } else { host = xstrdup(strBuf(r->urlpath)); } snprintf(urlres, 4096, "http://%s/uri-res/N2L?urn:%s", host, strBuf(r->urlpath)); safe_free(host); urlres_r = urlParse(METHOD_GET, urlres); if (urlres_r == NULL) { debug(52, 3) ("urnStart: Bad uri-res URL %s\n", urlres); err = errorCon(ERR_URN_RESOLVE, HTTP_NOT_FOUND); err->url = xstrdup(urlres); errorAppendEntry(e, err); return; } httpHeaderPutStr(&urlres_r->header, HDR_ACCEPT, "text/plain"); if ((urlres_e = storeGetPublic(urlres, METHOD_GET)) == NULL) { urlres_e = storeCreateEntry(urlres, urlres, null_request_flags, METHOD_GET); urnState->sc = storeClientListAdd(urlres_e, urnState); fwdStart(-1, urlres_e, urlres_r); } else { storeLockObject(urlres_e); urnState->sc = storeClientListAdd(urlres_e, urnState); } urnState->urlres_e = urlres_e; urnState->urlres_r = requestLink(urlres_r); storeClientCopy(urnState->sc, urlres_e, 0, 0, 4096, memAllocate(MEM_4K_BUF), urnHandleReply, urnState); }
static inline void modify_request(clientHttpRequest * http) { debug(97, 3)("modify_request: start, uri=[%s]\n", http->uri); request_t* old_request = http->request; request_t* new_request = urlParse(old_request->method, http->uri); safe_free(http->uri); if (new_request) { safe_free(http->uri); http->uri = xstrdup(urlCanonical(new_request)); if(!http->log_uri) http->log_uri = xstrdup(urlCanonicalClean(old_request)); new_request->http_ver = old_request->http_ver; httpHeaderAppend(&new_request->header, &old_request->header); new_request->client_addr = old_request->client_addr; new_request->client_port = old_request->client_port; #if FOLLOW_X_FORWARDED_FOR new_request->indirect_client_addr = old_request->indirect_client_addr; #endif /* FOLLOW_X_FORWARDED_FOR */ new_request->my_addr = old_request->my_addr; new_request->my_port = old_request->my_port; new_request->flags = old_request->flags; new_request->flags.redirected = 1; if (old_request->auth_user_request) { new_request->auth_user_request = old_request->auth_user_request; authenticateAuthUserRequestLock(new_request->auth_user_request); } if (old_request->body_reader) { new_request->body_reader = old_request->body_reader; new_request->body_reader_data = old_request->body_reader_data; old_request->body_reader = NULL; old_request->body_reader_data = NULL; } new_request->content_length = old_request->content_length; if (strBuf(old_request->extacl_log)) new_request->extacl_log = stringDup(&old_request->extacl_log); if (old_request->extacl_user) new_request->extacl_user = xstrdup(old_request->extacl_user); if (old_request->extacl_passwd) new_request->extacl_passwd = xstrdup(old_request->extacl_passwd); if(old_request->cc_request_private_data) { new_request->cc_request_private_data = old_request->cc_request_private_data; old_request->cc_request_private_data = NULL; } requestUnlink(old_request); http->request = requestLink(new_request); } }
static request_t * modifyRequestUrlstoreUrl(const char *url) { request_t *new_request = NULL; new_request = urlParse(METHOD_GET, (char*)url); char *new_storeurl = xstrdup((const char *)url); char* str = strchr(new_storeurl, '?'); if (str) { debug(207, 3)("modify_request_url_storeurl rid_question: storeurl=[%s] have question\n", new_storeurl); *str = '\0'; } new_request->store_url = xstrdup((const char *)new_storeurl); debug(207, 3)("after modifyRequestUrlstoreUrl url=%s,storeurl=%s,uri=%s\n",urlCanonical(new_request),new_request->store_url,strBuf(new_request->urlpath)); return requestLink(new_request); }
static void peerCountMcastPeersStart(void *data) { peer *p = data; ps_state *psstate; StoreEntry *fake; MemObject *mem; icp_common_t *query; int reqnum; method_t *method_get; LOCAL_ARRAY(char, url, MAX_URL); assert(p->type == PEER_MULTICAST); method_get = urlMethodGetKnownByCode(METHOD_GET); p->mcast.flags.count_event_pending = 0; snprintf(url, MAX_URL, "http://%s/", inet_ntoa(p->in_addr.sin_addr)); fake = storeCreateEntry(url, null_request_flags, method_get); psstate = cbdataAlloc(ps_state); psstate->request = requestLink(urlParse(method_get, url)); psstate->entry = fake; psstate->callback = NULL; psstate->callback_data = p; cbdataLock(psstate->callback_data); psstate->ping.start = current_time; mem = fake->mem_obj; mem->request = requestLink(psstate->request); mem->start_ping = current_time; mem->ping_reply_callback = peerCountHandleIcpReply; mem->ircb_data = psstate; mcastSetTtl(theOutIcpConnection, p->mcast.ttl); p->mcast.id = mem->id; reqnum = icpSetCacheKey(fake->hash.key); query = icpCreateMessage(ICP_QUERY, 0, url, reqnum, 0); icpUdpSend(theOutIcpConnection, &p->in_addr, query, LOG_ICP_QUERY, 0); fake->ping_status = PING_WAITING; eventAdd("peerCountMcastPeersDone", peerCountMcastPeersDone, psstate, Config.Timeout.mcast_icp_query / 1000.0, 1); p->mcast.flags.counting = 1; peerCountMcastPeersSchedule(p, MCAST_COUNT_RATE); }
int main(int argc, char *argv[]) { int failures; char **p; int total; URL *url; printURL(urlParse(loginTest)); failures = 0; total = 0; p = relativeURLTests; while (p[0]) { total++; url = urlRelative(baseURLTest, (unsigned char *) p[0]); if (url) { if (strcmp((char *) url->url, p[1])) { failures++; printf("urlRelative failed:\n"); printf("\"%s\" +\n", baseURLTest); printf("\"%s\" =\n", p[0]); printf("\"%s\"\n", url->url); printf("should be:\n"); printf("\"%s\"\n", p[1]); printf("-------------------\n"); } urlFree(url); } else { failures++; printf("urlRelative return NULL for \"%s\"\n", p[0]); printf("----------------------------------\n"); } p += 2; } printf("%d failures out of %d\n", failures, total); return 0; }
static void peerMonitorRequest(void *data) { PeerMonitor *pm = data; char *url; request_t *req; if (!cbdataValid(pm->peer)) { cbdataFree(pm); return; } url = pm->peer->monitor.url; if (!url) { cbdataFree(pm); return; } req = urlParse(METHOD_GET, url); if (!req) { debug(DBG, 1) ("peerMonitorRequest: Failed to parse URL '%s' for cache_peer %s\n", url, pm->peer->name); cbdataFree(pm); return; } pm->last_probe = squid_curtime; pm->running.timeout_set = 1; eventAdd(pm->name, peerMonitorTimeout, pm, (double) (pm->peer->monitor.timeout ? pm->peer->monitor.timeout : pm->peer->monitor.interval), 0); httpHeaderPutStr(&req->header, HDR_ACCEPT, "*/*"); httpHeaderPutStr(&req->header, HDR_USER_AGENT, full_appname_string); if (pm->peer->login) xstrncpy(req->login, pm->peer->login, MAX_LOGIN_SZ); pm->running.req = requestLink(req); pm->running.e = storeCreateEntry(url, req->flags, req->method); pm->running.sc = storeClientRegister(pm->running.e, pm); pm->running.buf = memAllocate(MEM_4K_BUF); fwdStartPeer(pm->peer, pm->running.e, pm->running.req); storeClientCopy(pm->running.sc, pm->running.e, 0, 0, 4096, pm->running.buf, peerMonitorFetchReplyHeaders, pm); return; }
/* ask store for a digest */ static void peerDigestRequest(PeerDigest * pd) { peer *p = pd->peer; StoreEntry *e, *old_e; char *url; const cache_key *key; request_t *req; DigestFetchState *fetch = NULL; pd->req_result = NULL; pd->flags.requested = 1; /* compute future request components */ if (p->digest_url) url = xstrdup(p->digest_url); else url = internalRemoteUri(p->host, p->http_port, "/squid-internal-periodic/", StoreDigestFileName); key = storeKeyPublic(url, METHOD_GET); debug(72, 2) ("peerDigestRequest: %s key: %s\n", url, storeKeyText(key)); req = urlParse(METHOD_GET, url); assert(req); /* add custom headers */ assert(!req->header.len); httpHeaderPutStr(&req->header, HDR_ACCEPT, StoreDigestMimeStr); httpHeaderPutStr(&req->header, HDR_ACCEPT, "text/html"); if (p->login) xstrncpy(req->login, p->login, MAX_LOGIN_SZ); /* create fetch state structure */ fetch = memAllocate(MEM_DIGEST_FETCH_STATE); cbdataAdd(fetch, memFree, MEM_DIGEST_FETCH_STATE); fetch->request = requestLink(req); fetch->pd = pd; fetch->offset = 0; /* update timestamps */ fetch->start_time = squid_curtime; pd->times.requested = squid_curtime; pd_last_req_time = squid_curtime; req->flags.cachable = 1; /* the rest is based on clientProcessExpired() */ req->flags.refresh = 1; old_e = fetch->old_entry = storeGet(key); if (old_e) { debug(72, 5) ("peerDigestRequest: found old entry\n"); storeLockObject(old_e); storeCreateMemObject(old_e, url, url); storeClientListAdd(old_e, fetch); } e = fetch->entry = storeCreateEntry(url, url, req->flags, req->method); assert(EBIT_TEST(e->flags, KEY_PRIVATE)); storeClientListAdd(e, fetch); /* set lastmod to trigger IMS request if possible */ if (old_e) e->lastmod = old_e->lastmod; /* push towards peer cache */ debug(72, 3) ("peerDigestRequest: forwarding to fwdStart...\n"); fwdStart(-1, e, req); cbdataLock(fetch); cbdataLock(fetch->pd); storeClientCopy(e, 0, 0, 4096, memAllocate(MEM_4K_BUF), peerDigestFetchReply, fetch); }
int main(int argc, char *argv[]) { int c; char *configFile = NULL; char *host = NULL; unsigned short port = 0; char *mount = NULL; shout_t *shout; extern char *optarg; extern int optind; #ifdef HAVE_SIGNALS struct sigaction act; unsigned int i; #endif #ifdef XALLOC_DEBUG xalloc_initialize_debug(2, NULL); #else xalloc_initialize(); #endif /* XALLOC_DEBUG */ playlist_init(); shout_init(); __progname = getProgname(argv[0]); pezConfig = getEZConfig(); mFlag = 0; nFlag = 0; qFlag = 0; vFlag = 0; while ((c = local_getopt(argc, argv, "c:hmnqsVv")) != -1) { switch (c) { case 'c': if (configFile != NULL) { printf("Error: multiple -c arguments given\n"); usage(); return (ez_shutdown(2)); } configFile = xstrdup(optarg); break; case 'h': usage(); usageHelp(); return (ez_shutdown(0)); case 'm': mFlag = 1; break; case 'n': nFlag = 1; break; case 'q': qFlag = 1; break; case 's': sFlag = 1; break; case 'V': printf("%s\n", PACKAGE_STRING); return (ez_shutdown(0)); case 'v': vFlag++; break; case '?': usage(); return (ez_shutdown(2)); default: break; } } argc -= optind; argv += optind; if (sFlag) { playlist_t *pl; const char *entry; switch (argc) { case 0: pl = playlist_read(NULL); if (pl == NULL) return (ez_shutdown(1)); break; case 1: pl = playlist_read(argv[0]); if (pl == NULL) return (ez_shutdown(1)); break; default: printf("Error: Too many arguments.\n"); return (ez_shutdown(2)); } playlist_shuffle(pl); while ((entry = playlist_get_next(pl)) != NULL) printf("%s\n", entry); playlist_free(&pl); return (ez_shutdown(0)); } if (configFile == NULL) { printf("You must supply a config file with the -c argument.\n"); usage(); return (ez_shutdown(2)); } else { /* * Attempt to open configFile here for a more meaningful error * message. Where possible, do it with stat() and check for * safe config file permissions. */ #ifdef HAVE_STAT struct stat st; if (stat(configFile, &st) == -1) { printf("%s: %s\n", configFile, strerror(errno)); usage(); return (ez_shutdown(2)); } if (vFlag && (st.st_mode & (S_IRGRP | S_IROTH))) printf("%s: Warning: %s is group and/or world readable\n", __progname, configFile); if (st.st_mode & (S_IWGRP | S_IWOTH)) { printf("%s: Error: %s is group and/or world writeable\n", __progname, configFile); return (ez_shutdown(2)); } #else FILE *tmp; if ((tmp = fopen(configFile, "r")) == NULL) { printf("%s: %s\n", configFile, strerror(errno)); usage(); return (ez_shutdown(2)); } fclose(tmp); #endif /* HAVE_STAT */ } if (!parseConfig(configFile)) return (ez_shutdown(2)); if (pezConfig->URL == NULL) { printf("%s: Error: Missing <url>\n", configFile); return (ez_shutdown(2)); } if (!urlParse(pezConfig->URL, &host, &port, &mount)) { printf("Must be of the form ``http://server:port/mountpoint''\n"); return (ez_shutdown(2)); } if (strlen(host) == 0) { printf("%s: Error: Invalid <url>: Missing server:\n", configFile); printf("Must be of the form ``http://server:port/mountpoint''\n"); return (ez_shutdown(2)); } if (strlen(mount) == 0) { printf("%s: Error: Invalid <url>: Missing mountpoint:\n", configFile); printf("Must be of the form ``http://server:port/mountpoint''\n"); return (ez_shutdown(2)); } if (pezConfig->password == NULL) { printf("%s: Error: Missing <sourcepassword>\n", configFile); return (ez_shutdown(2)); } if (pezConfig->fileName == NULL) { printf("%s: Error: Missing <filename>\n", configFile); return (ez_shutdown(2)); } if (pezConfig->format == NULL) { printf("%s: Warning: Missing <format>:\n", configFile); printf("Specify a stream format of either MP3, VORBIS or THEORA\n"); } xfree(configFile); if ((shout = stream_setup(host, port, mount)) == NULL) return (ez_shutdown(1)); if (pezConfig->metadataProgram != NULL) metadataFromProgram = 1; else metadataFromProgram = 0; #ifdef HAVE_SIGNALS memset(&act, 0, sizeof(act)); act.sa_handler = sig_handler; # ifdef SA_RESTART act.sa_flags = SA_RESTART; # endif for (i = 0; i < sizeof(ezstream_signals) / sizeof(int); i++) { if (sigaction(ezstream_signals[i], &act, NULL) == -1) { printf("%s: sigaction(): %s\n", __progname, strerror(errno)); return (ez_shutdown(1)); } } /* * Ignore SIGPIPE, which has been seen to give a long-running ezstream * process trouble. EOF and/or EPIPE are also easier to handle. */ act.sa_handler = SIG_IGN; if (sigaction(SIGPIPE, &act, NULL) == -1) { printf("%s: sigaction(): %s\n", __progname, strerror(errno)); return (ez_shutdown(1)); } #endif /* HAVE_SIGNALS */ if (shout_open(shout) == SHOUTERR_SUCCESS) { int ret; printf("%s: Connected to http://%s:%hu%s\n", __progname, host, port, mount); if (pezConfig->fileNameIsProgram || strrcasecmp(pezConfig->fileName, ".m3u") == 0 || strrcasecmp(pezConfig->fileName, ".txt") == 0) playlistMode = 1; else playlistMode = 0; if (vFlag && pezConfig->fileNameIsProgram) printf("%s: Using program '%s' to get filenames for streaming\n", __progname, pezConfig->fileName); do { if (playlistMode) { ret = streamPlaylist(shout, pezConfig->fileName); } else { ret = streamFile(shout, pezConfig->fileName); } if (quit) break; if (pezConfig->streamOnce) break; } while (ret); shout_close(shout); } else printf("%s: Connection to http://%s:%hu%s failed: %s\n", __progname, host, port, mount, shout_get_error(shout)); if (quit) printf("\r%s: SIGINT or SIGTERM received\n", __progname); if (vFlag) printf("%s: Exiting ...\n", __progname); xfree(host); xfree(mount); playlist_free(&playlist); return (ez_shutdown(0)); }
int main(int argc, char *argv[]) { char *ampersand; App *app; unsigned char *equals; HTTPNameValue *h; HTTPNameValue *headers; char *name; unsigned char *newURL; char *p; char *query; unsigned char *referer; URL *u; unsigned char *url; char *verbose; char *version; View *view; if (!netInit()) { return 1; } if (!threadInit()) { return 1; } referer = NULL; url = NULL; verbose = "?url="; query = getenv("QUERY_STRING"); app = appAlloc(); app->html = cgiviewHTML; app->htmlAttributeName = cgiviewHTMLAttributeName; app->htmlAttributeValue = cgiviewHTMLAttributeValue; app->htmlDeclaration = cgiviewHTMLDeclaration; app->htmlProcessingInstruction = cgiviewHTMLProcessingInstruction; app->htmlTag = cgiviewHTMLTag; app->htmlText = cgiviewHTMLText; app->httpRequest = cgiviewHTTPRequest; app->httpRequestHeaderName = cgiviewHTTPRequestHeaderName; app->httpRequestHeaderValue = cgiviewHTTPRequestHeaderValue; app->httpResponse = cgiviewHTTPResponse; app->httpResponseBody = cgiviewHTTPResponseBody; app->httpResponseHeaderName = cgiviewHTTPResponseHeaderName; app->httpResponseHeaderValue = cgiviewHTTPResponseHeaderValue; app->printHTML = cgiviewPrintHTML; view = &app->view; view->out = stdout; freopen("/dev/null", "w", stderr); fprintf(view->out, "Content-Type: text/html\n"); fprintf(view->out, "\n"); if (query) { p = query; do { name = p; ampersand = strchr(p, '&'); if (ampersand) { *ampersand = 0; p = ampersand + 1; } equals = (unsigned char *) strchr(name, '='); if (equals) { *equals = 0; if (!strcmp(name, "referer")) { referer = equals + 1; urlDecode(referer); } else if (!strcmp(name, "url")) { url = equals + 1; urlDecode(url); } else if (!strcmp(name, "verbose")) { verbose = "?verbose=on&url="; viewVerbose(); } } } while (ampersand); } else if (argc > 1) { url = (unsigned char *) argv[1]; } else { fprintf(view->out, "no environment variable QUERY_STRING<br>\n"); fprintf(view->out, "and no arg passed<br>\n"); return 1; } if (url && (*url)) { fprintf(view->out, "<html><head><title>View %s</title>", url); fprintf(view->out, "<link rel=stylesheet href=view.css>"); fprintf(view->out, "</head><body>\n"); viewReport(app, "input url:"); viewReport(app, (char *) url); viewReportHTML(app, "<hr>"); u = urlParse(url); if ( ((!u->scheme)||(!strcmp((char *) u->scheme, "http"))) && (!u->host) && (*url != '/') ) { newURL = calloc(strlen((char *) url) + 3, 1); if (!newURL) { viewReport(app, "calloc failed"); return 1; } strcpy((char *) newURL, "//"); strcat((char *) newURL, (char *) url); } else { newURL = copyString(url); } urlFree(u); u = urlParse(newURL); if ( ( (!u->scheme) || (!strcmp((char *) u->scheme, "http")) ) && (!*u->path) ) { url = newURL; newURL = calloc(strlen((char *) url) + 2, 1); if (!newURL) { viewReport(app, "calloc failed"); return 1; } strcpy((char *) newURL, (char *) url); free(url); strcat((char *) newURL, "/"); } urlFree(u); u = urlRelative( (unsigned char *) "http://www.mozilla.org/index.html", newURL); free(newURL); viewReport(app, "fully qualified url:"); viewReport(app, (char *) u->url); viewReportHTML(app, "<hr>"); if (!strcmp((char *) u->scheme, "http")) { version = NULL; headers = cgiviewGetEnv(app, (char *) referer, verbose, &version); if (!headers) { return 1; } httpFree(httpProcess(app, u, version, headers)); h = headers; while (h->name) { free(h->name); free(h->value); h++; } free(headers); } else { fprintf ( view->out, "Sorry, %s URLs are not supported yet. " "Only http URLs are supported.", u->scheme ); } fprintf(view->out, "</body></html>\n"); } else { fprintf(view->out, "<html><head><title>SniffURI Error</title>"); fprintf(view->out, "</head><body><h2>Please enter a URI</h2>"); fprintf(view->out, "<a href=index.html>Go Back</a>"); fprintf(view->out, "</body></html>"); } exit(0); return 1; }
CString ExecuteHTTPGet (const CString &sInput) { // Parse the input char *pPos = sInput.GetParsePointer() + STR_HTTP_GET_PREFIX.GetLength(); // Parse the URL CString sHost; CString sPath; if (!urlParse(pPos, NULL, &sHost, &sPath)) return CString("Invalid URL."); // If no host, then local host if (sHost.IsEmpty()) sHost = CString("localhost"); // Connect CSocket theSocket; if (!theSocket.Connect(sHost, 80)) return strPattern("Unable to connect to: %s.", sHost); // Compose a request CHTTPMessage Request; Request.InitRequest(CString("GET"), sPath); Request.AddHeader(HEADER_HOST, sHost); Request.AddHeader(HEADER_CONNECTION, CString("keep-alive")); #ifdef DEBUG_REQUEST_FRAGMENT_X Request.AddHeader(HEADER_USER_AGENT, CString("AI1/1.0 (This is a test of the header parsing system in Hexarc. There is probably a bug in which splitting the header across packets will cause failure of the HTTP parsing engine.)")); #else Request.AddHeader(HEADER_USER_AGENT, CString("AI1/1.0")); #endif // Send the request CBuffer Buffer(4096); Request.WriteToBuffer(Buffer); #ifdef DEBUG_REQUEST_FRAGMENT int iTotalLen = Buffer.GetLength(); int iSplit = 105; if (iSplit < iTotalLen) { printf("Split at %d bytes\n", iSplit); CString sPart(Buffer.GetPointer(), iSplit); printf("%s\n", (LPSTR)sPart); theSocket.Write(Buffer.GetPointer(), iSplit); ::Sleep(10); theSocket.Write(Buffer.GetPointer() + iSplit, iTotalLen - iSplit); } else theSocket.Write(Buffer.GetPointer(), Buffer.GetLength()); #else theSocket.Write(Buffer.GetPointer(), Buffer.GetLength()); #endif // Now read the response. We build up a buffer to hold it. CHTTPMessage Response; CBuffer ResponseBuff; // Keep reading until we've got enough (or until the connection drops) while (!Response.IsMessageComplete()) { CBuffer TempBuffer(8192); // Read int iBytesRead = theSocket.Read(TempBuffer.GetPointer(), 8192); TempBuffer.SetLength(iBytesRead); // If we're no making progress, then we're done if (iBytesRead == 0) return strPattern("Unable to read entire message."); // Add to entire buffer ResponseBuff.Write(TempBuffer.GetPointer(), iBytesRead); // Parse to see if we're done if (!Response.InitFromPartialBuffer(TempBuffer)) return strPattern("Unable to parse HTTP message."); } // Done theSocket.Disconnect(); return CString(ResponseBuff.GetPointer(), ResponseBuff.GetLength()); }
void ParseURL(const wchar_t *url, wstring *scheme, wstring *hostName, unsigned short *port, wstring *path, wstring *query, wstring *userName, wstring *password) { assert(url); wstring urlParse(url); //Parse scheme name const size_t delimScheme = urlParse.find(L"://"); if (delimScheme != string::npos) { if (scheme) { *scheme = urlParse.substr(0, delimScheme); transform(scheme->begin(), scheme->end(), scheme->begin(), tolower); } urlParse.erase(0, delimScheme + sizeof(L"://") / sizeof(wchar_t) - 1); } //Parse path const size_t delimPath = urlParse.find(L'/'); if (delimPath != string::npos) { wstring parsePath = urlParse.substr(delimPath); urlParse.erase(delimPath); //Parse query const size_t delimQuery = parsePath.rfind(L'?'); if (delimQuery != string::npos) { if (query) { *query = parsePath.substr(delimQuery); } parsePath.erase(delimQuery); } if (path) { *path = parsePath; } } if (path && path->empty()) { *path = L'/'; } //Parse user name/password const size_t delimLogin = urlParse.rfind(L'@'); if (delimLogin != string::npos) { wstring parseLogin = urlParse.substr(0, delimLogin); const size_t delimPwd = parseLogin.rfind(L':'); if (delimPwd != string::npos) { if (password) { *password = parseLogin.substr(delimPwd + 1); } parseLogin.erase(delimPwd); } if (userName) { *userName = parseLogin; } urlParse.erase(0, delimLogin + 1); } //Parse port if (port) { *port = 0; } const size_t delimPort = urlParse.rfind(L':'); if (delimPort != string::npos) { if (port) { const wstring portNum = urlParse.substr(delimPort + 1); *port = static_cast<unsigned short>(_wtoi(portNum.c_str())); } urlParse.erase(delimPort); } if (hostName) { *hostName = urlParse; } }
static void icpHandleIcpV2(int fd, struct sockaddr_in from, char *buf, int len) { icp_common_t header; StoreEntry *entry = NULL; char *url = NULL; const cache_key *key; request_t *icp_request = NULL; int allow = 0; aclCheck_t checklist; icp_common_t *reply; int src_rtt = 0; u_num32 flags = 0; int rtt = 0; int hops = 0; xmemcpy(&header, buf, sizeof(icp_common_t)); /* * Only these fields need to be converted */ header.length = ntohs(header.length); header.reqnum = ntohl(header.reqnum); header.flags = ntohl(header.flags); header.pad = ntohl(header.pad); /* * Length field should match the number of bytes read */ if (len != header.length) { debug(12, 3) ("icpHandleIcpV2: ICP message is too small\n"); return; } switch (header.opcode) { case ICP_QUERY: /* We have a valid packet */ url = buf + sizeof(icp_common_t) + sizeof(u_num32); if (strpbrk(url, w_space)) { url = rfc1738_escape(url); reply = icpCreateMessage(ICP_ERR, 0, url, header.reqnum, 0); icpUdpSend(fd, &from, reply, LOG_UDP_INVALID, 0); break; } if ((icp_request = urlParse(METHOD_GET, url)) == NULL) { reply = icpCreateMessage(ICP_ERR, 0, url, header.reqnum, 0); icpUdpSend(fd, &from, reply, LOG_UDP_INVALID, 0); break; } memset(&checklist, '\0', sizeof(checklist)); checklist.src_addr = from.sin_addr; checklist.my_addr = no_addr; checklist.request = icp_request; allow = aclCheckFast(Config.accessList.icp, &checklist); if (!allow) { debug(12, 2) ("icpHandleIcpV2: Access Denied for %s by %s.\n", inet_ntoa(from.sin_addr), AclMatchedName); if (clientdbCutoffDenied(from.sin_addr)) { /* * count this DENIED query in the clientdb, even though * we're not sending an ICP reply... */ clientdbUpdate(from.sin_addr, LOG_UDP_DENIED, PROTO_ICP, 0); } else { reply = icpCreateMessage(ICP_DENIED, 0, url, header.reqnum, 0); icpUdpSend(fd, &from, reply, LOG_UDP_DENIED, 0); } break; } if (header.flags & ICP_FLAG_SRC_RTT) { rtt = netdbHostRtt(icp_request->host); hops = netdbHostHops(icp_request->host); src_rtt = ((hops & 0xFFFF) << 16) | (rtt & 0xFFFF); if (rtt) flags |= ICP_FLAG_SRC_RTT; } /* The peer is allowed to use this cache */ entry = storeGetPublic(url, METHOD_GET); debug(12, 5) ("icpHandleIcpV2: OPCODE %s\n", icp_opcode_str[header.opcode]); if (icpCheckUdpHit(entry, icp_request)) { reply = icpCreateMessage(ICP_HIT, flags, url, header.reqnum, src_rtt); icpUdpSend(fd, &from, reply, LOG_UDP_HIT, 0); break; } if (Config.onoff.test_reachability && rtt == 0) { if ((rtt = netdbHostRtt(icp_request->host)) == 0) netdbPingSite(icp_request->host); } /* if store is rebuilding, return a UDP_HIT, but not a MISS */ if (store_dirs_rebuilding && opt_reload_hit_only) { reply = icpCreateMessage(ICP_MISS_NOFETCH, flags, url, header.reqnum, src_rtt); icpUdpSend(fd, &from, reply, LOG_UDP_MISS_NOFETCH, 0); } else if (hit_only_mode_until > squid_curtime) { reply = icpCreateMessage(ICP_MISS_NOFETCH, flags, url, header.reqnum, src_rtt); icpUdpSend(fd, &from, reply, LOG_UDP_MISS_NOFETCH, 0); } else if (Config.onoff.test_reachability && rtt == 0) { reply = icpCreateMessage(ICP_MISS_NOFETCH, flags, url, header.reqnum, src_rtt); icpUdpSend(fd, &from, reply, LOG_UDP_MISS_NOFETCH, 0); } else { reply = icpCreateMessage(ICP_MISS, flags, url, header.reqnum, src_rtt); icpUdpSend(fd, &from, reply, LOG_UDP_MISS, 0); } break; case ICP_HIT: #if ALLOW_SOURCE_PING case ICP_SECHO: #endif case ICP_DECHO: case ICP_MISS: case ICP_DENIED: case ICP_MISS_NOFETCH: if (neighbors_do_private_keys && header.reqnum == 0) { debug(12, 0) ("icpHandleIcpV2: Neighbor %s returned reqnum = 0\n", inet_ntoa(from.sin_addr)); debug(12, 0) ("icpHandleIcpV2: Disabling use of private keys\n"); neighbors_do_private_keys = 0; } url = buf + sizeof(icp_common_t); debug(12, 3) ("icpHandleIcpV2: %s from %s for '%s'\n", icp_opcode_str[header.opcode], inet_ntoa(from.sin_addr), url); key = icpGetCacheKey(url, (int) header.reqnum); /* call neighborsUdpAck even if ping_status != PING_WAITING */ neighborsUdpAck(key, &header, &from); break; case ICP_INVALID: case ICP_ERR: break; default: debug(12, 0) ("icpHandleIcpV2: UNKNOWN OPCODE: %d from %s\n", header.opcode, inet_ntoa(from.sin_addr)); break; } if (icp_request) requestDestroy(icp_request); }