/* Return a list of comma-separated names of supported encodings. */ char *Curl_all_content_encodings(void) { size_t len = 0; const content_encoding * const *cep; const content_encoding *ce; char *ace; for(cep = encodings; *cep; cep++) { ce = *cep; if(!strcasecompare(ce->name, CONTENT_ENCODING_DEFAULT)) len += strlen(ce->name) + 2; } if(!len) return strdup(CONTENT_ENCODING_DEFAULT); ace = malloc(len); if(ace) { char *p = ace; for(cep = encodings; *cep; cep++) { ce = *cep; if(!strcasecompare(ce->name, CONTENT_ENCODING_DEFAULT)) { strcpy(p, ce->name); p += strlen(p); *p++ = ','; *p++ = ' '; } } p[-2] = '\0'; } return ace; }
/* * Check if there's a session ID for the given connection in the cache, and if * there's one suitable, it is provided. Returns TRUE when no entry matched. */ bool Curl_ssl_getsessionid(struct connectdata *conn, void **ssl_sessionid, size_t *idsize, /* set 0 if unknown */ int sockindex) { struct curl_ssl_session *check; struct Curl_easy *data = conn->data; size_t i; long *general_age; bool no_match = TRUE; const bool isProxy = CONNECT_PROXY_SSL(); struct ssl_primary_config * const ssl_config = isProxy ? &conn->proxy_ssl_config : &conn->ssl_config; const char * const name = isProxy ? conn->http_proxy.host.name : conn->host.name; int port = isProxy ? (int)conn->port : conn->remote_port; *ssl_sessionid = NULL; DEBUGASSERT(SSL_SET_OPTION(primary.sessionid)); if(!SSL_SET_OPTION(primary.sessionid)) /* session ID re-use is disabled */ return TRUE; /* Lock if shared */ if(SSLSESSION_SHARED(data)) general_age = &data->share->sessionage; else general_age = &data->state.sessionage; for(i = 0; i < data->set.general_ssl.max_ssl_sessions; i++) { check = &data->state.session[i]; if(!check->sessionid) /* not session ID means blank entry */ continue; if(strcasecompare(name, check->name) && ((!conn->bits.conn_to_host && !check->conn_to_host) || (conn->bits.conn_to_host && check->conn_to_host && strcasecompare(conn->conn_to_host.name, check->conn_to_host))) && ((!conn->bits.conn_to_port && check->conn_to_port == -1) || (conn->bits.conn_to_port && check->conn_to_port != -1 && conn->conn_to_port == check->conn_to_port)) && (port == check->remote_port) && strcasecompare(conn->handler->scheme, check->scheme) && Curl_ssl_config_matches(ssl_config, &check->ssl_config)) { /* yes, we have a session ID! */ (*general_age)++; /* increase general age */ check->age = *general_age; /* set this as used in this age */ *ssl_sessionid = check->sessionid; if(idsize) *idsize = check->idsize; no_match = FALSE; break; } } return no_match; }
static CURLcode auth_digest_get_qop_values(const char *options, int *value) { char *tmp; char *token; char *tok_buf; /* Initialise the output */ *value = 0; /* Tokenise the list of qop values. Use a temporary clone of the buffer since strtok_r() ruins it. */ tmp = strdup(options); if(!tmp) return CURLE_OUT_OF_MEMORY; token = strtok_r(tmp, ",", &tok_buf); while(token != NULL) { if(strcasecompare(token, DIGEST_QOP_VALUE_STRING_AUTH)) *value |= DIGEST_QOP_VALUE_AUTH; else if(strcasecompare(token, DIGEST_QOP_VALUE_STRING_AUTH_INT)) *value |= DIGEST_QOP_VALUE_AUTH_INT; else if(strcasecompare(token, DIGEST_QOP_VALUE_STRING_AUTH_CONF)) *value |= DIGEST_QOP_VALUE_AUTH_CONF; token = strtok_r(NULL, ",", &tok_buf); } free(tmp); return CURLE_OK; }
static int do_file_type(const char *type) { if(!type || !type[0]) return SSL_FILETYPE_PEM; if(strcasecompare(type, "PEM")) return SSL_FILETYPE_PEM; if(strcasecompare(type, "DER")) return SSL_FILETYPE_ASN1; return -1; }
static enum alpnid alpn2alpnid(char *name) { if(strcasecompare(name, "h1")) return ALPN_h1; if(strcasecompare(name, "h2")) return ALPN_h2; if(strcasecompare(name, "h2c")) return ALPN_h2c; if(strcasecompare(name, "h3")) return ALPN_h3; return ALPN_none; /* unknown, probably rubbish input */ }
/* * Check if there's a session ID for the given connection in the cache, and if * there's one suitable, it is provided. Returns TRUE when no entry matched. */ bool Curl_ssl_getsessionid(struct connectdata *conn, void **ssl_sessionid, size_t *idsize) /* set 0 if unknown */ { struct curl_ssl_session *check; struct Curl_easy *data = conn->data; size_t i; long *general_age; bool no_match = TRUE; *ssl_sessionid = NULL; DEBUGASSERT(conn->ssl_config.sessionid); if(!conn->ssl_config.sessionid) /* session ID re-use is disabled */ return TRUE; /* Lock if shared */ if(SSLSESSION_SHARED(data)) general_age = &data->share->sessionage; else general_age = &data->state.sessionage; for(i = 0; i < data->set.ssl.max_ssl_sessions; i++) { check = &data->state.session[i]; if(!check->sessionid) /* not session ID means blank entry */ continue; if(strcasecompare(conn->host.name, check->name) && ((!conn->bits.conn_to_host && !check->conn_to_host) || (conn->bits.conn_to_host && check->conn_to_host && strcasecompare(conn->conn_to_host.name, check->conn_to_host))) && ((!conn->bits.conn_to_port && check->conn_to_port == -1) || (conn->bits.conn_to_port && check->conn_to_port != -1 && conn->conn_to_port == check->conn_to_port)) && (conn->remote_port == check->remote_port) && strcasecompare(conn->handler->scheme, check->scheme) && Curl_ssl_config_matches(&conn->ssl_config, &check->ssl_config)) { /* yes, we have a session ID! */ (*general_age)++; /* increase general age */ check->age = *general_age; /* set this as used in this age */ *ssl_sessionid = check->sessionid; if(idsize) *idsize = check->idsize; no_match = FALSE; break; } } return no_match; }
/* * Return TRUE on a match */ bool Curl_altsvc_lookup(struct altsvcinfo *asi, enum alpnid srcalpnid, const char *srchost, int srcport, enum alpnid *dstalpnid, const char **dsthost, int *dstport) { struct curl_llist_element *e; struct curl_llist_element *n; time_t now = time(NULL); DEBUGASSERT(asi); DEBUGASSERT(srchost); DEBUGASSERT(dsthost); for(e = asi->list.head; e; e = n) { struct altsvc *as = e->ptr; n = e->next; if(as->expires < now) { /* an expired entry, remove */ altsvc_free(as); continue; } if((as->srcalpnid == srcalpnid) && strcasecompare(as->srchost, srchost) && as->srcport == srcport) { /* match */ *dstalpnid = as->dstalpnid; *dsthost = as->dsthost; *dstport = as->dstport; return TRUE; } } return FALSE; }
static bool safe_strequal(char* str1, char* str2) { if(str1 && str2) /* both pointers point to something then compare them */ return (0 != strcasecompare(str1, str2)) ? TRUE : FALSE; else /* if both pointers are NULL then treat them as equal */ return (!str1 && !str2) ? TRUE : FALSE; }
/* * Curl_override_sspi_http_realm() * * This is used to populate the domain in a SSPI identity structure * The realm is extracted from the challenge message and used as the * domain if it is not already explicitly set. * * Parameters: * * chlg [in] - The challenge message. * identity [in/out] - The identity structure. * * Returns CURLE_OK on success. */ CURLcode Curl_override_sspi_http_realm(const char *chlg, SEC_WINNT_AUTH_IDENTITY *identity) { xcharp_u domain, dup_domain; /* If domain is blank or unset, check challenge message for realm */ if(!identity->Domain || !identity->DomainLength) { for(;;) { char value[DIGEST_MAX_VALUE_LENGTH]; char content[DIGEST_MAX_CONTENT_LENGTH]; /* Pass all additional spaces here */ while(*chlg && ISSPACE(*chlg)) chlg++; /* Extract a value=content pair */ if(Curl_auth_digest_get_pair(chlg, value, content, &chlg)) { if(strcasecompare(value, "realm")) { /* Setup identity's domain and length */ domain.tchar_ptr = Curl_convert_UTF8_to_tchar((char *) content); if(!domain.tchar_ptr) return CURLE_OUT_OF_MEMORY; dup_domain.tchar_ptr = _tcsdup(domain.tchar_ptr); if(!dup_domain.tchar_ptr) { Curl_unicodefree(domain.tchar_ptr); return CURLE_OUT_OF_MEMORY; } free(identity->Domain); identity->Domain = dup_domain.tbyte_ptr; identity->DomainLength = curlx_uztoul(_tcslen(dup_domain.tchar_ptr)); dup_domain.tchar_ptr = NULL; Curl_unicodefree(domain.tchar_ptr); } else { /* Unknown specifier, ignore it! */ } } else break; /* We're done here */ /* Pass all additional spaces here */ while(*chlg && ISSPACE(*chlg)) chlg++; /* Allow the list to be comma-separated */ if(',' == *chlg) chlg++; } } return CURLE_OK; }
static int checkmonth(const char *check) { int i; const char * const *what; bool found = FALSE; what = &Curl_month[0]; for(i = 0; i<12; i++) { if(strcasecompare(check, what[0])) { found = TRUE; break; } what++; } return found?i:-1; /* return the offset or -1, no real offset is -1 */ }
static int checktz(const char *check) { unsigned int i; const struct tzinfo *what; bool found = FALSE; what = tz; for(i = 0; i< sizeof(tz)/sizeof(tz[0]); i++) { if(strcasecompare(check, what->name)) { found = TRUE; break; } what++; } return found?what->offset*60:-1; }
/* altsvc_flush() removes all alternatives for this source origin from the list */ static void altsvc_flush(struct altsvcinfo *asi, enum alpnid srcalpnid, const char *srchost, unsigned short srcport) { struct curl_llist_element *e; struct curl_llist_element *n; for(e = asi->list.head; e; e = n) { struct altsvc *as = e->ptr; n = e->next; if((srcalpnid == as->srcalpnid) && (srcport == as->srcport) && strcasecompare(srchost, as->srchost)) { Curl_llist_remove(&asi->list, e, NULL); altsvc_free(as); asi->num--; } } }
bool Curl_if_is_interface_name(const char *interf) { bool result = FALSE; struct ifaddrs *iface, *head; if(getifaddrs(&head) >= 0) { for(iface=head; iface != NULL; iface=iface->ifa_next) { if(strcasecompare(iface->ifa_name, interf)) { result = TRUE; break; } } freeifaddrs(head); } return result; }
static int checkday(const char *check, size_t len) { int i; const char * const *what; bool found = FALSE; if(len > 3) what = &weekday[0]; else what = &Curl_wkday[0]; for(i = 0; i<7; i++) { if(strcasecompare(check, what[0])) { found = TRUE; break; } what++; } return found?i:-1; }
/*************************************************************************** * * ContentTypeForFilename() * * Provides content type for filename if one of the known types (else * (either the prevtype or the default is returned). * * Returns some valid contenttype for filename. * ***************************************************************************/ static const char *ContentTypeForFilename(const char *filename, const char *prevtype) { const char *contenttype = NULL; unsigned int i; /* * No type was specified, we scan through a few well-known * extensions and pick the first we match! */ struct ContentType { const char *extension; const char *type; }; static const struct ContentType ctts[]={ {".gif", "image/gif"}, {".jpg", "image/jpeg"}, {".jpeg", "image/jpeg"}, {".txt", "text/plain"}, {".html", "text/html"}, {".xml", "application/xml"} }; if(prevtype) /* default to the previously set/used! */ contenttype = prevtype; else contenttype = HTTPPOST_CONTENTTYPE_DEFAULT; if(filename) { /* in case a NULL was passed in */ for(i=0; i<sizeof(ctts)/sizeof(ctts[0]); i++) { if(strlen(filename) >= strlen(ctts[i].extension)) { if(strcasecompare(filename + strlen(filename) - strlen(ctts[i].extension), ctts[i].extension)) { contenttype = ctts[i].type; break; } } } } /* we have a contenttype by now */ return contenttype; }
static bool tailmatch(const char *cooke_domain, const char *hostname) { size_t cookie_domain_len = strlen(cooke_domain); size_t hostname_len = strlen(hostname); if(hostname_len < cookie_domain_len) return FALSE; if(!strcasecompare(cooke_domain, hostname + hostname_len-cookie_domain_len)) return FALSE; /* A lead char of cookie_domain is not '.'. RFC6265 4.1.2.3. The Domain Attribute says: For example, if the value of the Domain attribute is "example.com", the user agent will include the cookie in the Cookie header when making HTTP requests to example.com, www.example.com, and www.corp.example.com. */ if(hostname_len == cookie_domain_len) return TRUE; if('.' == *(hostname + hostname_len - cookie_domain_len - 1)) return TRUE; return FALSE; }
/* * Curl_altsvc_parse() takes an incoming alt-svc response header and stores * the data correctly in the cache. * * 'value' points to the header *value*. That's contents to the right of the * header name. */ CURLcode Curl_altsvc_parse(struct Curl_easy *data, struct altsvcinfo *asi, const char *value, enum alpnid srcalpnid, const char *srchost, unsigned short srcport) { const char *p = value; size_t len; enum alpnid dstalpnid = srcalpnid; /* the same by default */ char namebuf[MAX_ALTSVC_HOSTLEN] = ""; char alpnbuf[MAX_ALTSVC_ALPNLEN] = ""; struct altsvc *as; unsigned short dstport = srcport; /* the same by default */ const char *semip; time_t maxage = 24 * 3600; /* default is 24 hours */ bool persist = FALSE; CURLcode result = getalnum(&p, alpnbuf, sizeof(alpnbuf)); if(result) return result; DEBUGASSERT(asi); /* Flush all cached alternatives for this source origin, if any */ altsvc_flush(asi, srcalpnid, srchost, srcport); /* "clear" is a magic keyword */ if(strcasecompare(alpnbuf, "clear")) { /* TODO: clear whatever it is it should clear */ return CURLE_OK; } /* The 'ma' and 'persist' flags are annoyingly meant for all alternatives but are set after the list on the line. Scan for the semicolons and get those fields first! */ semip = p; do { semip = strchr(semip, ';'); if(semip) { char option[32]; unsigned long num; char *end_ptr; semip++; /* pass the semicolon */ result = getalnum(&semip, option, sizeof(option)); if(result) break; while(*semip && ISBLANK(*semip)) semip++; if(*semip != '=') continue; semip++; num = strtoul(semip, &end_ptr, 10); if(num < ULONG_MAX) { if(strcasecompare("ma", option)) maxage = num; else if(strcasecompare("persist", option) && (num == 1)) persist = TRUE; } semip = end_ptr; } } while(semip); do { if(*p == '=') { /* [protocol]="[host][:port]" */ dstalpnid = alpn2alpnid(alpnbuf); if(!dstalpnid) { infof(data, "Unknown alt-svc protocol \"%s\", ignoring...\n", alpnbuf); return CURLE_OK; } p++; if(*p == '\"') { const char *dsthost; p++; if(*p != ':') { /* host name starts here */ const char *hostp = p; while(*p && (ISALNUM(*p) || (*p == '.') || (*p == '-'))) p++; len = p - hostp; if(!len || (len >= MAX_ALTSVC_HOSTLEN)) return CURLE_BAD_FUNCTION_ARGUMENT; /* TODO: improve error code */ memcpy(namebuf, hostp, len); namebuf[len] = 0; dsthost = namebuf; } else { /* no destination name, use source host */ dsthost = srchost; } if(*p == ':') { /* a port number */ char *end_ptr; unsigned long port = strtoul(++p, &end_ptr, 10); if(port > USHRT_MAX || end_ptr == p || *end_ptr != '\"') { infof(data, "Unknown alt-svc port number, ignoring...\n"); return CURLE_OK; } p = end_ptr; dstport = curlx_ultous(port); } if(*p++ != '\"') return CURLE_BAD_FUNCTION_ARGUMENT; as = altsvc_createid(srchost, dsthost, srcalpnid, dstalpnid, srcport, dstport); if(as) { /* TODO: the expires time also needs to take the Age: value (if any) into account. [See RFC 7838 section 3.1] */ as->expires = maxage + time(NULL); as->persist = persist; Curl_llist_insert_next(&asi->list, asi->list.tail, as, &as->node); asi->num++; /* one more entry */ infof(data, "Added alt-svc: %s:%d over %s\n", dsthost, dstport, Curl_alpnid2str(dstalpnid)); } } /* after the double quote there can be a comma if there's another string or a semicolon if no more */ if(*p == ',') { /* comma means another alternative is presented */ p++; result = getalnum(&p, alpnbuf, sizeof(alpnbuf)); if(result) /* failed to parse, but since we already did at least one host we return OK */ return CURLE_OK; } } } while(*p && (*p != ';') && (*p != '\n') && (*p != '\r')); return CURLE_OK; }
struct Cookie * Curl_cookie_add(struct Curl_easy *data, /* The 'data' pointer here may be NULL at times, and thus must only be used very carefully for things that can deal with data being NULL. Such as infof() and similar */ struct CookieInfo *c, bool httpheader, /* TRUE if HTTP header-style line */ bool noexpire, /* if TRUE, skip remove_expired() */ char *lineptr, /* first character of the line */ const char *domain, /* default domain */ const char *path) /* full path used when this cookie is set, used to get default path for the cookie unless set */ { struct Cookie *clist; struct Cookie *co; struct Cookie *lastc = NULL; time_t now = time(NULL); bool replace_old = FALSE; bool badcookie = FALSE; /* cookies are good by default. mmmmm yummy */ size_t myhash; #ifdef USE_LIBPSL const psl_ctx_t *psl; #endif #ifdef CURL_DISABLE_VERBOSE_STRINGS (void)data; #endif /* First, alloc and init a new struct for it */ co = calloc(1, sizeof(struct Cookie)); if(!co) return NULL; /* bail out if we're this low on memory */ if(httpheader) { /* This line was read off a HTTP-header */ char name[MAX_NAME]; char what[MAX_NAME]; const char *ptr; const char *semiptr; size_t linelength = strlen(lineptr); if(linelength > MAX_COOKIE_LINE) { /* discard overly long lines at once */ free(co); return NULL; } semiptr = strchr(lineptr, ';'); /* first, find a semicolon */ while(*lineptr && ISBLANK(*lineptr)) lineptr++; ptr = lineptr; do { /* we have a <what>=<this> pair or a stand-alone word here */ name[0] = what[0] = 0; /* init the buffers */ if(1 <= sscanf(ptr, "%" MAX_NAME_TXT "[^;\r\n=] =%" MAX_NAME_TXT "[^;\r\n]", name, what)) { /* Use strstore() below to properly deal with received cookie headers that have the same string property set more than once, and then we use the last one. */ const char *whatptr; bool done = FALSE; bool sep; size_t len = strlen(what); size_t nlen = strlen(name); const char *endofn = &ptr[ nlen ]; if(nlen >= (MAX_NAME-1) || len >= (MAX_NAME-1) || ((nlen + len) > MAX_NAME)) { /* too long individual name or contents, or too long combination of name + contents. Chrome and Firefox support 4095 or 4096 bytes combo. */ freecookie(co); infof(data, "oversized cookie dropped, name/val %d + %d bytes\n", nlen, len); return NULL; } /* name ends with a '=' ? */ sep = (*endofn == '=')?TRUE:FALSE; if(nlen) { endofn--; /* move to the last character */ if(ISBLANK(*endofn)) { /* skip trailing spaces in name */ while(*endofn && ISBLANK(*endofn) && nlen) { endofn--; nlen--; } name[nlen] = 0; /* new end of name */ } } /* Strip off trailing whitespace from the 'what' */ while(len && ISBLANK(what[len-1])) { what[len-1] = 0; len--; } /* Skip leading whitespace from the 'what' */ whatptr = what; while(*whatptr && ISBLANK(*whatptr)) whatptr++; if(!co->name && sep) { /* The very first name/value pair is the actual cookie name */ co->name = strdup(name); co->value = strdup(whatptr); if(!co->name || !co->value) { badcookie = TRUE; break; } } else if(!len) { /* this was a "<name>=" with no content, and we must allow 'secure' and 'httponly' specified this weirdly */ done = TRUE; if(strcasecompare("secure", name)) co->secure = TRUE; else if(strcasecompare("httponly", name)) co->httponly = TRUE; else if(sep) /* there was a '=' so we're not done parsing this field */ done = FALSE; } if(done) ; else if(strcasecompare("path", name)) { strstore(&co->path, whatptr); if(!co->path) { badcookie = TRUE; /* out of memory bad */ break; } free(co->spath); /* if this is set again */ co->spath = sanitize_cookie_path(co->path); if(!co->spath) { badcookie = TRUE; /* out of memory bad */ break; } } else if(strcasecompare("domain", name)) { bool is_ip; /* Now, we make sure that our host is within the given domain, or the given domain is not valid and thus cannot be set. */ if('.' == whatptr[0]) whatptr++; /* ignore preceding dot */ #ifndef USE_LIBPSL /* * Without PSL we don't know when the incoming cookie is set on a * TLD or otherwise "protected" suffix. To reduce risk, we require a * dot OR the exact host name being "localhost". */ { const char *dotp; /* check for more dots */ dotp = strchr(whatptr, '.'); if(!dotp && !strcasecompare("localhost", whatptr)) domain = ":"; } #endif is_ip = isip(domain ? domain : whatptr); if(!domain || (is_ip && !strcmp(whatptr, domain)) || (!is_ip && tailmatch(whatptr, domain))) { strstore(&co->domain, whatptr); if(!co->domain) { badcookie = TRUE; break; } if(!is_ip) co->tailmatch = TRUE; /* we always do that if the domain name was given */ } else { /* we did not get a tailmatch and then the attempted set domain is not a domain to which the current host belongs. Mark as bad. */ badcookie = TRUE; infof(data, "skipped cookie with bad tailmatch domain: %s\n", whatptr); } } else if(strcasecompare("version", name)) { strstore(&co->version, whatptr); if(!co->version) { badcookie = TRUE; break; } } else if(strcasecompare("max-age", name)) { /* Defined in RFC2109: Optional. The Max-Age attribute defines the lifetime of the cookie, in seconds. The delta-seconds value is a decimal non- negative integer. After delta-seconds seconds elapse, the client should discard the cookie. A value of zero means the cookie should be discarded immediately. */ strstore(&co->maxage, whatptr); if(!co->maxage) { badcookie = TRUE; break; } } else if(strcasecompare("expires", name)) { strstore(&co->expirestr, whatptr); if(!co->expirestr) { badcookie = TRUE; break; } } /* else this is the second (or more) name we don't know about! */ } else { /* this is an "illegal" <what>=<this> pair */ } if(!semiptr || !*semiptr) { /* we already know there are no more cookies */ semiptr = NULL; continue; } ptr = semiptr + 1; while(*ptr && ISBLANK(*ptr)) ptr++; semiptr = strchr(ptr, ';'); /* now, find the next semicolon */ if(!semiptr && *ptr) /* There are no more semicolons, but there's a final name=value pair coming up */ semiptr = strchr(ptr, '\0'); } while(semiptr); if(co->maxage) { CURLofft offt; offt = curlx_strtoofft((*co->maxage == '\"')? &co->maxage[1]:&co->maxage[0], NULL, 10, &co->expires); if(offt == CURL_OFFT_FLOW) /* overflow, used max value */ co->expires = CURL_OFF_T_MAX; else if(!offt) { if(CURL_OFF_T_MAX - now < co->expires) /* would overflow */ co->expires = CURL_OFF_T_MAX; else co->expires += now; } } else if(co->expirestr) { /* Note that if the date couldn't get parsed for whatever reason, the cookie will be treated as a session cookie */ co->expires = curl_getdate(co->expirestr, NULL); /* Session cookies have expires set to 0 so if we get that back from the date parser let's add a second to make it a non-session cookie */ if(co->expires == 0) co->expires = 1; else if(co->expires < 0) co->expires = 0; } if(!badcookie && !co->domain) { if(domain) { /* no domain was given in the header line, set the default */ co->domain = strdup(domain); if(!co->domain) badcookie = TRUE; } } if(!badcookie && !co->path && path) { /* No path was given in the header line, set the default. Note that the passed-in path to this function MAY have a '?' and following part that MUST not be stored as part of the path. */ char *queryp = strchr(path, '?'); /* queryp is where the interesting part of the path ends, so now we want to the find the last */ char *endslash; if(!queryp) endslash = strrchr(path, '/'); else endslash = memrchr(path, '/', (size_t)(queryp - path)); if(endslash) { size_t pathlen = (size_t)(endslash-path + 1); /* include end slash */ co->path = malloc(pathlen + 1); /* one extra for the zero byte */ if(co->path) { memcpy(co->path, path, pathlen); co->path[pathlen] = 0; /* zero terminate */ co->spath = sanitize_cookie_path(co->path); if(!co->spath) badcookie = TRUE; /* out of memory bad */ } else badcookie = TRUE; } } if(badcookie || !co->name) { /* we didn't get a cookie name or a bad one, this is an illegal line, bail out */ freecookie(co); return NULL; } } else { /* This line is NOT a HTTP header style line, we do offer support for reading the odd netscape cookies-file format here */ char *ptr; char *firstptr; char *tok_buf = NULL; int fields; /* IE introduced HTTP-only cookies to prevent XSS attacks. Cookies marked with httpOnly after the domain name are not accessible from javascripts, but since curl does not operate at javascript level, we include them anyway. In Firefox's cookie files, these lines are preceded with #HttpOnly_ and then everything is as usual, so we skip 10 characters of the line.. */ if(strncmp(lineptr, "#HttpOnly_", 10) == 0) { lineptr += 10; co->httponly = TRUE; } if(lineptr[0]=='#') { /* don't even try the comments */ free(co); return NULL; } /* strip off the possible end-of-line characters */ ptr = strchr(lineptr, '\r'); if(ptr) *ptr = 0; /* clear it */ ptr = strchr(lineptr, '\n'); if(ptr) *ptr = 0; /* clear it */ firstptr = strtok_r(lineptr, "\t", &tok_buf); /* tokenize it on the TAB */ /* Now loop through the fields and init the struct we already have allocated */ for(ptr = firstptr, fields = 0; ptr && !badcookie; ptr = strtok_r(NULL, "\t", &tok_buf), fields++) { switch(fields) { case 0: if(ptr[0]=='.') /* skip preceding dots */ ptr++; co->domain = strdup(ptr); if(!co->domain) badcookie = TRUE; break; case 1: /* This field got its explanation on the 23rd of May 2001 by Andrés García: flag: A TRUE/FALSE value indicating if all machines within a given domain can access the variable. This value is set automatically by the browser, depending on the value you set for the domain. As far as I can see, it is set to true when the cookie says .domain.com and to false when the domain is complete www.domain.com */ co->tailmatch = strcasecompare(ptr, "TRUE")?TRUE:FALSE; break; case 2: /* It turns out, that sometimes the file format allows the path field to remain not filled in, we try to detect this and work around it! Andrés García made us aware of this... */ if(strcmp("TRUE", ptr) && strcmp("FALSE", ptr)) { /* only if the path doesn't look like a boolean option! */ co->path = strdup(ptr); if(!co->path) badcookie = TRUE; else { co->spath = sanitize_cookie_path(co->path); if(!co->spath) { badcookie = TRUE; /* out of memory bad */ } } break; } /* this doesn't look like a path, make one up! */ co->path = strdup("/"); if(!co->path) badcookie = TRUE; co->spath = strdup("/"); if(!co->spath) badcookie = TRUE; fields++; /* add a field and fall down to secure */ /* FALLTHROUGH */ case 3: co->secure = strcasecompare(ptr, "TRUE")?TRUE:FALSE; break; case 4: if(curlx_strtoofft(ptr, NULL, 10, &co->expires)) badcookie = TRUE; break; case 5: co->name = strdup(ptr); if(!co->name) badcookie = TRUE; break; case 6: co->value = strdup(ptr); if(!co->value) badcookie = TRUE; break; } } if(6 == fields) { /* we got a cookie with blank contents, fix it */ co->value = strdup(""); if(!co->value) badcookie = TRUE; else fields++; } if(!badcookie && (7 != fields)) /* we did not find the sufficient number of fields */ badcookie = TRUE; if(badcookie) { freecookie(co); return NULL; } } if(!c->running && /* read from a file */ c->newsession && /* clean session cookies */ !co->expires) { /* this is a session cookie since it doesn't expire! */ freecookie(co); return NULL; } co->livecookie = c->running; /* now, we have parsed the incoming line, we must now check if this superceeds an already existing cookie, which it may if the previous have the same domain and path as this */ /* at first, remove expired cookies */ if(!noexpire) remove_expired(c); #ifdef USE_LIBPSL /* Check if the domain is a Public Suffix and if yes, ignore the cookie. This needs a libpsl compiled with builtin data. */ if(domain && co->domain && !isip(co->domain)) { psl = psl_builtin(); if(psl && !psl_is_cookie_domain_acceptable(psl, domain, co->domain)) { infof(data, "cookie '%s' dropped, domain '%s' must not set cookies for '%s'\n", co->name, domain, co->domain); freecookie(co); return NULL; } } #endif myhash = cookiehash(co->domain); clist = c->cookies[myhash]; replace_old = FALSE; while(clist) { if(strcasecompare(clist->name, co->name)) { /* the names are identical */ if(clist->domain && co->domain) { if(strcasecompare(clist->domain, co->domain) && (clist->tailmatch == co->tailmatch)) /* The domains are identical */ replace_old = TRUE; } else if(!clist->domain && !co->domain) replace_old = TRUE; if(replace_old) { /* the domains were identical */ if(clist->spath && co->spath) { if(strcasecompare(clist->spath, co->spath)) { replace_old = TRUE; } else replace_old = FALSE; } else if(!clist->spath && !co->spath) replace_old = TRUE; else replace_old = FALSE; } if(replace_old && !co->livecookie && clist->livecookie) { /* Both cookies matched fine, except that the already present cookie is "live", which means it was set from a header, while the new one isn't "live" and thus only read from a file. We let live cookies stay alive */ /* Free the newcomer and get out of here! */ freecookie(co); return NULL; } if(replace_old) { co->next = clist->next; /* get the next-pointer first */ /* then free all the old pointers */ free(clist->name); free(clist->value); free(clist->domain); free(clist->path); free(clist->spath); free(clist->expirestr); free(clist->version); free(clist->maxage); *clist = *co; /* then store all the new data */ free(co); /* free the newly alloced memory */ co = clist; /* point to the previous struct instead */ /* We have replaced a cookie, now skip the rest of the list but make sure the 'lastc' pointer is properly set */ do { lastc = clist; clist = clist->next; } while(clist); break; } } lastc = clist; clist = clist->next; } if(c->running) /* Only show this when NOT reading the cookies from a file */ infof(data, "%s cookie %s=\"%s\" for domain %s, path %s, " "expire %" CURL_FORMAT_CURL_OFF_T "\n", replace_old?"Replaced":"Added", co->name, co->value, co->domain, co->path, co->expires); if(!replace_old) { /* then make the last item point on this new one */ if(lastc) lastc->next = co; else c->cookies[myhash] = co; c->numcookies++; /* one more cookie in the jar */ } return co; }
if2ip_result_t Curl_if2ip(int af, unsigned int remote_scope, unsigned int remote_scope_id, const char *interf, char *buf, int buf_size) { struct ifaddrs *iface, *head; if2ip_result_t res = IF2IP_NOT_FOUND; #ifndef ENABLE_IPV6 (void) remote_scope; #endif #if !defined(HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID) || \ !defined(ENABLE_IPV6) (void) remote_scope_id; #endif if(getifaddrs(&head) >= 0) { for(iface = head; iface != NULL; iface=iface->ifa_next) { if(iface->ifa_addr != NULL) { if(iface->ifa_addr->sa_family == af) { if(strcasecompare(iface->ifa_name, interf)) { void *addr; char *ip; char scope[12] = ""; char ipstr[64]; #ifdef ENABLE_IPV6 if(af == AF_INET6) { unsigned int scopeid = 0; unsigned int ifscope = Curl_ipv6_scope(iface->ifa_addr); if(ifscope != remote_scope) { /* We are interested only in interface addresses whose scope matches the remote address we want to connect to: global for global, link-local for link-local, etc... */ if(res == IF2IP_NOT_FOUND) res = IF2IP_AF_NOT_SUPPORTED; continue; } addr = &((struct sockaddr_in6 *)(void *)iface->ifa_addr)->sin6_addr; #ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID /* Include the scope of this interface as part of the address */ scopeid = ((struct sockaddr_in6 *)(void *)iface->ifa_addr) ->sin6_scope_id; /* If given, scope id should match. */ if(remote_scope_id && scopeid != remote_scope_id) { if(res == IF2IP_NOT_FOUND) res = IF2IP_AF_NOT_SUPPORTED; continue; } #endif if(scopeid) snprintf(scope, sizeof(scope), "%%%u", scopeid); } else #endif addr = &((struct sockaddr_in *)(void *)iface->ifa_addr)->sin_addr; res = IF2IP_FOUND; ip = (char *) Curl_inet_ntop(af, addr, ipstr, sizeof(ipstr)); snprintf(buf, buf_size, "%s%s", ip, scope); break; } } else if((res == IF2IP_NOT_FOUND) && strcasecompare(iface->ifa_name, interf)) { res = IF2IP_AF_NOT_SUPPORTED; } } } freeifaddrs(head); } return res; }
/* Make sure domain contains a dot or is localhost. */ static bool bad_domain(const char *domain) { return !strchr(domain, '.') && !strcasecompare(domain, "localhost"); }
/* * Curl_auth_decode_digest_http_message() * * This is used to decode a HTTP DIGEST challenge message into the seperate * attributes. * * Parameters: * * chlg [in] - The challenge message. * digest [in/out] - The digest data struct being used and modified. * * Returns CURLE_OK on success. */ CURLcode Curl_auth_decode_digest_http_message(const char *chlg, struct digestdata *digest) { bool before = FALSE; /* got a nonce before */ bool foundAuth = FALSE; bool foundAuthInt = FALSE; char *token = NULL; char *tmp = NULL; /* If we already have received a nonce, keep that in mind */ if(digest->nonce) before = TRUE; /* Clean up any former leftovers and initialise to defaults */ Curl_auth_digest_cleanup(digest); for(;;) { char value[DIGEST_MAX_VALUE_LENGTH]; char content[DIGEST_MAX_CONTENT_LENGTH]; /* Pass all additional spaces here */ while(*chlg && ISSPACE(*chlg)) chlg++; /* Extract a value=content pair */ if(Curl_auth_digest_get_pair(chlg, value, content, &chlg)) { if(strcasecompare(value, "nonce")) { free(digest->nonce); digest->nonce = strdup(content); if(!digest->nonce) return CURLE_OUT_OF_MEMORY; } else if(strcasecompare(value, "stale")) { if(strcasecompare(content, "true")) { digest->stale = TRUE; digest->nc = 1; /* we make a new nonce now */ } } else if(strcasecompare(value, "realm")) { free(digest->realm); digest->realm = strdup(content); if(!digest->realm) return CURLE_OUT_OF_MEMORY; } else if(strcasecompare(value, "opaque")) { free(digest->opaque); digest->opaque = strdup(content); if(!digest->opaque) return CURLE_OUT_OF_MEMORY; } else if(strcasecompare(value, "qop")) { char *tok_buf; /* Tokenize the list and choose auth if possible, use a temporary clone of the buffer since strtok_r() ruins it */ tmp = strdup(content); if(!tmp) return CURLE_OUT_OF_MEMORY; token = strtok_r(tmp, ",", &tok_buf); while(token != NULL) { if(strcasecompare(token, DIGEST_QOP_VALUE_STRING_AUTH)) { foundAuth = TRUE; } else if(strcasecompare(token, DIGEST_QOP_VALUE_STRING_AUTH_INT)) { foundAuthInt = TRUE; } token = strtok_r(NULL, ",", &tok_buf); } free(tmp); /* Select only auth or auth-int. Otherwise, ignore */ if(foundAuth) { free(digest->qop); digest->qop = strdup(DIGEST_QOP_VALUE_STRING_AUTH); if(!digest->qop) return CURLE_OUT_OF_MEMORY; } else if(foundAuthInt) { free(digest->qop); digest->qop = strdup(DIGEST_QOP_VALUE_STRING_AUTH_INT); if(!digest->qop) return CURLE_OUT_OF_MEMORY; } } else if(strcasecompare(value, "algorithm")) { free(digest->algorithm); digest->algorithm = strdup(content); if(!digest->algorithm) return CURLE_OUT_OF_MEMORY; if(strcasecompare(content, "MD5-sess")) digest->algo = CURLDIGESTALGO_MD5SESS; else if(strcasecompare(content, "MD5")) digest->algo = CURLDIGESTALGO_MD5; else return CURLE_BAD_CONTENT_ENCODING; } else { /* Unknown specifier, ignore it! */ } } else break; /* We're done here */ /* Pass all additional spaces here */ while(*chlg && ISSPACE(*chlg)) chlg++; /* Allow the list to be comma-separated */ if(',' == *chlg) chlg++; } /* We had a nonce since before, and we got another one now without 'stale=true'. This means we provided bad credentials in the previous request */ if(before && !digest->stale) return CURLE_BAD_CONTENT_ENCODING; /* We got this header without a nonce, that's a bad Digest line! */ if(!digest->nonce) return CURLE_BAD_CONTENT_ENCODING; return CURLE_OK; }
/* * Curl_auth_create_digest_http_message() * * This is used to generate a HTTP DIGEST response message ready for sending * to the recipient. * * Parameters: * * data [in] - The session handle. * userp [in] - The user name. * passdwp [in] - The user's password. * request [in] - The HTTP request. * uripath [in] - The path of the HTTP uri. * digest [in/out] - The digest data struct being used and modified. * outptr [in/out] - The address where a pointer to newly allocated memory * holding the result will be stored upon completion. * outlen [out] - The length of the output message. * * Returns CURLE_OK on success. */ CURLcode Curl_auth_create_digest_http_message(struct Curl_easy *data, const char *userp, const char *passwdp, const unsigned char *request, const unsigned char *uripath, struct digestdata *digest, char **outptr, size_t *outlen) { CURLcode result; unsigned char md5buf[16]; /* 16 bytes/128 bits */ unsigned char request_digest[33]; unsigned char *md5this; unsigned char ha1[33]; /* 32 digits and 1 zero byte */ unsigned char ha2[33]; /* 32 digits and 1 zero byte */ char cnoncebuf[33]; char *cnonce = NULL; size_t cnonce_sz = 0; char *userp_quoted; char *response = NULL; char *tmp = NULL; if(!digest->nc) digest->nc = 1; if(!digest->cnonce) { unsigned int rnd[4]; result = Curl_rand(data, &rnd[0], 4); if(result) return result; snprintf(cnoncebuf, sizeof(cnoncebuf), "%08x%08x%08x%08x", rnd[0], rnd[1], rnd[2], rnd[3]); result = Curl_base64_encode(data, cnoncebuf, strlen(cnoncebuf), &cnonce, &cnonce_sz); if(result) return result; digest->cnonce = cnonce; } /* If the algorithm is "MD5" or unspecified (which then defaults to MD5): A1 = unq(username-value) ":" unq(realm-value) ":" passwd If the algorithm is "MD5-sess" then: A1 = H(unq(username-value) ":" unq(realm-value) ":" passwd) ":" unq(nonce-value) ":" unq(cnonce-value) */ md5this = (unsigned char *) aprintf("%s:%s:%s", userp, digest->realm, passwdp); if(!md5this) return CURLE_OUT_OF_MEMORY; CURL_OUTPUT_DIGEST_CONV(data, md5this); /* convert on non-ASCII machines */ Curl_md5it(md5buf, md5this); free(md5this); auth_digest_md5_to_ascii(md5buf, ha1); if(digest->algo == CURLDIGESTALGO_MD5SESS) { /* nonce and cnonce are OUTSIDE the hash */ tmp = aprintf("%s:%s:%s", ha1, digest->nonce, digest->cnonce); if(!tmp) return CURLE_OUT_OF_MEMORY; CURL_OUTPUT_DIGEST_CONV(data, tmp); /* Convert on non-ASCII machines */ Curl_md5it(md5buf, (unsigned char *) tmp); free(tmp); auth_digest_md5_to_ascii(md5buf, ha1); } /* If the "qop" directive's value is "auth" or is unspecified, then A2 is: A2 = Method ":" digest-uri-value If the "qop" value is "auth-int", then A2 is: A2 = Method ":" digest-uri-value ":" H(entity-body) (The "Method" value is the HTTP request method as specified in section 5.1.1 of RFC 2616) */ md5this = (unsigned char *) aprintf("%s:%s", request, uripath); if(digest->qop && strcasecompare(digest->qop, "auth-int")) { /* We don't support auth-int for PUT or POST at the moment. TODO: replace md5 of empty string with entity-body for PUT/POST */ unsigned char *md5this2 = (unsigned char *) aprintf("%s:%s", md5this, "d41d8cd98f00b204e9800998ecf8427e"); free(md5this); md5this = md5this2; } if(!md5this) return CURLE_OUT_OF_MEMORY; CURL_OUTPUT_DIGEST_CONV(data, md5this); /* convert on non-ASCII machines */ Curl_md5it(md5buf, md5this); free(md5this); auth_digest_md5_to_ascii(md5buf, ha2); if(digest->qop) { md5this = (unsigned char *) aprintf("%s:%s:%08x:%s:%s:%s", ha1, digest->nonce, digest->nc, digest->cnonce, digest->qop, ha2); } else { md5this = (unsigned char *) aprintf("%s:%s:%s", ha1, digest->nonce, ha2); } if(!md5this) return CURLE_OUT_OF_MEMORY; CURL_OUTPUT_DIGEST_CONV(data, md5this); /* convert on non-ASCII machines */ Curl_md5it(md5buf, md5this); free(md5this); auth_digest_md5_to_ascii(md5buf, request_digest); /* For test case 64 (snooped from a Mozilla 1.3a request) Authorization: Digest username="******", realm="testrealm", \ nonce="1053604145", uri="/64", response="c55f7f30d83d774a3d2dcacf725abaca" Digest parameters are all quoted strings. Username which is provided by the user will need double quotes and backslashes within it escaped. For the other fields, this shouldn't be an issue. realm, nonce, and opaque are copied as is from the server, escapes and all. cnonce is generated with web-safe characters. uri is already percent encoded. nc is 8 hex characters. algorithm and qop with standard values only contain web-safe characters. */ userp_quoted = auth_digest_string_quoted(userp); if(!userp_quoted) return CURLE_OUT_OF_MEMORY; if(digest->qop) { response = aprintf("username=\"%s\", " "realm=\"%s\", " "nonce=\"%s\", " "uri=\"%s\", " "cnonce=\"%s\", " "nc=%08x, " "qop=%s, " "response=\"%s\"", userp_quoted, digest->realm, digest->nonce, uripath, digest->cnonce, digest->nc, digest->qop, request_digest); if(strcasecompare(digest->qop, "auth")) digest->nc++; /* The nc (from RFC) has to be a 8 hex digit number 0 padded which tells to the server how many times you are using the same nonce in the qop=auth mode */ } else { response = aprintf("username=\"%s\", " "realm=\"%s\", " "nonce=\"%s\", " "uri=\"%s\", " "response=\"%s\"", userp_quoted, digest->realm, digest->nonce, uripath, request_digest); } free(userp_quoted); if(!response) return CURLE_OUT_OF_MEMORY; /* Add the optional fields */ if(digest->opaque) { /* Append the opaque */ tmp = aprintf("%s, opaque=\"%s\"", response, digest->opaque); free(response); if(!tmp) return CURLE_OUT_OF_MEMORY; response = tmp; } if(digest->algorithm) { /* Append the algorithm */ tmp = aprintf("%s, algorithm=\"%s\"", response, digest->algorithm); free(response); if(!tmp) return CURLE_OUT_OF_MEMORY; response = tmp; } /* Return the output */ *outptr = response; *outlen = strlen(response); return CURLE_OK; }
static CURLcode check_telnet_options(struct connectdata *conn) { struct curl_slist *head; struct curl_slist *beg; char option_keyword[128] = ""; char option_arg[256] = ""; struct Curl_easy *data = conn->data; struct TELNET *tn = (struct TELNET *)conn->data->req.protop; CURLcode result = CURLE_OK; int binary_option; /* Add the user name as an environment variable if it was given on the command line */ if(conn->bits.user_passwd) { snprintf(option_arg, sizeof(option_arg), "USER,%s", conn->user); beg = curl_slist_append(tn->telnet_vars, option_arg); if(!beg) { curl_slist_free_all(tn->telnet_vars); tn->telnet_vars = NULL; return CURLE_OUT_OF_MEMORY; } tn->telnet_vars = beg; tn->us_preferred[CURL_TELOPT_NEW_ENVIRON] = CURL_YES; } for(head = data->set.telnet_options; head; head=head->next) { if(sscanf(head->data, "%127[^= ]%*[ =]%255s", option_keyword, option_arg) == 2) { /* Terminal type */ if(strcasecompare(option_keyword, "TTYPE")) { strncpy(tn->subopt_ttype, option_arg, 31); tn->subopt_ttype[31] = 0; /* String termination */ tn->us_preferred[CURL_TELOPT_TTYPE] = CURL_YES; continue; } /* Display variable */ if(strcasecompare(option_keyword, "XDISPLOC")) { strncpy(tn->subopt_xdisploc, option_arg, 127); tn->subopt_xdisploc[127] = 0; /* String termination */ tn->us_preferred[CURL_TELOPT_XDISPLOC] = CURL_YES; continue; } /* Environment variable */ if(strcasecompare(option_keyword, "NEW_ENV")) { beg = curl_slist_append(tn->telnet_vars, option_arg); if(!beg) { result = CURLE_OUT_OF_MEMORY; break; } tn->telnet_vars = beg; tn->us_preferred[CURL_TELOPT_NEW_ENVIRON] = CURL_YES; continue; } /* Window Size */ if(strcasecompare(option_keyword, "WS")) { if(sscanf(option_arg, "%hu%*[xX]%hu", &tn->subopt_wsx, &tn->subopt_wsy) == 2) tn->us_preferred[CURL_TELOPT_NAWS] = CURL_YES; else { failf(data, "Syntax error in telnet option: %s", head->data); result = CURLE_TELNET_OPTION_SYNTAX; break; } continue; } /* To take care or not of the 8th bit in data exchange */ if(strcasecompare(option_keyword, "BINARY")) { binary_option=atoi(option_arg); if(binary_option!=1) { tn->us_preferred[CURL_TELOPT_BINARY] = CURL_NO; tn->him_preferred[CURL_TELOPT_BINARY] = CURL_NO; } continue; } failf(data, "Unknown telnet option %s", head->data); result = CURLE_UNKNOWN_TELNET_OPTION; break; } failf(data, "Syntax error in telnet option: %s", head->data); result = CURLE_TELNET_OPTION_SYNTAX; break; } if(result) { curl_slist_free_all(tn->telnet_vars); tn->telnet_vars = NULL; } return result; }
struct Cookie *Curl_cookie_getlist(struct CookieInfo *c, const char *host, const char *path, bool secure) { struct Cookie *newco; struct Cookie *co; time_t now = time(NULL); struct Cookie *mainco = NULL; size_t matches = 0; bool is_ip; const size_t myhash = cookiehash(host); if(!c || !c->cookies[myhash]) return NULL; /* no cookie struct or no cookies in the struct */ /* at first, remove expired cookies */ remove_expired(c); /* check if host is an IP(v4|v6) address */ is_ip = isip(host); co = c->cookies[myhash]; while(co) { /* only process this cookie if it is not expired or had no expire date AND that if the cookie requires we're secure we must only continue if we are! */ if((!co->expires || (co->expires > now)) && (co->secure?secure:TRUE)) { /* now check if the domain is correct */ if(!co->domain || (co->tailmatch && !is_ip && tailmatch(co->domain, host)) || ((!co->tailmatch || is_ip) && strcasecompare(host, co->domain)) ) { /* the right part of the host matches the domain stuff in the cookie data */ /* now check the left part of the path with the cookies path requirement */ if(!co->spath || pathmatch(co->spath, path) ) { /* and now, we know this is a match and we should create an entry for the return-linked-list */ newco = dup_cookie(co); if(newco) { /* then modify our next */ newco->next = mainco; /* point the main to us */ mainco = newco; matches++; } else { fail: /* failure, clear up the allocated chain and return NULL */ Curl_cookie_freelist(mainco); return NULL; } } } } co = co->next; } if(matches) { /* Now we need to make sure that if there is a name appearing more than once, the longest specified path version comes first. To make this the swiftest way, we just sort them all based on path length. */ struct Cookie **array; size_t i; /* alloc an array and store all cookie pointers */ array = malloc(sizeof(struct Cookie *) * matches); if(!array) goto fail; co = mainco; for(i = 0; co; co = co->next) array[i++] = co; /* now sort the cookie pointers in path length order */ qsort(array, matches, sizeof(struct Cookie *), cookie_sort); /* remake the linked list order according to the new order */ mainco = array[0]; /* start here */ for(i = 0; i<matches-1; i++) array[i]->next = array[i + 1]; array[matches-1]->next = NULL; /* terminate the list */ free(array); /* remove the temporary data again */ } return mainco; /* return the new list */ }